Tuesday, 18 February 2014

Detailed ASP.NET MVC Pipeline

ASP.NET MVC is an open source framework built on the top of Microsoft .NET Framework to develop web application that enables a clean separation of code. ASP.NET MVC framework is the most customizable and extensible platform shipped by Microsoft. In this article, you will learn the detail pipeline of ASP.NET MVC.

Routing

Routing is the first step in ASP.NET MVC pipeline. typically, it is a pattern matching system that matches the incoming request to the registered URL patterns in the Route Table.
The UrlRoutingModule(System.Web.Routing.UrlRoutingModule) is a class which matches an incoming HTTP request to a registered route pattern in the RouteTable(System.Web.Routing.RouteTable).
When ASP.NET MVC application starts at first time, it registers one or more patterns to the RouteTable to tell the routing system what to do with any requests that match these patterns. An application has only one RouteTable and this is setup in the Application_Start event of Global.asax of the application.

  1. public class RouteConfig

  2. {

  3. public static void RegisterRoutes(RouteCollection routes)

  4. {

  5. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  6.  

  7. routes.MapRoute(

  8. name: "Default",

  9. url: "{controller}/{action}/{id}",

  10. defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

  11. );

  12. }

  13. }



  1. protected void Application_Start()

  2. {

  3. //Other code is removed for clarity

  4. RouteConfig.RegisterRoutes(RouteTable.Routes);

  5. }


When the UrlRoutingModule finds a matching route within RouteCollection (RouteTable.Routes), it retrieves the IRouteHandler(System.Web.Mvc.IRouteHandler) instance(default is System.Web.MvcRouteHandler) for that route. From the route handler, the module gets an IHttpHandler(System.Web.IHttpHandler) instance(default is System.Web.MvcHandler).

  1. public interface IRouteHandler

  2. {

  3. IHttpHandler GetHttpHandler(RequestContext requestContext);

  4. }


Detailed ASP.NET MVC Pipeline

Controller Initialization

The MvcHandler initiates the real processing inside ASP.NET MVC pipeline by using ProcessRequest method. This method uses the IControllerFactory instance (default is System.Web.Mvc.DefaultControllerFactory) to create corresponding controller.

  1. protected internal virtual void ProcessRequest(HttpContextBase httpContext)

  2. {

  3. SecurityUtil.ProcessInApplicationTrust(delegate {

  4. IController controller;

  5. IControllerFactory factory;

  6. this.ProcessRequestInit(httpContext, out controller, out factory);

  7. try

  8. {

  9. controller.Execute(this.RequestContext);

  10. }

  11. finally

  12. {

  13. factory.ReleaseController(controller);

  14. }

  15. });

  16. }


Action Execution

  1. When the controller is initialized, the controller calls its own InvokeAction() method by passing the details of the chosen action method. This is handled by the IActionInvoker.

    1. public virtual bool InvokeAction(ControllerContext controllerContext, string actionName)


  2. After chosen of appropriate action method, model binders(default is System.Web.Mvc.DefaultModelBinder) retrieves the data from incoming HTTP request and do the data type conversion, data validation such as required or date format etc. and also take care of input values mapping to that action method parameters.
  3. Authentication Filter was introduced with ASP.NET MVC5 that run prior to authorization filter. It is used to authenticate a user. Authentication filter process user credentials in the request and provide a corresponding principal. Prior to ASP.NET MVC5, you use authorization filter for authentication and authorization to a user.
    By default, Authenticate attribute is used to perform Authentication. You can easily create your own custom authentication filter by implementing IAuthenticationFilter.
  4. Authorization filter allow you to perform authorization process for an authenticated user. For example, Role based authorization for users to access resources.
    By default, Authorize attribute is used to perform authorization. You can also make your own custom authorization filter by implementing IAuthorizationFilter.
  5. Action filters are executed before(OnActionExecuting) and after(OnActionExecuted) an action is executed. IActionFilter interface provides you two methods OnActionExecuting and OnActionExecuted methods which will be executed before and after an action gets executed respectively. You can also make your own custom ActionFilters filter by implementing IActionFilter. For more about filters refer this article Understanding ASP.NET MVC Filters and Attributes
  6. When action is executed, it process the user inputs with the help of model (Business Model or Data Model) and prepare Action Result.

Result Execution

  1. Result filters are executed before(OnResultnExecuting) and after(OnResultExecuted) the ActionResult is executed. IResultFilter interface provides you two methods OnResultExecuting and OnResultExecuted methods which will be executed before and after an ActionResult gets executed respectively. You can also make your own custom ResultFilters filter by implementing IResultFilter.
  2. Action Result is prepared by performing operations on user inputs with the help of BAL or DAL. The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and EmptyResult.
    Various Result type provided by the ASP.NET MVC can be categorized into two category- ViewResult type and NonViewResult type. The Result type which renders and returns an HTML page to the browser, falls into ViewResult category and other result type which returns only data either in text format, binary format or a JSON format, falls into NonViewResult category.

