For training related to .net,OOPS,design patterns, MVC,WCF and .net fundamentals
contact at sukeshmarla@gmail.com or Click Here

05 August 2012

Asp.net page Life Cycle

In this article we will explore different events which take place right from the time user sends a request ,till he get the final rendered result.

Introduction

Just like normal living being, every asp.net control including Page has a life.
In our life we go through various events like Birth, Education, Marriage, Job and at the end death. And every event does some important task.
Similarly whenever a asp.net Page/Control is requested it goes through a sequence of events.

Before moving further i would like to put light towards some important concepts.

How the Request is handled by IIS.

We put URL to a aspx page in browser address bar and press enter, what happen..we get the response in terms of rendered HTML but how?
  1. We are requesting something from browser means indirectly we are requesting something from Web Server, that means IIS. IIS based on the file extension decides which ISAPI extension can serve the request.
    And in case of asp.net(.aspx) it will be aspnet_isapi_dll so passed to same for processing.
  2. When the first request comes to the website,
    1. Application domain gets created by ApplicationManager class where exactly the website runs, and which creates an isolation between 2 web applications.
    2. Within the application domain an instance of the HostingEnvironment class is created which provide access information about the application such as name of the folder where the application is stored.
  3. Next asp.net creates core objects like HttpContext, HttpRequest,HttpResponse.
  4. Finally Application Starts by creating an instance of HttpApplication Class (which can be reused for multiple requests to maximize performance).

Request processing by HttpApplication

  • While processing request, HttpApplication invokes various events which includes Module Events, handlers and Page Events.
  • Sequence is
    1. Module events - Important events are BeginRequest, AuthenticateRequest, AuthorizeRequest, ResolveRequestCache, AcquireRequestState and PreRequestHandlerExecute.
      We can use these events when we want to inject custom Pre-Processing logic, i.e, before Page Object is created.
      (you can read more about these events here
    2. Handler Events - Once the above 6 events are fired, ASP.NET engine will invoke ProcessRequest event if you have implemented HttpHandler in your project. (We normally use HttpHandlers when we want to put some logic based on the File extension, Like for ImageFiles, Aspx files,...)
    3. Page Events - After the HttpHandler logic executes Asp.net Page object is created during which various events will be fired and important ones are
      PreInit,Init,LoadViewState,LoadPostData ,Load,ControlEvents,PreRender,SaveViewState,Render.
      We go through every event as we move further.
    4. Module events - Important events are PostRequestHandlerExecute, ReleaserequestState, UpdateRequestCache and EndRequest.
      We use this when we want to custom Post-Processing logic.
  • Developer can extend any of the events as per there Convenience and logic.

A small Secret about Master Pages and Life Cycle Events

  • All though Master Pages seems like parent they are actually child or in short we can say they behave like user control for pages.
    <%@ Page Title="My Child Page" Language="C#" MasterPageFile="~/MyMaster.master" AutoEventWireup="true" CodeFile="ChildPage.aspx.cs" Inherits=" ChildPage "  %>
    
  • All events except Init and Unload fires from outside to inside manner.
    Means PageEvent will be fired first and then masterpages then user controls and so on.
  • PreInit is a kind of event which exists only for Page.
  • Some events get executed only if it's a postback(Full/Asynchronous).

Life Cycle Events

  1. PreInit - The properties like IsPostBack have been set at this time.
    This event will be used when we want to
    1. set master page dynamically.
    2. set theme dynamically.
    3. read or set profile property values.
    4. this event is also preferred if want to create any dynamic controls.
  2. Init
    1. Raised after all the controls have been initialized with their default values and any skin settings have been applied.
    2. Fired for individual controls first and then for page.
  3. LoadViewState
    1. Fires only if IsPostBack is true.
    2. Values stored in HiddenField with id as __ViewState decoded and stored into corresponding controls.
  4. LoadPostData - Some controls like
    1. Fires only if IsPostBack is true.
    2. Some controls like Textbox are implemented from IPostBackDataHandler and this fires only for such controls.
    3. In this event page processes postback data included in the request object pass it to the respective controls.
  5. PreLoad - Used only if want to inject logic before actual page load starts.
  6. Load - Used normally to perform tasks which are common to all requests, such as setting up a database query
  7. Control events
    • This event fired means IsPostBack is true.
    • Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
  8. PreRender - Raised after the page object has created all the controls that required for rendering which includes child controls and composite controls.
    1. Use the event to make final changes to the contents of the page or its controls before the values are stored into viewstate and rendering stage begins.
    2. Mainly used when want to inject custom Javascript logic.
  9. SaveViewState - All the control values that support viewstate are encoded and stored into the viewstate.
  10. Render-Generates output(html) to be rendered at client side.
    We can add custom html to the output if we want here.
  11. Unload
    1. Fired for individual controls first and then for page.
    2. Used to perform cleanup work like closing open files and database connections.

Reference links

http://msdn.microsoft.com/en-us/library/bb470252.aspx
http://msdn.microsoft.com/en-us/library/ms178472.aspx
http://msdn.microsoft.com/en-us/library/9ysfzy8h(v=vs.71)