Tuesday, 18 April 2017

Understanding ASP.NET MVC Architecture

Introduction
This article is intended to provide basic concepts and fundamentals of ASP.NET MVC (Model View Controller) architecture workflow for beginners.

“M” “V” “C” stands for “MODEL” “VIEW” “CONTROLLER”. ASP.NET MVC is an architecture to develop ASP.NET web applications in a different manner than the traditional ASP.NET web development. Web applications developed with ASP.NET MVC are even more SEO (Search Engine) friendly.

Developing ASP.NET MVC application requires Microsoft .NET Framework 3.5 or higher.
MVC Interaction with Browser
Like a normal web server interaction, MVC application also accepts requests and responds to the web browser in the same way.

Inside MVC Architecture
The entire ASP.NET MVC architecture is based on Microsoft .NET Framework 3.5 and in addition uses LINQ to SQL Server.
What is a Model?
  1. MVC model is basically a C# or VB.NET class
  2. model is accessible by both controller and view
  3. model can be used to pass data from Controller to view
  4. view can use model to display data in page.

What is a View?
  1. View is an ASPX page without having a code behind file
  2. All page specific HTML generation and formatting can be done inside view
  3. One can use Inline code (server tags ) to develop dynamic pages
  4. A request to view (ASPX page) can be made only from a controller’s action method

What is a Controller?
  1. Controller is basically a C# or VB.NET class which inherits system.mvc.controller
  2. Controller is a heart of the entire MVC architecture
  3. Inside Controller’s class action methods can be implemented which are responsible for responding to browser OR calling views.
  4. Controller can access and use model class to pass data to views
  5. Controller uses ViewData to pass any data to view


MVC File Structure & File Naming Standards
MVC uses a standard directory structure and file naming standards which are a very important part of MVC application development.
Inside the ROOT directory of the application, there must be 3 directories each for model, view and Controller.
Apart from 3 directories, there must have a Global.asax file in root folder, and a web.config like a traditional ASP.NET application.
  • Root [directory]
  • Controller [directory]
    • Controller CS files
  • Models [directory]
    • Model CS files
  • Views [directory]
    • View aspx/ascx files
  • Global.asax
  • Web.config


ASP.NET MVC Execution Life Cycle
Here is how MVC architecture executes the requests to browser and objects interactions with each other.
A step by step process is explained below [Refer to the figure as given below]:

Browser Request (Step 1)
Browser request happens with a specific URL. Let’s assume that the user enters URL like: [portal.binarytitans.com]/home/index/
Job of Global.asax – MVC routing (Step 2)
The specified URL will first get parsed via application_start() method inside Global.asax file. From the requested URL, it will parse the Controller, Action and ID.
So for [portal.binarytitans.com]/home/index/:
Controller = home
Action = index()
ID = empty — we have not specified ID in [portal.binarytitans.com]/home/index/, so it will consider as empty string
·    
Controller and Action methods (Step 3)
MVC now finds the home controller class in controller directory. A controller class contains different action methods,
There can be more than one action method, but MVC will only invoke the action method which has been parsed from the URL, its index() in our case.
So something like: homeController.index() will happen inside MVC controller class.
Invoking action method can return plain text string OR rendered HTML by using view.
Call to View (Step 4)
Invoking view will return view(). A call to view will access the particular ASPX page inside the view directory and generate the rendered HTML from the ASPX and will respond back to the browser.
In our case, controller was home and action was index(). So calling view() will return a rendered HTML from the ASPX page located at /views/home/index.aspx.

This is it, the whole process ends here. So, this is how MVC architecture works.

Monday, 10 April 2017

C# - Multithreading

thread is defined as the execution path of a program. Each thread defines a unique flow of control. If your application involves complicated and time consuming operations, then it is often helpful to set different execution paths or threads, with each thread performing a particular job.
Threads are lightweight processes. One common example of use of thread is implementation of concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and increase efficiency of an application.
So far we wrote the programs where a single thread runs as a single process which is the running instance of the application. However, this way the application can perform one job at a time. To make it execute more than one task at a time, it could be divided into smaller threads.

