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.

How to bind Sql View to an Entity Framework object

If you do not want to create an Entity and to configure this one with the ToTable() to the name of your view, you can use direct method from the context to call the database and bind the result into a class.

Here is how to do it with the ToTable method:

    public class WorkoutConfiguration : EntityTypeConfiguration<Workout>
    {
        public WorkoutConfiguration()
        {
            base.ToTable("dbo", "ViewNameHere");
            base.HasMany(d => d.Sessions)
                .WithRequired(d=>d.Workout)
                .WillCascadeOnDelete(true);
        }
    }

Here is how to do it with a direct SQL statement:

var workouts = _dbContext.Database.SqlQuery<Workout>("select * from dbo.Workout")

The SqlQuery acts the same with the binding of value than with Entity Framework. Every fields is mapped with the corresponding methods. You can use AS statement to change the return value of some fields to be the same name of your methods.

var workouts = _dbContext.Database.SqlQuery<Workout>("select id as ID, name as nameFR from dbo.Workout")

At first, the last solution seems to be faster and fine but consider the first one if you are using table or view because it’s better. Better because you do not have to handle a string with a SQL query. If the database change, you won’t notice any problem until the query is executed. It’s more a work around than a good “enterprise” solution. But, the last one can be a good compromise if you need to use stored procedure. Nevertheless, always ask yourself in the long term what will be the repercussion of your choice.

Jquery Get Html Text Without Children Elements

Some time, you have a hmtl list inside an other html list or in fact any html element inside html and you want to have the text but not other html tag. How can you do?

You cannot use .html() because it will return the inner html tag. You cannot use .text() because it will return the text of the html element with the text inside inner html element.

For example:

<ul>
   <li id="step1">This is Step 1
        <ul>
             <li>This is inside Step 1</li>
        </ul>
   </li>
   <li id="step2">This is Step 2
   </li>
</ul>

If we use “step1.html()”. The output is:

This is Step 1
        <ul>
             <li>This is inside Step 1</li>
        </ul>

If we use “step1.text()”. The output is:

This is Step 1
        
             This is inside Step 1

But if you want to get only “This is Step 1” you will have to use several Jquery calls.

$("#step1").clone()    
           .children() 
           .remove()   
           .end()      
          .text();    

The clone instruction do a copy of the ul structure. It contains the whole structure with inner list. The children get everything under the step 1. This is the ul right under the step1 id. The remove take out all children. In our case, it removes only the ul under the step1 id. The end method tell Jquery to select back the initial selector which is the cloned element and get its text. Since we have removed every children, the text method will return only the text of the element.

Visual Studio 2013 remove Development Server AKA Cassini

I have been developed with Visual Studio since the 2003 version and most of the time directly by executing the code with the default server which is the one that Visual Studio trig when you press F5 (Build and Execute). More and more, I had to use IIS because that bigger website (enterprise application) require a lot of IIS features which is more convenient than IIS Express or Cassini (the Development Server integrated with Visual Studio).

Since Visual Studio 2013, Cassini is gone. The default choice is IIS Express. You can change it to IIS or any external host.

cassini

This is a feature that I’ll miss because small project was easy to execute with just Visual Studio. IIS Express is fine but the lack of visual help to configure make it good for people who is familiar with IIS setting. Cassini was removing this learning curl. Nevertheless, it makes developers know more about IIS and possibly create better application because developers will understand the whole picture.