How to extend (or add) conditionnal clause to Expression

If you need to concatenate two expressions (with OR or AND) this can be done easily with the help of the LinqKit library.

The idea is to Invoke both expression with the same model object.

Expression<Func<Customer, bool>> filter1 = customer => customer.FirstName == "Test";
Expression<Func<Customer, bool>> filter2 = customer => customer.LastName == "Test";
Expression<Func<Customer, bool>> filter3 = customer => filter1 .Invoke(customer) || filter2.Invoke(customer);

The last step is to use AsExpendable() and to you Expand to the last filter (filter3).

IEnumerable<Customer> customers = CustomerRepository.GetAll().AsExpandable().Where(filter3.Expand()).OrderBy(c => c.Id);

The AsExpendable() method simple create a wrapper around the IQueryable to create a ExpendableQuery. From here, the provider will change with the concrete provider ExpendableQueryProvider which inherit from IQueryProvider. This one will call the .Expand() of the expression.

If you go check the source code of the method ExpendableQuery we can see the wrapping.

public static IQueryable<T> AsExpandable<T>(this IQueryable<T> query)
{
  if (query is ExpandableQuery<T>)
	return query;
  else
	return (IQueryable<T>) new ExpandableQuery<T>(query);
}

The expand look like this :

    public static Expression<TDelegate> Expand<TDelegate>(this Expression<TDelegate> expr)
    {
      return (Expression<TDelegate>) new ExpressionExpander().Visit((Expression) expr);
    }

It call the Visit method of the ExpressionExpander from the Expression.

In short, what you have to remember it the use of LinqKit.dll make you life really easier when you manipulate dynamic expression.

So you have appended two Linq To Entity expression
http://stackoverflow.com/questions/1266742/append-to-an-expression-linq-c

Asp.Net MVC sections are on-the-fly partial defined by view

In Asp.Net MVC we use layout to display common structural Html structure. If you are from Asp.Net you can see this as the Master Page. The layout contains the header, the menu, the main content, the footer, etc. The content itself is not defined inside the layout but use a Body and Section. It can also use Partial to load something that will be static for every page.

The body is the View that will be loaded. If you have a list of customer to display and the controller return the index view, this one will be loaded inside the layout at the RenderBody() statement.

//Controller
public ViewResult Index()
{
	var customers = db.Customers.ToList();
	return View(customers);
}

The layout will load the View of the Index (Index.cshtml) since no specific view is explicitly defined in the return.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <header>
            <div id="title">
                <h1>My MVC Application</h1>
            </div>
            <div id="logindisplay">
                @Html.Partial("_LogOnPartial")
            </div>
            <nav>
                <ul id="menu">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                </ul>
            </nav>
        </header>
        <section id="main">
            @RenderBody()
        </section>
        <footer>
        </footer>
    </div>
</body>
</html>

The line 17 show the load of a partial view, that mean that the login view is the same for every page. The code of the partial “_LogOnPartial” could have been set directly into the _Layout.cshtml but divide the main structure from details, it’s a good idea to split. The line 27 show you where the view is loaded. This is done by calling the RenderBody() function.

What’s about section that change from each view but are always at the same location in the _Layout.cshtml? This can be done with the RenderSection(“YourSectionName”).

RenderSection load a section that is defined directly inside the View. Let say you have this view for the customer list :

@model IEnumerable<EFCodeFirst.Models.Customer>
<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            FirstName
        </th>
        <th>
            LastName
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}

</table>

If the Layout is changed for :

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <header>
            <div id="title">
                <h1>My MVC Application</h1>
            </div>
            <div id="logindisplay">
                @Html.Partial("_LogOnPartial")
            </div>
            <nav>
                <ul id="menu">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                </ul>
            </nav>
        </header>
        <section id="main">
            
            @RenderBody()
        </section>
        <footer>
            @if(IsSectionDefined("MySectionName"))
            {
                @RenderSection("MySectionName")
            }
            else
            {
                <p>This is the footer when the View doesn't define a MySectionName section</p>
            }
        </footer>
    </div>
</body>
</html>

This produce to the main page (not the list of customer) :

But if we go inside the customer list view and we define the section with the “section” keyword we will have this section loaded.

In Asp.Net you could have used multiple placeholder. With Asp.Net MVC you have a main place holder and you can have multiple section. If the section is not defined, the default is rendered.

Asp.Net MVC Template EditorFor priorities

When using EditorFor, the system search for the right html input to produce. This is done in a cascade fashion.

