Friday, 19 December 2014

ASP.NET MVC - Part 1

Design Patterns
Design patterns are solutions to software design problems you find again and again in real-world application development. Patterns are about reusable designs and interactions of objects.
 A design pattern isn't a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.
Design patterns can speed up the development process by providing tested, proven development paradigms. Effective software design requires considering issues that may not become visible until later in the implementation. Reusing design patterns helps to prevent subtle issues that can cause major problems and improves code readability for coders and architects familiar with the patterns.
The 23 Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups:
¨  Creational,
¨  Structural, and
¨  Behavioral

Creational Design Patterns

These design patterns are all about class instantiation. This pattern can be further divided into class-creation patterns and object-creational patterns. While class-creation patterns use inheritance effectively in the instantiation process, object-creation patterns use delegation effectively to get the job done.

Abstract Factory
  Creates an instance of several families of classes
Builder
  Separates object construction from its representation
Factory Method
  Creates an instance of several derived classes
Prototype
  A fully initialized instance to be copied or cloned
Singleton
  A class of which only a single instance can exist


Structural Patterns

These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities.

  Adapter
  Match interfaces of different classes
  Bridge
  Separates an object’s interface from its implementation
  Composite
  A tree structure of simple and composite objects
  Decorator
  Add responsibilities to objects dynamically
  Facade
  A single class that represents an entire subsystem
  Flyweight
  A fine-grained instance used for efficient sharing
  Proxy
  An object representing another object

Behavioral Patterns
These design patterns are specifically concerned with communication between objects.  By doing so, these patterns increase flexibility in carrying out this communication.

  Chain of Resp.
  A way of passing a request between a chain of objects
  Command
  Encapsulate a command request as an object
  Interpreter
  A way to include language elements in a program
  Iterator
  Sequentially access the elements of a collection
  Mediator
  Defines simplified communication between classes
  Memento
  Capture and restore an object's internal state
  Observer
  A way of notifying change to a number of classes
  State
  Alter an object's behavior when its state changes
  Strategy
  Encapsulates an algorithm inside a class
  Template Method
  Defer the exact steps of an algorithm to a subclass
  Visitor
  Defines a new operation to a class without change


Architectural Patterns

An architectural style, sometimes called an architectural pattern, is a set of principles—a coarse grained pattern that provides an abstract framework for a family of systems. An architectural style improves partitioning and promotes design reuse by providing solutions to frequently recurring problems.

MVC
The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller.






¨  Model–view–controller (MVC) is a software architecture pattern
¨  Originally formulated in the late 1970s by Trygve Reenskaug as part of the Smalltalk
¨  Code reusability and separation of concerns
¨  Originally developed for desktop, then adapted for internet applications

  
Model
¨  Set of classes that describes the data we are working with as well as the business
¨  Rules for how the data can be changed and manipulated
¨  May contain data validation rules
¨  Often encapsulate data stored in a database as well as code used to manipulate the data
¨  Most likely a Data Access Layer of some kind
¨  Apart from giving the data objects, it doesn't have significance in the framework

View
¨  Defines how the application’s user interface (UI) will be displayed
¨  May support master views (layouts) and sub-views (partial views or controls)
¨  Web: Template to dynamically generate HTML

Controller
¨  The core MVC component
¨  Process the requests with the help of views and models
¨  A set of classes that handles
¤  Communication from the user
¤  Overall application flow
¤  Application-specific logic
¨  Every controller has one or more "Actions"


MVC Frameworks
PHP
Cake PHP, Code Igniter
Java
Spring
Perl
Catalyst, Dancer
Python
Django, Flask, Grok
Ruby
Ruby on Rails, Camping, Nitro, Sinatra
Java Script
Angular JS, JavaScript MVC, Spine
.NET Framework
ASP.NET MVC


  
The MVC Pattern for Web



¨  Incoming request routed to Controller
¤  For web: HTTP request
¨  Controller processes request and creates presentation Model
¤  Controller also selects appropriate result (view)
¨  Model is passed to View
¨  View transforms Model into appropriate output format (HTML)
¨  Response is rendered (HTTP Response)







