Entity Framework Saving Junction Entity

I was having a hard time for few hours with a case of an entity that has a list of an other kind of entity. The scenario was that the first entity has a collection of a junction entity because this one is planned to have junction data. The entity is called Contest and its having a collection of AllowedMarket that is a class having a Market Class and a Contest Class. Market classes are defined by the system and does not have a direct reference to any contest. Here is these classes simplified.

public class Contest
{
    public Id{get;set;}
    public Collection<ContestMarket> AllowedMarkets { get; set; }
}

public class ContestMarket
{
	public Contest Contest { get; set; }
	public int ContestId { get; set; }

	private int marketTypeId;
	private MarketType market;

	public MarketType Market        
	{
		get { return market; }
		set
		{
			if (value != null)
			{
				this.marketTypeId = value.Id;
			}
			market = value;
		}
	}

	public int MarketId
	{
		get { return marketTypeId; }
		set
		{
			marketTypeId = value;
			Market = MarketType.GetFromId(value);
		}
	}
}
public class MarketType
{
    public Id{get;set;}
}

The configuration for these entities are like the following. We do not want to do any configuration on the MarketType since this entity can be used at a lot of places. So we have to configure the entity to the Contest point of view and the ContestMarket class. In fact, we only need to configure the junction entity, the ContestMarket.

public class ContestMarketConfiguration : AssociationConfiguration<ContestMarket>
{
	public ContestMarketConfiguration() : base(Constants.SchemaNames.Contest)
	{
		this.HasKey(c => new {MarketId = c.MarketId, ContestId = c.ContestId});
		this.HasRequired(d => d.Market).WithMany().HasForeignKey(d => d.MarketId).WillCascadeOnDelete(false);
		this.HasRequired(d => d.Contest).WithMany().HasForeignKey(d => d.ContestId).WillCascadeOnDelete(false);
	}
}
public abstract class AssociationConfiguration<T> : EntityTypeConfiguration<T> where T : class
{
    protected AssociationConfiguration(string schemaName)
    {
        ToTable(typeof(T).Name, schemaName);
    }
}

The important code is to define both junction entity’s properties (associate entity) and to link the id properties to the class properties. This is done with the HasRequired method and WithMany method of Entity Framework. This configuration is required because when we insert a new entity and at the same time a new association entity, the id will be to the default value which is 0 for integer. The problem is that if you do not specify id and that we do not setup the link between, since we are setting the id to be primary key, than it tries to insert these entities with the id to 0. This raise an exception after the second insert. What we want is to insert the contest and than insert the contest market items. By the time we save, the contest is not yet saved (when it is a first save) and therefore not possible to set the contest’s id correctly. This is why, we create the contest and assign it to the ContestMarket entity by the property.

The associate class keeps synchronized the integer id and the class property by having in both properties’ setter code to set one of each other. Finally, when you save the entity you need to create the entity and add to the collection the association entity. After, use the normal SaveChanges. In my particular case, the entity Market is always existing so if I try to add the new junction entity, this one will be set to EntityState.Added state. This is why the repository have some state manipulation required.

public override void Save(Contest model)
{
	base.Save(model);
   
	foreach (var allowedMarket in model.AllowedMarkets)
	{
		UnitOfWork.Entry(allowedMarket).State = EntityState.Added;
		UnitOfWork.Entry(allowedMarket.Market).State = EntityState.Unchanged;
		UnitOfWork.Entry(allowedMarket.Contest).State = UnitOfWork.Entry(model).State;
	}
}

The first manipulation is to set the state depending if this one is a new or a modification. Then, we hardcode the Market to unchanged. This is because we know for sure this one exist and do not want to add any new of this entity. Finally, the Contest is set with the same state of the contest itself since we know that they are the same entity as the one saved. The code in this article is not full because in the case of modification, we would need to delete all the collection first. But, this is another stories.

Creating Integration Tests with Embedded Files

Unit Testing changes a lot by the enterprise your are working on and also the team. Often, Unit Testing and Integration Testing are done with the Unit Test framework and this is fine. Something that is more rare is to define the limit. Defining a different between the two are important for several reasons. First of all, unit tests target a single operation; a unit. Unit tests are fast, does not have dependencies and when they fail show without a doubt where the error is located. A second reason is that integration test may require some dependencies, even need to do query to database. A third reason is that we want to flag longer test by using a test’s category or by simply having them in a different assembly. Mostly because we do not want to run integration test on every commit but only once a day. The reason : speed. If you have thousand of tests, it should be executed in less than few seconds. If you have files to open, database connections, etc, this can lead to several minutes and increase by a lot your building time.

