ASP.Net Application and Page Life Cycle

In this article, we will try to understand what the different events are which take place right from the time the user sends a request, until the time the request is rendered on the browser. So we will first try to understand the two broader steps of an ASP.NET request and then we will move into different events emitted from ‘HttpHandler’, ‘HttpModule’ and ASP.NET page object. As we move in this event journey, we will try to understand what kind of logic should go in each and every one of these events.

The Two Step Process

From 30,000 feet level, ASP.NET request processing is a 2 step process as shown below. User sends a request to the IIS:

ASP.NET creates an environment which can process the request. In other words, it creates the application object, request, response and context objects to process the request.

Once the environment is created, the request is processed through a series of events which is processed by using modules, handlers and page objects. To keep it short, let’s name this step as MHPM (Module, handler, page and Module event), we will come to details later.

In the coming sections, we will understand both these main steps in more detail.

Creation of ASP.NET Environment

Step 1: The user sends a request to IIS. IIS first checks which ISAPI extension can serve this request. Depending on file extension the request is processed. For instance, if the page is an ‘.ASPX page’, then it will be passed to ‘aspnet_isapi.dll’ for processing.

Step 2: If this is the first request to the website, then a class called as ‘ApplicationManager’ creates an application domain where the website can run. As we all know, the application domain creates isolation between two web applications hosted on the same IIS. So in case there is an issue in one app domain, it does not affect the other app domain.

Step 3: The newly created application domain creates hosting environment, i.e. the ‘HttpRuntime’ object. Once the hosting environment is created, the necessary core ASP.NET objects like ‘HttpContext’ , ‘HttpRequest’ and ‘HttpResponse’ objects are created.

Step 4: Once all the core ASP.NET objects are created, ‘HttpApplication’ object is created to serve the request. In case you have a ‘global.asax’ file in your system, then the object of the ‘global.asax’ file will be created. Please note global.asax file inherits from ‘HttpApplication’ class.
Note: The first time an ASP.NET page is attached to an application, a new instance of ‘HttpApplication’ is created. Said and done to maximize performance, HttpApplication instances might be reused for multiple requests.

Step 5: The HttpApplication object is then assigned to the core ASP.NET objects to process the page.

Step 6: HttpApplication then starts processing the request by HTTP module events, handlers and page events. It fires the MHPM event for request processing.
Note: For more details, read this.

 

 

 

The below image explains how the internal object model looks like for an ASP.NET request. At the top level is the ASP.NET runtime which creates an ‘Appdomain’ which in turn has ‘HttpRuntime’ with ‘request’, ‘response’ and ‘context’ objects.

Process Request using MHPM Events Fired

Once ‘HttpApplication’ is created, it starts processing requests. It goes through 3 different sections ‘HttpModule’ , ‘Page’ and ‘HttpHandler’. As it moves through these sections, it invokes different events which the developer can extend and add customize logic to the same.
Before we move ahead, let’s understand what are ‘HttpModule’ and ‘HttpHandlers’. They help us to inject custom logic before and after the ASP.NET page is processed. The main differences between both of them are:

If you want to inject logic based in file extensions like ‘.ASPX’, ‘.HTML’, then you use ‘HttpHandler’. In other words, ‘HttpHandler’ is an extension based processor.

If you want to inject logic in the events of ASP.NET pipleline, then you use ‘HttpModule’. ASP.NET. In other words, ‘HttpModule’ is an event based processor.

 

You can read more about the differences from here.
Below is the logical flow of how the request is processed. There are 4 important steps MHPM as explained below:

Step 1(M: HttpModule): Client request processing starts. Before the ASP.NET engine goes and creates the ASP.NET HttpModule emits events which can be used to inject customized logic. There are 6 important events which you can utilize before your page object is created BeginRequest, AuthenticateRequest, AuthorizeRequest, ResolveRequestCache, AcquireRequestState and PreRequestHandlerExecute.

Step 2 (H: ‘HttpHandler’): Once the above 6 events are fired, ASP.NET engine will invoke ProcessRequest event if you have implemented HttpHandler in your project.

Step 3 (P: ASP.NET page): Once the HttpHandler logic executes, the ASP.NET page object is created. While the ASP.NET page object is created, many events are fired which can help us to write our custom logic inside those page events. There are 6 important events which provides us placeholder to write logic inside ASP.NET pages Init, Load, validate, event, render and unload. You can remember the word SILVER to remember the events S – Start (does not signify anything as such just forms the word) , I – (Init) , L (Load) , V (Validate), E (Event) and R (Render).

Step4 (M: HttpModule): Once the page object is executed and unloaded from memory, HttpModule provides post page execution events which can be used to inject custom post-processing logic. There are 4 important post-processing events PostRequestHandlerExecute, ReleaserequestState, UpdateRequestCache and EndRequest.
The below figure shows the same in a pictorial format.

In What Event Should We Do What?

The million dollar question is in which events should we do what? Below is the table which shows in which event what kind of logic or code can go.

Section Event Description
HttpModule BeginRequest This event signals a new request; it is guaranteed to be raised on each request.
HttpModule AuthenticateRequest This event signals that ASP.NET runtime is ready to authenticate the user. Any authentication code can be injected here.
HttpModule AuthorizeRequest This event signals that ASP.NET runtime is ready to authorize the user. Any authorization code can be injected here.
HttpModule ResolveRequestCache In ASP.NET, we normally use outputcache directive to do caching. In this event, ASP.NET runtime determines if the page can be served from the cache rather than loading the patch from scratch. Any caching specific activity can be injected here.
HttpModule AcquireRequestState This event signals that ASP.NET runtime is ready to acquire session variables. Any processing you would like to do on session variables.
HttpModule PreRequestHandlerExecute This event is raised just prior to handling control to the HttpHandler. Before you want the control to be handed over to the handler any pre-processing you would like to do.
HttpHandler ProcessRequest Httphandler logic is executed. In this section, we will write logic which needs to be executed as per page extensions.
Page Init This event happens in the ASP.NET page and can be used for:

Creating controls dynamically, in case you have controls to be created on runtime.

Any setting initialization.

Master pages and the settings.

In this section, we do not have access to viewstate, postedvalues and neither the controls are initialized.

Page Load In this section, the ASP.NET controls are fully loaded and you write UI manipulation logic or any other logic over here.
Page Validate If you have valuators on your page, you would like to check the same here.
  Render It’s now time to send the output to the browser. If you would like to make some changes to the final HTML which is going out to the browser, you can enter your HTML logic here.
Page Unload Page object is unloaded from the memory.
HttpModule PostRequestHandlerExecute Any logic you would like to inject after the handlers are executed.
HttpModule ReleaserequestState If you would like to save update some state variables like session variables.
HttpModule UpdateRequestCache Before you end, if you want to update your cache.
HttpModule EndRequest This is the last stage before your output is sent to the client browser.

 

A Sample Code for Demonstration

With this article, we have attached a sample code which shows how the events actually fire. In this code, we have created a ‘HttpModule’ and ‘Httphandler’ in this project and we have displayed a simple response write in all events, below is how the output looks like.
Below is the class for ‘HttpModule’ which tracks all events and adds it to a global collection.

public class clsHttpModule : IHttpModule

{

……

void OnUpdateRequestCache(object sender, EventArgs a)

{

objArrayList.Add(“httpModule:OnUpdateRequestCache”);

}

void OnReleaseRequestState(object sender, EventArgs a)

{

objArrayList.Add(“httpModule:OnReleaseRequestState”);

}

 

 

void OnPostRequestHandlerExecute(object sender, EventArgs a)

{

objArrayList.Add(“httpModule:OnPostRequestHandlerExecute”);

}

void OnPreRequestHandlerExecute(object sender, EventArgs a)

{

objArrayList.Add(“httpModule:OnPreRequestHandlerExecute”);

}

void OnAcquireRequestState(object sender, EventArgs a)

{

objArrayList.Add(“httpModule:OnAcquireRequestState”);

}

void OnResolveRequestCache(object sender, EventArgs a)

{

objArrayList.Add(“httpModule:OnResolveRequestCache”);

}

void OnAuthorization(object sender, EventArgs a)

{

objArrayList.Add(“httpModule:OnAuthorization”);

}

void OnAuthentication(object sender, EventArgs a)

{

objArrayList.Add(“httpModule:AuthenticateRequest”);

}

 

 

 

void OnBeginrequest(object sender, EventArgs a)

{

objArrayList.Add(“httpModule:BeginRequest”);

}

void OnEndRequest(object sender, EventArgs a)

{

objArrayList.Add(“httpModule:EndRequest”);

objArrayList.Add(“<hr>”);

foreach (string str in objArrayList)

{

httpApp.Context.Response.Write(str + “<br>”) ;

}

}

}

