C#: an attempt was made to load an assembly from a network location

“an attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .net framework.”

solution:

Go to the location of the assembly file (.dll) and right-mouse click it. Go to the General tab and click “unblock”.

🙂

Advertisements

Visual Studio 2015 C#6 replace INotifyPropertyChanged with nameof()

In Visual Studio 2015 with C#6.0 you can write your OnPropertyChange using the new nameof().

NotifyOfPropertyChange(() => Prop);

with

NotifyOfPropertyChange(nameof(Prop));

Regex for Visual Studio 2015 to find and replace:

Text to search:

(?:\()[()][)][ ][=][>] (.*)(?:\);)

Replace with:

(nameof($1));

Make sure the option “Use Regular Expressions” is enabled in the find and replace window.

Quick and dirty, comment your regex below 🙂

Slow performance on ASP.NET MVC application using EntityFramework + SQL Server

Used technologies and software:

  •  ASP.NET MVC 5
  • Entity Framework Code First 6.x
  • SQL Server 2014 Express
  • Windows Server 2012
  • IIS 8.0
  • Hyper-V Virtual Machine (SSD and 8GB RAM set dynamic with 4GB as start up value).
  • Visual Studio 2013

Problem:

Website in production is slow, takes several seconds (+30s) or even minutes to load a page. But this does not always happen.
In development everything works always fast.

Steps taken to figure out the problem:

  • Netword config, NIC, IP, DNS, … –> ok
  • Checking if connection string is set correctly. –> ok
    (tip: see https://teusje.wordpress.com/2012/02/21/how-to-test-an-sql-server-connection/ )
  • Adding caching to the ASP.NET MVC application. –> ok, but still too slow
  • SQL Server 2014 Profiler:
    Trying to figure out if it is the application or the SQL Server, so we ran the Profiler and copy several queries and executed them directly on the SQL Server without any problem.
  • Log files:
    Custom log file in the ASP.NET MVC application gave us a good hint:

    Exceptions:

     sqlexception: Timeout expired EntityCommandExecutionException
    
     SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
     Stack:    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
        at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
        at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
        at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
        at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
        at System.Data.SqlClient.SqlDataReader.get_MetaData()
        at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
        at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
        at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
        at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
        at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
        at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
        at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
        at Glimpse.Ado.AlternateType.GlimpseDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
        at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
        at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.b__c(DbCommand t, DbCommandInterceptionContext`1 c)<
        at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
        at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
        at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
        at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
        at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)

Start Microsoft SQL Server Management Studio and navigate to:
[Server Instance] –> [Management] –> [SQL Server Logs] –> double click [Current – …] there you select [Windows NT]

There we’ve seen the real problem several times in the logs:

"AppDomain 50 (master.sys[runtime].48) is marked for unload due to memory pressure."

sql server problem

Now we simply started Task Manager on the server and watched the ‘Memory’ in the ‘Performance’ tab.
The memory was constantly at 3.7GB or 3.8GB when we visited the website.

vm memory
Hooray! We found the problem. 🙂 Now we need to find a solution.

As you might remember from the beginning of this post, we’ve configured our Hyper-V Virtual Machine with the Dynamic Memory option.
This had a start up value of 4GB… and our server was constantly at 3.7GB or 3.8GB…

So why does our server not dynamically increase the RAM of the virtual machine?

It turns out that Hyper-V Dynamic Memory, introduced in Windows Server 2008 R2 SP1, is only supported in SQL Server Enterprise and Datacenter Editions!

Solution:

Don’t enable Hyper-V Dynamic Memory for your virtual machine but set it static with a value of e.g. 8GB RAM.

Voila:

vm memory fixed

🙂

Your Host Operating System needs to be at least Windows Server 2008 R2 SP1 or Microsoft Hyper-V Server 2008 R2 SP1 as your Hyper-V host.
The Guest Operating System edition (= your virtual machine) needs to be Web, Standard, Enterprise or Datacenter.
You need SQL Server Enterprise or Datacenter edition if you want that SQL Server automatically uses more RAM when needed using the Hyper-V Dynamic Memory feature.
In case you just have a Windows Server Standard and SQL Server Express and you have the same symptoms as described above just set your virtual machine RAM to a static value instead of using Hyper-V Dynamic Memory.

Extra information:

Visual Studio 2013 – Clean Solution

I recently upgraded a project from Visual Studio 2010 / .NET4.0 to Visual Studio 2013 (update 4) / .NET 4.5.
Code that was working for weeks, didn’t work anymore (exceptions in Caliburn.Micro).

Summary:
I reinstalled all my Nuget packages, verified the public key tokens of the libraries via the Strong Name Tool (SN.exe -T my.dll), did “Clean Solution”, “Rebuild Solution”, rewritten code, etc…

In a desperate action I manually cleaned every bin and obj folder in my Workspace.
After this action the code started to work again.

Then I was wondering: Does the “Clean Solution” in Visual Studio 2013 work different compared to Visual Studio 2010.
An internet stranger gave me a good hint:

“Sorry, but this is simply not true. It does not delete the contents of /obj which are the root of the problem. At least this is the situation with VS 2013 update 3.”

http://stackoverflow.com/questions/755382/i-want-to-delete-all-bin-and-obj-folders-to-force-all-projects-to-rebuild-everyt#comment41784938_755390

After searching some more, I was happy that I was not the only one who had problems with Visual Studio 2013 and the Clean Solution:

“However, once I’ve converted my projects to Visual Studio 2013 I star receiving error on build or deploy:”

http://kitsula.com/Article/How-to-remove-bin-obj-folder-before-build-deploy

Conclusion: if you upgrade to Visual Studio 2013 and receive strange exceptions, clean the obj directories manually or change your project file to remove the obj directory before each build via the BaseIntermediateOutputPath property/parameter.

By default the BeforeBuild and AfterBuild are not used. You can see this by unloading your project in Visual Studio and then right-mouse click it and select Edit:

<!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->

Uncomment the BeforeBuild.
Your project file should now contain this:

<!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets. -->
  <Target Name="BeforeBuild">
    <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
  </Target>
  <!--<Target Name="AfterBuild">
  </Target>-->

Information on the BaseIntermediateOutputPath property/parameter:

 “The top-level folder where all configuration-specific intermediate output folders are created. The default value is obj\. The following code is an example:  <BaseIntermediateOutputPath>c:\xyz\obj\</BaseIntermediateOutputPath>”

If you receive the Error after changing the project:

 Unable to remove directory “obj\”. The directory is not empty

Go have a look at this url: http://forums.asp.net/t/1976253.aspx
It might also be related to Visual Studio 2013…

Info:
https://msdn.microsoft.com/en-us/library/k5b5tt23(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/5ak1w89s.aspx
https://msdn.microsoft.com/en-us/library/bb629394.aspx

The Future of C# with Mads Torgersen: C# 6

 

Copy/paste from http://adamralph.com/2013/12/06/ndc-diary-day-3/

The NDC Wi-Fi was put to the test during this talk with the C# Twitter stream seeing an explosion in traffic as Mads revealed, for the first time publicly, a range of features either set to be delivered in the next version of C# or at least under strong consideration.

Unfortunately I was too caught up in the excitement to note everything down but after mining my memory and the Twitter feed, here is the list of implemented/potential language features (I’m sure I’m missing at least one of them):

  • primary constructors – public class Point(int x, int y) { }
  • read only auto-properties – public int X { get; } = x;
  • static type using statements – using System.Math;
  • property expressions – public double Distance => Sqrt(X * X + Y * Y);
  • method expressions – public Point Move(int dx, int dy) => new Point(X + dx, Y + dy);
  • params for enumerables – public Point Average(params IEnumerable<Point> points) { }
  • monadic null checking – if (points?.FirstOrDefault()?.X ?? -1) { }
  • constructor type parameter inference – var t = new Tuple(1,2); // infers Tuple<T1, T2>
  • inline declarations for out params – public void Foo(out var x, out var y) { }

I love all these features perhaps with the exception of the last one. Whist it doesn’t negatively effect the language (although some of the audience were concerned about encouraging the use of out parameters) it doesn’t really do much to achieve the stated goal of improving syntax for multiple return values. I was hoping for something like:

public (int x, int y) Foo() { }

But still, the rest of the features look awesome and I can’t wait to get my hands on C# vNext!

More info at http://adamralph.com/2013/12/06/ndc-diary-day-3/

Fixing comctl32.dll WIN32Exception

A C# project was recently upgraded from .NET 3.5 to .NET 4.0.
The program worked fine, except on a Windows 8 Pro x64 machine where this error was given:

Win32Exception: Cannot load the “comctl32.dll” DLL into memory.

The solution that worked for us (after a long search) was removing CorFlags to set the application to 32-bits mode. When a new build was created without CorFlags and setting Visual Studio to build the project to x86 instead of x64 solved the problem.

It looks like CorFlags is not reliable…

Orchard CMS 1.6.1 security patch available

A quote from the website:

A non-persistent XSS vulnerability has been discovered in the Orchard.Comments module that is distributed with the core distribution of the CMS. The module could in some circumstances let an external website render custom scripts on an Orchard website. This vulnerability might ultimately be used to gather your credentials if you further authenticate on the targeted Orchard website.

All released versions of Orchard are vulnerable and need to be patched immediately.

We are releasing today (April 30, 2013) a new version 1.6.1 of Orchard 1.6 that has the patch in place. This new version is replacing the previously available download. If you are downloading Orchard 1.6.1 today, you do not need to take any additional steps. The latest 1.x development branch is already patched as well. We are also releasing patch files for each version of Orchard from 1.0 to 1.6 that can be applied to existing web sites.

Great to see that security risks are getting patched immediately !

More information and download links at:

More information about Orchard CMS:

 

C# Linq: Zip method

string[] brands = new string[] { "BMW", "Mercedes", "Audi" };
string[] websites = new string[] { "www.bmw.com", "www.mercedes.com", "www.audi.com" };

var output = brands.Zip(websites, (b, w) => string.Format("{0} can be found at {1}", b, w));

foreach (var line in output)
  Console.WriteLine(line);

This gives you:

BMW can be found at www.bmw.com 
Mercedes can be found at www.mercedes.com 
Audi can be found at www.audi.com

More information at: http://msdn.microsoft.com/en-us/library/dd267698.aspx