Tuesday, June 21, 2016

MVC model binders

Model binder maps HTML form elements to the model. It acts like a bridge between HTML UI and MVC model.

Take the below simple HTML form example:-

View:

<form id="frm1" method=post action=”/Customer/SubmitCustomer”>
                Customer code :- <input name="CCode" type="text" />
                Customer name :- <input name="CName" type="text" />
               <input type=submit/>
</form>

Now this form needs to fill the below “Customer” class model. If you see the HTML control name they are different from the class property name. For example HTML textbox control name is “CCode” and the class property name is “CustomerCode”. This mapping code is written in HTML binder classes.

Model Class:
public class Customer
{
       public string CustomerCode { get; set; }
       public string CustomerName { get; set; }
}

To create a model binder we need to implement “IModelBinder” interface and mapping code needs to be written in the “BindModel” method as shown in the below code.

Model Binder Class:
public class CustomerBinder : IModelBinder
{
        public object BindModel(ControllerContext controllerContext, ModelBindingContext
                                                                                                                        bindingContext)
         {
           
               HttpRequestBase request = controllerContext.HttpContext.Request;
               string strCustomerCode = request.Form.Get("CCode");
               string strCustomerName = request.Form.Get("CName");
               return new Customer
               {
                      CustomerCode = strCustomerCode,
                      CustomerName = strCustomerName
                };
          }
}


Now in the action result method we need to use the “ModelBinder” attribute which will attach the binder with the class model.

Controller Class:
public ActionResult SubmitCustomer([ModelBinder(typeof(CustomerBinder))]Customer obj)
{
         return View(“DisplayCustomer”);
}

MVC Custom HTML Helper

Standard Html Helpers are very useful but limited to common scenarios like rendering links and Html form elements etc.  But for a specific scenario, we might need to create a Custom Html Helper. ASP.NET MVC facilitates us to create our Custom Html Helper in following simple ways:
  1. Creating Extension Method on Html Helper Class
  2. Creating Static Methods
Creating Extension Method on Html Helper Class:

      If we want a custom Html Helper to be used just like standard Html helper, then available approach is to create an extension method on Html Helper class. Custom Html Helpers we create using Extension methods will be available to Html property of View.
Step-1:
For the purpose of implementation, we will create a custom Html Helper i.e. “CustomImage” using extension method approach as follows:

namespace CustomHelpers
{
    public static class ImageHelper
    {
          public static MvcHtmlString CustomImage(this HtmlHelper htmlHelper,
                                                                   string src, string alt, int width, int height)
          {       
                   var imageTag = new TagBuilder(“image”);
                   imageTag.MergeAttribute(“src”, src);
                   imageTag.MergeAttribute(“alt”, alt);
                   imageTag.MergeAttribute(“width”, width.ToString());
                   imageTag.MergeAttribute(“height”, height.ToString());                   
                   
              return MvcHtmlString.Create(imageTag.ToString(TagRenderMode.SelfClosing));           
            }
     }
}

Step-2:

In order to make this extension method available in all Views, we will add CustomHelper namespace to namespace section of View’s web.config as follows:


<add namespace=”CustomHelpers” />

Step-3:

Now we can use CustomImage helper in Views. We will pass image source, alternate text, image width and height to our View as follows:
@Html.CustomImage(“../Images/Ahmad.jpg”, “Mohammad Ahmad”, 150, 200)
Using the same approach, we can create any Custom Html Helper to simplify the task of writing lots of Html code repeatedly.


ASP.NET MVC Custom Html Helper using Static Methods:

Second available approach for creating Custom Html Helper is by using Static Methods. It’s also as simple as that of above mentioned Extension Method approach. We will create a static method for TextBox that renders an HTML TextBox as string.
Step-1:
namespace CustomHelpers
{
    public static class CustomTextBox
    {
          public static string TextBox(string name, string value)
          {       
                  return String.Format(“<input id='{0}’ name='{0}’ value='{1}’ type=”text”      />”, name, value);                   
          }
     }
}
Step-2:
Verify the namespace is added to Web.Config namespace section as we did before for Extension Method approach.
<add namespace=”CustomHelpers” />

Step-3:

Now, we can simply use the CustomTextBox in our View as follows:
@CustomTextBox.TextBox(“strStudentName”, “Mohammad Ahmad”)
We can use the Static Method approach to generate more HTML rich Custom Helper in ASP.NET MVC.

What are the benefits of using MVC?

There are two big benefits of MVC:-