This article concerns integration test. The case is that we want to do an integration test on a file. This file contains a lot of Html elements and instead of creating a unit test for a single element, we want to execute the integration code that handle a complete file. We could have used a string with a lot of Html markup but editing the Html becode harder. It is also less clear and crowd the unit test file with huge string.

One option is to use embedded resource for file and inside the test to use the assembly method GetManifestResourceStream. This is the option that we are going to talk in this article. The first step is to create a folder where all your files for test will be used. I suggest that you put this folder inside the test assembly. This is not mandatory but is less confusing. The test codes is near of the test contents. After, I suggest that you have one folder per test class. This also help for maintenance to be able to figure out fast where is the file. Finally, my suggestion is to have another folder for each test. The reason is the same: simplify to search of resource. You can than create a file to use. In my scenario, an input file and an output file. The input file is what the test use to test the method to be tested. The output is the file to use to compare with the method result. It is the expected result.

The next step is to use that embedded file. Since we are using the same assembly that the unit test is created, we can call the Assembly.GetCallingAssembly method.

var assembly = Assembly.GetCallingAssembly();
var resourceName = assembly.GetName().Name + ".YourTestContentFolder.SubClassFolder.SubMethodFolder.Input.html";

The resource file is embedded which has created the resource identifier by using the assembly name with all the folder structure up to the file name. The separator used between folder are the dot. Once you have the resourceName, you need to use the GetManifestResourceStream method with a StreamReader.

using (var stream = new StreamReader(assembly.GetManifestResourceStream(resourceName), Encoding.UTF8))
{
    //...
}

This solution is great but keep in mind that nothing is better than real unit test. A lot of thing can be wrong by doing to much processing in a test. This increase the possibility of having error that does not have any relationship with the real purpose of the test.

Asp.Net Mvc EditorFor vs PartialView

I have entitle this article with EditorFor vs PartialView because it is the scenario where the difference matter the most. DisplayFor produces the same Html output but does not affect that much the end result because the data is not sent back to the server. This lead us to the main question about what is the difference between using Template, like EditorFor, instead of Partial View. In both case, we want to achieve the same thing, to display an input control that will allow to send the user input to the server. To help the understanding of the difference between the two, let’s create two classes that are going to be used. Both of them will contains a string to be inputted by a text box. One class will have a property to the second class. This way, we have a child object. This is where the difference make an impact.

public class Child
{
    public string ChildName { get; set; }
}
public class Parent
{
    public string ParentName { get; set; }
    public Child SingleChild { get; set; }
}

This is as simple as it can be. Next, we need to create a controller that will call the view with the Parent model. We choose the Parent class because this one contains the inner class.

public ActionResult Index()
{
    var parentModel = new Parent();
    parentModel.ParentName = "My Parent Name";
    parentModel.SingleChild = new Child {ChildName = "The Child Name"};
    return View(parentModel);
}

The last step is to create a view that is using both rendering technical choice. The first one is with templates (EditorFor) and the second is with Partial Views.

@model TemplateVsPartialView.Models.Parent
<div class="row">
    <div class="col-sm-6">
        <h2>Editor For</h2>
        @Html.EditorFor(d=>d)
    </div>
    <div class="col-sm-6">
        <h2>Partial View</h2>
        @Html.Partial("_parentPartialView", Model)
    </div>
</div>

The output looks like the same but the source code generated is different. Here is a screenshot of the Html output.
EditorTemplateVsPartialView

Here is the Html markup. We can see a difference in the name and the id of the input for the child name. The reason is that the partial view does not know about where the model is used. This is a major drawback when you need to send back everything to the server because the html query string name does not contain the property name of the child class. This mean that is cannot bind the information to the inner class.

<div class="row">
    <div class="col-sm-6">
        <h2>Editor For</h2>
        <h3>Parent Name</h3>
            <input id="ParentName" name="ParentName" type="text" value="My Parent Name" />
            <h3>Child Editor</h3>
                <h3>Child Name</h3>
                <input id="SingleChild_ChildName" name="SingleChild.ChildName" type="text" value="The Child Name" />
    </div>
    <div class="col-sm-6">
        <h2>Partial View</h2>
        <h3>Parent Name</h3>
            <input id="ParentName" name="ParentName" type="text" value="My Parent Name" />
            <h3>Child Editor</h3>
                <h3>Child Name</h3>
                <input id="ChildName" name="ChildName" type="text" value="The Child Name" />
    </div>
