Thursday, January 23, 2014

Compressing files for faster download

Web Page Requests Compression

While making a request to the server, if request contains following, server can send the compressed file which will be automatically decompressed by the browser after receiving.

Accept-Encoding: gzip, deflate

Above parameters shows that browser can accept GZIP or DEFLATE compression type.

It can be easily setup from the IIS directly. Open IISManager, and click on Compression. Set the values here. Don't compress to small files and cost of compressing/ decompressing could be more than actually downloading the file.


File Requests Compression 

If web site allows the user to download large files like manuals, videos etc, compression can be done on the fly. Check the following code to zip the files on the fly

using (FileStream oFileStream = article.LocalFile.OpenRead())
{
using (FileStream cFileStream = File.Create(
Guid.NewGuid().ToString() + ".gz"))
{
using (GZipStream compressionStream =
new GZipStream(cFileStream, CompressionMode.Compress))
{
oFileStream.CopyTo(compressionStream);
StreamReader reader = new StreamReader(compressionStream);
results = reader.ReadToEnd();
}
}
}

Bundling & Minifying in MVC

Bundling - Process of merging many script files into one file for faster download as to save on many server rounds and connections is called bundling.

In App_Start/BundleConfig.cs add the following code

  bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                        "~/Scripts/jquery-ui-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));

Minifying - Shorting the file by removing the empty spaces and is called minifying. As the size becomes small it takes much less time for download

Two ways to do it

1) Add following line of code in your web.config

<compilation debug="false" />

2) In App_Start/BundleConfig.cs add the following code in RegisterBundles() method

BundleTable.EnableOptimizations = true

Customizing Result Filter : Creating custom Result

We need  to inherit System.Web.Mvc.ActionResult and override the ExecuteResult method

Example
public class SatinderResult<T> :ActionResult
{
public override void ExecuteResult(ContollerContext context)
{
// do  something here
}

}

Creating Custom Controller Factory

Creating a custom ControllerFactory class requires that you implement System.Web.Mvc.IControllerFactory.
This method has three methods:

  • CreateController
  • ReleaseController
  • GetControllerSessionBehavior. 


The CreateController method handles the actual control creation, so if you were creating a customized constructor, this is where your code would participate.

The ReleaseController method cleans the controller up. In some cases, you might be freeing up your IoC container; in other cases, you might be logging out a service connection.

The GetControllerSessionBehavior method enables you to define and control how your controller works with session.

After you create your own ControllerFactory class, you need to register it for use. You can add the following code to the Global.asax Application_Start method:

ControllerBuilder.Current.SetControllerFactory(typeof(MyCustomControllerFactory());

Customizing MVC Action Filters

  • Authorization - System.Web.MVC.IAuthorizationFilter
  • Action- System.Web.MVC.IActionFilter
    • OnActionExecuting 
    • OnActionExecuted
  • Result - System.Web.MVC.IResultFilter
    • OnResultExecuting
    • OnResultExecuted
  • Exception - System.Web.MVC.IExceptionFilter
    • OnException

While customizing the filter, we can define attribute usage
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]

Once you create the custom filter, you need to register for it, You do this by adding them in the App_Start/FilterConfig.cs, in the RegisterGlobalFilters method:

filters.Add(new MyCustomAttribute());

Action Results


  • ContentResult
  • FileResult
  • JSONResult
  • JavaScriptResult
  • RedirectResult
  • RedirectToRouteResult
  • EmptyResult

Globalization in MVC

Globalization is the process of access the website in some local language. Its can be achieved in two parts

  • Internationalization - Process of making your application support other languages
    • All the content should come from resources files & then moved to satellite assemblies.
    • Resource files can 
      • Per view
      • Per Language
      • Individual views can also be created if language needs different layout.
  • Localization  - Process of adding your local language ( as resources files)
    • Add your local language to resource files.

Routing in MVC

Routes can be used to convert incoming URL request to internal URL (action) request

- Custom Routing
- Route Constraint - Helps filtering the incoming request and divert to specified action
- Ignore URL Patters - Put some of the incoming URL into ignore list
- Areas - Define areas for bulky applications 

Annotations

Various types of annotations to decorate the model

- IsRequired
- Range
- DataType
- InputType

MVC Filters

4 Types of filters in MVC

- Authorization filters
- Action Filters
- Result Filters
- Exception Filters

Model Binding

3 ways to to do Model binding

- Strongly typed 
- Loosely typed 
- Value Type

Introduction

This blog has been setup as a quick reference to MVC terminology