  • Separation of concerns is achieved as we are moving the code behind to a separate class file. By moving the binding code to a separate class file we can reuse the code to a great extent.
  • Automated UI testing is possible because now the behind code (UI interaction code) has moved to a simple.NET class. This gives us opportunity to write unit tests and automate manual testing.

MVC Lifecycle


NOTE: There is nothing as such called as MVC life cycle. I think lot of people are obsessed with ASP.NET page life cycle and they think there is life cycle in MVC as well. To be specific the MVC request goes through various steps of execution and that’s what is termed as MVC application life cycle.



Any web application has two main execution steps first understanding the request and depending on the type of the request sending out appropriate response. MVC application life cycle is not different it has two main phases first creating the request object and second sending our response to the browser.


Creating the request object: - The request object creation has four major steps. Below is the detail
explanation of the same.

Step 1 Fill route: - MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the route table with routes collection. This filling of route table happens in the global.asax file.

Step 2 Fetch route:- Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object which has the details of which controller and action to invoke.

Step 3 Request context created: - The “RouteData” object is used to create the “RequestContext”
object.

Step 4 Controller instance created: - This request object is sent to “MvcHandler” instance to create the controller class instance. Once the controller class object is created it calls the “Execute” method of the controller class.

Creating Response object: - This phase has two steps executing the action and finally sending the
response as a result to the view.

Step 5 Execute Action: - The “ControllerActionInvoker” determines which action to executed and
executes the action.

Step 6 Result sent: - The action method executes and creates the type of result which can be a view result , file result , JSON result etc. So in all there are six broad steps which get executed in MVC application life cycle.

What is MVC

MVC is an architectural pattern which separates the representation and the user interaction. It’s divided in to three broader sections, “Model”, “View” and “Controller”. Below is how each one of them handles the task.


  • The “View” is responsible for look and feel.
  •  “Model” represents the real world object and provides data to the “View”.
  •  The “Controller” is responsible to take the end user request and load the appropriate “Model” and “View”.

Monday, June 20, 2016

Serialization and DeSerialization

The process of converting an object into stream of bytes in order to persist the data to memory, a database or a file.
It save the state of an object in order to be able to recreate when needed.

When an object is serialized into stream, it does not just the data, but also information about the object’s type. DeSerialization is reverse process of Serialization.

Extension Methods

Extension Methods are used to add new behaviors of existing type without altering.
An Extension method is a static method of a static class that can be invoked using instance of method syntax.
In extension method “this” keyword is used with the first parameter and the type of the first parameter will be the type that is extended by the extension method.
At compile time an extension method call is translated into an ordinary static method.

A simple Extension Method Example


1.    //defining extension method
2.    public static class MyExtensions
3.    {
4.     public static int WordCount(this String str)
5.     {
6.     return str.Split(new char[] { ' ', '.', ',' }).Length;
7.     }
8.    } 
9.     
10. class Program
11. {
12.  public static void Main()
13.  {
14.  string s = "Dot Net Tricks Extension Method Example";
15.  
16.  //calling extension method
17.  int i = s.WordCount();
18.  
19.  Console.WriteLine(i);
20.  }
21. }
22. //output:
23. 6

Using Keyword

The Using statement simplifies the code that we have to write to create and then finally clean up the object. The using statement obtains the resource specified, executes the statements and finally calls the Dispose method of the object to clean up the object.

Anonymous Type

An Anonymous type is a simple class generated by the compiler within IL to store a set of values. Var data type and new keyword is used to create an anonymous type.

Eg:

    Var emp = new {Name=”SampleUser”, Address=”Banglore”};


The anonymous type is very useful when we want to shape the result in our desired form.

Dynamic

The dynamic type uses System.Object indirectly but it does not require explicit type casting for any operation at runtime, because it identifies the types at runtime only. No need to initialize at the time of declaration.

Eg : 
     dynamic Str;
     Str= “I am a string”; //Works fine and compiles

     Str=2 // works fine and compiles

Object

The object class represents the System.Object type, which is the root type in the C# class hierarchy.
Generally we use this class when we cannot specify the type of object at compile time.
We can store anything in the object type variable, but for performing any operation then explicit type casting before it can be used.





Var

Var is used to declare the implicitly typed local variable. It finds the type of the variable at compile time.

A Var variable must be initializing at the time of declaration.

Valid var statements:
1.    var str = "1";
2.    var num = 0;
3.    string s = "string";
4.    var s2 = s;
5.    s2 = null;
6.    string s3 = null;
7.    var s4 = s3; 

At compile time, the above var statements are compiled to IL, like this:

1.     string str = "1"; 
2.    int num = 0; 
3.    string s2 = s; 
4.    string s4 = s3;

The compile-time type value of var variable cannot be null but the runtime value can be null.



1.     // invalid var statements 
2.    var v; //need to initialize
3.    var num = null; // can’t be null at compile time 

Once var variable is initialized its data type became fixed to the type of the initial data.



1.     // invalid var statements 
2.    var v2 = "str12";
3.     v2 = 3; // int value can’t be assign to implicitly type string variable v2