Stage
Details
Receive first request for the application
In the Global.asax file, Route objects are added to the RouteTable object.
Perform routing
The UrlRoutingModule module uses the first matching Route object in theRouteTable collection to create the RouteData object, which it then uses to create aRequestContext (IHttpContext) object.
Create MVC request handler
The MvcRouteHandler object creates an instance of the MvcHandler class and passes it the RequestContext instance.
Create controller
The MvcHandler object uses the RequestContext instance to identify theIControllerFactory object (typically an instance of the DefaultControllerFactoryclass) to create the controller instance with.
Execute controller
The MvcHandler instance calls the controller s Execute method.
Invoke action
Most controllers inherit from the Controller base class. For controllers that do so, theControllerActionInvoker object that is associated with the controller determines which action method of the controller class to call, and then calls that method.
Execute result
A typical action method might receive user input, prepare the appropriate response data, and then execute the result by returning a result type. The built-in result types that can be executed include the following: ViewResult (which renders a view and is the most-often used result type), RedirectToRouteResult, RedirectResult,ContentResult, JsonResult, and EmptyResult.

Request Flow





ASP.NET Web Forms
ASP.NET MVC
Asp.Net Web Form follow a traditional event driven development model.
Asp.Net MVC is a lightweight and follow MVC (Model, View, Controller) pattern based development model.
Asp.Net Web Form has server controls.
Asp.Net MVC has html helpers.
Asp.Net Web Form supports view state for state management at client side.
Asp.Net MVC does not support view state.
Asp.Net Web Form has file-based URLs means file name exist in the URLs must have its physically existence.
Asp.Net MVC has route-based URLs means URLs are divided into controllers and actions and moreover it is based on controller not on physical file.
Asp.Net Web Form follows Web Forms Syntax
Asp.Net MVC follow customizable syntax (Razor as default)
In Asp.Net Web Form, Web Forms(ASPX) i.e. views are tightly coupled to Code behind(ASPX.CS) i.e. logic.
In Asp.Net MVC, Views and logic are kept separately.
Asp.Net Web Form has Master Pages for consistent look and feels.
Asp.Net MVC has Layouts for consistent look and feels.
Asp.Net Web Form has User Controls for code re-usability.
Asp.Net MVC has Partial Views for code re-usability.
Asp.Net Web Form has built-in data controls and best for rapid development with powerful data access.
Asp.Net MVC is lightweight, provide full control over markup and support many features that allow fast & agile development. Hence it is best for developing interactive web application with latest web standards.
Asp.Net Web Form is not Open Source.
Asp.Net Web MVC is an Open Source.



ASP.NET MVC Features

