Tuesday, March 29, 2011

Asp.Net Page LifeCycle

When a page request is sent to the Web server, the page is run through a series of events during its creation and disposal.Each request for an .aspx page that hits IIS is handed over to HTTP Pipeline. HTTP Pipeline is a chain of managed objects that sequentially process the request and convert it to plain HTML text content. The start point of HTTP Pipeline is the HttpRuntime class. The ASP.NET infrastructure creates each instance of this class per AppDomain hosted within the worker process. HttpRuntime class picks up an HttpApplication object from an internal pool and sets it to work on the request. It finds out what class has to handle the request. The association between the resources and handlers are stored in the configurable file of the application
Once the HTTP page handler class is fully identified, the ASP.NET runtime calls the handler's ProcessRequest to start the process. This implementation begins by calling the method FrameworkInitialize(), which builds the control trees for the page. This is a protected and virtual member of TemplateControl class, class from which page itself derives.

Next the processRequest() makes page transits various phases: initialization, loading of viewstate and postback data, loading of page's user code and execution postback server-side events. Then page enters in render mode, the viewstate is updated and HTML generated is sent to the output console. Finally page is unloaded and request is considered completely served. 

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

Page_Init : This is fired after the page's control tree has been successfully created. All the controls that are statically declared in the .aspx file will be initialized with the default values. Controls can use this event to initialize some of the settings that can be used throughout the lifetime of the incoming web request. Viewstate information will not be available at this stage. This Event 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. 
Page_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. 
Page_Load: After initialization, page framework loads the view state for the page. Viewstate is a collection of name/value pairs, where control's and page itself store information that is persistent among web requests. It contains the state of the controls the last time the page was processed on the server. By overriding LoadViewState() method, component developer can understand how viewstate is restored.Once viewstate is restored, control will be updated with the client side changes. It loads the posted data values. The PostBackData event gives control a chance to update their state that reflects the state of the HTML element on the client.

At the end of the posted data changes event, controls will be reflected with changes done on the client. At this point, load event is fired.

 
btnSubmit_Clicked: Key event in the life cycle is when the server-side code associated with an event triggered on the client. When the user clicks on the button, the page posts back. 
RaisePostBackEvent: Page framework calls the RaisePostBackEvent. This event looks up for the event handler and run the associated delegate.
 
Page_PreRender: After PostBack event, page prepares for rendering. PreRender event is called. This is the place where user can do the update operations before the viewstate is stored and output is rendered. This Event 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. 
SaveViewState: Next stage is saving view state, all the values of the controls will be saved to their own viewstate collection. The resultant viewstate is serialized, hashed, base24 encoded and associated with the _viewstate hidden field.
 
Render: Next the render method is called. This method takes the HtmlWriter object and uses it to accumulate all HTML text to be generated for the control. For each control the page calls the render method and caches the HTML output. The rendering mechanism for the control can be altered by overriding this render method. 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.

Page_Unload: This is called just before the page object is dismissed. In this event, you can release critical resources you have such as database connections, files, graphical objects etc. After this event browser receives the HTTP response packet and displays the page. At this time Response object not available. 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. If you observe the given sample, if we use Response in this event, the system raises an error that says 'Response Object not available at this stage'

To understand the page life cycle clearly, create a website and add a PageLifeCycle.aspx page to the website. Add the below lines of code to the page and view it in the browser. 
PageLifeCycle.aspx 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageLifeCycle.aspx.cs" Inherits="PageLifeCycle" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Name</td><td><asp:TextBox ID="tbName" runat="server" ></asp:TextBox></td>
</tr>
<tr>
<td>Designation</td><td><asp:DropDownList ID="ddlDesignation" runat="server" ></asp:DropDownList> </td>
</tr>
<tr>
<td>&nbsp;</td><td><asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Clicked" /> </td>
</tr>
</table>
</div>
</form>
</body>
</html>


PageLifeCycle.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class PageLifeCycle : System.Web.UI.Page
{
int counter = 1;


protected void Page_PreLoad(object sender, EventArgs e)
{
WriteOutput("Page_PreLoad");
}

protected void Page_Load(object sender, EventArgs e)
{
}

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!IsPostBack)
{
BindDesignation();
}
WriteOutput("Page_Load");
}


private void BindDesignation()
{
List<Info> infoList = new List<Info>();
for (int i = 1; i <= 5; i++)
{
infoList.Add(new Info("Venkat"+i,"Software Engineer"+i));
}
ddlDesignation.DataSource = infoList;
ddlDesignation.DataValueField = "Designation";
ddlDesignation.DataTextField = "Designation";
ddlDesignation.DataBind();
}

protected override void LoadControlState(object savedState)
{
base.LoadControlState(savedState);
WriteOutput("LoadControlState");

}

protected void Page_LoadViewState(object sender, EventArgs e)
{
WriteOutput("LoadViewState");
}

protected override void LoadViewState(object viewState)
{
base.LoadViewState(viewState);
WriteOutput("LoadViewState");
}

protected override object SaveViewState()
{
WriteOutput("SaveViewState");
return base.SaveViewState();
}


protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArg)
{
base.RaisePostBackEvent(sourceControl,eventArg);
WriteOutput("RaisePostBackEvent");
}

protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
WriteOutput("Render");
}


protected void btnSubmit_Clicked(object sender, EventArgs e)
{
WriteOutput("btnSubmit_Clicked");
}

protected void Page_PreInit(object sender, EventArgs e)
{
WriteOutput("Page_PreInit");
}
protected void Page_Init(object sender, EventArgs e)
{
WriteOutput("Page_Init");
}

protected void Page_PreRender(object sender, EventArgs e)
{
WriteOutput("Page_PreRender");
}
protected void Page_Unload(object sender, EventArgs e)
{
//WriteOutput("Page_Unload");
}


private void WriteOutput(string eventName)
{
Response.Write("Step no: " + counter++ + "--> "+eventName+"<br/>");
Response.Write("Name: " + (tbName.Text == null ? "Null" : tbName.Text + "<br/>"));
Response.Write("Designation: " + (ddlDesignation.SelectedValue == null ? "Null" : ddlDesignation.SelectedValue + "<br/><br/>"));
}

}

public class Info
{
public string Name { get; set; }
public string Designation { get; set; }
public Info(string name,string designation)
{
Name = name;
Designation = designation;
}
}

If you view the page in the browser , the below screen will be shown,

Click on the Submit Button to Postback the page, then the below screen will be shown.