Below is the code snippet for ‘HttpHandler’ which tracks ‘ProcessRequest’ event.

 

public class clsHttpHandler : IHttpHandler

{

public void ProcessRequest(HttpContext context)

{

clsHttpModule.objArrayList.Add(“HttpHandler:ProcessRequest”);

context.Response.Redirect(“Default.aspx”);

}

}

 

 

 

We are also tracking all the events from the ASP.NET page.

public partial class _Default : System.Web.UI.Page

{

protected void Page_init(object sender, EventArgs e)

{

clsHttpModule.objArrayList.Add(“Page:Init”);

}

protected void Page_Load(object sender, EventArgs e)

{

clsHttpModule.objArrayList.Add(“Page:Load”);

}

public override void Validate()

{

clsHttpModule.objArrayList.Add(“Page:Validate”);

}

protected void Button1_Click(object sender, EventArgs e)

{

clsHttpModule.objArrayList.Add(“Page:Event”);

}

protected override void Render(HtmlTextWriter output)

{

clsHttpModule.objArrayList.Add(“Page:Render”);

base.Render(output);

}

 

 

 

protected void Page_Unload(object sender, EventArgs e)

{

clsHttpModule.objArrayList.Add(“Page:UnLoad”);

}

}

Below is how the display looks like with all events as per the sequence discussed in the previous section.

Zooming ASP.NET Page Events

In the above section, we have seen the overall flow of events for an ASP.NET page request. One of the most important sections is the ASP.NET page, we have not discussed the same in detail. So let’s take some luxury to describe the ASP.NET page events in more detail in this section.

Any ASP.NET page has 2 parts, one is the page which is displayed on the browser which has HTML tags, hidden values in form of viewstate and data on the HTML inputs. When the page is posted, these HTML tags are created in to ASP.NET controls with viewstate and form data tied up together on the server. Once you get these full server controls on the behind code, you can execute and write your own login on the same and render the page back to the browser.

Now between these HTML controls coming live on the server as ASP.NET controls, the ASP.NET page emits out lot of events which can be consumed to inject logic. Depending on what task / logic you want to perform, we need to put this logic appropriately in those events.
Note: Most of the developers directly use the page_load method for everything, which is not a good thought. So it’s either populating the controls, setting view state, applying themes, etc., everything happens on the page load. So if we can put logic in proper events as per the nature of the logic, that would really make your code clean.

Seq Events Controls Initialized View state
Available
Form data
Available
What Logic can be written here?
1 Init No No No Note: You can access form data etc. by using ASP.NET request objects but not by Server controls.Creating controls dynamically, in case you have controls to be created on runtime. Any setting initialization.Master pages and them settings. In this section, we do not have access to viewstate , posted values and neither the controls are initialized.
2 Load view state Not guaranteed Yes Not guaranteed You can access view state and any synch logic where you want viewstate to be pushed to behind code variables can be done here.
3 PostBackdata Not guaranteed Yes Yes You can access form data. Any logic where you want the form data to be pushed to behind code variables can be done here.
4 Load Yes Yes Yes This is the place where you will put any logic you want to operate on the controls. Like flourishing a combobox from the database, sorting data on a grid, etc. In this event, we get access to all controls, viewstate and their posted values.
5 Validate Yes Yes Yes If your page has validators or you want to execute validation for your page, this is the right place to the same.
6 Event Yes Yes Yes If this is a post back by a button click or a dropdown change, then the relative events will be fired. Any kind of logic which is related to that event can be executed here.
7 Pre-render Yes Yes Yes If you want to make final changes to the UI objects like changing tree structure or property values, before these controls are saved in to view state.
8 Save view state Yes Yes Yes Once all changes to server controls are done, this event can be an opportunity to save control data in to view state.
9 Render Yes Yes Yes If you want to add some custom HTML to the output this is the place you can.
10 Unload Yes Yes Yes Any kind of clean up you would like to do here.

 

 

Advertisements

Asp.Net 2.0 Page Directives

Asp.Net Page directives are something that is a part of every asp.net pages. Page directives are instructions, inserted at the top of an ASP.NET page, to control the behavior of the asp.net pages. So it is type of mixed settings related to how a page should render and processed.

Here’s an example of the page directive:

 

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Sample.aspx.cs” Inherits=”Sample” Title=”Sample Page Title” %>

Totally there are 11 types of Pages directives in Asp.Net 2.0. Some directives are very important without which we cannot develop any web applications in Asp.Net. Some directives are used occasionally according to its necessity. When used, directives can be located anywhere in an .aspx or .ascx file, though standard practice is to include them at the beginning of the file. Each directive can contain one or more attributes (paired with values) that are specific to that directive.

Asp.Net web form page framework supports the following directives

1. @Page
2. @Master
3. @Control
4. @Register
5. @Reference
6. @PreviousPageType
7. @OutputCache
8. @Import
9. @Implements
10. @Assembly
11. @MasterType

@Page Directive

The @Page directive enables you to specify attributes and values for an Asp.Net Page to be used when the page is parsed and compiled. Every .aspx files should include this @Page directive to execute. There are many attributes belong to this directive. We shall discuss some of the important attributes here. 

a. AspCompat: When set to True, this allows to the page to be executed on a single-threaded apartment. If you want to use a component developed in VB 6.0, you can set this value to True. But setting this attribute to true can cause your page’s performance to degrade.

b. Language: This attribute tells the compiler about the language being used in the code-behind. Values can represent any .NET-supported language, including Visual Basic, C#, or JScript .NET.

c. AutoEventWireup: For every page there is an automatic way to bind the events to methods in the same .aspx file or in code behind. The default value is true.

d. CodeFile: Specifies the code-behind file with which the page is associated.

e. Title:  To set the page title other than what is specified in the master page.

f. Culture: Specifies the culture setting of the page. If you set to auto, enables the page to automatically detect the culture required for the page.

g. UICulture: Specifies the UI culture setting to use for the page. Supports any valid UI culture value.

h. ValidateRequest: Indicates whether request validation should occur. If set to true, request validation checks all input data against a hard-coded list of potentially dangerous values. If a match occurs, an HttpRequestValidationException Class is thrown. The default is true. This feature is enabled in the machine configuration file (Machine.config). You can disable it in your application configuration file (Web.config) or on the page by setting this attribute to false.

i. Theme:  To specify the theme for the page. This is a new feature available in Asp.Net 2.0.

j. SmartNavigation: Indicates the smart navigation feature of the page. When set to True, this returns the postback to current position of the page. The default value is false.

k. MasterPageFile: Specify the location of the MasterPage file to be used with the current Asp.Net page.

 

l. EnableViewState: Indicates whether view state is maintained across page requests. true if view state is maintained; otherwise, false. The default is true.

 

m. ErrorPage: Specifies a target URL for redirection if an unhandled page exception occurs.

 

n. Inherits: Specifies a code-behind class for the page to inherit. This can be any class derived from the Page class.

 

There are also other attributes which are of seldom use such as Buffer, CodePage, ClassName, EnableSessionState, Debug, Description, EnableTheming, EnableViewStateMac, TraceMode, WarningLevel, etc.

 

Here is an example of how a @Page directive looks

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Sample.aspx.cs” Inherits=”Sample” Title=”Sample Page Title” %>

@Master Directive

The @Master directive is quite similar to the @Page directive. The @Master directive belongs to Master Pages that is .master files. The master page will be used in conjunction of any number of content pages. So the content pages can the inherits the attributes of the master page. Even though, both @Page and @Master page directives are similar, the @Master directive has only fewer attributes as follows

a. Language: This attribute tells the compiler about the language being used in the code-behind. Values can represent any .NET-supported language, including Visual Basic, C#, or JScript .NET.

b. AutoEventWireup: For every page there is an automatic way to bind the events to methods in the same master file or in code behind. The default value is True.

c. CodeFile: Specifies the code-behid file with which the MasterPage is associated.

d. Title: Set the MasterPage Title.

e. MasterPageFile: Specifies the location of the MasterPage file to be used with the current MasterPage. This is called as Nested Master Page.

f. EnableViewState: Indicates whether view state is maintained across page requests. true if view state is maintained; otherwise, false. The default is true.

