Saturday, August 23, 2014

ASP.NET MVC3 Vs MVC4 Vs MVC5

ASP.NET MVC 3

  • New Project Templates having support for HTML 5 and CSS 3.
  • Improved Model validation.
  • Razor View Engine introduced with a bundle of new features.
  • Having support for Multiple View Engines i.e. Web Forms view engine, Razor or open source.
  • Controller improvements like ViewBag property and ActionResults Types etc.
  • Unobtrusive JavaScript approach.
  • Improved Dependency Injection with new IDependencyResolver.
  • Partial page output caching.

ASP.NET MVC 4

  • ASP.NET Web API, a framework that simplifies the creation of HTTP services and serving a wide range of clients. Follow to create your first ASP.NET Web API service.
  • Adaptive rendering and other look-n-feel improvements to Default Project Templates.
  • A truly Empty Project Template.
  • Based on jQuery Mobile, new Mobile Project Template introduced.
  • Support for adding controller to other project folders also.
  • Task Support for Asynchronous Controllers.
  • Controlling Bundling and Minification through web.config.
  • Support for OAuth and OpenID logins using DotNetOpenAuth library.
  • Support for Windows Azure SDK 1.6 and new releases.

ASP.NET MVC 5

Creating your first ASP.NET MVC 5 Application in 4 simple steps
  • Bootstrap replaced the default MVC template.
  • ASP.NET Identity for authentication and identity management.
  • Authentication Filters for authenticating user by custom or third-party authentication provider.
  • With the help of Filter overrides, we can now override filters on a method or controller.
  • Attribute Routing is now integrated into MVC 5.
 

Singleton Pattern

In this blog post, I will try to create an example demonstrating the usage of singleton pattern.
When:

  • for situations where you only need one and only one object to exist
  • class needs to be accessible to clients
  • class should not require any parameters for its object creation
  • if creating an object is expensive, singleton can be useful
How:
In this example, we will try to create a LoadBalancer. LoadBalancer monitors the memory, processor resources etc and then decides which server to assign a particular task to. We won't create all those details as they are not necessary for this demonstration. Instead, we will use the C# Random class to make that decision. Why we need singleton pattern in this case? Because we don't want multiple instances of LoadBalancer. There should only be one LoadBalancer who makes the decision about multiple servers. Let's take a look at the consumer code first:

static void Main(string[] args)
        {
            SingletonPatternExample();

            Console.ReadLine();
        }

        private static void SingletonPatternExample()
        {
            for (int i = 0; i < 20; i++)
            {
                LoadBalancer lb = LoadBalancer.GetLoadBalancer();
                Console.WriteLine("Task " + i + " is assigned to " + lb.Server);
                System.Threading.Thread.Sleep(1000);
            }
        }
In this code, I just have a simple for loop to imitate tasks coming in. For every task, we get the LoadBalancer object and assign the Server to it randomly. For this example, you can argue that we could have achieved the same result by declaring the LoadBalancer object outside the for loop. That is true, but that is not the point of this demo. The point here is that singleton pattern is proactively stopping any new instances being created. Let's take a look at the LoadBalancer class now.

sealed class LoadBalancer
    {
        // Static members are lazily initialized. 
        // .NET guarantees thread safety for static initialization 
        private static readonly LoadBalancer instance = new LoadBalancer();

        private ArrayList servers = new ArrayList();
        private Random random = new Random();

        // Note: constructor is private.
        private LoadBalancer()
        {
            // List of available servers 
            servers.Add("Server 1");
            servers.Add("Server 2");
            servers.Add("Server 3");
            servers.Add("Server 4");
            servers.Add("Server 5");
        }

        public static LoadBalancer GetLoadBalancer()
        {
            return instance;
        }

        // Simple, but effective load balancer 
        public string Server
        {
            get
            {
                int r = random.Next(servers.Count);
                return servers[r].ToString();
            }
        }
    } 
The class is sealed so that it can not be inherited. Then we define a LoadBalancer instance as private and as static. If you don't define it a static then its not thread-safe. The class also has an ArrayList of servers and a Random object. The class also has a private constructor which just adds the servers to the ArrayList. Private constructor makes sure that class can not be initialized outside the scope. The GetLoadBalancer() method returns the one and only instance. There is no other way to get hold of this instance. And lastly, the simple Server property does the main work of finding out a Server and then notifying it to the caller.
Here are the results:

Factory Pattern

In this blog post, I will try to create a simple program which will demonstrate the utility and significance of the factory pattern.
When:

  • when many classes are implementing an interface and you are unsure about which concrete implementation to return
  • when you want to separate creation logic from the object's main goal like when creating an object if you want to assign values to many properties and you want to separate this kinda logic from object's main functionality
  • if there are many if-else or switch statements for deciding which object to create
