Infragistics NetAdvantage for WPF!

CONNECT WITH US

Featured Post

ASP.NET MVC View Model: Entity Framework & JSON Serialization

Many times I came across an ASP.NET MVC application, where Entity Framework Model (or Database Model) is being used as view model as well. No this post is not about to discuss whether entity model should be used as view model or not but in this post we will discuss one tip with respect to JSON Serialization which will help to improve performance in terms of CPU processing and bandwidth usage while using entity model as view model.

Before we get into implementation scenario, let me list down few points which leads to use entity model as view model. Once again please note that this post is not to discuss or justify whether entity model should be used as view model or not.

  • One argument I heard is that not in all cases but most of the time your view model would be almost ditto as entity model or database model and in such case why should we maintain another type for view model.
  • While we are maintaining separate type for view model, we need to convert entity model into view model each and every time view is rendered. Yes of course we can use AutoMapper or something similar mapper library for type mapping and conversion but still personally I believe why this extra overhead of type conversion?

So above is two major concern which leads to use entity model itself as a view model. So now we will try to understand whole scenario by formulating one example. Below is application/project setup.

  • MVC 3/4
  • Use of AJAX wherever possible for better user experience
  • Entity Framework with Entity Context or Entity Object (Default EDMX template with Visual Studio 2010, DbContext scenario is also covered later in this post)
  • Newtonsoft.Json for JSON Serialization

For this post demo we will use Northwind Database Category & Product table. Following is the diagram of Entity Designer with Category & Product table.

Entity Framework creates Navigation Properties for parent/child table. Now whenever we will try to serialize entity model it will also populate & serialize navigation properties. For better understanding consider the Category Listing page with paging which will refresh category list via AJAX call and server response is in JSON format. Look at the below two images.

As we can see that it is populating & serializing each navigation properties while in this specific scenario we are not going to use child record i.e. Products record. Along with child record it is also serializing details of Entity Keys for category have a look at below image.

In this specific case or most cases, we are not going to use child records or entity keys because most of the time our strategy would be on demand loading. And more importantly serialization of child records also leads to increases response size see marked box in above both images. Here there are two scope for improvements one Stop Serializing of Child Records to reduce response size. And eventually when we are omitting child records from serialization, it will reduce CPU processing as well. Before we look into actual implementation have a look at below image which shows response detail after optimization.

Voila we have reduced response size from 37.3 KB to 1.1 KB :) yes this is oblivious because in this case we are not serializing child records of entity framework model. In this demo post there are only 8 records in Category Table but consider real time application scenario where there can be few hundreds or more records. So below is the implementation for the same how we achieved this.

As earlier noted, we are using Newtonsoft.Json library for JSON serialization. To achieve above optimization in JSON serialization we have created custom JSON Converter by deriving Newtonsoft.Json.JsonConverter. Below is the actual implementation of custom JSON Converter.

public class EFNavigationPropertyConverter : Newtonsoft.Json.JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        bool isValid = false;
 
        if (objectType.FullName == "System.Data.EntityKey")
            isValid = true;
 
        if (objectType.IsGenericType &&
            objectType.GetGenericTypeDefinition().FullName
            .Contains("System.Data.Objects.DataClasses.EntityCollection"))
        {
            isValid = true;
        }
 
        return isValid;
    }
 
    public override object ReadJson(JsonReader reader, Type objectType, 
        object existingValue, JsonSerializer serializer)
    {
        return existingValue;
    }
 
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteNull();
    }
}

In above custom JSON converter we are checking if target object type is of EntityKey or EntityCollection then we are serializing NULL. That’s it and below is the code snippet of how to use this custom JSON converter with JSON.NET.

public ActionResult GetCategory()
{
    EF.EO.Northwind40Entities e = new EF.EO.Northwind40Entities();
 
    List<EF.EO.Category> categoryList = e.Categories.ToList();
 
    string strJSON = JsonConvert.SerializeObject(categoryList, 
        new EFNavigationPropertyConverter());
            
    return Content(strJSON, "application/json");
}

Entity Framework & DbContext Approach

We have discussed optimization with Entity Framework Entity Context or Entity Object approach as the application was built with Visual Studio 2010. But with Visual Studio 2012 default EDMX templates generate classes based on DbContext approach so here we will see how to optimize entity model serialization with DbContext.

Serializing DbContext Entity Model Class

When we try to serialize DbContext model class into JSON it will throw an exception as displayed in below image.

For clear separation of topic, we are not discussing here why this exception thrown with DbContext while it was working fine with Entity Context approach but for now it is preventing us to serialize DbContext model class into JSON. So what’s solution for it? Custom JSON Converter yes again custom JSON converter can be used to resolve this exception. So below is the code of Custom JSON Converter which will allow us to serialize DbContext model class into JSON.