g. Inherits: Specifies a code-behind class for the page to inherit. This can be any class derived from the Page class.

Here is an example of how a @Master directive looks

<%@ Master Language=”C#” AutoEventWireup=”true” CodeFile=”WebMaster.master.cs” Inherits=”WebMaster” %>

@Control Directive

The @Control directive is used when we build an Asp.Net user controls. The @Control directive helps us to define the properties to be inherited by the user control. These values are assigned to the user control as the page is parsed and compiled. The attributes of @Control directives are

a. Language: This attribute tells the compiler about the language being used in the code-behind. Values can represent any .NET-supported language, including Visual Basic, C#, or JScript .NET.

b. AutoEventWireup: For every page there is an automatic way to bind the events to methods in the same .ascx file or in code behind. The default value is true.

c. CodeFile: Specifies the code-behid file with which the user control is associated.

d. EnableViewState: Indicates whether view state is maintained across page requests. true if view state is maintained; otherwise, false. The default is true.

e. Inherits: Specifies a code-behind class for the page to inherit. This can be any class derived from the Page class.

f. Debug: Indicates whether the page should be compiled with debug symbols.

g. Src: Points to the source file of the class used for the code behind of the user control.

The other attributes which are very rarely used is ClassName, CompilerOptions, ComplieWith, Description, EnableTheming, Explicit, LinePragmas, Strict and WarningLevel.

Here is an example of how a @Control directive looks

<%@ Control Language=”C#” AutoEventWireup=”true” CodeFile=”MyControl.ascx.cs” Inherits=” MyControl ” %>

@Register Directive

The @Register directive associates aliases with namespaces and class names for notation in custom server control syntax. When you drag and drop a user control onto your .aspx pages, the Visual Studio 2005 automatically creates an @Register directive at the top of the page. This register the user control on the page so that the control can be accessed on the .aspx page by a specific name.

The main attributes of @Register directive are

a. Assembly: The assembly you are associatin with the TagPrefix.
b. Namespace: The namspace to relate with TagPrefix.
c. Src: The location of the user control.
d. TagName: The alias to relate to the class name.
e. TagPrefix: The alias to relate to the namespace.

Here is an example of how a @Register directive looks

<%@ Register Src=”Yourusercontrol.ascx” TagName=” Yourusercontrol ” TagPrefix=”uc1″ Src=”~\usercontrol\usercontrol1.ascx” %>

@Reference Directive

The @Reference directive declares that another asp.net page or user control should be complied along with the current page or user control. The 2 attributes for @Reference direcive are

a. Control: User control that ASP.NET should dynamically compile and link to the current page at run time.

b. Page:
The Web Forms page that ASP.NET should dynamically compile and link to the current page at run time.

c. VirutalPath: Specifies the location of the page or user control from which the active page will be referenced.

Here is an example of how a @Reference directive looks

<%@ Reference VirutalPath=”YourReferencePage.ascx” %>

@PreviousPageType Directive

The @PreviousPageType is a new directive makes excellence in asp.net 2.0 pages. The concept of cross-page posting between Asp.Net pages is achieved by this directive. This directive is used to specify the page from which the cross-page posting initiates. This simple directive contains only two attibutes

a. TagName: Sets the name of the derived class from which the postback will occur.

b. VirutalPath: sets the location of the posting page from which the postback will occur.

Here is an example of @PreviousPageType directive

<%@ PreviousPageType VirtualPath=”~/YourPreviousPageName.aspx” %>

@OutputCache Directive

The @OutputCache directive controls the output caching policies of the Asp.Net page or user control. You can even cache programmatically through code by using Visual Basic .NET or Visual C# .NET. The very important attributes for the @OutputCache directive are as follows

Duration: The duration of time in seconds that the page or user control is cached.

Location: To specify the location to store the output cache. To store the output cache on the browser client where the request originated set the value as ‘Client’. To store the output cache on any HTTP 1.1 cache-capable devices including the proxy servers and the client that made request, specify the Location as Downstream. To store the output cache on the Web server, mention the location as Server.

 

VaryByParam: List of strings used to vary the output cache, separated with semi-colon.

 

VaryByControl: List of strings used to vary the output cache of a user Control, separated with semi-colon.

VaryByCustom: String of values, specifies the custom output caching requirements.

 

VaryByHeader: List of HTTP headers used to vary the output cache, separated with semi-colon.

 

The other attributes which is rarely used are CacheProfile, DiskCacheable, NoStore, SqlDependency, etc.

<%@ OutputCache Duration=”60″ Location=”Server” VaryByParam=”None” %>

To turn off the output cache for an ASP.NET Web page at the client location and at the proxy location, set the Location attribute value to none, and then set the VaryByParam value to none in the @ OutputCache directive. Use the following code samples to turn off client and proxy caching.

<%@ OutputCache Location=”None” VaryByParam=”None” %>

@Import Directive

The @Import directive allows you to specify any namespaces to the imported to the Asp.Net pages or user controls. By importing, all the classes and interfaces of the namespace are made available to the page or user control. The example of the @Import directive

<%@ Import namespace=”System.Data” %>
<%@ Import namespace=”System.Data.SqlClient” %>

@Implements Directive

The @Implements directive gets the Asp.Net page to implement a specified .NET framework interface. The only single attribute is Interface, helps to specify the .NET Framework interface. When the Asp.Net page or user control implements an interface, it has direct access to all its events, methods and properties.

<%@ Implements Interface=”System.Web.UI.IValidator” %>

@Assembly Directive

The @Assembly directive is used to make your ASP.NET page aware of external components. This directive supports two attributes:

a. Name: Enables you specify the name of an assembly you want to attach to the page. Here you should mention the filename without the extension.

b. Src: represents the name of a source code file

<%@ Assembly Name=”YourAssemblyName” %>

@MasterType Directive

To access members of a specific master page from a content page, you can create a strongly typed reference to the master page by creating a @MasterType directive. This directive supports of two attributes such as TypeName and VirtualPath.

a. TypeName: Sets the name of the derived class from which to get strongly typed references or members.

b. VirtualPath: Sets the location of the master page from which the strongly typed references and members will be retrieved.

If you have public properties defined in a Master Page that you’d like to access in a strongly-typed manner you can add the MasterType directive into a page as shown next

<%@ MasterType VirtualPath=”MasterPage.master” %>

this.Master.HeaderText = “Label updated using MasterType directive with VirtualPath attribute”;

Windows Communication Foundation (WCF)

Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.

Below figures shows the different technology combined to form WCF.

 

Advantage

  1. WCF is interoperable with other services when compared to .Net Remoting, where the client and service have to be .Net.
  2. WCF services provide better reliability and security in compared to ASMX web services.
  3. In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
  4. WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.

Disadvantage

Making right design for your requirement is little bit difficult. I will try to help you on solving these difficulties in the following article.

Development Tools

WCF application can be developed by the Microsoft Visual Studio. Visual studio is available at different edition. You can use Visual Studio 2008 Expression edition for the development.

http://www.microsoft.com/express/product/default.aspx

Visual Studio 2008 SDK 1.1

http://www.microsoft.com/downloads/details.aspx?FamilyID=59ec6ec3-4273-48a3-ba25-dc925a45584d…

Microsoft Visual Studio 2008

Microsoft Visual studio 2008 provides new features for WCF compared to Visual Studio 2005. These are the new features added to VS 2008.

1.    Multi-targeting

You can create application in different framework like Framework 2.0, 3.0 and 3.5

 

2.    Default template is available for WCF

 

 

3.    WCF – Test Client tools for testing the WCF service.

Microsoft provides inbuilt application to test the WCF application. This can be done by opening the Visual Studio command prompt and type the wcfClient Serviceurl shows below. This will help the developer to test the service before creating the client application.

 

4.    WCF services can be debugged now in Visual Studio 2008. Wcfsvchost.exe will do it for you because service will be self hosted when you start debugging.

Difference between WCF and Web service

Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them.

Features

Web Service

WCF

Hosting It can be hosted in IIS It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming [WebService] attribute has to be added to the class [ServiceContraact] attribute has to be added to the class
Model [WebMethod] attribute represents the method exposed to client [OperationContract] attribute represents the method exposed to client
Operation One-way, Request- Response are the different operations supported in web service One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML System.Xml.serialization name space is used for serialization System.Runtime.Serialization namespace is used for serialization
Encoding XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom XML 1.0, MTOM, Binary, Custom
Transports Can be accessed through HTTP, TCP, Custom Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols Security Security, Reliable messaging, Transactions