Why:
  • to encapsulate the creation of object
  • to separate the creation of object from the decision about which object to create
  • to allow adding new objects without breaking open closed principle (classes should be open for extension, closed for modification)
  • to allow (if needed) storing which objects to create in a separate place like database or configuration
How:
Let's create an example to see how factory pattern works. Let's say that we have a consumer which wants to perform search. The consumer doesn't care about which actual search engine does the search, as long as it can perform the search. From a factory perspective, we have multiple search providers and we want some kind of configuration to switch the providers. Let's take a look at the consumer code first.
class Program
{
        static void Main(string[] args)
        {
            ISearchEngineFactory factory = LoadFactory();

            ISearchEngine engine = factory.CreateMapSearchEngine();
            engine.Search();

            engine = factory.CreateNormalSearchEngine();
            engine.Search();

            Console.ReadLine();
        }

        private static ISearchEngineFactory LoadFactory()
        {
            string factoryName = Properties.Settings.Default.SearchFactory;
            return Assembly.GetExecutingAssembly().CreateInstance(factoryName) as ISearchEngineFactory;
        }
    }
In this code, first we create a factory by calling the LoadFactory() method. This method looks into the settings file to see which factory to load and then by using reflection creates an instance of that factory. The ISearchEngineFactory defines two methods as shown below: one for normal search and the other for map search.
public interface ISearchEngineFactory
{
        ISearchEngine CreateNormalSearchEngine();

        ISearchEngine CreateMapSearchEngine();
    }
In this example, we are defining two search engines: Google and Bing. So, first up, we create 2 factories for them as shown below:
public class GoogleFactory : ISearchEngineFactory
{
        public ISearchEngine CreateNormalSearchEngine()
        {
            return new Google() as ISearchEngine;
        }

        public ISearchEngine CreateMapSearchEngine()
        {
            Google g = new Google {Context = "Maps"};
            return g as ISearchEngine;
        }
    }
public class BingFactory : ISearchEngineFactory
{
        public ISearchEngine CreateNormalSearchEngine()
        {
            return new Bing() as ISearchEngine;
        }

        public ISearchEngine CreateMapSearchEngine()
        {
            return new BingMaps() as ISearchEngine;
        }
    }
In this example, we are also demonstrating, how the actual object creation can be different. The Bing engine returns Bing object for normal searches and BingMaps object for map searches. The Google engine for normal search, just returns the Google object with context as null. For maps search, it returns the normal google object with Context set as "Maps". All of these engines, implement the ISearchEngine interface which has a Search method and a context property as shown below.
public interface ISearchEngine
{
        void Search();

        string Context { get; set; }
    }
public class Bing : ISearchEngine
{
        public void Search()
        {
            Console.WriteLine("You searched on Bing");
        }

        public string Context { get; set; }

    }
public class BingMaps : ISearchEngine
{
        public void Search()
        {
            Console.WriteLine("You searched on Bing Maps");
        }

        public string Context { get; set; }
    }
public class Google : ISearchEngine
{
        public void Search()
        {
            string str = "You searched on Google";

            if (string.IsNullOrEmpty(Context))
                Console.WriteLine(str);
            else
                Console.WriteLine(str + " " + Context);
        }

        public string Context { get; set; }
    }
When you run this app, with search provider set as Google, you see the following output.



And if you go to settings page and change the settings configuration to use Bing as the search provider, the output is as below:




Once we have set up the factory pattern in our code, we can easily add newer factories and newer search engine classes without affecting any of the other classes, hence respecting the Open-Closed principle. Once that is done, you can easily change the configuration to point to say Yahoo factory and the factory pattern will take care of correct object creations.

LINQ Examples

In this blog, I will try to create samples of LINQ extension methods which are very helpful in accomplishing things which earlier would take 10-15 lines (or more) of code and were difficult to manage as well as to understand. I will also try to keep this blog as a running list of good LINQ extension methods.
First up, let's see the whole code listing. For my data, I have created a simple SportsPerson class and have populated with arbitrary values.

public class A07LinqExamples
    {
        public static void Run()
        {
            ToLookupExample();

            ToDictionaryExample();
        }

        private static void ToDictionaryExample()
        {
            Console.WriteLine("\n---------ToDictionaryExample-----------------");
            var sportsPersons = LoadSportsPerson();

            // get a dictionary with id as id and value as SportsPerson
            var sportsPersonDict = sportsPersons.ToDictionary(sp => sp.Id, sp => sp);

            // get sportsperson with id 8
            var val = sportsPersonDict[8];
            Console.WriteLine(val.Name + "(" + val.Sport + ")");
        }

        public static void ToLookupExample()
        {
            Console.WriteLine("\n---------ToLookupExample-----------------");
            var sportsPersons = LoadSportsPerson();

            // get a lookup with id as sport and value as list of SportsPerson
            var sportsPersonsCategorized = sportsPersons.ToLookup(sp => sp.Sport, sp => sp);

            // get all sportsperson who play cricket
            foreach (var lkup in sportsPersonsCategorized["Cricket"])
                Console.WriteLine(lkup.Name);
        }

        private static IEnumerable LoadSportsPerson()
        {
            return new List()
                       {
                           new SportsPerson() {Id = 1, Name = "Sachin Tendulkar", Sport = "Cricket"},
                           new SportsPerson() {Id = 10, Name = "Roger Federer", Sport = "Tennis"},
                           new SportsPerson() {Id = 8, Name = "Rafael Nadal", Sport = "Tennis"},
                           new SportsPerson() {Id = 6, Name = "Pete Sampras", Sport = "Tennis"},
                           new SportsPerson() {Id = 5, Name = "Andre Agassi", Sport = "Tennis"},
                           new SportsPerson() {Id = 4, Name = "Brian Lara", Sport = "Cricket"},
                           new SportsPerson() {Id = 7, Name = "Glenn McGrath", Sport = "Cricket"},
                           new SportsPerson() {Id = 3, Name = "Michael Jordan", Sport = "Basketball"},
                           new SportsPerson() {Id = 9, Name = "Magic Johnson", Sport = "Basketball"},
                           new SportsPerson() {Id = 2, Name = "Steve Nash", Sport = "Basketball"}
                       };
        }
    }

    public class SportsPerson
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Sport { get; set; }
    }
ToDictionary
ToDictionary creates a key-value pair from an IEnumerable where all the keys have to be unique. The inputs that you have to provide are obviously the key and the value.

ToLookup
Many a times there is a need to create a lookup structure with some kind of grouping. For example, in our case, we want all sports persons to be categorized based on the sports they play. Lookup provides a simple key-value pair approach where the key can be the sports category and value can be all the sportsperson that belong to that sport. This is very different than dictionary. In a dictionary the key has to be unique. In Lookup keys can be the same.

Result

Simple jQuery getJSON Example in ASP.NET MVC

In this post, I will create a very basic and simple example demonstrating jQuery's getJSON method using ASP.NET MVC.

First up, I create an empty MVC project with one Controller. The code for this controller is shown below. For simplicity, the data model is also stored here and we create the data on fly. In a production application, this will be separated using multiple layers and the data, of course, would come from the database.
public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetJsonData()
        {
            var persons = new List
                              {
                                  new Person{Id = 1, FirstName = "F1", 
                                      LastName = "L1", 
                                      Addresses = new List
{ new Address{Line1 = "LaneA"}, new Address{Line1 = "LaneB"} }}, new Person{Id = 2, FirstName = "F2", LastName = "L2", Addresses = new List
{ new Address{Line1 = "LaneC"}, new Address{Line1 = "LaneD"} }}}; return Json(persons, JsonRequestBehavior.AllowGet); } } public class Person { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public List
Addresses { get; set; } } public class Address { public string Line1 { get; set; } public string Line2 { get; set; } public string ZipCode { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } }
This controller has just 2 actions. The Index action has a view associated with it and that view contains a button which will fire a JSON request. That request would be handled by the GetJsonData action method. As you can see, our data model is pretty simple and it contains a list of persons and each person can have multiple addresses.
The Index view contains just a button and an empty div tag in the beginning. The javascript code block contains the click handler for this button. When this button is clicked, we use the getJSON method to call the GetJsonData action. Once this data is returned we use the .each() jQuery method to loop through each person and then through each address and append some of their properties to the div tag. Code for Index view and the output when we click on the button is shown below.
<input id="btnGetPersons" type="button" value="Get Persons" />
<div>
    <div id="ajaxDiv">
    </div>
</div>
<script type="text/javascript">
    $(document).ready(function () {
        $('#btnGetPersons').click(function () {
            $.getJSON("/Home/GetJsonData", null, function (data) {
                var div = $('#ajaxDiv');
                div.html("
 " + "Persons received from server: " + "
");
                $.each(data, function (i, item) {
                    printPerson(div, item);
                });
            });
        });
    });

    function printPerson(div, item) {
        div.append("
" + "FName: " + item.FirstName + ", LName: " + item.LastName);
        $.each(item.Addresses, function (i, addr) {
            printAddress(div, addr);
        });
    }

    function printAddress(div, item) {
        div.append("
" + "   " + "Line1: " + item.Line1);
    }
</script>
The output looks like:
In the getJSON method we can pass parameters as well. For ex, if we had to pass the number of persons to retrieve, we could have passed something like {count:"5"} instead of null and then in the action method we could have changed the GetJsonData() method to GetJsonData(int count).

jQuery AutoComplete by Example in ASP.NET

This article helps you to create AutoComplete textbox using jQuery library. This will also give you details about jQuery AutoComplete UI, CSS and select event.
In this example you will create a ASP.NET Web Form application which will connect to Northwind database.  The AutoComplete TextBox's change event will call PageMethod written in WebForm code behind file. This method will get country names from Customer table and return as suggestion for AutoComplete TextBox.

jQuery AutoComplete Widget

jQuery AutoComplete Widget gives pre-populated list of suggestions as user types in input field. You need to provide array of strings as source to this widget. Array can be created by some static values or get values from database. Also you can mention minLength to specify after how many characters input call for suggestions to be made.

Implement jQuery AutoComplete

  1. jQuery.Ajax() with PageMethod

     It has a DropDownList control to display Country and a Table object to display Customer details of selected country. On change event of DropDownList control customer detail will be read from database using jQuery.Ajax() call and append as row to Table object.
    In this article we will add a TextBox control which will be AutoComplete to suggest countries and replace functionality of existing DropDownList control.
  2. TextBox with AutoComplete

    Open Default.aspx page and add a TextBox control. Name it as txtCountry. Whenever user types some characters in txtCountry it will make jQuery.Ajax() to Northwind database and select related Country names which will be associated as source for AutoComplete widget.
        
        
  3. WebMethod for GetCountryNames

    The method GetCountryNames is a WebMetod meaning that it can be called from client side script code like JavaScript. It accepts parameter keyword and get Country names which contains specific keyword from database. Those country names will be return as array of string to AutoComplete widget.

    Add below code in Default.aspx.cs file
        [WebMethod]
        public static string[] GetCountryNames(string keyword)
        {
            List country = new List();  
            string query = string.Format("SELECT DISTINCT Country FROM 
                    Customers WHERE Country LIKE '%{0}%'", keyword);
    
            using (SqlConnection con =
                    new SqlConnection("your connection string"))
            {
                using (SqlCommand cmd = new SqlCommand(query, con))
                {
                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
    
                    while (reader.Read())
                    {
                        country.Add(reader.GetString(0));    
                    }
                }
            }
            return country.ToArray();
        }
         
         
  4. TextBox Autocomplete event

    AutoComplete widget has many properties which you can use to customize your execution and control look and feel.
    For this tutorial we will use Source, minLength and Select event.
    From Solution Explorer -> Scripts folder open Customer.js. It contains a jQuery method for getting customer from Database and append customer details to Table object.
    below jQuery code to Customer.js file.
     $("#MainContent_txtCountry").autocomplete({
        source: function (request, response) {
        var param = { keyword: $('#MainContent_txtCountry').val() };
        $.ajax({
            url: "Default.aspx/GetCountryNames",
            data: JSON.stringify(param),
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataFilter: function (data) { return data; },
            success: function (data) {
                response($.map(data.d, function (item) {
                    return {
                        value: item
                    }
                }))
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
        },
        select: function (event, ui) {
            if (ui.item) {
                GetCustomerDetails(ui.item.value);
            }
        },
        minLength: 2
    });         
                
    We have added Source method which makes a call to GetCountryNames PageMethod written in code behind file. The return values from method shown as pre populated suggestions for user.
    We mentioned minLength as 2, it means when ever user enter 2 character in TextBox the AutoComplete method will fire and get its source data.
    Select event gives you selected value by user. The value can be read by ui.item.value
  5. jQuery AutoComplete Select Event

    In this step we will use selected value by user and perform required operation.

    For this tutorial you are going to make another jQuery.Ajax() call and get customer details who belongs to selected country.

    In Previous step we mention that on selection of value from pre populated list of AutoComplete TextBox we will call jQuery GetCustomerDetails function. It takes Country name as input parameter, make ajax call to WebMethod get Customer details and render in table object. 
         
  1. Add below GetCustomerDetails function in Customer.js
    function GetCustomerDetails(country) {
        
    $("#tblCustomers tbody tr").remove();
    
    $.ajax({
        type: "POST",
        url: "Default.aspx/GetCustomers",
        data: '{country: "' + country + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
        response($.map(data.d, function (item) {
            var rows = "
    "
                + "" + item.CustomerID + ""
                + "" + item.CompanyName + ""
                + "" + item.ContactName + ""
                + "" + item.ContactTitle + ""
                + "" + item.City + ""
                + "" + item.Phone + ""
                + "
    ";
            $('#tblCustomers tbody').append(rows);
        }))
        },
        failure: function (response) {
            alert(response.d);
        }
    });
    }
    
    GetCustomers PageMethod already written in Default.aspx.cs file.
  2. jQuery AutoComplete ui

    You will have to include required jQuery and css files. jQuery AutoComplete UI provides those files, using it your TextBox will perform autocomplete and render suggestions for user.
    Add reference to those files in Site.Master file.
    
    
    
        
      
    
     
    
         
          
    

jQuery AutoComplete by example in asp.net