Tuesday, April 10, 2012

Partial View Vs. Display/Editor Templates

ASP.net MVC provides two different options to create re-usable components
  • Partial Views
  • Display/Editor Templates
But whats the different between both of them and what advantage one has got over the other.
Difference between Display and Editor Templates: 
Display templates and Editor templates are model driven templates but only differ by the convention that display should only render read only html like divs, labels or spans etc where are editor should render editable html with forms, input controls, etc. Developers are the one whole create these templates and there is no validation which prevent us to create templates in the opposite order. It is the convention over configuration policy which drives MVC to follow a specific standardize pattern and sticking to this will ensure that no matter what you pass into Display helper method(s) will always render the same result as expected. Once we specify UIHint on any property, we instructor MVC view engine to render the respective property using given template specified either under DisplayTemplates folder or EditorTemplates folder under shared folder depending whether we want readonly mode (Html.Display) or editable mode (Html.Editor).

Sample ViewModel for the same to demonstrate how we ViewModel can be decorated with attributes to leverage templates rendering thru ViewModels in MVC
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using ReferenceImplementation.ViewModels;
 
namespace ReferenceImplementation.ViewModels
{
    public class PersonViewModel
    {
        public string FirstName { getset; }
 
        public string LastName { getset; }
 
        [UIHint("Int")]
        public int Age { getset; }
 
        [UIHint("Date")]
        public DatetimeViewModel DateOfBirth { getset; }
 
        [UIHint("Phone")]
        public PhoneViewModel MobileNumber { getset; }
    }
}
By specifying the UIHint attribute on properties in ViewModel, we are instructing MVC to render these properties with the respective templates (depending on its display or editor reference) from the respective folder instead of using standard MVC editor.
For the view code like the one given below
<div class="readonly">@Html.DisplayFor(m => m.DateOfBirth)</div>
Since we are using Display helper method, MVC will look for the Date template under DisplayTemplates folder and  for the view code given below
<div class="editale">@Html.EditorFor(m => m.Phone)</div>
MVC will look for template under EditorTemplates folder for the Editor helper method.

Difference between Partial View and Display/Editor Templates

By convention, Partial Views are considered to be View Centeric and MVC Templates are considered to be Model Centeric. This means that templates are more dependent on the view model and way they are rendered depends a lot on their properties but same is not true for the partial view as you are more concerned in choosing the correct partial view.
Partial View differs from Templates in the way they render Id's from the ViewModels. Partial view render the element name as it is but MVC Templates adhere to model hierarchies when rendering HTML helpers. e.g if you have a "Bar" object on your "Foo" model, the HTML elements for "Bar" will be rendered with "Foo.Bar.ElementName", whilst a partial will have "ElementName".
MVC Templates are more robust and smart. If you had a List<T> of something in your ViewModel, you could use @Html.DisplayFor(=> m.CollectionOfFoo), MVC templates are smart enough to see it as a collection and render out the single display for each item as opposed to a Partial, which would require an explicit for loop.
Templates are passed with additional information that partial views are not, in particular you receive ModelMetadata, such as that created by attributes. ModelMetadata are part of ViewData which is also accessible in partial view but are null as its only populated in templates ().
Note: Templates are partials which adhere to a specific convention. The situations which make templates better or worse than old partials are almost strictly dependent on whether or not the convention is worth adherence in your application

Monday, April 9, 2012

Bundle and Minification in MVC4

What is meant by MINIFICATION?

As described in wiki ...


"Minification (also minimisation or minimization), in computer programming languages and especially JavaScript, is the process of removing all unnecessary characters from source code, without changing its functionality. These unnecessary characters usually include white space characters, new line characters, comments, and sometimes block delimiters, which are used to add readability to the code but are not required for it to execute."


This is very helpful as we can reduce the size of the javascript file to be downloaded to the client browser from the server which reduces the data to be downloaded and increases the performance


What is meant by BUNDLING?