WCF Fundamental

In this part of tutorial you are going to learn about some fundamental concepts in WCF. These concepts and terms will be used throughout this tutorial.

EndPoint

WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.

All the WCF communications are take place through end point. End point consists of three components.

Address

Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.g

http://localhost:8090/MyService/SimpleCalculator.svc

 

Binding

Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.

A binding has several characteristics, including the following:

  • Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
  • Encoding (Optional) – Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).
  • Protocol(Optional) – Defines information to be used in the binding such as Security, transaction or reliable messaging capability

The following table gives some list of protocols supported by WCF binding.

Binding

Description

BasicHttpBinding Basic Web service communication. No security by default
WSHttpBinding Web services with WS-* support. Supports transactions
WSDualHttpBinding Web services with duplex contract and transaction support
WSFederationHttpBinding Web services with federated security. Supports transactions
MsmqIntegrationBinding Communication directly with MSMQ applications. Supports transactions
NetMsmqBinding Communication between WCF applications by using queuing. Supports transactions
NetNamedPipeBinding Communication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBinding Communication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBinding Communication between WCF applications across computers. Supports duplex contracts and transactions

Contract

Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply.

Below figure illustrate the functions of Endpoint

Example:

Endpoints will be mentioned in the web.config file on the created service.

<system.serviceModel>
<services>
      <service name="MathService"
        behaviorConfiguration="MathServiceBehavior">
       <endpoint
         address="http://localhost:8090/MyService/MathService.svc" contract="IMathService"
          binding="wsHttpBinding"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

 

 

 

Binding and Behavior

Binding

Simple definition for Binding describes how the client will communicate with service. We can understand with an example.

Consider a scenario say, I am creating a service that has to be used by two type of client. One of the client will access SOAP using http and other client will access Binary using TCP. How it can be done? With Web service it is very difficult to achieve, but in WCF its just we need to add extra endpoint in the configuration file.

<system.serviceModel>
    <services>
      <service name="MathService"
        behaviorConfiguration="MathServiceBehavior">
      <endpoint address="http://localhost:8090/MyService/MathService.svc"
        contract="IMathService"
          binding="wsHttpBinding"/>
<endpoint address="net.tcp://localhost:8080/MyService/MathService.svc"
contract="IMathService"
          binding="netTcpBinding"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

 

See how simple it is in WCF. Microsoft is making everything simple.cording to its scope: common behaviors affect all endpoints globally, service behaviors affect only service-related aspects, endpoint behaviors affect only endpoint-related properties, and operation-level behaviors affect particular operations.

Example:

In the below configuration information, I have mentioned the Behavior at Service level. In the service behavior I have mention the servieMetadata node with attribute httGetEnabled=’true’. This attribute will specifies the publication of the service metadata. Similarly we can add more behavior to the service.

<system.serviceModel>
    <services>
      <service name="MathService"
        behaviorConfiguration="MathServiceBehavior">
        <endpoint address="" contract="IMathService"
          binding="wsHttpBinding"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
 

Note: Application can be controlled either through coding, configuring or through combination of both. Specification mention in the configuration can also be overwritten in code.

Contracts and Service Host

Contracts

In WCF, all services are exposed as contracts. Contract is a platform-neutral and standard way of describing what the service does. Mainly there are four types of contracts available in WCF

Service Contract

Service contracts describe the operation that service can provide. For Eg, a Service provide to know the temperature of the city based on the zip code, this service is called as Service contract. It will be created using Service and Operational Contract attribute.

To know more on Service contract see Service contract tutorial.

Data Contract

Data contract describes the custom data type which is exposed to the client. This defines the data types, that are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or data types cannot be identified by the client e.g. Employee data type. By using DataContract we can make client to be aware of Employee data type that are returning or passing parameter to the method.

To know more on DataContract see DataContract tutorial.

Message Contract

Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

To know more on Message Contract see Message contract tutorial.

Fault Contract

Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error occurred in the service to client. This helps us to easy identity, what error has occurred.

To know more on Fault Contract see Fault Contract tutorial.

Service Host

Service Host object is in the process of hosting the WCF service and registering endpoints. It loads the service configuration endpoints, apply the settings and start the listeners to handle the incoming request. System.ServiceModel.ServiceHost namespace hold this object. This object is created while self hosting the WCF service.

In the below example you can find that WCF service is self hosted using console application.

//Creating uri for the hosting the service
Uri uri = new Uri("http://localhost/CategoryService");
//Creating the host object for MathService
  ServiceHost host = new ServiceHost(typeof(CategoryService), uri);
//Adding endpoint to the Host object
  host.AddServiceEndpoint(typeof(ICategoryService),new WSHttpBinding(), uri);
  host.Open(); //Hosting the Service
  Console.WriteLine("Waiting for client invocations");
  Console.ReadLine();
  host.Close();

Message and Channel

Message

WCF Message is the unit of data exchange between client and service. It consists of several parts, including a body and headers.

WCF Runtime

WCF runtime is the set of object responsible for sending and receiving message. For example formatting the message, applying security and transmitting and receiving message using various protocol.

Channels:

Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as

Transport Channels

– Handles sending and receiving message from network. Protocols like HTTP, TCP name pipes and MSMQ.

Protocol Channels

– Implements SOAP based protocol by processing and possibly modifying message. e.g. WS-Security and WS-Reliability.

WCF Client and Metadata

WCF Client

WCF client is a client application creates to expose the service operations as method. Any application can host a WCF client, including an application that host a service. Therefore it is possible to create a service that includes WCF clients of other services.

A client application is a managed application that uses a WCF client to communicate with another application. To create a client application for a WCF service requires the following steps:

  1. Get the Proxy class and service end point information

Using SvcUtil.exe we can create proxy class for the service and configuration information for endpoints. Example type the following sentence in the Visual studio command prompt, this will generate the class file and configuration file which contain information about the endpoints.

svcutil /language:vb /out:ClientCode.vb /config:app.config http://localhost:8090/MyService/SimpleCalculator.svc?wsdl

  1. Call operations.

Add this class files in the client application. Then create the object for this class and invoke the service operation. Configuration information we got from the above step has to be added to the client application configuration file. When the client application calls the first operation, WCF automatically opens the underlying channel. This underlying channel is closed, when the object is recycled.

//Creating the proxy on client side

MyCalculatorServiceProxy.MyServiceProxy proxy

= new MyCalculatorServiceProxy.MyServiceProxy();

 Console.WriteLine(“Counter: ” + proxy.MyMethod());

  1. Close the WCF client object.

After using the object created in the above steps, we have to dispose the object. Channel will be closed with the service, when the object is cleared.

Metadata

Characteristics of the service are described by the metadata. This metadata can be exposed to the client to understand the communication with service. Metadata can be set in the service by enabling the ServiceMetadata node inside the servcieBehaviour node of the service configuration file.

<system.serviceModel>

    <services>

      <service name=”MathService”

        behaviorConfiguration=”MathServiceBehavior”>

        <endpoint address=”” contract=”IMathService”

          binding=”wsHttpBinding”/>

      </service>

    </services>

    <behaviors>

      <serviceBehaviors>

        <behavior name=”MathServiceBehavior”>

    <serviceMetadata httpGetEnabled=”True”/>

          <serviceDebug includeExceptionDetailInFaults=”true” />

        </behavior>

      </serviceBehaviors>

    </behaviors>

  </system.serviceModel>

This metadata can be viewed while creating WCF client application using SvcUtil.exe

WCF Architecture

The following figure illustrates the major components of WCF.

Contracts

Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. We are also going to do the same now. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system.

Service contracts

– Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute.

Data contract

– It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method.

Message Contract

– Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

Policies and Binding

– Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.

Service Runtime

– It contains the behaviors that occur during runtime of service.

  • Throttling Behavior- Controls how many messages are processed.
  • Error Behavior – Specifies what occurs, when internal error occurs on the service.
  • Metadata Behavior – Tells how and whether metadata is available to outside world.
  • Instance Behavior – Specifies how many instance of the service has to be created while running.
  • Transaction Behavior – Enables the rollback of transacted operations if a failure occurs.
  • Dispatch Behavior – Controls how a message is processed by the WCF Infrastructure.

Messaging

– Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as

  • Transport Channels

Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.

  • Protocol Channels

Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.

Activation and Hosting

– Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism

  • IIS

Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.

  • Windows Activation Service

(WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.

  • Self-Hosting

WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.

  • Windows Service

WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).

WCF Hosting