First, if the user has used the the EditorFor with the signature that contain the template name, this one will be used in first priority.

At first, this html helper may look useless because instead of relying on a parameter, why not use directly the correct helper. For Example, instead of doing @Html.EditorFor(x=>x.Name, “Textbox”) you should use @Html.TextBoxFor(x=>x.Name). Right? In fact, no. If you do so, you might see the textbox, but in reality, it doesn’t show the textbox because you wrote it but more because it hasn’t found the template in the EditorTemplates folder. If you want to use the named template EditorFor you need to ensure that this one is inside the EditorTemplates, otherwise, the Asp.Net MVC Framework will pass on the next priority.

The second priority for the choice of the correct template is ModelMetadata.TemplateHint. This attribute is set at the top of the property. The attribute is inside the namespace System.ComponentModel.DataAnnotations. This one take 1 parameter which is the name of the template (in the EditorTemplates or DisplayTemplates depending of the situation of if EditorFor or DisplayFor is used).

    [UIHint("MyTemplate")]
    public string FirstName { get; set; }

This is quite simple to use but from my perspective smell bad. Why would you want to setup a UI element inside the model. It breaks the separation of concern (SOC). The model shouldn’t care about how it will be represented. It would be better to specify the type of the data instead which is the third priority. Keep in mind that it’s okay to use UIHint in the scenario that you are using ViewModel and not directly the Model.

The third priority is another attribute called DataType.

This come with a list of predefined values. This is interested for basic type and you can define a template for each of those type inside EditorTemplates and DisplayTemplates folder. The separation of concern is respected because the model only specify the type of its property and not how they will be represented.

The fourth priority is the Model type. If you have defined a Template for one of your class, this one will be used automatically.

In a previous post, we had created a LocalizedString.cs which is displayed depending of the user culture differently. It requires to have its template. This is done by adding inside EditorTemplates a template that define the type.

@model EFCodeFirst.General.LocalizedString
@Html.LabelFor(s => s.Current)

This is also how UI library work to override basic template. For example, the Telerik or DevExpress suite will add their own template for String, Date, Int, Double to override the default input with their enhanced ones.

The last priority will be the base type.

So that’s it with template for EditorFor (or for DisplayFor) and priorities.

How to render a partial view for an Ajax call in Asp.Net MVC

If you have an Ajax call to do an action on the server side you may want to answer back with a message, refreshed values or a portion of the page to be updated. To do, you need to send back into a JSON object the view (or partial view). In this article, we will create a method that should be placed into every of your controller (maybe in a Base Controller).

The method is this one:

/// <summary>
/// Render a PartialView into a string that contain the Html to display to the browser.
/// </summary>
/// <param name="partialViewName">The name of the partial view to render</param>
/// <param name="model">The model to bind to the partial view</param>
/// <returns>The html rendered partial view</returns>
protected virtual string RenderPartialView(string partialViewName, object model)
{
	if (ControllerContext == null)  
		return string.Empty;

	if (model == null)
		throw new ArgumentNullException("model");

	if (string.IsNullOrEmpty(partialViewName))
		throw new ArgumentNullException("partialViewName");

	ModelState.Clear();//Remove possible model binding error.

	ViewData.Model = model;//Set the model to the partial view

	using (var sw = new StringWriter())
	{
		var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, partialViewName);
		var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
		viewResult.View.Render(viewContext, sw);
		return sw.GetStringBuilder().ToString();
	}
}

In short, it uses the View Engines of Mvc to get the result of the partial view (if found). From there, a view context is generated from the current call (with the current controller context). The model is passed with the ViewData that is required by the ViewContext constructor. Finally, we generated the html that is returned.

Here is an example of use.

return Json(new {
                    StatusCode= 1,
                    StatusMessage = "Customer has been created",
                    ResponseView = RenderPartialView("CustomerPanel", customer)
                });

This could have been otherwise, but you can see the logic behind using Json to have an anonymous object serialized back to the client. From there, you can use JQuery or a plain Javascript statement to display the ResponseView into an html element. The idea of rendering a partial view from a controller came from this other blog.

How to have localized string with MVC and Entity Framework

In some situation, you may have a string that will require to be localized and be displayed differently depending of the current culture.

This can be the case of a specific name or description. You may want to display the name of the product in French if the user is logged in French but to be able to display in English for other users.