Bundling is the process of combining all the javascript files into one file so that client browser has to make only one request to the server to download all the files in go. For example, max browser can only process 2 request at a given instance (possibly has increased with the modern browsers). If we have more number of files then they have to wait for browser to request from server once the previous requests are complete which creates delay for the page to get complete resources before it is ready. On the other hand bundling process bundle up all the js files needed to be downloaded into one and does not have to wait for the server to process other request hence increasing the performance of the application. Same can be done for the CSS files.


Bundling and minification go well together as we can reduce the size of the file by minification and bundle up all the files like js and css in there respective file types to reduce the calls to the server.


Figure 1.1 shows a page being loaded with multiple script files. Total time to download all the files and before DOM ready event is fired is 2.14s.




Figure 1.1


Figure 1.2 shows a same page being loaded but this time we are using bundling and minification for the script files. So we have reduced the number of server calls to one and file is loaded in 370ms.


Figure 1.2




Using Bundling and Minification in ASP.net MVC4


ASP.net MVC 4 comes with new feature called bundling and minification.

var mainWebStyle = new Bundle("~/Scripts/libs"typeof(JsMinify));
mainWebStyle.AddFile("~/Scripts/jquery-1.7.1.min.js");
mainWebStyle.AddFile("~/Scripts/Knockout-2.0.0.js");
BundleTable.Bundles.Add(mainWebStyle);

In the above example, we can how bundles are created. This this example, we are bundling up two js file into one lib1 file. we can also bundle all the files in one folder with the following code.

var mainWebStyle = new Bundle("~/Scripts/libs"typeof(JsMinify));
mainWebStyle.AddDirectory("~/Scripts", "*.js", false);
BundleTable.Bundles.Add(mainWebStyle);

And in the view we can refer to  bundled file like this.

<script src="@Microsoft.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/libs")" type="text/javascript"></script>

Microsoft.Web.optimization help to cache the file on the clients machine and at the same time also adds a magical versioning number to the file which changes if file is changed, hence forcing the client to request for new file if file is modified and not refer to cached file on the client side.

We can also use our own minification utility if we dont like the one provided by the microsoft e.g

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Web.Optimization;
using Yahoo.Yui.Compressor;