public class EFNavigationPropertyConverter : Newtonsoft.Json.JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        bool isValid = false;
            
        if (objectType.IsGenericType && 
            objectType.GetGenericTypeDefinition().FullName.
            Contains("System.Collections.Generic.HashSet"))
        {
            isValid = true;
        }
 
        return isValid;
    }
 
    // other code removed for clarity
}

DbContext model populates navigation property with System.Collections.Generic.HashSet collection. So we are serializing NULL for it and below is the image which shows response with above custom JSON Converter.

In above image we can see that how custom JSON converter enable us to serialize DbContext model and omitting serialization of Navigation Property for child table.

Separate View Model & Mapper Library

Yes we can create separate view model and can get rid from all above custom JSON converter and etc. but what are the things we need to take care in such cases. Below is the list of prime points.

  • Whenever any new property is added in entity model we need to sync our view model with it.
  • Entity Model to View Model Conversion: if we are manually handling this conversion then we need to alter code at each place and if we are using mapper library than it might requires to change configuration of Object Mapping. This depends on newly added property sometime we even do not require to alter Object Mapping.
  • Processing Overhead: if we are creating separate type for View Model then first it will populate custom View Model and then after it will serialize it into JSON. While in case of Entity Model as a View Model, it will take care of omitting Navigation Property on the fly at a time of serialization so there is less processing overhead in Entity Model as a View Model.

Conclusion

As noted in starting, this post is not to discuss or justify whether Entity Model should be used as View Model or not but here we have tried to discuss small but useful tip which can lead performance improvements while JSON serializing in ASP.NET MVC application with Entity Framework. Hope this would be helpful.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

IIS: Create & Configure Self-Signed Certificate in IIS 7 or Later

In past one of my friends asked me how to configure self-signed SSL certificate in local IIS 7 or later. Steps for creating & configuring SSL in IIS 7 or later is pretty much straight forward. Before few days I received same comment on ASP.NET MVC Action Filter Series that how to setup SSL in local IIS websites. So here in this post, we are going to address it as part of IIS administration & configuration posts series. Yes yes this post is going to be very basic and straight forward few clicks configuration but you can stay tuned for more post in next week and later.

Steps here mentioned are based on IIS 8, but it would be almost same on IIS 7 as well. Ok so to get started open IIS and select Server Certificates feature.

It will display list of all installed Server Certificate on web server.

To create new self-signed certificate, click on Create Self-Signed Certificate... in action pane.

It will open dialog box where you can specify friendly name for server certificate and certificate store for newly created SSL certificate.

Specify name of the certificate, certificate store and click on OK. So we are half way done, we have created Self-Signed Certificate with IIS, but still half way to go. After creating certificate, we need to bind it with websites then only we will be able to browse local IIS website with HTTPS.

To bind websites with this certificate, select website in IIS and right click on it and select Edit Bindings...

It will open Site Bindings dialog where we can see binding information for selected websites. By default you will find one HTTP binding listed here.

Click on Add button to Add new binding for selected website.

Here, select binding type HTTPS and select newly created SSL certificate from drop down and click on OK. So we have added HTTPS binding to website which uses self-signed certificate in local IIS. To verify open and browse https://localhost.

Hope this quick post would be helpful and for more post on IIS checkout this index page.

Read More

ASP.NET MVC: HandleError action filter

ASP.NET MVC: HandleError

HandleError attribute is used to catch unhandled exception in controller action method. In default MVC template, HandleError attribute is already added to GlobalFilterCollection. In MVC 3, we can see it in Global.asax while in MVC 4 we can see it in App_Start/FilterConfig.cs. One thing to keep in mind is that HandleError will handle exception only if customErrors mode="On" is set in web.config.

Attribute Usage: Controller & method

Sample Code:

[HandleError]
public ActionResult Index()
{
    throw new Exception("HandleError Exception");
    return View();
}

As noted earlier, if we have not set customErrors mode="On" then HandleError will not catch this exception and it will show default YSOD(Yellow Screen Of Death).

YSOD(Yellow Screen Of Death) ASP.NETA

To enable exception catching, enable customErrors in web.config as below.

<system.web>
  <customErrors mode="On"></customErrors>
</system.web>

Now again run application, it should catch exception & it should display error.cshtml as displayed below.

With HandleError we can also specify ExceptionType for which to catch unhandled exception, View to display when exception is caught, and Master view.

Check out ASP.NET MVC: Action filter series post to read about other available  action filters.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET Web Optimization Framework (Bundling & Minification) Articles

Right from developer preview version of ASP.NET 4.5 & MVC 4 (vNext), I have covered ASP.NET Web Optimization Framework (a.k.a Bundling & Minification) in my MVC 4 article series. Later on I have posted several articles covering different aspects of ASP.NET Web Optimization Framework and how I implemented it. So I'm writing this post as an index post of articles covering ASP.NET Web Optimization Framework. So it would be easier to access all posts under one roof. In upcoming days I'm planning to add few more articles on this topic, as and when I will add new articles I will update this index post as well.

