Friday, 24 June 2016

MVC Questions - 6 (Bundling and Minification and Filters)



1. Bundling and Minification


Bundling and minification are two techniques you can use in ASP.NET 4.5 to improve request load time.  Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.)


Bundling: It’s a simple logical group of files that could be referenced by unique name and being loaded with one HTTP requestor.


Minification: It’s a process of removing unnecessary whitespace, line break and comments from code to reduce its size thereby improving load times.


What is Bundle?



A bundle is a logical group of files that is loaded with a single HTTP request. You can create style and script bundle for css and javascripts respectively by calling BundleCollection class Add() method with in BundleConfig.cs file.


Creating Style Bundle



  1. bundles.Add (new StyleBundle("~/Content/css").Include("~/Content/site.min.css",
"~/Content/mystyle.min.css"));


Creating Script Bundle



  1. bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
            "~/Scripts/jquery-1.7.1.min.js",
            "~/Scripts/jquery.validate.min.js",
            "~/Scripts/jquery.validate.unobtrusive.min.js"));


Above both the bundles are defined with in BundleConfig class as shown below:


  1. public class BundleConfig
  2. {
  3.         public static void RegisterBundles(BundleCollection bundles)
                     {
 
  1.           bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.min.css",
  2.           "~/Content/mystyle.min.css"));
  3.           bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
  4.           "~/Scripts/jquery-1.7.1.min.js",
  5.           "~/Scripts/jquery.validate.min.js",
  6.           "~/Scripts/jquery.validate.unobtrusive.min.js"));
  7.        }
  8. } 


Creating Bundle using the "*" Wildcard Character



"*" wildcard character is used to combines the files that are in the same directory and have same prefix or suffix with its name. Suppose you want to add all the scripts files that exist with in "~/Script" directory and have "jquery" as prefix then you can create bundle like below:


  1. bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery*.js"));


You can also add all the css that exist with in "~/Content" directory and have ".css" extension(as suffix) like below:


  1. bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/*.css"));


Registering Bundle



All bundles are registered with in Application_Start event of Global.asax file of you web application.


  1. protected void Application_Start()
  2. {
  3.       BundleConfig.RegisterBundles(BundleTable.Bundles);
  4.       // Other Code is removed for clarity
  5. }


Minification



Minification is technique for removing unnecessary characters (like white space, newline, tab) and comments from the JavaScript and CSS files to reduce the size which cause improved load times of a webpage. There are so many tools for minifying the js and css files. JSMin and YUI Compressor are two most popular tools for minifying the js and css files.


2. What are different filters available?
They are


  • Authorization filters–Used to make security decisions. It decides whether the current user has rights to execute action or not.
  • Action Filters – It is for the action method execution behavior. It exposes two methods
            o OnActionExecuting – which executes before action method        o OnActionExecuted – after action method is executed
  • Result Filters – It is for the result of action method result. It exposes two methods
            o OnResultExecuting – executed before action result is returned
            o OnResultExecuted – executed after action result is returned
  • Exception Filters – Executed when there is an unhandled exception occurs in the Asp.net MVC request pipeline.


3. Is it possible to create custom filters?


Yes. We have to implement a class from one of these interfaces IAuthorizationFilter, IActionFilter, IResultFilter, IExceptionFilter and either declaratively or by programming we can apply those filters to controller or action methods.


4. Types of Filters



The ASP.NET MVC framework provides five types of filters.


  1. Authentication filters (New in ASP.NET MVC5)
  2. Authorization filters
  3. Action filters
  4. Result filters
  5. Exception filters


5. Order of Filter Execution



All ASP.NET MVC filter are executed in an order. The correct order of execution is given below:


  1. Authentication filters
  2. Authorization filters
  3. Action filters
  4. Result filters




6. Configuring Filters



You can configure your own custom filter into your application at following three levels:


1.               Global level


By registering your filter into Application_Start event of Global.asax.cs file with the help of FilterConfig class.


1.  protected void Application_Start()
2.  {
3.   FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
4.  }


 


2.               Controller level


By putting your filter on the top of the controller name as shown below-


1.  [Authorize(Roles="Admin")]
2.  public class AdminController : Controller
3.  {
4.   //
5.  }


 


3.               Action level


By putting your filter on the top of the action name as shown below-


1.  public class UserController : Controller
2.  {
3.   [Authorize(Users="User1,User2")]
4.   public ActionResult LinkLogin(string provider)
5.   {
6.   // TODO:
7.   return View();
8.   }
9.  }


 
 




 

Authentication Filters


This filter is introduced with ASP.NET MVC5. The IAuthenticationFilter interface is used to create CustomAuthentication filter. The definition of this interface is given below-

1.  public interface IAuthenticationFilter
2.  {
3.   void OnAuthentication(AuthenticationContext filterContext);
4.   
5.   void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
6.  }

You can create your CustomAuthentication filter attribute by implementing IAuthenticationFilter as shown below-

1.  public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
2.  {
3.   public void OnAuthentication(AuthenticationContext filterContext)
4.   { 
5.   //Logic for authenticating a user
6.   }
7.   //Runs after the OnAuthentication method
8.   public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
9.   { 
10. //TODO: Additional tasks on the request
11. }
12.}

Authorization Filters


The ASP.NET MVC Authorize filter attribute implements the IAuthorizationFilter interface. The definition of this interface is given below-

1.  public interface IAuthorizationFilter
2.  {
3.   void OnAuthorization(AuthorizationContext filterContext);
4.  }

The AuthorizeAttribute class provides the following methods to override in the CustomAuthorize attribute class.

1.  public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
2.  {
3.   protected virtual bool AuthorizeCore(HttpContextBase httpContext);
4.   protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext);
5.   public virtual void OnAuthorization(AuthorizationContext filterContext);
6.   protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext);
7.  }

In this way you can make your CustomAuthorize filter attribute either by implementing IAuthorizationFilter interface or by inheriting and overriding above methods of AuthorizeAttribute class.

Action Filters


Action filters are executed before or after an action is executed. The IActionFilter interface is used to create an Action Filter which provides two methods OnActionExecuting and OnActionExecuted which will be executed before or after an action is executed respectively.

1.  public interface IActionFilter
2.  {
3.   void OnActionExecuting(ActionExecutingContext filterContext);
4.   void OnActionExecuted(ActionExecutedContext filterContext);
5.  }

Result Filters


Result filters are executed before or after generating the result for an action. The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and EmptyResult which derives from the ActionResult class. Result filters are called after the Action filters. The IResultFilter interface is used to create an Result Filter which provides two methods OnResultExecuting and OnResultExecuted which will be executed before or after generating the result for an action respectively.

1.  public interface IResultFilter
2.  {
3.   void OnResultExecuted(ResultExecutedContext filterContext);
4.   void OnResultExecuting(ResultExecutingContext filterContext);
5.  }

Exception Filters


Exception filters are executed when exception occurs during the actions execution or filters execution. The IExceptionFilter interface is used to create an Exception Filter which provides OnException method which will be executed when exception occurs during the actions execution or filters execution.

1.  public interface IExceptionFilter
2.  {
3.   void OnException(ExceptionContext filterContext);
4.  }

ASP.NET MVC HandleErrorAttribute filter is an Exception filter which implements IExceptionFilter. When HandleErrorAttribute filter receives the exception it returns an Error view located in the Views/Shared folder of your ASP.NET MVC application.

 


No comments:

Post a Comment