You have a lot of different way to handle this situation. The one proposed here is simple, it respects the SOC (separation of concern), and doesn’t change the database drastically. By not changing the database drastically I mean that I do not have to have a table with association to multiple languages.

First, let create some model classes. To have relative useful example that is near of a real life example I will re-use the Customer and Avatar classes defined in previous blog post.

public class Customer:BaseEntity
{
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public Avatar Avatar { get; set; }
}

The Customer class contain 2 strings that won’t be localized and a property of type Avatar. This class contain 2 fields : name and description that require to be translated in multiple languages.

public class Avatar : BaseEntity
{
	public string Name { get; set; }
	public string Description { get; set; }
}

Right here, we see something wrong. The Name and Description properties are type of string which can only have one value. So, we need to have Name in 2 languages (or more).

public class Avatar : BaseEntity
{
	public string NameFrench { get; set; }
	public string DescriptionFrench { get; set; }

	public string NameEnglish { get; set; }
	public string DescriptionEnglish { get; set; }

        //And so on...
}

The problem with this solution is that it goes really out of proportion if you have let say 10 languages to support. It’s also a problem when it’s the time to bind to the view. Which one is the good to display depend of the user language and you couldn’t simply bind to one property.

This lead us to think that maybe the problem is that we are using a wrong approach. In fact, what we want to use is not a string but a LocalizedString. What we would like is to have the Avatar having only 2 properties, one for the Name and one for the Description.

public class Avatar : BaseEntity
{
	public LocalizedString Name { get; set; }
	public LocalizedString Description { get; set; }
}

The LocalizedString is a class that we will create and will handle all different languages that we have. Let say we want French and English. The class could look like the above with 2 properties. If we would need 10 languages, we would have 10 properties. I choose to have 1 property per language because I want to have in the database 1 column per language and not having a table with multiple languages. The reason is that I do not want the overhead of multiple join tables.

[ComplexType]
public class LocalizedString
{
	public string French { get; set; }
	public string English { get; set; }
	public override string ToString()
	{
		return English;
	}
	[NotMapped]
	public string Current {
		get
		{
			switch (Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToUpperInvariant())
			{
				case "FR":
					return French;
				case "EN":
					return English;
			}
			return ToString();
		}

		set {
			switch (Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToUpperInvariant())
			{
				case "FR":
					French = value;
					break;
				case "EN":
					English = value;
					break;
			}
			
		}
	}
}

Many stuff in the LocalizedString. First, the attribute ComplexType is added to the class. The reason is that I do not want to have a new class for each Model that will use the new type of string. In fact, what I want is to have Avatar having all properties automatically generated for me. From the database point of view, it’s the same thing. I do not want to have a table Customer with a 1-1 association to the table Avatar and from there having 10 relations for 10 different languages. I would like to have Customer having a relation to Avatar that contains all name and description. This is the reason of the Complex Type.

The second attribute is the NotMapped over the Current property. The Current property is there to display the string in the active language. I could have directly put the code of Current into the ToString() but I didn’t because I want to be able to bind to a property from the view.

From here, we are almost done. The last step is to create templates. We need one EditorTemplates and one DisplayTemplates. Both of them are here let know Asp.Net MVC how to display the new type LocalizedString.

Both DisplayTemplates and EditorTemplates require to be into the Shared folder. You need to create 1 file per folder with the name of your new type. In our case, it’s LocalizedString.

Both of them are very simple. This is of the DisplayTemplates.

@model EFCodeFirst.General.LocalizedString
<p>@Model.Current</p>

And this is for the EditorTemplates.

@model EFCodeFirst.General.LocalizedString
@Html.TextBoxFor(s => s.Current)

If we go into the view, the code use EditorFor for the Name and Description of the Avatar. This will trig in MVC to use the good template for the type LocalizedString.

<fieldset>
        <legend>Customer</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Avatar.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Avatar.Name)
            @Html.ValidationMessageFor(model => model.Avatar.Name)
        </div>
        
        <div class="editor-label">
            @Html.LabelFor(model => model.Avatar.Description)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Avatar.Description)
            @Html.ValidationMessageFor(model => model.Avatar.Description)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>

The generated html contain a valid name that link to the Current property of Avatar.

 <input id="Avatar_Name_Current" name="Avatar.Name.Current" type="text" value="" />

The controller will use the model binding to be able to set the Current value to the good language. This is automatically done because of the setter of Current that check the current language and set the value into the good property.

Once saved, the data is inserted into the avatar table.

And the data :