Thread Life Cycle

The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends when the thread is terminated or completes execution.
Following are the various states in the life cycle of a thread:
  • The Unstarted State: It is the situation when the instance of the thread is created but the Start method is not called.
  • The Ready State: It is the situation when the thread is ready to run and waiting CPU cycle.
  • The Not Runnable State: A thread is not executable, when:
    • Sleep method has been called
    • Wait method has been called
    • Blocked by I/O operations
  • The Dead State: It is the situation when the thread completes execution or is aborted.

The Main Thread

In C#, the System.Threading.Thread class is used for working with threads. It allows creating and accessing individual threads in a multithreaded application. The first thread to be executed in a process is called the main thread.
When a C# program starts execution, the main thread is automatically created. The threads created using the Thread class are called the child threads of the main thread. You can access a thread using the CurrentThread property of the Thread class.
The following program demonstrates main thread execution:
using System;
using System.Threading;

namespace MultithreadingApplication
{
   class MainThreadProgram
   {
      static void Main(string[] args)
      {
         Thread th = Thread.CurrentThread;
         th.Name = "MainThread";
         Console.WriteLine("This is {0}", th.Name);
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces the following result:
This is MainThread

Properties and Methods of the Thread Class

The following table shows some most commonly used properties of the Thread class:
PropertyDescription
CurrentContextGets the current context in which the thread is executing.
CurrentCultureGets or sets the culture for the current thread.
CurrentPrincipleGets or sets the thread's current principal (for role-based security).
CurrentThreadGets the currently running thread.
CurrentUICultureGets or sets the current culture used by the Resource Manager to look up culture-specific resources at run-time.
ExecutionContextGets an ExecutionContext object that contains information about the various contexts of the current thread.
IsAliveGets a value indicating the execution status of the current thread.
IsBackgroundGets or sets a value indicating whether or not a thread is a background thread.
IsThreadPoolThreadGets a value indicating whether or not a thread belongs to the managed thread pool.
ManagedThreadIdGets a unique identifier for the current managed thread.
NameGets or sets the name of the thread.
PriorityGets or sets a value indicating the scheduling priority of a thread.
ThreadStateGets a value containing the states of the current thread.
The following table shows some of the most commonly used methods of the Thread class:
Sr.No.Methods
1public void Abort()
Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.
2public static LocalDataStoreSlot AllocateDataSlot()
Allocates an unnamed data slot on all the threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
3public static LocalDataStoreSlot AllocateNamedDataSlot(string name)
Allocates a named data slot on all threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
4public static void BeginCriticalRegion()
Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain.
5public static void BeginThreadAffinity()
Notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread.
6public static void EndCriticalRegion()
Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception are limited to the current task.
7public static void EndThreadAffinity()
Notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread.
8public static void FreeNamedDataSlot(string name)
Eliminates the association between a name and a slot, for all threads in the process. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
9public static Object GetData(LocalDataStoreSlot slot)
Retrieves the value from the specified slot on the current thread, within the current thread's current domain. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
10public static AppDomain GetDomain()
Returns the current domain in which the current thread is running.
11public static AppDomain GetDomain()
Returns a unique application domain identifier
12public static LocalDataStoreSlot GetNamedDataSlot(string name)
Looks up a named data slot. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
13public void Interrupt()
Interrupts a thread that is in the WaitSleepJoin thread state.
14public void Join()
Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping. This method has different overloaded forms.
15public static void MemoryBarrier()
Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier execute after memory accesses that follow the call to MemoryBarrier.
16public static void ResetAbort()
Cancels an Abort requested for the current thread.
17public static void SetData(LocalDataStoreSlot slot, Object data)
Sets the data in the specified slot on the currently running thread, for that thread's current domain. For better performance, use fields marked with the ThreadStaticAttribute attribute instead.
18public void Start()
Starts a thread.
19public static void Sleep(int millisecondsTimeout)
Makes the thread pause for a period of time.
20public static void SpinWait(int iterations)
Causes a thread to wait the number of times defined by the iterations parameter
21
public static byte VolatileRead(ref byte address)
public static double VolatileRead(ref double address)
public static int VolatileRead(ref int address)
public static Object VolatileRead(ref Object address)
Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache. This method has different overloaded forms. Only some are given above.
22
public static void VolatileWrite(ref byte address,byte value)
public static void VolatileWrite(ref double address, double value)
public static void VolatileWrite(ref int address, int value)
public static void VolatileWrite(ref Object address, Object value)
Writes a value to a field immediately, so that the value is visible to all processors in the computer. This method has different overloaded forms. Only some are given above.
23public static bool Yield()
Causes the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the thread to yield to.

Creating Threads

Threads are created by extending the Thread class. The extended Thread class then calls the Start() method to begin the child thread execution.
The following program demonstrates the concept:
using System;
using System.Threading;

namespace MultithreadingApplication
{
   class ThreadCreationProgram
   {
      public static void CallToChildThread()
      {
         Console.WriteLine("Child thread starts");
      }
      
      static void Main(string[] args)
      {
         ThreadStart childref = new ThreadStart(CallToChildThread);
         Console.WriteLine("In Main: Creating the Child thread");
         Thread childThread = new Thread(childref);
         childThread.Start();
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces the following result:
In Main: Creating the Child thread
Child thread starts

Managing Threads

The Thread class provides various methods for managing threads.
The following example demonstrates the use of the sleep() method for making a thread pause for a specific period of time.
using System;
using System.Threading;

namespace MultithreadingApplication
{
   class ThreadCreationProgram
   {
      public static void CallToChildThread()
      {
         Console.WriteLine("Child thread starts");
         
         // the thread is paused for 5000 milliseconds
         int sleepfor = 5000; 
         
         Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000);
         Thread.Sleep(sleepfor);
         Console.WriteLine("Child thread resumes");
      }
      
      static void Main(string[] args)
      {
         ThreadStart childref = new ThreadStart(CallToChildThread);
         Console.WriteLine("In Main: Creating the Child thread");
         Thread childThread = new Thread(childref);
         childThread.Start();
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces the following result:
In Main: Creating the Child thread
Child thread starts
Child Thread Paused for 5 seconds
Child thread resumes

Destroying Threads

The Abort() method is used for destroying threads.
The runtime aborts the thread by throwing a ThreadAbortException. This exception cannot be caught, the control is sent to the finally block, if any.
The following program illustrates this:
using System;
using System.Threading;

namespace MultithreadingApplication
{
   class ThreadCreationProgram
   {
      public static void CallToChildThread()
      {
         try
         {
            Console.WriteLine("Child thread starts");
            
            // do some work, like counting to 10
            for (int counter = 0; counter <= 10; counter++)
            {
               Thread.Sleep(500);
               Console.WriteLine(counter);
            }
            
            Console.WriteLine("Child Thread Completed");
         }
         
         catch (ThreadAbortException e)
         {
            Console.WriteLine("Thread Abort Exception");
         }
         finally
         {
            Console.WriteLine("Couldn't catch the Thread Exception");
         }
      }
      
      static void Main(string[] args)
      {
         ThreadStart childref = new ThreadStart(CallToChildThread);
         Console.WriteLine("In Main: Creating the Child thread");
         Thread childThread = new Thread(childref);
         childThread.Start();
         
         //stop the main thread for some time
         Thread.Sleep(2000);
         
         //now abort the child
         Console.WriteLine("In Main: Aborting the Child thread");
         
         childThread.Abort();
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces the following result:
In Main: Creating the Child thread
Child thread starts
0
1
2
In Main: Aborting the Child thread
Thread Abort Exception
Couldn't catch the Thread Exception