</div>

Here is the code for the editor for and for the partials.

//parent.cshtml
@model TemplateVsPartialView.Models.Parent
<h3>Parent Name</h3>
@Html.TextBoxFor(d=>d.ParentName)
<h3>Child Editor</h3>
@Html.EditorFor(d=>d.SingleChild)


//child.cshtml
@model TemplateVsPartialView.Models.Child
<h3>Child Name</h3>
@Html.TextBoxFor(d => d.ChildName)

//parent partial view (_parentPartialView.cshtml)
@model TemplateVsPartialView.Models.Parent
<h3>Parent Name</h3>
@Html.TextBoxFor(d => d.ParentName)
<h3>Child Editor</h3>
@Html.Partial("_childPartialView", Model.SingleChild)

//child partial view (_childPartialView.cshtml)
@model TemplateVsPartialView.Models.Child
<h3>Child Name</h3>
@Html.TextBoxFor(d => d.ChildName)

As you can notice, the editor for and the partial view is the same code. The only change concern the first call from the view. The view uses for one the EditorFor Html helper while the second use the Partial View Html helper. Another difference concerns where the templates are located and where the template view are located. The templates can be closer to the view inside EditorTemplates/DisplayTemplates folder or can be shared across the application with Shared folder. This is also true for partial view where they can be in a Shared folder at the root of the Views folder or directly under the controller folder with all views of the controller.

You can find the source code in GitHub or download the Zip.

Unit Testing Nancy Routing, Controller and IoC

Maybe the title should be more integrating test with Nancy than unit testing because this is far more integrated than unit. However, the goal is to test and a NuGet package allow you to test easily test Nancy application. This NuGet package is called Nancy.Testing and can be installed with the following command.

Install-Package Nancy.Testing 

This allow to create a Browser (from the CsQuery.dll that is a dependency of the Nancy.Testing.dll) object that will act like a client to the Nancy server. From there, you create a unit test like usual and use the browser object to request to a specific url. Here is an example that request the base page (no page just the localhost). We expect to have a default webpage that return a 202 status.

[TestClass]
public class IndexModuleTest
{
    private readonly Browser browser;
    public IndexModuleTest()
    {
        var bootstrapper = new NancySelfHostedWithSignalR.Bootstrapper();
        browser = new Browser(bootstrapper);
    }

   [TestMethod]
   public void GivenDefaultUrl_WhenMarkdownListReturnData_ThenIndexPageLoad()
   {
       var result = browser.Get("/", with =>
       {
           with.HttpRequest();
       });

       Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
    }
}

One problem that you may stumble into is that the IoC of of BootStrapper is using some of the class that you may want to mock. This will require you to create a new Bootstrap and to override your default configuration. Instead of having multiple BootStrap class, we can have one for test where we can push all the mock required for each test. Imagine that you have a BootStrapper that define a lot of Interface to concrete type inside the ConfigureRequestContainer method. What you have to do it to override at your turn of your own Bootstrapper and override too the ConfigureRequestContainer. However, you call the base method before your testing ones. This way, it will override the one you redefine with your mock when testing.

private class TestingBootstrapper : YourDefaultBootstrapper
{
    public List<Tuple<Type, object>> Types { get; set; }

    public TestingBootstrapper(List<Tuple<Type, object>> types)
    {
        this.Types = types;
    }

    protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
    {
        base.ConfigureRequestContainer(container, context);
        //Override here for test
        foreach (var typeInterfaceAndImplementation in this.Types)
        {
            container.Register(typeInterfaceAndImplementation.Item1, typeInterfaceAndImplementation.Item2);
        }
    }
}
// Later inside one of your test:
var types = new List<Tuple<Type, object>>();
var bootstrapper = new TestingBootstrapper(types);
            
var mock1 = new Mock<IFile1>();
mock1.Setup(...);
types.Add(new Tuple<Type, object>(typeof(IFile1),mock1.Object));
var browser = new Browser(bootstrapper);

The browser uses your testing bootstrapper and in the same time redefine only the interface that you want for your test. This is interesting if you want to reuse a big part of your existing bootstrapper. Otherwise, you can just use the lambda action method to define your classes.

 var browser = new Browser((c) => c.Module<IndexModule>().Dependency<IFile1>(mock1.Object))