That’s it. The model is clean with 1 property, the view is clean because it uses template so it’s a one liner like normal string. The controller is clean because it doesn’t have any logical for the language. The database is clean because the information is stored what ever which class will use LocalizedString. Those additional rows are automatically create by Entity Framework and doesn’t require any.

To conclude, alternative solution like using a ViewModel could have been a solution but would add a lot of additional overhead like having to auto-map most of field, having to redo mapping for localized string every new model and the last one would been to have additional testing because you would have a ViewModel with condition which could have lead to possible error. I suggest you to use this approach which is simple, object oriented and work fine with Entity Framework.

Edit: Reflection

Instead of using a Switch case, you can use reflection to get the good property depending of the thread language. Here is the version with reflection.

[ComplexType]
    public class LocalizedString
    {
        public string French { get; set; }
        public string English { get; set; }

        [NotMapped]
        public string Current
        {
            get { return (string) LanguageProperty().GetValue(this,null); }
            set { LanguageProperty().SetValue(this, value,null); }
        }

        public override string ToString()
        {
            return Current;
        }

        private PropertyInfo LanguageProperty()
        {
            string currentLanguage = Thread.CurrentThread.CurrentUICulture.DisplayName;
            return GetType().GetProperty(currentLanguage);
        }
    }

How to do a custom secured file access with Http Handler and MVC framework

In diverse scenario you could require to give to your user files. You can let them access them directly by having a directory of files and give the complete path to the file but this can lead to different issue. First of all, this will bind the server folders/files structures to the url that you give the the user which might not be interesting. Second, it doesn’t give you any control over the files shared. Third, you may want to add algorithm for caching or give expiry to some files. All those customs code can’t be done by giving a direct access to files, the solution : using Http Handler.

HttpHandler was there in Asp.Net traditional and in Asp.Net MVC is even easier because not configuration is required for IIS.

First, you need to add a new route to let know the MVC routing system that the url sent is not going to go to a traditional controller but to go to your http handler.

public class ExternalFileRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
         
    }
}

Inside the Global.asax.cs you need to add your route. You need to put the new route BEFORE the default route because otherwise it won’t trig the route. The reason is that because the default route has default parameter that 2 parameters will automatically goes inside the Default route. But, if you set the FilesRoute before, the condition will match and this one will be executed.

public static void RegisterRoutes(RouteCollection routes)
{
	routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
	routes.Add("FilesRoute", new Route("files/{uniqueidentifier}", new ExternalFileRouteHandler()));
	routes.MapRoute(
		"Default", // Route name
		"{controller}/{action}/{id}", // URL with parameters
		new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
	);

}

At this moment, the code doesn’t compile because our IRouteHandler doesn’t return anything from the GetHttpHandler. This is why we need to create a class that will inherit of IHttpHandler.

public class ExternalFileHandler : IHttpHandler
{

	public void ProcessRequest(HttpContext context)
	{
		
	}

	public bool IsReusable { get; private set; }
}


public class ExternalFileRouteHandler : IRouteHandler
{
	public IHttpHandler GetHttpHandler(RequestContext requestContext)
	{
		return new ExternalFileHandler();
	}
}

At this point, we have nothing to do anymore from the perspective of the url. Every call will look like this:

http://yourwebsite.com/files/yourIdenfierHere.abc

Now, you need to get the file but first let’s get some information about the request like the request itself, the response where we will send back the image and some information about the server and what file is requested.

    public class ExternalFileHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {

            var response = context.Response;
            var request = context.Request;
            var server = context.Server;
            var uniqueFileIdentifier = RequestContext.RouteData.Values["uniqueidentifier"].ToString();
        }

        public bool IsReusable { get; private set; }
    }

If we debug we can see that if the request is sent with the good url that the http handler catch the request with the good value.

The next step is to check if the file really exist. In fact, we need to check if the unique identifier match a file. If it’s not the case, in a scenario of a people trying to get some body else file, it should return a message.

This can be done by simply writing in the Response a string.

public void ProcessRequest(HttpContext context)
{

	var response = context.Response;
	var request = context.Request;
	var server = context.Server;
	var uniqueFileIdentifier = request.RequestContext.RouteData.Values["uniqueidentifier"].ToString();

	FileInformation file = GetFromPersistenceStorage(uniqueFileIdentifier);
	if (file == null)
	{
		response.Write("File not found");
	}
}

As you can see, the file came from GetFromPersistenceStorage method. This method in reality would go into the database and search the file from the unique file identifier. This field in the database should be indexed and unique.