In this part of the tutorial we are going to see the four different way of hosting the WCF service. WCF service cannot exist on its own; it has to be hosted in windows process called as host process. Single host process can host multiple servers and same service type can be hosted in multiple host process. As we discussed there are mainly four different way of hosting the WCF service.

  1. IIS hosting
  2. Self hosting
  3. Windows Activation Service
  4. Windows Service

Multiple hosting and protocols supported by WCF.Microsoft has introduced the WCF concept in order to make distributed application development and deployment simple.

 

 

 

Hosting Environment

Supported protocol

Windows console and form application HTTP,net.tcp,net.pipe,net.msmq
Windows service application (formerly known as NT services) HTTP,net.tcp,net.pipe,net.msmq
Web server IIS6 http, wshttp
Web server IIS7 – Windows Process Activation Service (WAS) HTTP,net.tcp,net.pipe,net.msmq

A summary of hosting options and supported features.

Feature

Self-Hosting

IIS Hosting

WAS Hosting

Executable Process/ App Domain Yes Yes Yes
Configuration App.config Web.config Web.config
Activation Manual at startup Message-based Message-based
Idle-Time Management No Yes Yes
Health Monitoring No Yes Yes
Process Recycling No Yes Yes
Management Tools No Yes Yes

 

State Management Techniques

This article discusses various options for state management for web applications developed using ASP.NET. Generally, web applications are based on stateless HTTP protocol which does not retain any information about user requests. In typical client and server communication using HTTP protocol, page is created each time the page is requested.

Developer is forced to implement various state management techniques when developing applications which provide customized content and which “remembers” the user.

Here we are here with various options for ASP.NET developer to implement state management techniques in their applications. Broadly, we can classify state management techniques as client side state management or server side state management. Each technique has its own pros and cons. Let’s start with exploring client side state management options.

Client side State management Options:

ASP.NET provides various client side state management options like Cookies, QueryStrings (URL), Hidden fields, View State and Control state (ASP.NET 2.0). Let’s discuss each of client side state management options.

Bandwidth should be considered while implementing client side state management options because they involve in each roundtrip to server. Example: Cookies are exchanged between client and server for each page request.

Cookie: 

A cookie is a small piece of text stored on user’s computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user. 

Let’s see an example which makes use of cookies to customize web page.

if (Request.Cookies[“UserId”] != null)
    lbMessage.text = “Dear” + Request.Cookies[“UserId”].Value + “, Welcome to our website!”;
else
    lbMessage.text = “Guest,welcome to our website!”;

If you want to store client’s information use the below code

Response.Cookies[“UserId”].Value=username;

Advantages:

  • Simplicity

Disadvantages:

  • Cookies can be disabled on user browsers
  • Cookies are transmitted for each HTTP request/response causing overhead on bandwidth
  • Inappropriate for sensitive data

Hidden fields:

Hidden fields are used to store data at the page level. As its name says, these fields are not rendered by the browser. It’s just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page. Now that all the asp.net web controls have built in state management in the form of view state and new feature in asp.net 2.0 control state, hidden fields functionality seems to be redundant. We can still use it to store insignificant data. We can use hidden fields in ASP.NET pages using following syntax

protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;

 

//to assign a value to Hidden field

Hidden1.Value=”Create hidden fields”;

//to retrieve a value

string str=Hidden1.Value;

Advantages:

  • Simple to implement for a page specific data
  • Can store small amount of data so they take less size.

Disadvantages:

  • Inappropriate for sensitive data
  • Hidden field values can be intercepted(clearly visible) when passed over a network

View State:

View State can be used to store state information for a single user. View State is a built in feature in web controls to persist data between page post backs. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true. View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. To reduce performance penalty, disable View State for all the controls for which you don’t need state. (Data grid usually doesn’t need to maintain state). You can also disable View State for the entire page by adding EnableViewState=false to @page directive. View state data is encoded as binary Base64 – encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size. View State can be used using following syntax in an ASP.NET web page.

// Add item to ViewState

ViewState[“myviewstate”]  = myValue;

 

//Reading items from ViewState
Response.Write(ViewState[“myviewstate”]);

Advantages:

  • Simple for page level data
  • Encrypted 
  • Can be set at the control level

Disadvantages:

  • Overhead in encoding View State values
  • Makes a page heavy

Query strings:

Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text. Now that cross page posting feature is back in asp.net 2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on URL length. We can only pass smaller amounts of data using query strings. Since Query strings are sent in clear text, we can also encrypt query values. Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode.

Let’s assume that we have a Data Grid with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be an ideal use of the Query String to include the product ID in the Query String of the link to the product details page (for example, productdetails.aspx?productid=4).

When product details page is being requested, the product information can be obtained by using the following codes:

string productid;
productid=Request.Params[“productid”];            

Advantages:

  • Simple to Implement

Disadvantages:

  • Human Readable 
  • Client browser limit on URL length
  • Cross paging functionality makes it redundant 
  • Easily modified by end user

Control State:

Control State is new mechanism in ASP.NET 2.0 which addresses some of the shortcomings of View State. Control state can be used to store critical, private information across post backs. Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control’s contents (UI). Control State shares same memory data structures with View State. Control State can be propagated even though the View State for the control is disabled. For example, new control Grid View in ASP.NET 2.0 makes effective use of control state to maintain the state needed for its core behavior across post backs. Grid View is in no way affected when we disable View State for the Grid View or entire page

Server Side State management:

As name implies, state information will be maintained on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server.

Care must be taken to conserve server resources. For a high traffic web site with large number of concurrent users, usage
of sessions object for state management can create load on server causing performance degradation

Application object:

Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.

In classic ASP, application object is used to store connection strings. It’s a great place to store data which changes infrequently. We should write to application variable only in application_Onstart event (global.asax) or application.lock event to avoid data conflicts. Below code sample gives idea

Application.Lock();

Application[“mydata”]=”mydata”;

Application.UnLock();

Session object:

Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session’s data on web server in different ways. Session state can be configured using the <session State> section in the application’s web.config file. 

Configuration information:

<sessionState mode = <“inproc” | “sqlserver” | “stateserver”>
 cookieless = <“true” | “false”>
 timeout = <positive integer indicating the session timeout in minutes>
 sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode>
 server = <The server name that is only required when the mode is State Server>
 port = <The port number that is only required when the mode is State Server>       

Mode:

This setting supports three options. They are InProc, SQLServer, and State Server

Cookie less:

This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.

Timeout:

This indicates the Session timeout vale in minutes.  This is the duration for which a user’s session is active.  Note that the session timeout is a sliding value; Default session timeout value is 20 minutes

SqlConnectionString:

This identifies the database connection string that names the database used for mode SQLServer.

Server:

In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state.
 
Port:

This identifies the port number that corresponds to the server setting for mode State Server.  Note that a port is an unsigned integer that uniquely identifies a process running over a network.

You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.

Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability

  • In process mode (in-memory)- State information is stored in memory of web server
  • Out-of-process mode- session state is held in a process called aspnet_state.exe that runs as a windows service.
  • Database mode – session state is maintained on a SQL Server database.

In process mode:

This mode is useful for small applications which can be hosted on a single server. This model is most common and default method to store session specific information. Session data is stored in memory of local web server

Configuration information:

<sessionState mode=”Inproc”

 sqlConnectionString=”data source=server;user id=freelance;password=freelance”

 cookieless=”false” timeout=”20″ />

Advantages:

  • Fastest mode 
  • Simple configuration

Disadvantages:

  • Session data will be lost if the worker process or application domain recycles
  • Not ideal for web gardens and web farms

Out-of-process Session mode (state server mode):

This mode is ideal for scalable and highly available applications. Session state is held in a process called aspnet_state.exe that runs as a windows service which listens on TCP port 42424 by default. You can invoke state service using services MMC snap-in or by running following net command from command line.

Net start aspnet_state

Configuration information:

<sessionState mode=”StateServer”
 StateConnectionString=”tcpip=127.0.0.1:42424″
 sqlConnectionString=”data source=127.0.0.1;user id=freelance; password=freelance”
 cookieless=”false” timeout=”20″/>                                                           

Advantages:

  • Supports web farm and web garden configuration
  • Session data is persisted across application domain recycles. This is achieved by using separate worker process for maintaining state

Disadvantages:

  • Out-of-process mode provides slower access compared to In process
  • Requires serializing data  

SQL-Backed Session state:

ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that persists across IIS restarts.

SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework’s installed directory
 C:\<windows>\microsoft.net\framework\<version>. Running this utility will create a database which will manage the session state.

Configuration Information:

<sessionState mode=”SQLServer”

  sqlConnectionString=”data source=server;user id=freelance;password=freelance”

  cookieless=”false” timeout=”20″ />

Advantages:

  • Supports web farm and web garden configuration
  • Session state is persisted across application domain recycles and even IIS restarts    when session is maintained on different server.

Disadvantages:

  • Requires serialization of objects

In Short about the Session Types:

InProc: Stores Session state in the same process as the ASP.NET process [aspnet_wp.exe].

StateServer: Stores Session state in a Windows NT process, which is distinct from the ASP.NET process [aspnet_state.exe].

SQLServer: Stores Session state in a SQL Server database.

Choosing between client side and Server side management techniques is driven by various factors including available server resources, scalability and performance. We have to leverage both client side and server side state management options to build scalable applications. 

When leveraging client side state options, ensure that little amount of insignificant information is exchanged between page requests. 

Various parameters should be evaluated when leveraging server side state options including size of application, reliability and robustness. Smaller the application, In process is the better choice. We should account in the overheads involved in serializing and deserializing objects when using State Server and Database based session state. Application state should be used religiously.

 

Collections in .Net

Collection means group of values can be kept in an object or variable and then we can retrieve it and use it.

Array:

Array is a collection which can be used to store a list of values (single data type is allowed in it for eg int means only integer values will be allowed).

Example of Single Dimension Array in .Net

int [] intArray = new int[3];

intArray[2] = 22; // set the third element to 22

Example of Multi Dimension Array in .Net

int [][] myTable = new int[2,3];

myTable[1,2] = 22;

Example of Jagged Array in .Net: Variable Length Array in .Net

int [][] myTable = new int[3][];

myTable[0] = new int[5];

myTable[1] = new int[2];

myTable[2] = new int[4];

myTable[0][2] = 11;

Example of String Array in .Net

string []names = new string[4];

names[2] = “God will make me win”;

Limitation of Arrays:

• The size of an array is always fixed and must be defined at the time of instantiation of an array.

• Secondly, an array can only contain objects of the same data type, which we need to define at the time of its instantiation.

Namespace for Collections in .Net

System.Collections namespace

ArrayList:

Arraylist is collection where we can store multiple datatypes in a single array. its input is object.

Example

static void Main()

{

ArrayList alist1 = new ArrayList();

alist1.Add(“Hello”);  // Add a System.String

alist1.Add(714);   // Add a System.Int32

alist1.Add(new DateTime(2003, 1, 1));  // Add a System.DateTime

alist1.Add(#, (1 / (1 / 2003)), #);  // Add a System.DateTime

alist1.Add(4.5);  // Add a System.Double

alist1.Add(4.5F);

object o;

foreach (o in alist1) {

    Console.WriteLine((o + (“: ” + o.GetType().ToString())));

}

}

Stack:

A collection that works on the Last In First Out (LIFO) principle,

i.e., the last item inserted is the first item removed from the collection.

Push – To add element and

Pop – To Remove element

Example:

using System;

using System.Collections;

class Test

{

    static void Main()

    {

        Stack stack = new Stack();

        stack.Push(2);

        stack.Push(4);

        stack.Push(6);

       while(stack.Count != 0)

        {

            Console.WriteLine(stack.Pop());

        }

    }

}

Output

6

4

2

Queue:

A collection that works on the First In First Out (FIFO) principle, i.e.,

the first item inserted is the first item removed from the collection. 

Enqueue – To add element and Dequeue – To Remove element

Example:

static void Main()

{

    Queue queue = new Queue();

    queue.Enqueue(2);

    queue.Enqueue(4);

    queue.Enqueue(6);

    while(queue.Count != 0)

    {

        Console.WriteLine(queue.Dequeue());

    }

}

Output

2

4

6

 

 

Dictionaries:

Dictionaries are a kind of collection that store items in a key-value pair fashion.

Hashtable:

Provides a collection of key-value pairs that are organized based on the hash code of the key.

Example:

static void Main()

{

    Hashtable ht =  new Hashtable(20);

    ht.Add(“ht01”, “DotNetGuts”);

    ht.Add(“ht02”, “EasyTutor.2ya.com”);

    ht.Add(“ht03”, “DailyFreeCode.com”);

    Console.WriteLine(“Printing Keys…”);

    foreach(string key in ht.Keys)

    {

        Console.WriteLine(key);

    }

    Console.WriteLine(“\nPrinting Values…”);

    foreach(string Value in ht.Values)

    {

        Console.WriteLine(Value);

    }

    Console.WriteLine(“Size of Hashtable is {0}”, ht.Count);

    Console.WriteLine(ht.ContainsKey(“ht01”));

    Console.WriteLine(ht.ContainsValue(“DailyFreeCode.com”));

    Console.WriteLine(“\nRemoving element with key = ht02”);

    ht.Remove(“ht02”);

    Console.WriteLine(“Size of Hashtable is {0}”, ht.Count);

}

Output

Printing Keys…

ht01

ht02

ht03

 

Printing Values…

DotNetGuts

EasyTutor.2ya.com

DailyFreeCode.com

 

Size of Hashtable is 3

True

True

 

Removing element with key = ht02

Size of Hashtable is 2

SortedList:

Provides a collection of key-value pairs where the items are sorted according to the key. The items are accessible by both the keys and the index.

Example:

static void Main()

{

SortedList sl = new SortedList();

sl.Add(18, “Java”);

sl.Add(5, “C#”);

sl.Add(11, “VB.Net”);

sl.Add(1, “C++.Net”);

Console.WriteLine(“The items in the sorted order are…”);

Console.WriteLine(“\t Key \t\t Value”);

Console.WriteLine(“\t === \t\t =====”);

for(int i=0; i<sl.Count; i++)

{

Console.WriteLine(“\t {0} \t\t {1}”, sl.GetKey(i),

sl.GetByIndex(i));

}

}

Output

Key                    Value

—————————

1                     C++.Net

5                     C#

11                   VB.Net

18                   Java

Application blocks for the .NET Framework

Microsoft offers application blocks for the .NET Framework. Application blocks encapsulate certain key areas by adding a layer over the .NET Framework, and they aid in faster application development and promote certain best practices.

Two examples of application blocks: the Data Access application block and the Exception Handling application block (see Figure A).

Figure A

 

Why use application blocks?
Application blocks encapsulate an optimized way of doing things in the .NET Framework into a reusable package, allowing you to cut down on redundant code. Consider an application requiring data access. Most of it is the same piece of code used repeatedly. The application block encapsulates this infrastructure code and provides a simple way to use the features that you may need in an optimized way.

Another advantage of application blocks is the fact that these plug-and-play components form a layer over the .NET Framework. The .NET Framework is continuously evolving—Microsoft has already released a version 1.1 beta, which makes quite a few changes to the class library. If you’ve used these application blocks, it will make it much easier to move to future versions of the .NET Framework. The application blocks wrap the framework, and even if the underlying framework introduces some changes, you can then make changes to just this wrapper.

By using application blocks, you’ll retain the exposed methods of these building blocks and internally handle the changes in the .NET Framework. Your application is shielded from the changes that might occur in the .NET class library, thus enhancing maintainability. In fact, you can view these application blocks as black boxes through which functionality is used.

Data Access application block
The Data Access application block contains optimized code for data access. It encapsulates the System.Data.SqlClient namespace and may be used for accessing SQL Server data. You can download the Data Access application block here.

The Data Access application block is encapsulated in the Microsoft.ApplicationBlocks.Data namespace. First, you open the source code and build the assembly, adding a reference to the Microsoft.ApplicationBlocks.Data.Dll file. The Data Access block consists of two classes. A detailed view of the contents of the classes is shown in Figure B.

 

Figure B

 

Data Access block classes

The SqlHelper class has five static methods (shared in VB.NET) that are used for all common data access needs. Based on the situation and the return type needed, you can call the corresponding ExecuteXYZ( ) method of the SqlHelper class. For example, if you need a Dataset object returned, you can use the ExecuteDataset method.

Let’s take a look at a VB.NET code snippet showing the SqlHelper class in use:
 
Dim dsProducts As DataSet
Dim sConnectionString As String = “Data Source=(local);Initial Catalog=Northwind;User Id=sa;Password=”
dsProducts = SqlHelper.ExecuteDataset(sConnectionString, CommandType.Text, “SELECT * FROM Products”)

This returns a Dataset populated with the results from a query executed using the ExecuteDataset method. By making use of the CommandType parameter and setting it to CommandType.StoredProcedure, you can also call stored procedures. In this case, you can specify the stored procedure parameters.

You can make use of SqlHelper.ExecuteNonQuery whenever you make an INSERT, UPDATE, or DELETE statement. The ExecuteReader can be used when a stream of forward-only data is needed. The SqlHelper class also supports XML with the ExecuteXmlReader method, which can be used to retrieve data as XML. The ExecuteScalar method is used for retrieving a single value.

The SqlHelperParameterCache is a utility class that caches parameters used with the commands on SQL Server databases. The application blocks include complete source code in both VB.NET as well as C#.

Exception Handling application block
The Exception Handling application block contains optimized code for exception handling. You can download it here. It is encapsulated in the Microsoft.ApplicationBlocks.ExceptionManagement namespace. To use it, you must add a reference to the Microsoft.ApplicationBlocks.ExceptionManagement.dll.

The Exception Handling application block provides a way to manage exceptions in your applications. The main classes in this building block are the ExceptionManager, BaseApplicationException, and the ExceptionManagementSectionHandler class. A detailed view of the classes in this layer is shown in Figure C.

 

Figure C

 

Exception Handling block

Application exceptions are caught by the BaseApplicationException class. The ExceptionManager class is the key class. The ExceptionManager class has a Publish method used for handling the exception. This publishing mechanism is configured with an XML configuration file. Internally, the ExceptionManager class uses the ExceptionManagementSectionHandler class to retrieve the publisher settings from the XML configuration file. A default publisher logs the details of the Exception in the EventLog. You can also extend this building block by adding your own custom publishers. .

The only requirement is that these custom publishers should implement either the IExceptionPublisher or the IExceptionXmlPublisher interfaces. You can change the way the exceptions are published. This could be writing to a file, sending an e-mail notification, or logging the error in a database table. All you need to do is to encapsulate the algorithm to implement in a publisher—which implements one of the interfaces—and set the configuration file to use this publisher. The ExceptionManager uses the CustomPublisher for publishing exceptions.

This configuration XML file can be any of these three:

  • Machine.config (for all applications)
  • Web.Config (for Web applications)
  • ApplicationName.Exe.Config (for Windows applications)

Here is a sample XML fragment for configuring a custom publisher:
 
<configuration>
<configSections>
<section name=”exceptionManagement”
type=”Microsoft.ApplicationBlocks.ExceptionManagement
.ExceptionManagerSectionHandler,
Microsoft.ApplicationBlocks.ExceptionManagement”/>
</configSections>
<exceptionManagement>
<publisher mode=”on” assembly=”CustomPublisher”
type=”CustomPublisher.ExceptionPublisher”
DB=”Data Source=(local);User Id=sa; Password=;Initial Catalog=MyApp”  />
</exceptionManagement>
</configuration>
 
In case the CustomPublisher isn’t available, the application block uses the default publisher. A VB.NET sample code is shown below, which illustrates how exceptions are published in code:
 
Try
objConn.ConnectionString = “Data Source=(local);
User Id=sa;Password=;Initital Catalog=SouthWind”
objConn.Open()
Catch objSqlEx As SqlClient.SqlException
ExceptionManager.Publish(objSqlEx)
Catch objEx As Exception
ExceptionManager.Publish(objEx)
Finally
objConn = Nothing
End Try
 
Any exception caught by the above code is published by the ExceptionManager.

Building a foundation
By using the Microsoft application blocks for .NET as the building blocks of your applications, you can hasten your development process and improve the maintainability of the application. The examples I’ve shared above can help you get off on the right foot when using these application blocks.

Framework 1.0, 1.1, 2.0, 3.0, 3.5, 4.0

.Net Framework1.0:

This is the initial version of Microsoft .NET Framework.

.Net Framework 1.1:

This is the major upgrade to the .NET Framework 1.0 to provide:

1) .NET Compact Framework – a version of the .NET Framework for small devices
2) Internet Protocol version 6 (IPv6) support
3) Built-in support for ODBC and Oracle databases: previously available as an add-on for .NET Framework 1.0, now part of the framework
4) Built-in support for mobile ASP.NET controls: previously available as an add-on for .NET Framework, now part of the framework
5) Security changes: enable Windows Forms assemblies to execute in a semi-trusted manner from the Internet and enable Code Access Security in ASP.NET applications
6) Numerous API changes and many more