¨  Runs on top of ASP.NET
¤  Not a replacement for WebForms
¤  Leverage the benefits of ASP.NET
¨  Embrace the web
¤  User/SEO friendly URLs, HTML 5, SPA
¤  Adopt REST concepts
¨  Uses MVC pattern
¤  Conventions and Guidance
¤  Separation of concerns
¨  Tight control over markup
¨  Testable
¨  Loosely coupled and extensible
¨  Convention over configuration
¨  Razor view engine
¤  One of the greatest view engines
¤  With intellisense, integrated in Visual Studio
¨  Reuse of current skills (C#, LINQ, HTML, etc.)
¨  Application-based (not scripts like PHP)

  
Separation of Concerns

¨  Each component has one responsibility
¤  SRP – Single Responsibility Principle
¤  DRY – Don’t Repeat Yourself
¨  More easily testable
¤  TDD – Test-driven development
¨  Helps with concurrent development
¤  Performing tasks concurrently
n  One developer works on views
n  Another works on controllers

Extensible

¨  Replace any component of the system
¤  Interface-based architecture
¨  Almost anything can be replaced or extended
¤  Model binders (request data to CLR objects)
¤  Action/result filters (e.g. OnActionExecuting)
¤  Custom action result types
¤  View engine (Razor, WebForms, NHaml, Spark)
¤  View helpers (HTML, AJAX, URL, etc.)
¤  Custom data providers (ADO.NET), etc.
  
Clean URL’s

¨  REST-like
¤  /products/update
¤  /blog/posts/2014/11/28/mvc-is-cool
¨  Friendlier to humans
¤  /product.aspx?catId=123 or post.php?id=123
¤  Becomes /products/chocolate/
¨  Friendlier to web crawlers
¤  Search engine optimization (SEO)

ASP.NET MVC Release History
Date
Version
10 December 2007
ASP.NET MVC 
13 March 2009
ASP.NET MVC 1.0
16 December 2009
ASP.NET MVC 2 RC
4 February 2010
ASP.NET MVC 2 RC 2
10 March 2010
ASP.NET MVC 2
6 October 2010
ASP.NET MVC 3 Beta
9 November 2010
ASP.NET MVC 3 RC
10 December 2010
ASP.NET MVC 3 RC 2
13 January 2011
ASP.NET MVC 3
20 September 2011
ASP.NET MVC 4 Developer Preview
15 February 2012
ASP.NET MVC 4 Beta
31 May 2012
ASP.NET MVC 4 RC
15 August 2012
ASP.NET MVC 4
30 May 2013
ASP.NET MVC 4 4.0.30506.0 
26 June 2013
ASP.NET MVC 5 Preview 
23 August 2013
ASP.NET MVC 5 RC 1
17 October 2013
ASP.NET MVC 5
17 January 2014
ASP.NET MVC 5.1
10 February 2014
ASP.NET MVC 5.1.1
4 April 2014
ASP.NET MVC 5.1.2
22 June 2014
ASP.NET MVC 5.1.3
1 July 2014
ASP.NET MVC 5.2.0
28 August 2014
ASP.NET MVC 5.2.2

What’s new in MVC 4?
¨  ASP.NET Web API
¨  Refreshed and modernized default project templates
¨  New mobile project template
¨  Many new features to support mobile apps
¨  Enhanced support for asynchronous methods

What’s new in MVC 5?


  
What’s new in MVC 6?


Rebuilt from the Ground Up

¨  MVC, Web API, and Web Pages are merged into one framework, called MVC 6. The new framework uses a common set of abstractions for routing, action selection, filters, model binding, and so on.
¨  Dependency injection is built into the framework. Use your preferred IoC container to register dependencies.
¨  vNext is host agnostic. You can host your app in IIS, or self-host in a custom process. (Web API 2 and SignalR 2 already support self-hosting; vNext brings this same capability to MVC.)
¨  vNext is open source and cross platform.

Leaner, Faster

¨  MVC 6 has no dependency on System.Web.dll. The result is a leaner framework, with faster startup time and lower memory consumption.
¨  vNext apps can use a cloud-optimized runtime and subset of the .NET Framework. This subset of the framework is about 11 megabytes in size compared to 200 megabytes for the full framework, and is composed of a collection of NuGet packages.
¨  Because the cloud-optimized framework is a collection of NuGet packages, your app can include only the packages you actually need. No unnecessary memory, disk space, loading time, etc.
¨  Microsoft can deliver updates to the framework on a faster cadence, because each part can be updated independently.

True Side-by-Side Deployment

¨  The reduced footprint of the cloud-optimized runtime makes it practical to deploy the framework with your app.
¨  You can run apps side-by-side with different versions of the framework on the same server.
¨  Your apps are insulated from framework changes on the server.
¨  You can make framework updates for each app on its own schedule.
¨  No errors when you deploy to production resulting from a mismatch between the framework patch level on the development machine and the production server.

 New Development Experience

¨  vNext uses the Roslyn compiler to compile code dynamically.
¨  You can edit a code file, refresh the browser, and see the changes without rebuilding the project.
¨  Besides streamlining the development process, dynamic code compilation enables development scenarios that were not possible before, such as editing code on the server using Visual Studio Online (“Monaco”).
¨  You can choose your own editors and tools.







Tuesday, 18 November 2014

MultiThreading in C#

Thread Synchronization Sample 


using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;

// The thread synchronization events are encapsulated in this
// class to allow them to easily be passed to the Consumer and
// Producer classes.
public class SyncEvents
{
    public SyncEvents()
    {
        // AutoResetEvent is used for the "new item" event because
        // we want this event to reset automatically each time the
        // consumer thread responds to this event.
        _newItemEvent = new AutoResetEvent(false);

        // ManualResetEvent is used for the "exit" event because
        // we want multiple threads to respond when this event is
        // signaled. If we used AutoResetEvent instead, the event
        // object would revert to a non-signaled state with after
        // a single thread responded, and the other thread would
        // fail to terminate.
        _exitThreadEvent = new ManualResetEvent(false);

        // The two events are placed in a WaitHandle array as well so
        // that the consumer thread can block on both events using
        // the WaitAny method.
        _eventArray = new WaitHandle[2];
        _eventArray[0] = _newItemEvent;
        _eventArray[1] = _exitThreadEvent;
    }

    // Public properties allow safe access to the events.
    public EventWaitHandle ExitThreadEvent
    {
        get { return _exitThreadEvent; }
    }
    public EventWaitHandle NewItemEvent
    {
        get { return _newItemEvent; }
    }
    public WaitHandle[] EventArray
    {
        get { return _eventArray; }
    }

    private EventWaitHandle _newItemEvent;
    private EventWaitHandle _exitThreadEvent;
    private WaitHandle[] _eventArray;
}

// The Producer class asynchronously (using a worker thread)
// adds items to the queue until there are 20 items.
public class Producer
{
    public Producer(Queue<int> q, SyncEvents e)
    {
        _queue = q;
        _syncEvents = e;
    }
    public void ThreadRun()
    {
        int count = 0;
        Random r = new Random();
        while (!_syncEvents.ExitThreadEvent.WaitOne(0, false))
        {
            lock (((ICollection)_queue).SyncRoot)
            {
                while (_queue.Count < 20)
                {
                    _queue.Enqueue(r.Next(0, 100));
                    _syncEvents.NewItemEvent.Set();
                    count++;
                }
            }
        }
        Console.WriteLine("Producer thread: produced {0} items", count);
    }
    private Queue<int> _queue;
    private SyncEvents _syncEvents;
}

// The Consumer class uses its own worker thread to consume items
// in the queue. The Producer class notifies the Consumer class
// of new items with the NewItemEvent.
public class Consumer
{
    public Consumer(Queue<int> q, SyncEvents e)
    {
        _queue = q;
        _syncEvents = e;
    }
    public void ThreadRun()
    {
        int count = 0;
        while (WaitHandle.WaitAny(_syncEvents.EventArray) != 1)
        {
            lock (((ICollection)_queue).SyncRoot)
            {
                int item = _queue.Dequeue();
            }
            count++;
        }
        Console.WriteLine("Consumer Thread: consumed {0} items", count);
    }
    private Queue<int> _queue;
    private SyncEvents _syncEvents;
}

public class ThreadSyncSample
{
    private static void ShowQueueContents(Queue<int> q)
    {
        // Enumerating a collection is inherently not thread-safe,
        // so it is imperative that the collection be locked throughout
        // the enumeration to prevent the consumer and producer threads
        // from modifying the contents. (This method is called by the
        // primary thread only.)
        lock (((ICollection)q).SyncRoot)
        {
            foreach (int i in q)
            {
                Console.Write("{0} ", i);
            }
        }
        Console.WriteLine();
    }

    static void Main()
    {
        // Configure struct containing event information required
        // for thread synchronization.
        SyncEvents syncEvents = new SyncEvents();

        // Generic Queue collection is used to store items to be
        // produced and consumed. In this case 'int' is used.
        Queue<int> queue = new Queue<int>();

        // Create objects, one to produce items, and one to
        // consume. The queue and the thread synchronization
        // events are passed to both objects.
        Console.WriteLine("Configuring worker threads...");
        Producer producer = new Producer(queue, syncEvents);
        Consumer consumer = new Consumer(queue, syncEvents);

        // Create the thread objects for producer and consumer
        // objects. This step does not create or launch the
        // actual threads.
        Thread producerThread = new Thread(producer.ThreadRun);
        Thread consumerThread = new Thread(consumer.ThreadRun);

        // Create and launch both threads.  
        Console.WriteLine("Launching producer and consumer threads...");      
        producerThread.Start();
        consumerThread.Start();

        // Let producer and consumer threads run for 10 seconds.
        // Use the primary thread (the thread executing this method)
        // to display the queue contents every 2.5 seconds.
        for (int i = 0; i < 4; i++)
        {
            Thread.Sleep(2500);
            ShowQueueContents(queue);
        }

        // Signal both consumer and producer thread to terminate.
        // Both threads will respond because ExitThreadEvent is a
        // manual-reset event--so it stays 'set' unless explicitly reset.
        Console.WriteLine("Signaling threads to terminate...");
        syncEvents.ExitThreadEvent.Set();

        // Use Join to block primary thread, first until the producer thread
        // terminates, then until the consumer thread terminates.
        Console.WriteLine("main thread waiting for threads to finish...");
        producerThread.Join();
        consumerThread.Join();
    }
}

Thread Start - Stop Sample

using System;
using System.Threading;

public class Worker
{
    // This method will be called when the thread is started.
    public void DoWork()
    {
        while (!_shouldStop)
        {
            Console.WriteLine("worker thread: working...");
        }
        Console.WriteLine("worker thread: terminating gracefully.");
    }
    public void RequestStop()
    {
        _shouldStop = true;
    }
    // Volatile is used as hint to the compiler that this data
    // member will be accessed by multiple threads.
    private volatile bool _shouldStop;
}

public class WorkerThreadExample
{
    static void Main()
    {
        // Create the thread object. This does not start the thread.
        Worker workerObject = new Worker();
        Thread workerThread = new Thread(workerObject.DoWork);

        // Start the worker thread.
        workerThread.Start();
        Console.WriteLine("main thread: Starting worker thread...");

        // Loop until worker thread activates.
        while (!workerThread.IsAlive);

        // Put the main thread to sleep for 1 millisecond to
        // allow the worker thread to do some work:
        Thread.Sleep(1);

        // Request that the worker thread stop itself:
        workerObject.RequestStop();

        // Use the Join method to block the current thread 
        // until the object's thread terminates.
        workerThread.Join();
        Console.WriteLine("main thread: Worker thread has terminated.");
    }
}


Simple Timer Using Thread


using System;
using System.Threading;

public class Test
{
    static void Main()
    {
        Console.WriteLine ("Started at {0:HH:mm:ss.fff}", DateTime.Now);
        // Start in three seconds, then fire every one second
        using (Timer timer = new Timer(new TimerCallback(Tick), null, 3000, 1000))
        {
     
            // Wait for 10 seconds
            Thread.Sleep(10000);
         
            // Then go slow for another 10 seconds
            timer.Change (0, 2000);
            Thread.Sleep(10000);
        }
     
        // The timer will now have been disposed automatically due to the using
        // statement, so there won't be any other threads running, and we'll quit.
    }  
 
    static void Tick(object state)
    {
        Console.WriteLine ("Ticked at {0:HH:mm:ss.fff}", DateTime.Now);
    }
}


Dead Lock Sample


using System;
using System.Threading;

public class Test
{
    static readonly object firstLock = new object();
    static readonly object secondLock = new object();
   
    static void Main()
    {
        new Thread(new ThreadStart(ThreadJob)).Start();
       
        // Wait until we're fairly sure the other thread
        // has grabbed firstLock
        Thread.Sleep(500);
       
        Console.WriteLine ("Locking secondLock");
        lock (secondLock)
        {
            Console.WriteLine ("Locked secondLock");
            Console.WriteLine ("Locking firstLock");
            lock (firstLock)
            {
                Console.WriteLine ("Locked firstLock");
            }
            Console.WriteLine ("Released firstLock");
        }
        Console.WriteLine("Released secondLock");
    }
   
    static void ThreadJob()
    {
        Console.WriteLine ("\t\t\t\tLocking firstLock");
        lock (firstLock)
        {
            Console.WriteLine("\t\t\t\tLocked firstLock");
            // Wait until we're fairly sure the first thread
            // has grabbed secondLock
            Thread.Sleep(1000);
            Console.WriteLine("\t\t\t\tLocking secondLock");
            lock (secondLock)
            {
                Console.WriteLine("\t\t\t\tLocked secondLock");
            }
            Console.WriteLine ("\t\t\t\tReleased secondLock");
        }
        Console.WriteLine("\t\t\t\tReleased firstLock");
    }
}


Monitoring Threads Sample


using System;
using System.Collections;
using System.Threading;

public class Test
{
    static ProducerConsumer queue;
   
    static void Main()
    {
        queue = new ProducerConsumer();
        new Thread(new ThreadStart(ConsumerJob)).Start();
       
        Random rng = new Random(0);
        for (int i=0; i < 10; i++)
        {
            Console.WriteLine ("Producing {0}", i);
            queue.Produce(i);
            Thread.Sleep(rng.Next(1000));
        }
    }
   
    static void ConsumerJob()
    {
        // Make sure we get a different random seed from the
        // first thread
        Random rng = new Random(1);
        // We happen to know we've only got 10
        // items to receive
        for (int i=0; i < 10; i++)
        {
            object o = queue.Consume();
            Console.WriteLine ("\t\t\t\tConsuming {0}", o);
            Thread.Sleep(rng.Next(1000));
        }
    }
}

public class ProducerConsumer
{
    readonly object listLock = new object();
    Queue queue = new Queue();

    public void Produce(object o)
    {
        lock (listLock)
        {
            queue.Enqueue(o);

            // We always need to pulse, even if the queue wasn't
            // empty before. Otherwise, if we add several items
            // in quick succession, we may only pulse once, waking
            // a single thread up, even if there are multiple threads
            // waiting for items.          
            Monitor.Pulse(listLock);
        }
    }
   
    public object Consume()
    {
        lock (listLock)
        {
            // If the queue is empty, wait for an item to be added
            // Note that this is a while loop, as we may be pulsed
            // but not wake up before another thread has come in and
            // consumed the newly added object. In that case, we'll
            // have to wait for another pulse.
            while (queue.Count==0)
            {
                // This releases listLock, only reacquiring it
                // after being woken up by a call to Pulse
                Monitor.Wait(listLock);
            }
            return queue.Dequeue();
        }
    }
}