Friday, January 6, 2012

ASP.NET Application and Page Life Cycle

ASP.NET Application and Page Life Cycle

Introduction

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.

This is a small Ebook for all my .NET friends which covers topics like WCF, WPF, WWF, Ajax, Core .NET, SQL, etc. You can download the same from here or else you can catch me on my daily free training here.

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.

http://www.codeproject.com/KB/aspnet/ASPDOTNETPageLifecycle/1.jpg

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.

http://www.codeproject.com/KB/aspnet/ASPDOTNETPageLifecycle/2.jpg

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.

http://www.codeproject.com/KB/aspnet/ASPDOTNETPageLifecycle/3.jpg

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.

http://www.codeproject.com/KB/aspnet/ASPDOTNETPageLifecycle/4.jpg

  • 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.

http://www.codeproject.com/KB/aspnet/ASPDOTNETPageLifecycle/5.jpg

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.

http://www.codeproject.com/KB/aspnet/ASPDOTNETPageLifecycle/6.jpg

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.



SQL SERVER – Rules for Optimizining Any Query – Best Practices for Query Optimization And Sql Avoid Cursors alternate to While Loop

SQL SERVER – Rules for Optimizining Any Query – Best Practices for Query Optimization

  • Table should have primary key
  • Table should have minimum of one clustered index
  • Table should have appropriate amount of non-clustered index
  • Non-clustered index should be created on columns of table based on query which is running
  • Following priority order should be followed when any index is created a) WHERE clause, b) JOIN clause, c) ORDER BY clause, d) SELECT clause
  • Do not to use Views or replace views with original source table
  • Triggers should not be used if possible, incorporate the logic of trigger in stored procedure
  • Remove any adhoc queries and use Stored Procedure instead
  • Check if there is atleast 30% HHD is empty – it improves the performance a bit
  • If possible move the logic of UDF to SP as well
  • Remove * from SELECT and use columns which are only necessary in code
  • Remove any unnecessary joins from table
  • If there is cursor used in query, see if there is any other way to avoid the usage of this (either by SELECT … INTO or INSERT … INTO, etc)

Sql Avoid Cursors alternate to While Loop

set nocount on;

declare @tbl_record table(record_id int)

declare @record_id int

insert into @tbl_record

select top 3 record_id from tbl_record order by 1

select top 1 @record_id=record_id From @tbl_record

while(@@ROWCOUNT!=0)

begin

select * from @tbl_record

print @record_id

delete from @tbl_record where record_id=@record_id

select top 1 @record_id=record_id From @tbl_record

end

How IIS Process ASP.NET Request

How IIS Process ASP.NET Request

Introduction

When request come from client to the server a lot of operation is performed before sending response to the client. This is all about how IIS Process the request. Here I am not going to describe the Page Life Cycle and there events, this article is all about the operation of IIS Level. Before we start with the actual details, let’s start from the beginning so that each and everyone understand it’s details easily. Please provide your valuable feedback and suggestion to improve this article.

What is Web Server ?

When we run our ASP.NET Web Application from visual studio IDE, VS Integrated ASP.NET Engine is responsible to execute all kind of asp.net requests and responses. The process name is “WebDev.WebServer.Exe” which actually takw care of all request and response of an web application which is running from Visual Studio IDE.

Now, the name “Web Server” comes into picture when we want to host the application on a centralized location and wanted to access from many locations. Web server is responsible for handle all the requests that are coming from clients, process them and provide the responses.

http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041500763171406_Firstone.JPG

What is IIS ?

IIS (Internet Information Server) is one of the most powerful web servers from Microsoft that is used to host your ASP.NET Web application. IIS has it’s own ASP.NET Process Engine to handle the ASP.NET request. So, when a request comes from client to server, IIS takes that request and process it and send response back to clients.

http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041501029987812_IISProcessRequest.JPG

Request Processing :

Hope, till now it’s clear to you that what is Web server and IIS is and what is the use of them. Now let’s have a look how they do things internally. Before we move ahead, you have to know about two main concepts

1. Worker Process
2. Application Pool

