Tuesday, June 19, 2007

Introduction to Application Object in ASP.NET

We are familiar with the Application object since ASP days. Most of the functionality of the Application object continues to be there in the .NET equivalent. However, the Application object in ASP.NET is much more flexible and enriched. There are a large number of events available. Each type of event can be used for a specific functional purpose. Here is a quick summary of which event to use in which scenario.

Before we understand the events, we need to know the steps that a Web request goes through during its life cycle. The request begins with the client browser and continues till the request is completely processed and the response (if any) is sent back to the client.

Order of execution

This lifecycle is called the ASP.NET pipeline. Here is how the pipeline looks. It is a step-by-step process through which various parts of the request are processed in a structured manner.

The order is as follows:

Events

Here are the types of events.

1. Events which always occur for every request

a. Request related events
b. Response related events

2. Events which occur only under certain conditions

Events which occur for each request

a) Request related events:

These events occur when a new request is received. These are listed in the order of occurrence.

Event: Application_OnBeginRequest

Comment: Raised for each request. Even for Web service requests

Event: Application_OnAuthenticateRequest

Comment: Raised when authentication is about to begin

Practical Usage: Use this to override the default authentication mechanism and write completely custom authentication code here.



When do you use this? When you require an authentication mechanism that does not fit into the default authentication methodologies given with .NET.

Further, you can use this during the development phase to quickly override the base authentication mechanism.

During production phase, simply remove this event code.

Event:Application_OnAuthorizeRequest

Comment:Raised when authorisation is about to begin. This decides what privileges to offer the current requestor.

Practical Usage: Again used to override the default authorisation and replace it with custom authorisation.

Event: Application_OnResolveRequestCache

Comment: This one is used in Page Caching. Page Caching stores page output in a cache and later serves similar requests from the cache. This increases performance dramatically.

This event is used by ASP.NET to decide whether to rerun the page code or deliver the page from the cache.

Practical Usage: Writing code for this event allows you to customise how page caching works. Further it also allows you to write code that can execute for each request, irrespective of whether the page was delivered from page cache or from the ASPX page.

For example, you can use this for generating an audit trail or performance log or for incrementing online page view counters.

Event: Application_OnAcquireRequestState

Comment: Event fires when the Session state is about to be populated for the request.

Practical Usage: Your code can customise the content of the Session stateThis is done when you want a pre-created custom item to be inserted in the Session state. This can then be handled by the page or Web service.

This will centralise the code that we often write in the page level events.

It is important to cross check with your existing code, to judge which piece of code can be better handled in this event.

Event: Application_OnPreRequestHandlerExecute

Comment:Before the page handler (or Web service handler) is called for the incoming request.

Practical Usage: Useful if you want to perform some operations before the default page handler takes over.

b) Response related events:

Event: Application_OnUpdateRequestCache

Comment:This is raised when ASP.NET decides to update the Page Output cache by actually executing a page.

Practical Usage: Write custom code here to monitor cache refresh rate (to judge the effectiveness of page caching in your application).

Event: Application_OnReleaseRequestState

Comment:Occurs when the Session data is released.

Practical Usage: Custom objects created on OnRequestState can be now handled.

Event: Application_OnPostRequestHandlerExecute

Comment: Raised after the default handler finishes execution.

Practical Usage: Used to create custom HTTP header and body.

Event: Application_OnEndRequest

Comment: Corresponding to BeginRequest.



Practical Usage: Last event to fire. Cleanup tasks are best done here.

If you want to add something to ALL pages within an application do it here.

Event: PreSendRequestHeaders and PreSendRequestContent

Comment: These events fire after the entire data is ready to be sent as the client response.

Practical Usage: Pre-event is fired when HTTP headers are sent. If you want to change any content, you must update the operation before this event fires. Otherwise, wrong size information would be sent in the header.

The content event fires after the entire body text is sent to the client.

Of all these events the EndRequest event is guaranteed to occur. This event is the place which you should use to perform tasks which require to be done after request completion – including cleanup, in this event code.

Conditional events

Event: Application_OnStart

Comment: This one is familiar to all ASP developers. This occurs only once per application when it starts. Practical Usage: One-time tasks can be done here. These could be data connections, adding data that is likely to be used frequently to cache objects, setting values for variables and so on.

Event: Application_OnEnd

Comment: Occurs when application ends.

Practical Usage: Generally used to cleanup things that were set up during the application execution period.

Event: Session_OnStart

Comment: Fires for each user when the session begins.

Practical Usage: Setting user specific values, caching items based upon user context.

Event: Session_OnEnd

Comment: Opposite of the previous event.

Practical Usage: User Specific Cleanup, audit trail, usage statistics, logging how the state terminated and so on.

Event: Application_Error

Comment: When unhandled error occurs.

Practical Usage: Good for logging errors, logging additional environmental information, notifying administrators depending upon type of error, taking global actions to manage impact of errors.

Event: Application_OnDisposed

Comment: Occurs when CRL removes the application from memory.

Practical Usage: Additional cleanup procedures.

CompleteRequest method

This method is used to bypass normal processing of the HTTP request. If you handle some event with custom code and then you do not want the control to pass to further default event handlers in the request processing chain, call this method. This method, when called, ignores all further handlers and then raises EndRequest event.

HTTP modules

Handlers for various HTTP functions are configured using HTTPModules. These modules are defined in ‘machine.config’ and can be overridden in ‘web.config’.

Various modules are utilised in serving a particular request. It is possible to write your own custom HTTP modules for implementing special functionality not available within .NET.

The HTTP handler is the class which manages the actual HTTP request. By default this is the page class in ‘system.web.ui.page’ namespace.

To create an HTTP module, you need to write a class which implements the IHTTPModule interface. To inform the runtime to use the custom module, you need to modify the ‘web.config’ file.

Handlers for various types of files are mapped in IIS application configuration settings.

The diagram below shows the ASP.NET file extensions and the relevant handlers.

Global.ASAX

All the custom code for overriding the Application events is written here. This file is optional. But if you need to customise the application event management logic, you need to create this and write code in it.

No comments: