Asp.Net MVC error 404 The request filtering module is configured to deny a request where the query string is too long.

If you create a new MVC projet and hit F5 to start the application. As you may know by now, Visual Studio 2013 doesn’t have Cassini, the internal web server inside Visual Studio. So, IIS Express is quickly automatically configured and the default website start.

RequestQueryStringIsTooLong

Unfortunatly, if I do nothing, I am having a issue with query string being too long. This is because it redirect to the login page which redirect to the login page and so on.

So far, I haven’t found solution, neither StackOverFlow. But, if you are using IIS, everything works. Personally, I am always using IIS, but I am still curious why the IIS express, even with a brand new project doesn’t work.

EDIT

I finally found that in IIS Express configuration file (located inside your document setting), I had windows authentication enabled. You need to remove this and to use anonymous authentication.

Two differents approaches to save data from Javascript to Asp.Net MVC

They are more than two approaches to send data from Javascript with Ajax to Asp.Net MVC. Today, I’ll present you one that use dynamic and one that use DTO (data transfert object). The first approach is faster because it requires less code but is dynamic which open the door to several problems. Before anything, let see the Javascript that will be used by both approaches.

$(document).on("click", "#btnSaveOrder", function () {
    var button = $(this);
    $(button).attr('disabled', 'disabled');
    $('.loadingAnimationfixed').show();
    var listIdOrdered = [];
    $('#sessiongrid tbody tr').each(function () {
        listIdOrdered.push($(this).attr("data-workoutsessionid"));
    });

    var toSave = {
        'OrderedWorkoutSessionList': listIdOrdered
        ,'WorkoutId': $('#Id').val()
    }; 

    $.ajax(
        {
            url: "/WorkoutSession/SaveWorkoutSessionOrder",
            type: "POST",
            data: JSON.stringify(toSave),
            success: function (response, status, xhr) {
                successMessage(response.Status);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (errorThrown == "Forbidden") {
                    errorMessage("Forbidden access");
                } else {
                    errorMessage('An error occurred please retry.');
                }
            }
            , complete: function () {
                $(button).removeAttr('disabled');
                $('.loadingAnimationfixed').hide();
            }
        }
    );

    return false; //Prevent button to submit the form
});

The code bind with JQuery a click event to the button with the ID “btnSaveOrder”. We disable the button and display a loading animation division. This is so far good practice. It disallows the user to click twice on the button and it displays to the user what’s going on. Next, we are building from the user interface a list of id. The situation here is that we need to save a list of ID to the database in a specific order. The line that initialize the tosave variable contains a list of all ID which is ordered, then a variable of the current workout. So, we have an object that contain a workout ID with a list of workout session ID that is ordered as FIFO (first in first out) list. This object need to be sent to the server to be saved. This is done by the JQuery Ajax method. First, we specify the URL and the method to contact the server. Second, we specify the object to send and we transform the Json into a string. Finally, we display a success message or an error message. In both case, we enable the button and remove the animation with the complete method. From this code, we know that from the server side we need to have a POST action that is called SaveWorkoutSessionOrder which take a class with 2 properties, one is a list of integer and one is an integer.

The first approach to handle this is to go fast and to not create a class that contain a list of integer and one integer. We can do it by using the dynamic keyword.

[HttpPost]
public JsonResult SaveWorkoutSessionOrder()
{
	dynamic json = JsonConvert.DeserializeObject(Request.Form.Get(0));

	int order = 1;
	var workout = new Workout { Id = json.WorkoutId };
	workout.Sessions = new List<WorkoutSession>();

	foreach (var id in json.OrderedWorkoutSessionList)
	{
		workout.Sessions.Add(new WorkoutSession { Id = id, Order = order++});
	}

	try
	{
		ServiceFactory.Workout.UpdateSessionOrderOnly(workout);
	}
	catch (DataNotFoundException)
	{
		throw new HttpException((int)HttpStatusCode.Forbidden,"Cannot update the session");
	}
	return Json(new { Status="Saved" });
}

The first thing we remark is that the method doesn’t contain any parameter. This is because we won’t allow the model binder to act but deserialize it manually inside the method. This is what the first line of the method is doing with the JsonConvert.DeserializeObject. We need to get the Request object and to get the first element of the form which is the one sent by Javascript with the Ajax calls. The return value of the deserialization go to a dynamic variable. This allow us to skip the creation of a concrete class for the list of integer and integer. Then, we can use the variable but you won’t have any intellisence. You need to be sure to write correctly the property name of this dynamic variable with the same name as the Javascript prototype. If you do, everything will be fine in the execution. Nevertheless, this is not an optimal way to develop a enterprise application because of many problem. Yes, it’s faster, but the cost is heavier in the long term.

As you can see, we do not have a parameter to this controller’s action. Even if it’s not dramatic, it’s harder to unit test because it requires to mock the Request object. The second problem is with the dynamic itself. The use of dynamic weak the entire method. The problem is that error is not detected until execution. If you are unit testing with a full coverage this method, you shouldn’t have a problem. The last problem is that we are deserializing inside the controller’s action instead of delegating the process to the Model Binder. Every mapping between http request and controller’s methods are done by the Model Binder. The cohesion of your controller is compromise and may come a problem later on in the maintenance phase of your system.

To solution is to change the controller to take a parameter that will be deserialized by the Model Binder of Asp.Net MVC and will give us a strongly typed object. This one will be easily testable since we will be able to pass in our tests a parameter.

[HttpPost]
public JsonResult SaveWorkoutSessionOrder(WorkoutSessionOrder workoutSessionOrder)
{
	int order = 1;
	var workout = new Workout { Id = workoutSessionOrder.WorkoutId };
	workout.Sessions = new List<WorkoutSession>();

	foreach (var id in workoutSessionOrder.OrderedWorkoutSessionList)
	{
		workout.Sessions.Add(new WorkoutSession { Id = id, Order = order++});
	}

	try
	{
		ServiceFactory.Workout.UpdateSessionOrderOnly(workout);
	}
	catch (DataNotFoundException)
	{
		throw new HttpException((int)HttpStatusCode.Forbidden,"Cannot update the session");
	}
	return Json(new { Status="Saved" });
}

As you can see, the first signature as changed to have a parameter. That mean that we need to provide this data from the Javascript. In fact, we were sending this object previously but this time we have to specify the data type to indicate to Asp.Net MVC framework what information we are sending to deserialize. To mark the data sent to be JSON format, we need to add this line in the Ajax’s call : contentType: ‘application/json’.

$(document).on("click", "#btnSaveOrder", function () {
    var button = $(this);
    $(button).attr('disabled', 'disabled');
    $('.loadingAnimationfixed').show();
    var listIdOrdered = [];
    $('#sessiongrid tbody tr').each(function () {
        listIdOrdered.push($(this).attr("data-workoutsessionid"));
    });

    var toSave = {
        'OrderedWorkoutSessionList': listIdOrdered
        ,'WorkoutId': $('#Id').val()
    }; 

    $.ajax(
        {
            url: "/WorkoutSession/SaveWorkoutSessionOrder",
            type: "POST",
            data: JSON.stringify(toSave),
            contentType: 'application/json',
            success: function (response, status, xhr) {
                successMessage(response.Status);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (errorThrown == "Forbidden") {
                    errorMessage("Forbidden access");
                } else {
                    errorMessage('An error occurred please retry.');
                }
            }
            , complete: function () {
                $(button).removeAttr('disabled');
                $('.loadingAnimationfixed').hide();
            }
        }
    );

That’s it! Now we have seen two different approaches. The last one is the one you should use every time because it’s strongly typed, easier to test and won’t compile with possible error like the one with Dynamic which will crash on execution if a typo is done.

How to migrate from ASP.NET MVC 4 to ASP.NET MVC 5

The new version of MVC is out since few weeks. If you have Microsoft Visual Studio 2013 and create a new web application, you will notice some improvements. First, MVC default version is now version 5 and not version 4. This come with a brand new razor version which is the third. Also, Entity Framework is now at version 6. Before going further, notice that if you are migrating to MVC5 than some older version of other assembly won’t be compatible. For example, razor version 2 won’t work with MVC5.

This is not an easy step to do, migrating, but if you have your MVC4 already up-to-date and have used Nuget for your external libraries, the process won’t be that hard. The first step is to make sure you commit all your code to your repository. Preferably, label it with “Last Version MVC4”. This way, if something is wrong, you will be able to go back and start from scratch.

PackageManagerConsole

The second step is to run Nuget to update every packages. This can be done with a single statement in the Nuget Console.

PM> Update-Package

This may take several minutes if you use a lot of package. This will do about half of the job. You will need to do this for every of your project that use package from Nuget. A good practice is to have always referenced your external library with Nuget. Even if you are using the same package from some of your projects, this won’t duplicate them in your solution/packages.

The third step is to be done in every of your project. I suggest you start from your web site project since it’s the one that will have the most job to do. Open the web.config of the web project. Verify that you have Entity Framework set to version 6. The information is set inside configuration>configSections inside a section named “EntityFramework”.

<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
...................

As you can see, the version MUST be set to 6.0.0.0 and in fact it should have been modified by the Nuget update that we have done earlier. If it’s not, go in your project reference and be sure that you have a reference to EntityFramework.dll.

EntityFrameworkVersion6

The screenshot show you that not only the version is set to version 6.0.0.0 but that the version 6 of Entity Framework has a new dll called “EntityFramework.SqlServer”. This is now required.

The next step is to go lower in your web.config to the appSetting section. You need to update the version of webpages from 2.0.0.0 to 3.0.0.0


Then, you need to set the framework to 4.5.1 (if you want to be all up to date). This can be done in the web.config also inside the configuration tag, under system.web:


  <system.web>
    <compilation debug="true" targetFramework="4.5.1"/>
    <httpRuntime targetFramework="4.5.1"/>

Before going any further in the web.config. Do not forget to open ALL your project to go in the properties of the project and to select the Target Framework to 4.5.1.
ApplicationPropertiesTargetFramework

Back to the web.config, we have the runtime tag to update. Here is my runtime information, yours should be almost the same.

<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
	<dependentAssembly>
		<assemblyIdentity name="WebMatrix.WebData" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="WebMatrix.Data" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="System.Web.Razor" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
		<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
		<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
		<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="AutoMapper" publicKeyToken="be96cd2c38ef1005" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="Microsoft.Practices.Unity" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-4.3.0.0" newVersion="4.3.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-4.3.0.0" newVersion="4.3.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
	</dependentAssembly>
	<dependentAssembly>
		<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral"/>
		<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2"/>
	</dependentAssembly>
</assemblyBinding>

This tell the .Net compiler to use the new version if a reference is made to an older version. You can find information through MSDN concerning Assembly Unification.

Now, do that in all your web.config that contain similar XML elements. Once it’s done, go into the view folder. This one also should contain a web.config. You need to change some version number here too. Here is one of my view folder (you can have few because of area).

<?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization"/>
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>

  <system.web>
    <httpHandlers>
      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
    </httpHandlers>

    <!--
        Enabling request validation in view pages would cause validation to occur
        after the input has already been processed by the controller. By default
        MVC performs request validation before a controller processes the input.
        To change this behavior apply the ValidateInputAttribute to a
        controller or action.
    -->
    <pages
        validateRequest="false"
        pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5Install-Package -Id  Microsoft.AspNet.WebHelpers.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <controls>
        <add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
      </controls>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>
</configuration>

You have 3 entries to change for razor. You need to change version 2.0.0.0 to version 3.0.0.0. Also, System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc need to be to 5.0.0.0. Then, under pages you have 3 others change concerning MVC that need to be to version 5.

The last modification that is require to use MVC5 is to open with note pad the project file of the web. Search for ProjectTypeGuids and remove the GUID for MVC4 : {E3E379DF-F4C6-4180-9B81-6769533ABE47}.

You won’t have the stuff that a brand new MV5 project has like BootStrap but this can be added later on. What you have is a project up-to-date with Microsoft MVC framework 5, Entity Framework 6 and using the .Net Framework 4.5.1

Unit Test and References with CodeLens

CodeLens is a new feature that enhance your code by adding additional information over yours methods. CodeLens add information concerning references, unit testing and TFS. We won’t talk about TFS in this article but concentrate on the two first features that is available even if you do not use TFS. Before anything, CodeLens is available only with Visual Studio 2013 Ultimate.

The first information CodeLens add over your method signature is the number of reference that the method does has. References are all codes entries that your code contain to the method where the information is added. If you are using ReSharper, you may find it similar to “Find Usage” feature but with the advantage of being dynamically available for all your method directly in Visual Studio. Visual Studio add this information directly above the method which allow to be very rapid to figure out if the method is used and where the method is called. To see it in action, open Visual Studio 2013 Ultimate Edition and select any of your existing project. The reference count will be written in small gray letter above each classes and each methods.

reference

To be able to get additional information concerning reference, pressing ALT+2 or clicking on the numbers of reference open a contextual window with all calls occurrences. You can from there select a reference to be transported directly to the file and line that call the method.
reference2

It also possible from the same menu to generate the Code Map of the method. This is an interesting way to see all references links.
reference3

If you do not want to move to the usage of your method because you just want to have a look but not to move from where you are, you can. To see the code that use it, you can have a small snapshot of 2 lines before and 2 lines after the call by moving the focus on a reference without clicking.
reference4

The second information that is added by CodeLens is the number of unit test that is successful for the method compared to the number of total unit test. This is one of the greatest features to improve your code quality because in a single look, you can see if a method is tested or not. You can also visualize which test is in error or have passed. Within a single click, you can move from your method to your test. Another information that is provided is the amount of time the test took. This is a new metric used by executing unit testing and it allows you to improve your code by having near of each code the time that it takes to execute it.

reference5

As you can see, Visual Studio 2013 improves the integration of good software development by having near of your hand different information. Reference is a key information to have and unit testing help you and your team to work toward the objective to have a code quality better.

How to setup Entity Framework Code first to have only one side 0 to 1 relationship

Let say you have an entity that can but doesn’t mean will have a relation to another entity. This is a 0..1 to 1 or 0..1 to many.

In this example, we show a scenario where we have one entity that has a relation to a second entity. The second entity doesn’t have any reference to the first one.

At first, we may think than this code below works.

            modelBuilder
                .Entity<EntityOne>()
                .HasOptional(d => d.EntityTwo)
                .WithOptionalDependent();

The WithOptionalDependent tells EF (Entity Framework) that EntityOne is the one of the two entities that hold the reference which is optional as stated with the HasOptional property. No! This raise an error that tell that it cannot find EntityTwo_ID key. This is problematic because in the scenario we are talking about the foreign key has a special name. So, we have to configure the foreign key. Of course, if your FK is named EntityTwo_ID than you are all fine.

            modelBuilder
                .Entity<EntityOne>()
                .HasOptional(d => d.EntityTwo)
                .WithOptionalDependent()
                .Map(d => d.MapKey("EntityTwoID");

The HasForeignKey is not available from WithOptionalDependant, but with Map we can setup the foreign key name. Unfortunately, this won’t work either. The error is an invalid column name. From here, we can realise that the MapKey is used by the principal entity and not the dependent.

Still, we want to have 0..1 relation. How can we setup this optional relation ship with Entity Framework without having on the other side the property to the other entity? We need to use HasOption and threat the whole situation not as 0..1 to 1 but 0..1 to many.

            modelBuilder
                .Entity<EntityOne>()
                .HasOptional(d => d.EntityTwo)
                .WithMany()
                .HasForeignKey(d => d.EntityTwoID)
                ;

To make it works, we use WithMany without specifying the other side property (since we do not have it) and we use HasForeignKey to specify the correct foreign key. And that’s it! It works!

ImmutableList and the namespace System.Collections.Immutable

An immutable list has the propriety of being not modifiable after its creation. String is immutable because each time you change its value a new instance is created. If you want to have the same behavior with a list, you need to use an immutable list.

The creation of an ImmutableArray can be created from a method or from another list. But first, you need to use NuGet to download the package. You also need to use .Net Framework 4.5.

MicrosoftImmutableCollection

or with the package console with this line:

Install-Package Microsoft.Bcl.Immutable


using System.Collections.Immutable;

ImmutableList<int> array = ImmutableList.Create<int>(100, 101, 300);

List<int> myList = new List<int> { 100, 101, 300 };ImmutableList<int> array2 = ImmutableList.ToImmutableList<int>(myList);

As you can see, you need to use the namespace System.Collections.Immutable. The namespace contains more than only ImmutableList, but also contains an ImmutableDictionary, ImmutableQueue, ImmutableSet and ImmutableStack.

ImmutableCollection

Implicit Implementation of Interface vs Explicit Implementation of Interface

What is the difference between implicit and explicit interface?

ImplicitExplicitInterface

Implicit interface allow access the the method without having to cast the object to the interface type while explicit interface require you to cast your object to the interface. Why would you want to have explicit interface? Because if you have several method from different interface with the same signature, the only way to call the good method is to do it explicitly.

Here is an example of an implicit interface:

    public class Interface : IInterface
    {
        public void Method1()
        {
            throw new NotImplementedException();
        }
    }

Here is an example of an explicit interface:

    public class Interface : IInterface
    {
        public void IInterface.Method1()
        {
            throw new NotImplementedException();
        }
    }

And you can use both in the same time:

    public class Interface : IInterface
    {
        void Method1()
        {
            throw new NotImplementedException();
        }

        void IInterface.Method1()
        {
            throw new NotImplementedException();
        }
    }

Let examine the following code :

class Program
{
	static void Main(string[] args)
	{
		var x = new Interface();
		x.Method1();
		Console.ReadLine();
	}
}

public class Interface : IInterface, IInterfaceWithSameMethodSignature
{
	public void Method1()
	{
		Console.WriteLine("IInterface:Method1 Implicit");
	}

	void IInterface.Method1()
	{
		Console.WriteLine("IInterface:Method1");
	}

	void IInterfaceWithSameMethodSignature.Method1()
	{
		Console.WriteLine("IInterfaceWithSameMethodSignature:Method1");
	}
}

interface IInterface
{
	void Method1();
}
interface IInterfaceWithSameMethodSignature
{
	void Method1();
}

As you can see, the Main method has a variable named ‘x’. If we check the IntelliSence we see only the first Method1() of the Interface class. The reason is that we pass through the implicit method. If we want to use the explicit Method of the IInterface we need to cast ‘x’.

Interface x = new Interface(); 
x.Method1();    //Implicit prints: "IInterface:Method1 Implicit" 
((IInterface)x).Method1();    //Explicit 1 prints: "IInterface:Method1"
((IInterfaceWithSameMethodSignature)x).Method1();    //Explicit 2 prints: "IInterfaceWithSameMethodSignature:Method1"

This is handy because it disambiguates which methods to be called. This can be handy if the object is passed to a method that require the interface in a parameter. This one is cast when passed by parameters.

class Program
{
    static void Main(string[] args)
    {
        var x = new Interface();
        Method(x);

        Console.ReadLine();
    }

    static void Method(IInterfaceWithSameMethodSignature expl)
    {
        expl.Method1();
    }
}

The Interface class is used with the x object. This one is passed to a method that require the interface IInterfaceWithSameMethodSignature. When Method1 is called, the one of IInterfaceWithSameMethodSignature is called, the explicit method.

How to create a JQuery plugin that accept public function

If you have a web project that use JQuery framework and you have a lot of functions that has cohesive meaning in a single Javascript file, maybe you should think to create a plugin. The choice to create a JQuery pluging let you act on Html element by using JQuery. You extend JQuery. I won’t write here how to create a plugin but how to add to your plugin some public functions. This is something important that may have turn you off concerning to convert all your functions into a JQuery plugin. But, in this article, I’ll show you how to extend JQuery for a simple pluging and to allow to use pluging public function. Those public functions will be called commands.

(function($) {  
    //define the commands that can be used  
    var commands = {  
        publicMethod1Name: innerPluginMethod1,  
        publicMethod2Name: innerPluginMethod2  
    };  
  
    $.fn.yourPlugin = function() {  
        if (typeof arguments[0] === 'string') {  
            var property = arguments[1];  
            var args = Array.prototype.slice.call(arguments);  //Erase command name which is index 0.
            args.splice(0, 1);  
            commands[arguments[0]].apply(this, args);  //Execute command with the rest of argument (1...n)
        }  
        else {  
            initialize.apply(this, arguments);  
        }  
        return this;  
    };  
  
    function initialize(options){  

    }  
  
    function innerPluginMethod1(param1) {  

    }  
  
    function innerPluginMethod2() {  

    }  
})(jQuery);  

The code above can be used this way:

$('#htmlElement').yourPlugin({option1:value1, option2:value2});
$('#htmlElement').yourPlugin("innerPluginMethod1", "parameter1");

As you can see, the plugin can be called by two different ways. The first line initialize the JQuery plugin and the second line call a public function. The weak point is that you have to pass the name of the function (command) by a string. The strong point is that commands have access to all the plugin variable. They can access your option initialized by the first line in the example above or can set values which will be available to all other commands.

The code is pretty simple as you can see. The first line verify that we pass a string as the first parameter. It’s the case when we call the command by string. Otherwise, we pass an object which are the options of the plugin or we pass nothing. If it’s a string, we take the string and get the function. This is why we have a dictionary of command name to function. Before calling the function, we remove the first parameter because it’s the name of the function, we do it by calling “slice“. The next call is “apply” which take the context of the “this” into the function. This give the the command all reference of the JQuery plugin. If the first parameter wasn’t a string, it can be nothing or an object (for plugin option) we simply call the method initialize that let you setup option and execute the main goal of your plugin. We also call “apply” to give all arguments.

C# two dimensional array with double bracket and with single bracket

With Microsoft .Net and C# it’s possible to have multiple dimension array with two different ways. One use double bracket and one with single bracket with a comma.

int [][] myDoubleArray = new int[100][];
int [,] mySingleArrayActingAsTwoDimensional = new int[100,100];

The first example, is in fact an array of array. You can have multiple dimension for your second dimension. It’s called a jagged array.

int [][] myDoubleArray = new int[100][];
myDoubleArray[0] = new int[5];
myDoubleArray[1] = new int[10];
myDoubleArray[2] = new int[50];
myDoubleArray[...] = new int[...];

This lead to the possibility to have a variable that is not uniform in its size, it can but it doesn’t mean it is a perfect rectangle. The second way to make a multiple dimensional array is by using the comma. This force to have the size defined for both dimension and to be the same for each rows. It also not possible to get a row like array of array because it’s based on index.

int [,] mySingleArrayActingAsTwoDimensional = new int[100,100];
mySingleArrayActingAsTwoDimensional[50] = ... // CRASH!!!
mySingleArrayActingAsTwoDimensional[50,0] = 1;

For the jagged array, to loop through all items, we must check for each array. This is require to get its size because it can change.

for (int i = 0; i < myDoubleArray.Length; i++)
{
     for (int j = 0; j < myDoubleArray[i].Length; j++)
     {
          myDoubleArray[i][j] = i * j;
     }
}

For a rectangle array, it’s not required and we can just check the first item lenght.

for (int i = 0; i < mySingleArrayActingAsTwoDimensional.GetLength(0); i++)
{
    for (int j = 0; j < mySingleArrayActingAsTwoDimensional.GetLength(1); j++)
    {
       mySingleArrayActingAsTwoDimensional[i, j] = i * j;
    }
}

Finally, you can create jagged array with a short nomenclature.

var jaggedArrayTwoDimension= {new int[5] ,new int[10], new int[]{1,2,3,4,5,6,7,8,9,10}};  

The last example create an array of 2 dimensions. 3 rows, the first one has 5 integers, the second has 10 integer and the last rows and 10 integers. The first two rows are integer not defined and the last row has integer defined from 1 to 10.

How to use Json.Net library as the default serializer of Json in Asp.Net

Using the default json serializer with Asp.Net MVC can be limited. One classic example is with date which return a slashed format with a integer from the epoch number. Usually, people want a formatted date with a standard format like yyyy-MM-dd. Json.Net library handle this kind of feature. It also give you a lot of options that I’ll let you explore directly from the Json.Net newton king website.

The goal of this article is to show you how to use Json.Net library manually. This solution will require to repeat the use of a class manually into each of your action method every time you want to use the new serializer. This can be useful if you do not want to change at large in your system. Often, if you have a big system and you do not want to test everything, you may want to keep the new serializer for few methods. Later, we will see how to change to default .Net serializer with the Json.Net one.

First, we need to inherit from ActionResult (or JsonResult) to have your own custom result class. This is where we will use Json.Net library.

public class JsonNetResult : ActionResult
{
        public Encoding ContentEncoding { get; set; }
        public string ContentType { get; set; }
        public object Data { get; set; }

        public JsonSerializerSettings SerializerSettings { get; set; }
        public Formatting Formatting { get; set; }

        public JsonNetResult(object data)
        {
            this.Data = data;
            SerializerSettings = new JsonSerializerSettings();
            Formatting = Formatting.Indented;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var response = context.HttpContext.Response;
            response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";

            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }

            if (Data != null)
            {
                var writer = new JsonTextWriter(response.Output) { Formatting = Formatting };
                var serializer = JsonSerializer.Create(SerializerSettings);
                serializer.Serialize(writer, Data);
                writer.Flush();
            }
        }
}

Most of the work is at the end where we use JsonSerializer.Create and .Serialize. You could set additional default serialization setting in this class.

If you want to use this class in an action method, you need to return this class.

public JsonResult YourMethodAction()
{
    var model = //...
    return new JsonNetResult(model);
}

As you see, you need to return every time a new class manually. If you do not want to do it manually and continue to use the return Json(…) as you are used to do with Asp.Net MVC, you will need to override the default method. This can be easily done if you have a base controller where all your controller inherit. In fact, you should have a base controller for many reasons.

public class BaseController:Controller
{
   protected internal override JsonResult Json(object data)
   {
       return new JsonNetResult(data);
   }
}

This create for you the new custom serialization class and it’s transparent for all your method that need to return a Json formatted value.