Worker Process: Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system. All the ASP.Net functionality runs under the scope of worker process. When a request comes to the server from a client worker process is responsible to generate the request and response. In a single word we can say worker process is the heart of ASP.NET Web Application which runs on IIS.
Application Pool: Application pool is the container of worker process. Application pools is used to separate sets of IIS worker processes that share the same configuration. Application pools enables a better security, reliability, and availability for any web application. The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected. This makes sure that a particular web application doesn’t not impact other web application as they they are configured into different application pools.

http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041500651403828_AppPool.JPG

Application Pool with multiple worker process is called “Web Garden”.
Now, I have covered all the basic stuff like Web server, Application Pool, Worker process. Now let’s have look how IIS process the request when a new request comes up from client.
If we look into the IIS 6.0 Architecture, we can divided them into Two Layer

1. Kernel Mode
2. User Mode

Now, Kernel mode is introduced with IIS 6.0, which contains the HTTP.SYS. So whenever a request comes from Client to Server, it will hit HTTP.SYS First.

http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041500723005391_BasicLevel.JPG

Now, HTTP.SYS is Responsible for pass the request to particular Application pool. Now here is one question, How HTTP.SYS comes to know where to send the request? This is not a random pickup. Whenever we creates a new Application Pool, the ID of the Application Pool is being generated and it’s registered with the HTTP.SYS. So whenever HTTP.SYS Received the request from any web application, it checks for the Application Pool and based on the application pool it send the request.

http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041501112380391_RegisterApp.JPG

So, this was the first steps of IIS Request Processing.
Till now, Client Requested for some information and request came to the Kernel level of IIS means at HTTP.SYS. HTTP.SYS has been identified the name of the application pool where to send. Now, let’s see how this request moves from HTTP.SYS to Application Pool.

In User Level of IIS, we have Web Admin Services (WAS) which takes the request from HTTP.SYS and pass it to the respective application pool.

http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041501155671406_Was.JPG

When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) . The worker process “w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll) and adds the mapping into IIS.
Note : Sometimes if we install IIS after installing asp.net, we need to register the extension with IIS using aspnet_regiis command.

http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041501195202656_WithAll.JPG

When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application. HTTPRuntime is a class which calls the ProcessRequest method to start Processing.

http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041501078679219_ProcessRequest.JPG

When this methods called, a new instance of HTTPContext is been created. Which is accessible using HTTPContext.Current Properties. This object still remains alive during life time of object request. Using HttpContext.Current we can access some other objects like Request, Response, Session etc.

http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041500806755391_HttpContext.JPG

After that HttpRuntime load an HttpApplication object with the help of HttpApplicationFactory class.. Each and every request should pass through the corresponding HTTPModule to reach to HTTPHandler, this list of module are configured by the HTTPApplication.
Now, the concept comes called “HTTPPipeline”. It is called a pipeline because it contains a set of HttpModules ( For Both Web.config and Machine.config level) that intercept the request on its way to the HttpHandler. HTTPModules are classes that have access to the incoming request. We can also create our own HTTPModule if we need to handle anything during upcoming request and response.

http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041500917175312_httppipleline.JPG

HTTP Handlers are the endpoints in the HTTP pipeline. All request that are passing through the HTTPModule should reached to HTTPHandler. Then HTTP Handler generates the output for the requested resource. So, when we requesting for any aspx web pages, it returns the corresponding HTML output.

All the request now passes from httpModule to respective HTTPHandler then method and the ASP.NET Page life cycle starts. This ends the IIS Request processing and start the ASP.NET Page Lifecycle.

http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041500577575703_allStep.JPG

Conclusion

When client request for some information from a web server, request first reaches to HTTP.SYS of IIS. HTTP.SYS then send the request to respective Application Pool. Application Pool then forward the request to worker process to load the ISAPI Extension which will create an HTTPRuntime Object to Process the request via HTTPModule and HTTPHanlder. After that the ASP.NET Page LifeCycle events starts.

This was just overview of IIS Request Processing to let Beginner’s know how the request get processed in backend. If you want to learn in details please check the link for Reference and further Study section.