View Initialization and Rendering

  1. ViewResult type i.e. view and partial view are represented by IView(System.Web.Mvc.IView) interface and rendered by the appropriate View Engine.

    1. public interface IView

    2. {

    3. void Render(ViewContext viewContext, TextWriter writer);

    4. }


  2. This process is handled by IViewEngine(System.Web.Mvc.IViewEngine) interface of the view engine. By default ASP.NET MVC provides WebForm and Razor view engines. You can also create your custom engine by using IViewEngine interface and can registered your custom view engine in to your Asp.Net MVC application as shown below:

    1. protected void Application_Start()

    2. {

    3. //Remove All View Engine including Webform and Razor

    4. ViewEngines.Engines.Clear();

    5. //Register Your Custom View Engine

    6. ViewEngines.Engines.Add(new CustomViewEngine());

    7. //Other code is removed for clarity

    8. }


  3. Html Helpers are used to write input fields, create links based on the routes, AJAX-enabled forms, links and much more. Html Helpers are extension methods of the HtmlHelper class and can be further extended very easily. In more complex scenario, it might render a form with client side validation with the help of JavaScript or jQuery.
What do you think?
I hope you will enjoy the ASP.NET MVC pipeline while extending ASP.NET MVC features. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

A brief history of Asp.Net MVC framework

sp.Net MVC is a new Framework built on the top of Microsoft .Net Framework to develop web application. This framework implements the MVC pattern which helps to provides separation of code and also provide better support for test-driven development (TDD).
Asp.Net MVC is a lightweight and highly testable open source framework for building highly scalable and well designed web applications. Here is the list of released version history of ASP.NET MVC Framework with theirs features.

Asp.Net MVC1

  1. Released on Mar 13, 2009
  2. Runs on .Net 3.5 and with Visual Studio 2008 & Visual Studio 2008 SP1
  3. MVC Pattern architecture with WebForm Engine
  4. Html Helpers
  5. Ajax helpers
  6. Routing
  7. Unit Testing

Asp.Net MVC2

  1. Released on Mar 10, 2010
  2. Runs on .Net 3.5, 4.0 and with Visual Studio 2008 & 2010
  3. Strongly typed HTML helpers means lambda expression based Html Helpers
  4. Templated Helpers
  5. Support for Data Annotations Attribute
  6. Client-side validation
  7. UI helpers with automatic scaffolding & customizable templates
  8. Attribute-based model validation on both client and server
  9. Overriding the HTTP Method Verb including GET, PUT, POST, and DELETE
  10. Areas for partitioning a large applications into modules
  11. Asynchronous controllers

Asp.Net MVC3

  1. Released on Jan 13, 2011
  2. Runs on .Net 4.0 and with Visual Studio 2010
  3. The Razor view engine
  4. Improved Support for Data Annotations
  5. Remote Validation
  6. Compare Attribute
  7. Sessionless Controller
  8. Child Action Output Caching
  9. Dependency Resolver
  10. Entity Framework Code First support
  11. Partial-page output caching
  12. ViewBag dynamic property for passing data from controller to view
  13. Global Action Filters
  14. Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding
  15. Use of NuGet to deliver software and manage dependencies throughout the platform
  16. Good Intellisense support for Razor into Visual Studio

Asp.Net MVC4

  1. Released on Aug 15, 2012
  2. Runs on .Net 4.0, 4.5 and with Visual Studio 2010SP1 & Visual Studio 2012
  3. ASP.NET Web API
  4. Enhancements to default project templates
  5. Mobile project template using jQuery Mobile
  6. Display Modes
  7. Task support for Asynchronous Controllers
  8. Bundling and minification
  9. Support for the Windows Azure SDK

Asp.Net MVC5 Preview

  1. Released on Jun 26, 2013
  2. Runs on .Net 4.5, 4.5.1 and with Visual Studio 2013 Preview
  3. One Asp.Net
  4. Asp.Net Identity
  5. ASP.NET Scaffolding
  6. Authentication filters - run prior to authorization filters in the ASP.NET MVC pipeline
  7. Bootstrap in the MVC template
  8. ASP.NET Web API2

Note

In this article, I have mention only stable released version of Asp.Net MVC Framework.


Announcing the Release of ASP.NET MVC 5.1, ASP.NET Web API 2.1 and ASP.NET Web Pages 3.1