The next step is to check if the file is really on the server. It might be stored correctly into the database but not available on the server.

public void ProcessRequest(HttpContext context)
{

	var response = context.Response;
	var request = context.Request;
	var server = context.Server;
	var uniqueFileIdentifier = request.RequestContext.RouteData.Values["uniqueidentifier"].ToString();

	FileInformation file = GetFromPersistenceStorage(uniqueFileIdentifier);

	//Validate the file exist in the persistence storage
	if (file == null)
	{
		response.Write("File not found");
		return;
	}

	//Validate the the file exist on the server physically
	string completeFilePath = Path.Combine(file.PathOnServer, file.FileName);
	if(!File.Exists(completeFilePath))
	{
		response.Write("File not on the server");
		return;
	}

	//Prepare to send the file
	response.Clear();
	response.ContentType = file.FileType;
	response.TransmitFile(completeFilePath);
	response.End();

}

Finally, if the file is present, we will receive its content.

You can now secure the file. This can be done in many ways. First, I suppose that the database table that contain every files will have some kind of relation between the user and files. Let say that every files has the possibility to allow many users, that mean the you should have 3 tables : User, UsersFiles and Files. UsersFiles table contain the id of the User that can access the file and the id of the file.

So the FileInformation class that we have defined earlier would have a List that can access the file. A small modification will be required to get the current user from the session and to check if the file allow the user.

public void ProcessRequest(HttpContext context)
{

	var response = context.Response;
	var request = context.Request;
	var server = context.Server;
	var uniqueFileIdentifier = request.RequestContext.RouteData.Values["uniqueidentifier"].ToString();

	FileInformation file = GetFromPersistenceStorage(uniqueFileIdentifier);

	//Validate the file exist in the persistence storage
	if (file == null)
	{
		response.Write("File not found");
		return;
	}

	//Validate if the current logged user can access the file
	if (!file.UserIdAuthorized.Contains(SessionUserId))
	{
		response.Write("You are not authorized to see this file.");
		return;
	}

	//Validate the the file exist on the server physically
	string completeFilePath = Path.Combine(file.PathOnServer, file.FileName);
	if(!File.Exists(completeFilePath))
	{
		response.Write("File not on the server");
		return;
	}

	//Prepare to send the file
	response.Clear();
	response.ContentType = file.FileType;
	response.TransmitFile(completeFilePath);
	response.End();
}

public class FileInformation
{
	public string PathOnServer { get; set; }
	public string FileName { get; set; }
	public string FileType { get; set; }
	public List<int> UserIdAuthorized { get; set; }
}

And that’s it. You can from here add any other type of validation or expiry or caching. The method GetFromPersistenceStorage() could store into the cache the content of the file and if the file is requested again would get it from the cache instead of the server. You could also add expiry for file that may be deleted later by setting a timespan on the FileInformation and having a generated DateTime inside the table that contain the file information. A simple validation inside ProcessRequest will do the job.

You are now limitless about what to do with files on your server.

Entity Framework boost select performance with AsNoTracking() method

Entity Framework provide a method that remove the tracking ability of objects which will increase the performance. Of course, the drawback is that the DbContext won’t be able to know if an entity has changed.

Let’s start with a simple example. First the model which contain an ID (in BaseEntity) and a FirstName and LastName.

public class Customer:BaseEntity
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

We will add 5000 rows into the database to be able to get some time information about loading these 5000 customers into the view.

DECLARE @count INT
DECLARE @firstname varchar(100)
DECLARE @lastname varchar(100)

SET @count = 0

WHILE (@count < 5000)
BEGIN
	SET @firstname = 'FirstName' + cast(@count as varchar)
	SET @lastname = 'LastName' + cast(@count as varchar)
	
	INSERT INTO [Autoshop].[dbo].[Customers] 
				(
				 [FirstName]
				,[LastName]      
				)
	VALUES (
			   @firstname
			 , @lastname
		    )


   SET @count = (@count + 1)
END

Finally, we will time the time it takes to Entity Framework to generate the loading of the object into the view.

public ViewResult Index()
{
	var watch = new Stopwatch();
	watch.Start();
	var customers = db.Customers.Include(c => c.License).ToList();
	watch.Stop();
	ViewBag.TimeElapsed = watch.ElapsedMilliseconds;
	return View(customers);
}

The result from several test give me (on my machine) 237ms. Now, let’s do the same test with AsNoTracking().