namespace MVC4Example
{
    public class YuiJsMinify : IBundleTransform
    {
        public void Process(BundleResponse bundle)
        {
            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            bundle.Content = JavaScriptCompressor.Compress(bundle.Content);
            bundle.ContentType = "text/javascript";
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Web.Optimization;
using Yahoo.Yui.Compressor;

namespace MVC4Example
{
    public class YuiCssMinify : IBundleTransform
    {
        public void Process(BundleResponse bundle)
        {
            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            bundle.Content = CssCompressor.Compress(bundle.Content);
            bundle.ContentType = "text/css";
        }
    }
}


In the above example, i have used Yahoo Yui compressor dll to minify my javascript and style files instead of JsMinify and CssMinify.

Please visit the link of the presentation that Scott Gu gave in Netherlands to demo bundling and minifications and some other new features coming out in MVC 4


Happy Coding

Saturday, February 11, 2012

jQuery Google Plusify

I recently created new plugin to imitate Google Plus photo album. I will try to explain briefly how to use this plugin. For demo click here and you can also download full and minified version over here.
To start with, include minified (for production) or full version (for development) in your page.


<script type="text/javascript" src="<javascript folder path>/jquery.imagePlusify-1.0.min.js" ></script>


Place your div with width and height where you want place your albums.


<div id='plusifyPics' ></div>


Remember to set style for the div. Set your width and height to cover the area where you want to display your photo album. 


On document ready, initialize your imagePlusify and pass the options.


$(function () {
    $.AjaxGet({
        url: imgUrl,
        callback: function (data) {
            $('#plusifyPics').imagePlusify({
                backgroundColor: 'white',
                source: data,
                displayLabel: true,
                onClick: function (id, name, src) {
                    alert('you have clicked on album with id: [' + id + '] with name "' + name + '" and ' + 'it has total of ' + src.length +' images !!!');
                }
            });
        }
    });
});

Here is the list of all the options we can set in this plugin.

Property Values Additional Info
border
valid css border style
'1px solid gray' is default value
borderOnMouseOver
valid css border style
'1px solid black' is default value
padding
valid css padding size
'5px' is default value
backgroundColor
valid css color
 '#fff' is default value
displayLabel
true / false
by default its false
labelColor
valid css color for the text color
'#000' is default value
randomize
true / false
by default its true
margin
margin between the image albums
'30px' is the default value
width
album width
'200px' is the default width
height
album height
'200px' is the default height
slideBy
int distance by which images should slide
30 is the default value
source
images, name and id as source to display image albums
source can be sent in 3 ways
1. Array of string where string is url of images
2. Object with id, name and array of string as members
3 Array of object where object has id, name and array of string as members
onClick
Callback event raised on click of album
album id, album name and all images url as array are returned in the callback function.

Wednesday, January 4, 2012

Singleton Pattern


Introduction
Singleton can be defined as single instance object. Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.

Implementation
Singleton has one static object which is the gateway to create the instantiate the class. 

using System;

public class Singleton
{
   private static Singleton _instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get
      {
         if (_instance == null)
         {
            _instance = new Singleton();
         }
         return _instance;
      }
   }
}

Above example has a static member, "_instance" of type Singleton class. This was _instance can be accessed anywhere in the application.
Then we have private constructor of the singleton class which means that constructor can only be accessed within the same class, hence class cannot be initiated from the outside but only from inside the same class.
We also have readonly property called "Instance" which is only entry point to the singleton class. Since _instance is static object, so once _instance object is instantiated it is for lifetime.

Singleton Vs. Static Class
There are important differences between the singleton design pattern and the static keyword on classes. Static classes and singletons both provide sharing of redundant objects in memory, but they are very different in usage and implementation. 

Static class example 
You can make a static class with the static keyword. In the following example, look carefully at how the static keyword is used on the class and constructor. Static classes may be simpler, but the singleton example has many important advantages.

Static classes and singletons both provide sharing of redundant objects in memory, but they are very different in usage and implementation.



Singleton Static Class
you can create one instance of the object and reuse it. You cannot create the instance of static class. 
Singleton instance is created for the first time when the user requested.
Static classes- are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded. 
Singleton class can implement interface
Interface cannot be implemented on static classes
Singleton class can have constructor.
Static class cannot have constructor.

Hope you enjoyed reading this post ....

Friday, December 16, 2011

Design Patterns

Design Patterns are the proven solution to the common development problems faced during the software designing. These are the suggested way to solve the problems by providing cleaner, robust and efficient framework.
Design Patterns can be grouped into different categories
  1. Creational Patterns
  2. Structural Patterns
  3. Behavioral Patterns
Creational Patterns
Creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation. Creational design patterns are further categorized into Object-creational patterns and Class-creational patterns. Where, Object-creational patterns deal with Object creation and Class-creational deal with Class-instantiation.
  • Abstract factory pattern: Creates an instance of several families of classes.
  • Builder pattern: Separates object construction from its representation.
  • Factory method pattern: Creates an instance of several derived classes.
  • Lazy initialization pattern: Is used as tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed
  • Prototype pattern: A fully initialized instance to be copied or cloned.
  • Object pool pattern: Helps in avoiding expensive acquisition and release of resources by recycling objects that are no longer in use.
  • Singleton pattern: A class of which only a single instance can exist.
Structural Patterns
Structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.
  • Adapter pattern: Match interfaces of different classes.
  • Bridge pattern: Separates an object’s interface from its implementation.
  • Composite pattern: A tree structure of simple and composite objects.
  • Decorator pattern: Add responsibilities to objects dynamically.
  • Facade pattern: A single class that represents an entire subsystem.
  • Flyweight pattern: A fine-grained instance used for efficient sharing.
  • Proxy pattern: An object representing another object.
Behavioral Patterns
Behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.
  • Chain of responsibility pattern: A way of passing a request between a chain of objects.
  • Command pattern: Encapsulate a command request as an object.
  • Interpreter pattern: A way to include language elements in a program.
  • Iterator pattern: Sequentially access the elements of a collection.
  • Mediator pattern: Defines simplified communication between classes.
  • Memento pattern: Capture and restore an object's internal state.
  • Observer pattern: A way of notifying change to a number of classes.
  • State pattern: Alter an object's behavior when its state changes.
  • Strategy pattern: Encapsulates an algorithm inside a class.
  • Template method pattern: Defer the exact steps of an algorithm to a subclass.
  • Visitor pattern: Defines a new operation to a class without change.

Monday, December 12, 2011

GZIP compression for better performance

Compression is easy and effective way to reduce the bandwidth to download data from internet and increase the performance of the web site. In other words, server sends the compressed HTML in the form of zip file to the client and the client browser unzips the file to retrieve the HTML. All the latest browsers support gzip/deflate. 


Why we need it?


Lets understand how the web model works. When we visit the web page e.g. http://jassra.com/, basically we are requesting for Index file from the server and server returns the same file to the client.


The way communication takes place between the client and the server is described below:
  1. Browser requests a file from the server and the data sent for the request is 100 B
  2. Server finds the requested file
  3. Creates HTML for the response
  4. Server sends 1.9 KB of data back to the browser. And user needs to wait for the data to be downloaded and finally browser displays the page
Network trace


Now with gzip if we can compress the file to reduce the size of the file and less data needs to be transferred to the client resulting in less bandwidth and quick response.
  1. Browser requests a file from server. Data sent for the request is 100 B
  2. Server finds the requested file
  3. Creates HTML for the response and  zips the file
  4. Server sends 874 B of data back to the browser. 874 B of data is downloaded quickly as compared to the uncompressed data and browser displays the page much faster
Means Happy Customer..... :o)

Network trace



For more understanding about how gzip algorithm works, please view this video.



Please feel free to leave your feedback ....

Sunday, December 11, 2011

Web Storage in HTML (5)

In newer version of HTML (so called HTML 5), we have two new mechanisms introduced to store structured data related to session cookies and cookies.
  1. Session Storage (sessionStorage)
  2. Local Storage (localStorage)
As the name specifies, local storage is for the long term  and session storage is only limited to that particular session.


Session Storage


Session storage allows to save data on the client side persisting for that particular session only. Data can be saved on the client side and shared between multiple pages during that session but once session is closed, all the stored data on the client side is deleted and is never accessible again. This also helps in differentiating the two different windows of the same site opened on the same machine and maintaining their instance without being affected with the activities on the other window. So i would think its right to say that session storage is dependent on combination of session id and site id together.


Note : The lifetime of a browsing context can be unrelated to the lifetime of the actual user agent process itself, as the user agent may support resuming sessions after a restart.


Local Storage


Local storage allows to save data on the client side for the longer duration for the returning users. Local storage data is save on the client side and is only dependent on site id. With local storage, changes made on the one site window will affect on the other window opened on the same machine.


The API



Web storage provide list to key/value pair called items.Keys are strings. Any string (including the empty string) is a valid key. Values are similarly strings.


Adding Item  - Insert new item in the storage 
sessionStorage.setItem(key, value)
localStorage.setItem(key, value)


Retrieving Item - Retrieve item from the storage 
sessionStorage.getItem(key)
localStorage.getItem(key)


Removing Item - Removes item for the storage 
sessionStorage.removeItem(key)
localStorage.removeItem(key)


Clear - Removes all the items for the storage 
sessionStorage.clear()
localStorage.clear()


Length - Get the count of items in the storage
sessionStorage.length
localStorage.length


Code Example


To check whether local or session storage is supported


// Check for the browser supports session storage
if ("sessionStorage" in window && window["sessionStorage"] != null) {
    // Session storage supported
}

// Check for the browser supports local storage

if ("localStorage" in window && window["localStorage"] != null) {
    // Local storage supported
}


// Write to session storage
sessionStorage.setItem("language""en-us");
// Read from session storage
var sessValLang = sessionStorage.getItem("language");
// Removing session storage item
sessionStorage.removeItem("language");

// Write to local storage
localStorage.setItem("language""en-us");
// Read from local storage
var locValLang= localStorage.getItem("language");
// Removing local storage item
localStorage.removeItem("language");



Click here for the demo ...

P.S. This is my first post, please feel free to guide me or correct me for betterment ... Thanks in advance.