Nancy Configuration of IoC for Module

Nancy module constructor is by default without parameters. However, soon you will need to have your route match to some of your logic which should be under some business logic classes. In fact, the next step after routing should be to call your controllers or or service layer classes. To be able to inject your service layer class, you need to inject this class. Nancy Bootstrap class come to the rescue. You only need to override a single method to be in business. Nancy comes with a default small IoC. The method to override is named ConfigureRequestContainer.

public class YouBootstrapper : DefaultNancyBootstrapper
{
    protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
    {
        base.ConfigureRequestContainer(container, context);
        container.Register<IServiceLayer, YourServiceLayer>();
    }
}

After this modification, you only need to remove the parameterless constructor and have the one with the interface defined in the request container of the BootStrap class.

public class IndexModule : NancyModule
{
    public IndexModule(IServiceLayer serviceLayer,
}

Concerning the boot strap class, Nancy will load automatically your class by scanning the assembly where you startup class reside.

Owin platform with Nancy and Signalr

Here is the context. Imagine that you have to host a web content in someone computer that does not have IIS. How can you do it? It exists multiple solutions from Node.js server to having a JavaScript only solution. However, if you have a lot of code already done in .Net and want to reuse that code, something else exist. In fact, what the solution exist since few years. Microsoft has the project Katana with the goal of removing hard dependencies on different web modules like we have with Asp, Asp.Net Web Form and Asp.Net MVC. An open standard called Owin emerged from that project. Owin means Open Web Interface for .Net. It goals is to create new components that can be easily developed and consumed but also create applications that could be more easily ported between hosts and potentially entire platforms/operating systems.

In this article, I will show you how to start with Owin to host inside a console a web server. We will use Nancy to be able to render Asp.Net MVC and use Signalr to have some real time update. The project will be very simple so you will not see the full potential but you will be able to do few things like displaying a razor page (.cshtml), use static resource like images for some images in a specific folder and handles all others with your code, get a real time notification when a client connect to the system and be able to notify from the server to the client content with Signalr.

Nancyvisualstudiotemplate

First of all, we need to create a solution with a project. One way to do it is to start with Nancy template. You can search for Nancy in Visual Studio and choose a template. Let’s choose “Nancy Empty Application with ASP.NET hosting and Razor”. This will come with some references that we will change but it will give us some of the stuff to work with. First thing to do is to remove the Nancy.Hosting.Aspnet. The reason is that Nancy come with its own self hosting environment, based on Owin but we want to use the generic one. The reason is that we will not only use Nancy but Signalr. So we will use the Owin bootstrap and attach in the pipeline Nancy and Signalr. We can uninstall with the Package Manager Console:

Uninstall-Package Nancy.Hosting.Aspnet

Then, let’s install some packages. First, the Owin host (generic one). Second, SignalR core library and the JS one that allow the view to connect to the backend. Third, we need to use the Razor View engin of Nancy. This differ a little bit from Asp.Net MVC Razor. We cannot use the Asp one because it has dependencies on the Asp stack. Forth, is the Cors package that allow us to do cross-domain call. This is required by SignalR.

Install-Package Microsoft.Owin.Host.SystemWeb
Install-Package Microsoft.Owin.Hosting
Install-Package Microsoft.AspNet.SignalR.Owin
Install-Package Microsoft.AspNet.SignalR.JS
Install-Package Nancy.Viewengines.Razor
Install-Package Microsoft.Owin.Cors

Before continuing, be sure that you are targeting the latest .Net Framework. I have set mine to 4.5.2, 4.5.1 works too but 4.0 fail on some packages. Also, verify that you have the latest package for all Owin libraries. You can get a list of the package that are not updated with that commands:

Get-Package -updates 

The next step is to create the console that will host the process. Keep in mind that you could create a Windows Service too or any other kind of container to host your Owin solution.

class Program
{
	static void Main(string[] args)
	{
		var url = "http://+:8080";

		using (WebApp.Start<Startup>(url))
		{
			Console.WriteLine("Running on {0}", url);
			Console.WriteLine("Press enter to exit");
			Console.ReadLine();
		}
	}
}

This code start the web application host at the post 8080. You can use what ever port you want. The important information is the line with WebApp.Start. It takes a type of startup project. This is the core of the configuration about what we are going to host. In our case, we will host for Nancy and Signalr. Here is the configuration class.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app
        .Map("/signalr", map =>
        {

            map.UseCors(CorsOptions.AllowAll);
            var hubConfiguration = new HubConfiguration();
            map.RunSignalR(hubConfiguration);
        })
        .UseNancy();
    }
}