public ViewResult Index()
{
	var watch = new Stopwatch();
	watch.Start();
	var customers = db.Customers.Include(c => c.License).AsNoTracking().ToList();
	watch.Stop();
	ViewBag.TimeElapsed = watch.ElapsedMilliseconds;
	return View(customers);
}

Now I have an average on 108ms. It’s about 2 times faster with 5000 rows of a simple Entity.

The Entity Framework’s keyword AsNoTracking() give a big boost of speed if you need to display data without having them tracked by Entity Framework. Most report, list or data that are display to the user as information should use AsNoTracking() since it removes overhead that is not used.

What does AsNoTracking() behind the scene is a good question. First, AsNoTracking came from the DbExtensions.cs file. It’s an extension method (static method) that will call the dbQuery.AsNoTracking() if the dbQuery is defined and if yes will call the AsNoTracking of this one which will simply return a new DbQuery with a parameter of IInternalQuery with the speciality of being AsNoTracking. This lead us to some implementation. The one that concern us is the InternalQuery that look like this:

public virtual IInternalQuery<TElement> AsNoTracking()
{
  return (IInternalQuery<TElement>) new InternalQuery<TElement>(this._internalContext, (ObjectQuery) DbHelpers.CreateNoTrackingQuery((ObjectQuery) this._objectQuery));
}

As you can see, it create a new InternalQuery with the second parameter who use DbHelpers.CreateNoTrackingQuery(…). The second parameter should be ObjectQuery, so what does the DbHelpers.CreateNoTrackingQuery to remove the overhead?

public static IQueryable CreateNoTrackingQuery(ObjectQuery query)
{
  IQueryable queryable = (IQueryable) query;
  ObjectQuery objectQuery = (ObjectQuery) queryable.Provider.CreateQuery(queryable.Expression);
  objectQuery.MergeOption = MergeOption.NoTracking;
  return (IQueryable) objectQuery;
}

Well it does the samething that if you has set at the ObjectContext property MergeOption to NoTracking. The only advantage is that it doesn’t affect every DbContext but only the query specified. But in Code First, you no longer have access to MergeOption since you are no longer using the ObjectContext but the DbContext. DbContext is a lightweight version of ObjectContext. This is why you should use now the extension AsNoTracking() instead of configuring the ObjectContext (that even if you use DbContext could be accessed).

For the curious, you could access the ObjectContext from the DbContext by casting the dbContext with IObjectContextAdapter.

ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;

ASP.Net MVC Model Binding

ASP.Net MVC Model Binding is one of the powerful “in-the-box” feature s that make the life of developer easy.

The primary goal is to let you get information from the http request without having to map manually all string to your objects. This can be the case of any http request type like POST after a form is submitted or a GET where information are requested. In fact, it will get query string with many values or values in JSON format and take the information to instantiate the object specified with the good values. Of course, this is possible only if some convention are followed.

Without Model Binding

Without model binding the code of loading an object from an html form would look like the following code:

public ActionResult Create()
{
  var product = new User() {
    BirthDay = DateTime.Parse(Request["birthdate"]),
    UserId= Int32.Parse(Request["userid"]),
    Name = Request["name"]
  };
}

As you can see, we directly go to the Http Request to get every parameters that correspond to the name of the input of the html form.

Binding simple value with Model Binding

With Asp.Net MVC you can let the model binding automatically parse every parameters to the parameter type specified in the signature of the method. For example, if you have a method with 2 parameters, one is an integer and one a string, if the method (which is called “action” in the MVC world) detect a request parameter name that fit with the action parameter name, it will get by reflection the time required and will automatically parse it. If the parameter is not provided, the null value is used or the default value if one is provided. The code above will now look like this:

public ActionResult Create(DateTime birthdate, int userid, string name)
{
  var product = new User() {
    BirthDay = birthdate,
    UserId= userid,
    Name = name
  };
}

This is not bad! In fact, the MVC model binding can do even better which is to create the user object itself. This is called Binding Complex Object.

Asp.Net MVC Binding Complex Object

Complex object will need to have scalar property that has the same name has the form inputs name and if the complex object contains more than only scalar object (like having sub object) will need to receive a JSON object. .Net will be able to transform this JSON object into C# object if every json variable has its property call the same way. With the example that we use since the beginning, this mean that we could have :

public ActionResult Create(User user)
{
   //User user here
}

