Wednesday, July 8, 2015

MVC 5 New Features

ASP.NET MVC is Microsoft’s latest web application development technology based on the principle of the separation of concerns. MVC stands for Models, Views and Controllers, respectively. Prior to MVC pattern, Web Forms was the prime Microsoft technology for web application development. However, Web Forms lacked flexibility of development and loose coupling. MVC addressed these concerns. We’ll discuss some of the new features offered by ASP.NET MVC 5, which is the 5th version of the Microsoft MVC technology
  1. Scaffolding
  2. ASP.NET 
  3. IdentityOne ASP.NET 
  4. Bootstrap
  5. Attribute Routing
  6. Filter Overrides
    Some of these features like ASP.NET Identity etc. are not exactly new features of the core MVC 5 framework, but are worth looking at, as they directly affect/change the way we create MVC 5 applications.

    Scaffolding

    Visual Studio 2013 includes a new Scaffolding Framework for ASP.NET MVC 5 and the ASP.NET Web API 2. Simply put, Scaffolding is a code generation framework provided for ASP.NET Web Applications. Using this framework, you can quickly generate code that interacts with your data models. This feature reduces the amount of time required to build MVC application with standard data operations. Scaffolding uses code-first approach for data operations.
    Basically we need to add model class in project and on the project, right-click and select Add > New Scaffolded item as shown there, we can select API or controller. Then it will generate required classes automatically.  It will help in moving ahead quickly with Code First Approach.

    ASP.NET Identity

    In earlier days of ASP.NET 2.0 programming, a membership provider approach was introduced. This allowed the application to store user’s data in a SQL Server database. This membership model has changed over the years. The notion that a user can log-in by only using a user-name and password registered in the application, can now be ignored. In today’s world, the web has become more social and users connect to each other, and with applications, using social sites like Facebook, Twitter etc. So considering these social integrations, web applications too need to be enhanced to allow users to log-in using their social media credentials.

    To get this done, the modern membership framework is now extended to integrate with social credentials and for this purpose, ASP.NET Identity has been introduced. The advantages of the ASP.NET Identity are explained as follows:
    - One ASP.NET Identity System: Can be used across all the ASP.NET Frameworks like Web Forms, MVC, Web Pages, Web API and SignalR etc.
    - Ease of plugging-in profile data about the user: The user’s profile schema information can be integrated with the web application.
    - Persistence Control: ASP.NET Identity system stores all user information in the database.
    - Social Login Provider: Social log-in providers such as Microsoft Account, Facebook, Twitter, Google, and others can be easily added to the web application.
    - Windows Azure Active Directory (WAAD): The Login-in information from WAAD can also be used for authenticating a web application.
    - OWIN Integration: ASP.NET Identity is fully compliant with OWIN Framework. OWIN Authentication can be used for login. If you are new to OWIN, read this article.
    All these features in the ASP.NET Identity membership system are available if you are using Visual Studio 2013. Alternatively, you can also obtain it via NuGet packages Microsoft.Aspnet.Identity.Core and Microsoft.Aspnet.Identity.EntityFramework.

    One ASP.NET

    One ASP.NET is a new unified project system for .NET Web Developers. This system makes it easier to work with multiple frameworks like Web Forms, MVC, Web API etc., in a single project. So essentially using the One ASP.NET project system, you can use ASP.NET Web Forms and MVC together, and can easily add ASP.NET Web API and SignalR too; in the same Web application.
    In Visual Studio 2013, the ASP.NET MVC project template integrates with this new system. One of the useful features while creating a MVC project is that the authentication mechanism can be configured using following steps.
    Step 1: Open VS 2013 and select File > New > Project, select Web from installed template
    Step 2: Make sure that .NET Framework 4.5.1 is selected; click OK, New ASP.NET Project window displays various Web Templates, and based upon the selection of template, the necessary references will get added in the project. Checkboxes indicates the necessary folder structure and core references for the project.
    Step 3: Click on Change Authentication and the authentication provider windows will be displayed. There are four different authentication types that can be set for the application:

    1. No Authentication: The application does not require authentication.
    2. Individual User Accounts: SQL Server database is used to store user profile information. This authentication can also be extended to provide the end-user with the option to make use of their social profiles like Facebook, Google, Microsoft, Twitter or any other customized provider.
    3. Organizational Accounts: The application can authenticate users using the user profiles stored in Active Directory, Windows Azure Active Directory, or Office 365. This provides Single Sign-on access level to the application. The Organizational Accounts require the following details:
    ·         Cloud-Single Organization
    ·         Cloud-Multi Organization – This and the previous one can be used when the user authentication information is stored on the Windows Azure Activity Directory (WAAD)
    ·         On-Premises - Used for the Active Directory on-premises.
    ·         Domain - The WAAD domain for setting application in it.
    ·         Access Level - The application needs to query or update directory information.
    ·         Application ID URI - Created by appending the project name to the domain.
    4. Windows Authentication: Used for intranet applications.

    Attribute Routing

    The major difference in ASP.NET MVC and ASP.NET web forms is the way incoming requests are handled. In Web Forms, incoming requests map to a file or resource on the web server. For instance, the requested URL can be of the form www.abcd.com/xyz.aspx. Here, the URL refers to an ASP.NET Web Form named xyz.aspx, located at the root directory. There is a one-to-one mapping between the URL and the page that is accessed, which must physically reside on the server.
    On the other hand, MVC routing pattern maps URLs with action methods, resulting in cleaner and more SEO-friendly URLs (for instance, www.abcd.com/xyz/buy). This URL refers to the action method “buy” of the controller “xyz” on the domain “abcd”.


    To see where these routes are configured, go to the solution explorer of your ASP.NET MVC application and find App_Start folder and find the RouteConfig.cs file. It contains a method named RegisterRoutes which takes a collection of type RouteCollection as a parameter. Inside this method are routes that are to be ignored; routes that are to be added can be defined. This is shown in the following code snippet:
    public static void RegisterRoutes(RouteCollection routes){
       routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
       routes.MapRoute(
          name: "Default",
          url: "{controller}/{action}/{id}",
          defaults: new { controller = "Home", action = "Index", id = UrlParameter.Option }
          );
    }
    Apart from defining routes in the RouteConfig.cs file, ASP.NET MVC 5 has introduced a new feature known as attribute routing which allows developers to specify a route as an attribute of the action method. To enable attribute based routing, you need to modify the RegisterRoutes method of RouteConfig.cs file as follows:
    public static void RegisterRoutes(RouteCollection routes){
         routes.MapMvcAttributeRoutes();
    }
    To add a route on any action method, you simple have to add an attribute named Route and pass the route as parameter to it. For instance:
    [Route("Products/Sports/{id}")]
    public ActionResult GetSportsItems(string id){
          ViewBag.Id = id;
          return View();
    }


    Optional Parameter
    We can also specify if there is any optional parameter in the URL pattern defined by the Route attribute with the “?” character.
    [Route("Products/Sports/{id?}")]
    public ActionResult GetSportsItems(int? id){
          ViewBag.Id = id;
          return View();
    }
    Route Prefix & Route constraints
    If we have multiple action methods in a controller all using the same prefix we can use Route Prefix attribute on the controller instead of putting that prefix on every action method & We can also specify parameter constraints placing the constraint name after the parameter name separated by colon
     [RoutePrefix("Products")]
    [Route("Sports /{id:int}")]
    public ActionResult GetSportsItems(int? id){
          ViewBag.Id = id;
          return View();
    }

    Filter Overrides

    MVC 5 provides a filter overrides feature which we can apply to the action method or controller which selectively excludes the global filter or the controller filter for the specified action method or controller.
    Now if want to override our global action filter in one of our action method's then we just need to apply the OverrideActionFilters attribute. Below we have applied the attribute to the default About method in the HomeController.
    [OverrideActionFilters]      
     public ActionResult About(){          
     ViewBag.Message = "Your application description page.";        
     return View();   } 


    Courtesy: ASP.NET MVC 5 & several other online resources.


    Wednesday, May 28, 2014

    Inversion of control and Dependency injection



    Inversion of control is one of the design patterns, which help us to build decoupled software components. Let’s see that with one of the very common example over Internet


    public class clsCustomer
    {
        Private clsAddress _address
        public clsCustomer ()
        {
             _address = new clsAddress();
        }
    }

    Here we can see two problems
    1.       clsCustomer is having reference of clsAddress.
    2.       clsCustomer is aware of concrete address class.
    So the main problem is Tight Coupling.  This problem is created by approach followed for object creation so solution is somehow we have to make sure that clsCustomer must not be holding reference of address class.  We can achieve this by following principle of Inversion of control which states:
    • ·         High level modules should not depend upon low level modules. Both should depend upon abstractions.
    • ·         Abstractions should not depend upon details. Details should depend upon abstractions.
    In other popular words its stands on the base of Hollywood principle (response given to amateurs auditioning in Hollywood): Do not call us we will call you.

     It’s like address class saying to the customer class, do not create me I will create myself using someone else. The simplest way would be to expose a method which allows us to set the address object.

    public class clsCustomer
    {
        Private IAddress _address

        public clsCustomer (IAddress address)
        {
             _address = address;
        }
    }

    And now question is who will be someone else? And answer is IOC Containers. We have several containers around e.g. Structure Map, Ninject, Unity, Windsor etc.   By using any of these Containers we can implement Dependency injection and let object creation to be delegated to our Container.


    I’ll discuss here Ninject along with MVC 4. Let’s create MVC 4 Internet application and name that “MVC4WithNinject” now it will look as follows
      
     

    Let’s add Ninject NuGet package:




    Don’t worry that it says MVC3 – it works in MVC 4 as well. This will add a new class NinjectWebCommon in app_start folder.




    NinjectWebCommon class has start, stop, CreateKernel and RegisterServices methods.  At this stage will be able to build and run application, home page will look as follows:

     


    If you look at the HomeController class definition, then you will find that the class has no constructor. We all know that if there is no constructor defined then at compile time .NET Framework creates a default parameter-less constructor. 
     
    public class HomeController : Controller

    {

        public HomeController()

        {

        }

    }
    Now I will create ILogger interface and its implementation DefaultLogger class. Home controller class will use that ILogger object. I will inject it throw constructor. 

    public interface ILogger {
        void Log(string logData);
    }
     
    public class DefaultLogger : ILogger {
        public void Log(string logData)
        {
            System.Diagnostics.Debug.WriteLine(logData, "default");
        }
    }
     
    Let’s pass ILogger into HomeController, now code will look as follows:

    public class HomeController : Controller {

        private readonly ILogger _logger;

        public HomeController(ILogger logger)

        {        _logger = logger;    }

    }
    Let’s run application again, as we have created a parametrized constructor it will throw error 

     


    All we need to do is to tell Ninject to provide instance of DefaultLogger when ILogger is used.  We can do this by adding following lines into RegisterServices method:
     
    private static void RegisterServices(IKernel kernel) {  
      kernel.Bind<ILogger>().To<DefaultLogger>();

     }


    Now if we’ll run application again we’ll able to see home page again.





    This was simplest example of implementation of Dependency injection using Ninject as Inversion of control container.  I hope this discussion had given you basic understanding of IoC and DI. For other details refer Head First Design Patterns or internet you will get other implementation approach for Dependency injection .Let me know if any question.


    Courtesy: MSDN , Head First Design Patterns & Several other online resources.