.Net Framework 2.0:

This version shipped with Microsoft Windows Server 2003 Release Candidate [RC]. This is the last version with support for Microsoft Windows 2000.

Changes in .NET Framework since 1.1:

1) Full 64-bit support for both the x64 and the IA64 hardware platforms.
2) Language support for Generics built directly into the .NET CLR.
3) Many additional and improved ASP.NET web controls.
4) New data controls with declarative data binding.
5) New personalization features for ASP.NET, such as support for themes, skins and webparts.
6) Numerous API changes and many more.

New in .NET framework 2.0

It brings a lot of evolution in class of the framework and refactor control including the support of

Generics
Anonymous methods
Partial class
Nullable type
The new API gives a fine grain control on the behavior of the runtime with regards to multithreading, memory allocation, assembly loading and more
Full 64-bit support for both the x64 and the IA64 hardware platforms
New personalization features for ASP.NET, such as support for themes, skins and webparts.
.NET Micro Framework

New in .NET framework 3.0

Also called WinFX,includes a new set of managed code APIs that are an integral part of Windows Vista and Windows Server 2008 operating systems and provides

Windows Communication Foundation (WCF), formerly called Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services.
Windows Presentation Foundation (WPF), formerly called Avalon; a new user interface subsystem and API based on XML and vector graphics, which uses 3D computer graphics hardware and Direct3D technologies.
Windows Workflow Foundation (WF) allows for building of task automation and integrated transactions using workflows.
Windows CardSpace, formerly called InfoCard; a software component which securely stores a person’s digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website

New in .NET framework 3.5

It implement Linq evolution in language. So we have the following evolution in class:

Linq for SQL, XML, Dataset, Object
Addin system
p2p base class
Active directory
ASP.NET Ajax
Anonymous types with static type inference
Paging support for ADO.NET
ADO.NET synchronization API to synchronize local caches and server side datastores
Asynchronous network I/O API
Support for HTTP pipelining and syndication feeds.
New System.CodeDom namespace.

If we take a look into .net Framework 3.0,

What’s new in .NET Framework 4.0

·         Next versions of Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) will provide better support for Web 2.0 technologies like REST, POX, ATOM.

·         Performance and Scalability of WCF and WF are expected to increase by minimum 10X.

·         New workflow models.

·         Seamless integration between WCF and WF including a new Visual Designer.

·         Parallel Programming framework using PLINQ, Task Parallel Library and Coordination Data Structures to better utilize power of multi-processor and multi-core machines.

·         Build declarative applications with WF, WCF and WPF using XAML. So, XAML is no more only for WPF and WF.

·         WCF enhancements:

o    RESTful enhancements

§  Simplifying the building of REST Singleton & Collection Services, ATOM Feed and Publishing Protocol Services, and HTTP Plain XML Services using WCF

§  WCF REST Starter Kit to be released on Codeplex to get early feedback

o    Messaging enhancements

§  Transports – UDP, MQ, Local in-process

§  Protocols – SOAP over UDP, WS-Discovery, WS-BusinessActivity, WS-I BP 1.2

§  Duplex durable messaging

o    Correlation enhancements

§  Content and context driven, One-way support

o    Declarative Workflow Services

§  Seamless integration between WF and WCF and unified XAML model

§  Build entire application in XAML, from presentation to data to services to workflow

·         WF enhancements :

o    Significant improvements in performance and scalability

§  Ten-fold improvement in performance

o    New workflow flow-control models and pre-built activities

§  Flowcharts, rules

§  Expanded built-in activities – PowerShell, database, messaging, etc.

o    Enhancements in workflow modeling

§  Persistence control, transaction flow, compensation support, data binding and scoping

§  Rules composable and seamlessly integrated with workflow engine

o    Updated visual designer

§  Easier to use by end-users

§  Easier to rehost by ISVs

§  Ability to debug XAML

·         First CTP to be released during PDC in Oct 2008.

·         Information on this page will be updated as and when it is available.

ASP.NET Page Life Cycle

Page Event Typical Use
PreInit Raised after the start stage is complete and before the initialization stage begins.