This is very strong isn’t? The only think we require was to have the signature of the method with User and than, the view to have input names that is similar to the model’ properties name. What is even more powerful is that if you use the framework to generate the form, let say to bind the model User to the Razor view, the name used will be automatically the property name. The reason is that the Razor view can use Html extension which will reflect the name when bound to property.

@Html.TextBoxFor(model=>model.userId);

Will generate something like:

<input name="userId" value=""/>

When the user enter a value, let say for example 123, and submit the form, this will put in the http request, inside the http post data in the http header the value. The format look like this: “userId=123”. If you have many parameters, every will be seperated with the symbol an ampersand (&). Asp.net MVC will receive the information and will check the type of the parameter that is a User and check for all public property to find match. In our example, it will find the property userId. Since it’s an integer time, it will try to parse and convert the string.

Note that you need to have an empty constructor to be able to let the model binding being able to instantiate the object.

If you ask yourself “what’s about a wrong type value? how does it handle error?” Don’t worry, you can check if the model binding had error. You can see this in a previous post.

MVC Model Binding Example

Let image a really simple model object : Customer.

public class BaseEntity
{
    public int Id { get; set; }
}
public class Customer:BaseEntity
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

To be able to create a new customer, the view create need to bind input fields to the name of the property.

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Customer</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

These Html helpers will create the Html with the good name to be able to read them back from the controller once posted (the create is a POST Http method).

When the user hit “Save” the server will receive “FirstName=Patrick&LastName=Desjardins”.

We can save the new customer :

[HttpPost]
public ActionResult Create(Customer customer)
{
	if (ModelState.IsValid)
	{
		db.Customers.Add(customer);
		db.SaveChanges();
		return RedirectToAction("Index");  
	}

	ViewBag.Id = new SelectList(db.Licenses, "Id", "Name", customer.Id);
	return View(customer);
}

but we could have simply use:

[HttpPost]
public ActionResult Create(string firstName, string lastName)
{
	var customer = new Customer { FirstName = firstName, LastName = lastName };
	if (ModelState.IsValid)
	{
		db.Customers.Add(customer);
		db.SaveChanges();
		return RedirectToAction("Index");  
	}

	ViewBag.Id = new SelectList(db.Licenses, "Id", "Name", customer.Id);
	return View(customer);
}

or

[HttpPost]
public ActionResult Create(FormCollection inputs)
{
	var customer = new Customer { FirstName = inputs["FirstName"], LastName = inputs["LastName"]};
	if (ModelState.IsValid)
	{
		db.Customers.Add(customer);
		db.SaveChanges();
		return RedirectToAction("Index");  
	}

	ViewBag.Id = new SelectList(db.Licenses, "Id", "Name", customer.Id);
	return View(customer);
}

All three ways are correct, but the first one use the power of MVC to automatically bind input values to the object.

Complex object

Complex object are instanced classes that contain another object. Let say that we change the Customer class to have a 1 to 1 relation with the Avatar class.

public class Customer:BaseEntity
{
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public Avatar Avatar { get; set; }
}

public class Avatar : BaseEntity
{
	public string Name { get; set; }
}

How can we modify the View to have a possibility to receive the Avatar name and to save it when the form is submit to the controller?

The only thing that need to be done is to modify the view.

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Customer</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Avatar.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Avatar.Name)
            @Html.ValidationMessageFor(model => model.Avatar.Name)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

This will automatically load the Customer object in the controller. Let’s see the generated Html.

<form action="/Customer/Create" method="post">    <fieldset>
        <legend>Customer</legend>

        <div class="editor-label">
            <label for="FirstName">FirstName</label>
        </div>
        <div class="editor-field">
            <input class="text-box single-line" id="FirstName" name="FirstName" type="text" value="" />
            <span class="field-validation-valid" data-valmsg-for="FirstName" data-valmsg-replace="true"></span>
        </div>

        <div class="editor-label">
            <label for="LastName">LastName</label>
        </div>
        <div class="editor-field">
            <input class="text-box single-line" id="LastName" name="LastName" type="text" value="" />
            <span class="field-validation-valid" data-valmsg-for="LastName" data-valmsg-replace="true"></span>
        </div>

         <div class="editor-label">
            <label for="Avatar_Name">Name</label>
        </div>
        <div class="editor-field">
            <input class="text-box single-line" id="Avatar_Name" name="Avatar.Name" type="text" value="" />
            <span class="field-validation-valid" data-valmsg-for="Avatar.Name" data-valmsg-replace="true"></span>
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
</form>