The NuGet packages for ASP.NET MVC 5.1, ASP.NET Web API 2.1 and ASP.NET Web Pages 3.1 are now live on the NuGet gallery!

Download this release

You can install or update to the released NuGet packages for ASP.NET MVC 5.1, ASP.NET Web API 2.1 and ASP.NET Web Pages 3.1 using the NuGet Package Manager Console, like this:
  • Install-Package Microsoft.AspNet.Mvc -Version 5.1.0
  • Install-Package Microsoft.AspNet.WebApi -Version 5.1.0
  • Install-Package Microsoft.AspNet.WebPages -Version 3.1.0

Pre-requisites for this release

What’s in this release?

This release is packed with great new features summarized below:
ASP.NET MVC 5.1
ASP.NET Web API 2.1
ASP.NET Web Pages 3.1
You can find a complete listing of the features and fixes included in this release by referring to the corresponding release notes:

Documentation

Tutorials and other information about this release are available from the ASP.NET web site (http://www.asp.net).

Questions and feedback

You can submit related to this release on the ASP.NET forums (MVC, Web API, Web Pages). Please submit any issues you encounter and feature suggestions for future releases on our CodePlex site.
Thanks and enjoy!

5 Tips to improve performance of C# code

5 Tips to improve performance of C# code

In this article I show you 5 best practices of C# programming. I have learned these practices from my daily programming experience. I have tested all code in release mode and have taken screen shots after the stability of the development environment. And I think you will enjoy these tips.
  1. Choose your data type before using it
    For many types we prefer to not decide what data type to use in our daily programming life. Even a few months ago I too was among them. But when I started to learn best practices in programming to improve code performance I learned how a wrong data type can impact code. I will show one demonstration to prove this concept.
    staticvoid Main(string[] args)
    {
        List<Int32> li = new List<int>();
        Stopwatch sw =new Stopwatch();
        sw.Start();

        for (int i = 0; i < 10000; i++)
        {
            li.Add(i);
        }
        sw.Stop();

        Console.Write("Using Arraylist(Object)" + sw.ElapsedTicks + "\n");
        sw.Reset();

        sw.Start();
        Int32[] a = new Int32[10000];
        for (int i = 0; i < 10000; i++)
        {
            a[i] = i;
        }
        sw.Stop();
        Console.Write("Using Value(Integer Array)" + sw.ElapsedTicks);
        Console.ReadLine();
    }

    5-tips-to-improve-performance-of-Csharp-code-1.jpg

    In the code above at first I used a generic List to store 1000 integer values and in the second time for the same operation I used an integer array. And my output screenshot shows which storage mechanism is best for the integer array. Now, you may think why does the List take more time? The reason is that the List stores the data in object format and when we try to store the value type at first it converts it to a reference type, then it's stored. So the first point is to always choose the proper storage mechanism to get the best performance.
  2. Use For loop instead of foreach
    I am will now explain a very interesting fact. I think all of you are familiar with both for and foreach loops. Now if I ask you which one is faster ? Hmm... Don't know. Right?
    Guys, a for loop is much faster than a foreach loop. Let's see the following example.
    List<Int32> Count = new List<int>();
    List<Int32> lst1 = new List<Int32>();
    List<Int32> lst2 = new List<Int32>();
    for (int i = 0; i < 10000; i++)
    {
        Count.Add(i);
     }

      Stopwatch sw =new Stopwatch();
      sw.Start();
      for (int i = 0; i < Count.Count; i++)
       {
              lst1.Add(i);
       }
       sw.Stop();

      Console.Write("For Loop :- "+ sw.ElapsedTicks+"\n");
       sw.Restart();

      foreach (int a in Count)
     {
          lst2.Add(a);
      }
     sw.Stop();
     Console.Write("Foreach Loop:- " +  sw.ElapsedTicks);
     Console.ReadLine();

    5-tips-to-improve-performance-of-Csharp-code-3.jpg

    And don't worry, I have tested this example in release mode and this screen shot is taken after several test runs. And still if you want to use a for loop then I will request you to have a look at the output screen shot one more time.
     
  3. Choose when to use a class and when to use a structure

    By accepting that you pretty much understand structures and classes in C# or at least in your favorite programming language, if they are present there. 

    Ok, if you are thinking that "long ago I had learned structures and in daily coding life never used then" then you are among those 95% of developers who have never measured the performance of classes and structures. Don't worry; neither have I before writing this article.
    And what about classes? Yes now and then we implement a class in our daily routine project development.

    Now my question is "Which one is faster, class or structure"? I expect that you are thinking that "Never tested it". Ok then let's test it here. Have a look at the following code.
    namespace BlogProject
    {
       struct MyStructure
        {
           public string Name;
           public string Surname;
        }
       class MyClass
        {
           public string Name;
           public string Surname;
        }
       class Program
        {
           static void Main(string[] args)
            {
               
               MyStructure [] objStruct =new MyStructure[1000];
                MyClass[] objClass = new MyClass[1000];


               Stopwatch sw = new Stopwatch();
                sw.Start();
               for (int i = 0; i < 1000; i++)
                {
                    objStruct[i] = newMyStructure();
                    objStruct[i].Name = "Sourav";
                    objStruct[i].Surname = "Kayal";
                }
                sw.Stop();
               Console.WriteLine("For Structure:- "+ sw.ElapsedTicks);
                sw.Restart();

               for (int i = 0; i < 1000; i++)
                {
                    objClass[i] = newMyClass();
                    objClass[i].Name = "Sourav";
                    objClass[i].Surname = "Kayal";
                }
                sw.Stop();
               Console.WriteLine("For Class:- " + sw.ElapsedTicks);
               
                Console.ReadLine();
            }
        }
    }

    And the output is here:

    5-tips-to-improve-performance-of-Csharp-code-2.jpg

    Now it's clear that the structure is much faster than the class. Again, I have tested this code in release mode and taken at least 20 outputs to get the program to a stable position.

    Now the big question is "why is a structure faster than a class"?

    As we know, structure variables are value types and in one location the value (or structure variable) is stored. 

    And a class object is a reference type. In case of an object type the reference is created and the value is stored in some other location of memory. Basically the value is stored in a manageable heap and the pointer is created in the stack. And to implement an object in memory in this fashion, generally it will take more time than a structure variable.
  4. Always use Stringbuilder for String concatenation operations
    This point is very crucial for developers. Please use StringBuilder in place of String when you are making heavy string concatenation operations. To demonstrate how it impacts on code performance I have prepared the following example code. I am doing a string concatenation operation 500 times within the for loop.
       public classTest
        {
           public staticstring Name { get;set; }
           public staticString surname;
        }
       class Program
        {
           static void Main(string[] args)
            {
               string First = "A";
                StringBuilder sb = new StringBuilder("A");

                Stopwatch st = new Stopwatch();
                st.Start();
               for (int i = 0; i < 500; i++)
                {
                    First = First + "A";
                }
                st.Stop();
               Console.WriteLine("Using String :-" + st.ElapsedTicks);
                st.Restart();

               for (int i = 0; i < 500; i++)
                {
                    sb.Append("A");
                }
                st.Stop();
               Console.WriteLine("Using Stringbuilder :-" + st.ElapsedTicks);
               Console.ReadLine();
            }
        } And this is the output.

    5-tips-to-improve-performance-of-Csharp-code-4.jpg
     
  5. Choose best way to assign class data member
    Before assigning a value to your class variable, I suggest you look at the following code and output screen at this point.
     
    namespace Test
    {
       public classTest
        {
           public staticstring Name { get;set; }
           public staticString surname;
        }
       class Program
        {
           static void Main(string[] args)
            {

                Stopwatch st = new Stopwatch();
                st.Start();
               for (int i = 0; i < 100; i++)
                {
                   Test.Name = "Value";
                }
                st.Stop();
               Console.WriteLine("Using Property: " + st.ElapsedTicks);
                st.Restart();
               for (int i = 0; i < 100; i++)
                {
                   Test.surname ="Value";
                }
                st.Stop();
               Console.WriteLine("Direct Assign: " + st.ElapsedTicks);
               Console.ReadLine(); 
            }
        }
    }

    5-tips-to-improve-performance-of-Csharp-code-5.jpg

    Yes, our output screen is saying that the data member is assigned using a property is much slower than direct assignment.

How to use int.TryParse

USE OF INT.TRYPARSE :-

When converting values in C#, we have three options : ParseConvert, and TryParse. My suggestion would be to use which method based on where the conversion is taking place. If you are validating input, an int parse or a convert will allow you to give specific error messages.
I am giving you a short example of int.TryParse:-
public static void Main(string[] args)
{
string str = "";
int intStr;
bool intResultTryParse = int.TryParse(str, out intStr);
if (intResultTryParse == true)
{
Console.WriteLine(intStr);
}
else
{
Console.WriteLine("Input is not in integer format");
}
Console.ReadLine();
}

In above Program str is not a integer. Whenever we use int.TryParse it returns boolean value.
First of all it validate your string. If your string is integer it returns True else False.
int.TryParse contain two arguments first is string and another is int(out type). If the input string is integer it returns 2nd arguments(out type int). Else it returns first argument(string).
untitled.JPG

Thanks for Reading.