Use this event for the following:

  • Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.Create or re-create dynamic controls.
  • Set a master page dynamically.
  • Set the Theme property dynamically.
  • Read or set profile property values.

Note

If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.

Init Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.

Use this event to read or initialize control properties.

InitComplete Raised at the end of the page’s initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.

Use this event to make changes to view state that you want to make sure are persisted after the next postback.

PreLoad Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.
Load The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.

Use the OnLoad event method to set properties in controls and to establish database connections.

Control events Use these events to handle specific control events, such as a Button control’s Click event or a TextBox control’s TextChanged event.

Note

In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.

LoadComplete Raised at the end of the event-handling stage.

Use this event for tasks that require that all other controls on the page be loaded.

PreRender Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)

The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.

Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.

PreRenderComplete Raised after each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.
SaveStateComplete Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.
Render This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control’s markup to send to the browser.

If you create a custom control, you typically override this method to output the control’s markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.

A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.

Unload Raised for each control and then for the page.

In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.

For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

Note

During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception

 

Object-oriented programming (OOP)

Object-oriented programming (OOP) is a programming paradigm that uses “objects” and their interactions to design applications and computer programs. Programming techniques may include features such as abstraction, encapsulation, inheritance, and polymorphism.

It is a problem solving technique to develop software systems.

Class: A class describes all the attributes of objects , as well as the methods that implement the behavior of member objects.

Object: It’s a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Objects are members of a class.Attributes and behavior of an object are defined by the class definition.

Access keywords: Access keywords define the access to class members from the same class and from other classes. The most common access keywords are:

  • Public: Allows access to the class member from any other class.
  • Private: Allows access to the class member only in the same class.
  • Protected: Allows access to the class member only within the same class and from inherited classes.
  • Internal: Allows access to the class member only in the same assembly.
  • Protected internal: Allows access to the class member only within the same class, from inherited classes, and other classes in the same assembly.
  • Static: Indicates that the member can be called without first instantiating the class.

Abstraction: “Abstraction” simply means showing only those details to the user which are of use to them , and hiding up the unnecessary portion.

Example: When an user uses the ATM he/she thinks that the ATM card is validated by the ATM machine he/she is using
But the user has no idea how it is validated

Encapsulation: Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. In other words, encapsulation is the ability of an object to be a container (or capsule) for related properties (ie. data variables) and methods (ie. functions).

Example:
public class Box
{
private int length;
private int width;
private int height;

public void setLength(int p)
{length = p;}

public void setWidth(int p)
{width = p;}

public void setHeight(int p)
{height = p;}

public int displayVolume()
{System.out.println(length*width*height)…
}

public static void main(String args [ ])
{
Box b1=new Box(3,4,5);
b1.displayvolume();
}

Polymorphism: Polymorphism is briefly described as “one interface, many implementations”.

There are two types of polymorphism:

Compile time polymorphism – It is achieved by overloading functions and operators.
Method Overloading
– Method with same name but with different arguments is called method overloading.
– Method Overloading forms compile-time polymorphism.

Example of Method Overloading:
class A1
{
void hello()
{ Console.WriteLine(“Hello”); }

void hello(string s)
{ Console.WriteLine(“Hello {0}”,s); }
}

Run time polymorphism – It is achieved by overriding virtual functions. Method Overriding
– Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass.
– Method overriding forms Run-time polymorphism.
– Note: By default functions are not virtual in C# and so you need to write “virtual” explicitly. By declaring base class function as virtual, we allow the function to be overridden in any of derived class.

Example of Method Overriding:
Class parent
{
virtual void hello()
{ Console.WriteLine(“Hello from Parent”); }
}

Class child : parent
{
override void hello()
{ Console.WriteLine(“Hello from Child”); }
}

static void main()
{
parent objParent = new child();
objParent.hello();
}
//Output
Hello from Child.

Inheritance: Inheritance allows a class to have the same behavior as another class and extend or tailor that behavior to provide special action for specific needs.

Inheritance is achieved by using “Inherits” keyword in VB.NET (For C# it is “:”). There are two classes one is the parent “ClsParent” and second is the child “ClsChild”.Parent class has a string which has to parsed for junk data “@” and “/”.ClsParent has the functionality which parses only cleans up “@”.”ClsChild” then inherits from parent and adds extra functionality by parsing “/”.

public class ClsParent {
    
protected string strData = “jksdhkj@dadad///ajkdhsjakd“;
    public string 
Parse() {
        
string PstrData;
        
PstrData strData;
        
PstrData Replace(PstrData, “@”, ” “);
        return 
PstrData;
    
}
    
public string GetActualString() {
        
return strData;
    
}
}

Above is the source which parses only “@” of strData variable.

public class ClsChild : ClsParent {
    
public void ParseBackSlash() {
        
string PstrData;
        
PstrData = this.Parse();
        
PstrData Replace(PstrData, “/”, ” “);
        return 
PstrData;
    
}
}

Above is the source code for “ClsChild” which does the remaining work.It adds extra functionality by parsing “/” junk character’s of the data.

Note:- Strdata was accessible only because it was defined as protected in the parent class.



 

.Net Framework

CLS(Common Language Specification): This is a subset of the CTS which all .NET languages are expected to support.Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner.

ADO.NET: ADO.NET provides support for data access in Microsoft .NET and its features include:

·         Support for disconnected data access model
·         Integration with the .Net framework
·         XML support

This model can, however, only be used from the managed code environment. This implies that there is no COM interoperability allowed for ADO.NET.

Class library:

The .NET Framework includes a set of standard class libraries. The class library is organized in a hierarchy of namespaces. Most of the built in APIs are part of either System.* or Microsoft.* namespaces. These class libraries implement a large number of common functions, such as file reading and writing, graphic rendering, database interaction, and XML document manipulation, among others. The .NET class libraries are available to all CLI compliant languages. The .NET Framework class library is divided into two parts: the Base Class Library and the Framework Class Library.

The Base Class Library (BCL) includes a small subset of the entire class library and is the core set of classes that serve as the basic API of the Common Language Runtime.[11] The classes in mscorlib.dll and some of the classes in System.dll and System.core.dll are considered to be a part of the BCL. The BCL classes are available in both .NET Framework as well as its alternative implementations including .NET Compact Framework, Microsoft Silverlight and Mono.

Namespaces in the BCL

System
System. CodeDom
System. Collections
System. Diagnostics
System. Globalization
System. IO
System. Resources
System. Text
System. Text.RegularExpressions

The Framework Class Library (FCL) is a superset of the BCL classes and refers to the entire class library that ships with .NET Framework. It includes an expanded set of libraries, including Windows Forms, ADO.NET, ASP.NET, Language Integrated Query, Windows Presentation Foundation, Windows Communication Foundation among others. The FCL is much larger in scope than standard libraries for languages like C++, and comparable in scope to the standard libraries of Java.

Common Language Runtime (CLR): It is the heart of the .NET framework. All Languages have runtime and its the responsibility of the runtime to take care of the code execution of the program. The CLR is a runtime engine that handles memory allocation, security, code verification, type verification, exception handling, and garbage collection.

Managed code runs inside the environment of CLR i.e. .Net runtime.In short all IL are managed code.

The source code in .NET is compiled to an intermediate language called the Microsoft Intermediate Language or the MSIL. This is then converted to the native code at runtime by the Just In Time Compiler (JIT).

CLR Services:
The CLR provides a lot of services for applications that run in the .NET environment. These include:
• Just In Time Compilation
• Memory management and isolation of the application memory
• Garbage Collection
• Code Verification
• Code Access Security
• Verification of type safety
• Exception handling
• Conversion of the MSIL to the native code
• Access to metadata

The JIT compiler: The MSIL code and metadata are loaded into the memory with the help of Common Language Runtime (CLR). The JIT compiler then compiles the MSIL code to native code and executes it at runtime. The JIT does not convert the entire MSIL code to its native equivalent. Rather, it does so in demands, i.e., the portion of the current execution code is converted and loaded into the memory. Hence, it works the same way that Demand Paging works in Virtual Memory supporting Operating Systems. 

Garbage Collection: CLR automatically manages memory thus eliminating memory leakes. When objects are not referred GC automatically releases those memory thus providing efficient memory management.

IL( Intermediate language )-to-native translators and optimizer’s : CLR uses JIT and compiles the IL code to machine code and then executes.

Code Verification: This ensures proper code execution and type safety while the code runs.It prevents the source code to perform illegal operation such as accessing invalid memory locations etc.