As you can see, the name of the input is the property of Customer followed with a dot and the name of the property of the Avatar object. This is how the Model Binding can figure out that the value inside the text box belong to the Avatar object of Customer.

Understand basic navigation with Entity Framework Code First (4.3) with 1 to many relationship

Like configuring Entity Framework Code First for 1 to 1 or 1 to 0 relation, you need to go in your DbContext and to configure your entities.

For 1 to many, the syntax is quite the same but is changed to fill up the need of one to many. First, of all, unlike 0 to 1 or 1 to 1 the choice of the relation is simpler. The foreign key is always at the “1” side. That mean that if you have a Dealer that sale many car, every car will have a reference in the database the its seller.

Lets use the same objects that we did previously with 1 to 1 relation.

    public class Dealer:BaseEntity
    {
        public string Name { get; set; }
        public ICollection<Car> CarToSale { get; set; }     //Relationship: Many to one   (one side)
        public ICollection<Customer> Customers { get; set; }//Relationship: Many to many  (two side)
    }

and the car is like :

    public class Car:BaseEntity
    {
        public decimal Price { get; set; }
        public CarBrand Brand { get; set; }             //Relationship : One to one
        public Customer CurrentOwner { get; set; }      //Relationship : One to (zero or one)
    }

As you can see, I only put the CarToSale property which is the one that will link to the Car. This is a little bit the reverse of what I just said about having the Car table having the reference to the Dealer right? Well, in fact, the way we will configure the DbContext will still put the Foreign Key of the table the way we previously stated.

First, lets configure the dealer by stating that we have many cars associated to its.

public class DealerConfiguration : EntityTypeConfiguration<Dealer>
{
     public DealerConfiguration()
     {
         HasMany(x => x.CarToSale);   //One to many
     }
}

But, let say that we want to add in our model the property Dealer inside the car. For the car, the relation is 1 to 0..1.

So, it’s now possible to join to the car the dealer by setting the car to the dealer or to set the dealer to the car.

//Add to the database from the car
using (var db = new DatabaseContext())
{
	var dealer = new Dealer() {Name = "Patrick"};
	var car = new Car {Brand = new CarBrand(), Seller = dealer};
	db.Dealers.Add(dealer);
	db.Cars.Add(car);
	db.SaveChanges();
}

or

//Add to the database from the Dealer
using (var db = new DatabaseContext())
{
	var car = new Car { Brand = new CarBrand() };
	var dealer = new Dealer() {Name = "Melodie", CarToSale = new Collection<Car>{car}};
	db.Dealers.Add(dealer);
	db.Cars.Add(car);
	db.SaveChanges();
}

In both case, the table still has the foreign key inside the car and the dealer is not aware (from the table Dealer alone) about the car he has sell. From the Entity Framework Entities, both know. Both can read the value and both can save value as we just saw.

Required relation of one to many

For the moment, if we take a look at the database, the generated table contain a NULL at the dealer_id foreign key.

Let say that we want to have this field has a required field. We want “Not NULL” to be generated into the table column property.

public CarConfiguration()
{
	HasRequired(x => x.Seller);         //One to many is now a required field. It's really 1 to * and not 0 to *
}

Will produce:

Not bad! Now we have what we want, a required field for the Dealer (called seller from the car perspective). Could we have configure this from the Dealer’s entity instead of using the Car configuration? Of course!

public class DealerConfiguration : EntityTypeConfiguration<Dealer>
{
	public DealerConfiguration()
	{
		HasMany(x => x.CarToSale).WithRequired(e=>e.Seller);        //One to many (1 to *)
	}
}

So, now you are able to create 0..* and 1..* relationship with Entity Framework.

Getting 404 error after publishing with .Net4.5 from Visual Studio 2012

After the migration to the new framework you can have the scenario where it works on your computer but not when publishing. Even publishing to the local IIS on the computer may work but not on a remote one.

The 404 page is shown without any more information. To solve this issue, I created a MVC3 web application and published. It works! I did the same with an MVC4 and it was also working.

The difference between the two projects was that the web.config file has different assemblies version in the config file.

    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </compilation>

As you can see I have in the code above the version 1.0 for Helpers and Routing and this is problematic because the assembly I have in the project has been converted to the version 2. So two options : migrate everything with MVC4 and use the version 2 or use MVC3 with the version 1.

I hope that if you fall into this type of 404 error after migrating from Asp.Net 4 to 4.5 that you will think to check all references.