If you come across any good article on this topic then do comment here, I will include it in this list.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

[Picture] ASP.NET MVC: Flow between Model-View-Controller

Many times I'm asked this very basic question that how the ASP.NET MVC application flows between Model-View-Controller. So here we will try to understand it with Picture Post.

Flow between Model-View-Controller in ASP.NET MVC
  • User requests URL
  • Request is mapped to Controller('s Action Method)
  • Action Method process Model and select View(Result Type)
  • Processed Model is passed to View or Result Type
  • Generated response sent back to user

Hope this would be helpful. Stay tuned for more post.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET 4.5 Model Binding: Creating Custom Value Provider

With ASP.NET 4.5, ASP.NET introduced model binding for web forms as well. Model binding helps to simplify code focused data access logic within web forms. Check out this video by Scott Hanselman to know more on ASP.NET 4.5 Web Forms Model Binding.

Here in this post, we will see how we can create our own custom value provider (read my post on how I used value provider for encrypted query string in MVC application). We will also examine inbuilt class of ASP.NET 4.5 model binding framework which can be useful in creating custom value provider more easily with focused approach.

Before we look into actual interfaces and classes, let us examine few basics of model binding framework. All model binding framework and corresponding classes are resides in System.Web.ModelBinding namespace which is newly introduced with ASP.NET 4.5. For any value provider to work with model binder it requires two components one is implementation of value provider which reads data from request and forward it to model binder and other one is value provider source attribute which expose the actual value provider instance. Have a look at below code snippet here QueryStringAttribute is value provider source attribute which expose object of QueryStringValueProvider so model binder can use it to fetch data.

public IQueryable<Blog> SelectMethod([QueryString]int? id)

Creating Value Provider Source Attribute

To create custom value provider attribute we can derive Attribute class and implement IValueProviderSource interface as displayed in below code snippet.

public class CustomValueProviderAttribute : Attribute, IValueProviderSource
{
    public IValueProvider GetValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
    {
        return new CustomValueProvider(modelBindingExecutionContext);
    }
}

Here we can have access of ModelBindingExecutionContext and we can pass same to value provider if it is required. Through ModelBindingExecutionContext we can also have access of HttpContextBase and ModelStateDictionary.

Creating Value Provider

Same way we can create Custom Value Provider by implementing IValueProvider interface. Below code snippet shows pseudo code for the same.

public class CustomValueProvider : IValueProvider
{
    ModelBindingExecutionContext _modelBindingExecutionContext;
 
    public CustomValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
    {
        this._modelBindingExecutionContext = modelBindingExecutionContext;
    }
 
    public bool ContainsPrefix(string prefix)
    {
        // validate if requested key is exist or not
    }
 
    public ValueProviderResult GetValue(string key)
    {
        // return ValueProviderResult object we 
        // can use ModelBindingExecutionContext
        // to access request data
    }
}

Once we are ready we can use created value provider as

SelectMethod([CustomValueProvider]int? id, [CustomValueProvider]string name)

As noted earlier, there are few inbuilt classes in ASP.NET 4.5 model binding framework which give more focused control over custom business logic. Here we will also examine one of its which is SimpleValueProvider. Here we will examine how we can focus on core logic and leaving other responsibility on core framework.

public class CustomValueProvider : SimpleValueProvider
{
    public CustomValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
        : base(modelBindingExecutionContext)
    {
    }
 
    protected override object FetchValue(string key)
    {
        // here we can access this.ModelBindingExecutionContext
        // and can look into request data. Once we fetch requested
        // data we just need to return actual value for e.g.            
        return "dotnetExpertGuide.com";
        // NOTE: WE ARE NOT RETURNING ValueProviderResult INSTANCE
    }
}

Earlier with IValueProvider, we had to check if requested key exist or not and if it is then instantiating ValueProviderResult and return it. While with SimpleValueProvider we only need to return actual value of requested key or null incase if it does not exist rest will be taken care by SimpleValueProvider class. Another such framework class is NameValueCollectionValueProvider which act as a base class to create value provider from name value collection. Here I am not demonstrating it. I am leaving it for reader :).

SimpleValueProvider and ASP.NET MVC

Can’t we have/introduce SimpleValueProvider class for MVC in upcoming version?

ModelStateDictionary

Once model binding is done for parameter it is added to ModelStateDictionary dictionary along with its value. For e.g.

SelectMethod([CustomValueProvider]int? id, [CustomValueProvider]string name)

In above code once model binding is done for parameter id, it is added to ModelStateDictionary and it is accessible in rest of the parameter model binding i.e. parameter name here.

Hope this would be helpful. Stay tuned for more post.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More