Two important configuration. The first one is Signalr that allow to use Cors (cross origin references) and the second is Nancy. It is important to notice that SignalR has been defined first. This is because in the request pipeline, we want Signalr to be the first to verify if it can handle the request, and then Nancy. The reason is that in the application I am doing, I want to catch all URL and do something with them. I do not want to catch specify SignalR calls.

Nancy requires to have a bootstrapper class.

public class Bootstrapper : DefaultNancyBootstrapper
{
    protected override void ConfigureConventions(NancyConventions nancyConventions)
    {
        base.ConfigureConventions(nancyConventions);
        nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("Scripts"));
    }
}

If you define a class that inherit from DefaultNancyBootstrapper, the system will use it. Here we can define a directory that Nancy will not handle request from. This is how to say to Nancy to do not take care of the JavaScript requests. By default, Nancy does not handle static files from the Content folder. However, for the Scripts folder, you must add this one with the StaticContentsConventions.

It is important to note that Nancy will catch all extensions. See the web.config file. You should see that by default, the HttpHandler configured use all path. If you open the web.config and this is not the case, you should add these two configurations. This will allow you to handle every call. For example,

http://localhost:8080/your/path/to/action
or
http://localhost:8080/your/path/to/action/test.png
but not
http://localhost:8080/content/image.png
or 
http://localhost:8080/scripts/jquery.js
<system.web>
    <httpHandlers>
      <add verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*" />
    </httpHandlers>
</system.web>
<system.webServer>
    <handlers>
      <add verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*" />
    </handlers>
</system.webServer>

The next thing to do is to define Nancy’s modules. This is like defining Asp.Net Mvc routing in the same time of defining your Asp.Net Controller.

public class IndexModule : NancyModule
{
    public IndexModule()
    {

        Get[@"/{uri*}"] = parameters =>
        {
            var regex = new Regex(@"\.(png|gif|jpg|jpeg)$");
            if (regex.IsMatch(parameters.uri))
            {
                return View["image"];
            }
            else
            {
                return View["content"];
            }
        };
        Get["/"] = parameters =>
        {
            return View["index"];
        };
    }
}

Every routes has a priorities depending of the routing syntax used and order. In that case, I want to handle every images (which are not in the content folder, remember!) and also all other routes that will be for content. I also define a second route for the main web page. This is a case of using Owin/Nancy to handle images. Let’s say that you have some logic for dynamic image or for image that are not on the server but somewhere else. This way you can have your Http Image Handler withing your code.

The next step is to enable Signalr. This is to add the capability to the server and webpage to communicate. The code will not do a lot of thing here but in fact can update the content in real time. First, in the backend you need to create a class that inherit from Hub.

public class ExchangeHub : Hub
{
    public void Init(string urlHere)
    {
        Console.WriteLine(urlHere);
    }

    public void SendDataToClients(string data)
    {
        Clients.All.UpdateContent(data);
    }
}

This will generate by default some JavaScript code to all the client to call the server. The Init function all to send from the client side a string to the server. What we will do is when the page finish to load to call the server. The server can after that use the SendDataToClients to send some data back the the client.

The JavaScript file that need to be inserted inside your cshtml file should look this way:

<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/jquery.signalR-2.1.2.js"></script>
<script src="http://localhost:8080/signalr/hubs"></script>
<script type="text/javascript">
    $(document).ready(function () {
        //Set the hubs URL for the connection
        $.connection.hub.url = "http://localhost:8080/signalr";

        // Declare a proxy to reference the hub.
        var chat = $.connection.exchangeHub;

        // Create a function that the hub can call to broadcast messages.
        chat.client.UpdateContent = function (data) {
            alert(data);
        };

        // Start the connection.
        $.connection.hub.start().done(function () {

            // Call the Send method on the hub.
            chat.server.init("url here");


        });
    });
</script>

First, we need to define in that specific order three scripts. The first one is JQuery, the second one is Signalr and the third one is the Signalr hub that has been automatically generated.
After, we connect to the server hub and we get the exchangehub that come from the proxy file generated and we setup what happen when the server call the update content. In this example, we just alert the message. Finally, we send a request to the server when the page is finally loaded and that the hub is ready (connection is established between client and server). You can find the source code into this Git repository.