Friday, August 28, 2009

ASP.NET Page Life Cycle - Interview Huh !!!

When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. It is important for you to understand the page life cycle so that you can write code at the appropriate life-cycle stage for the effect you intend and obviously to clear some BULLSHIT INTERVIEW !!!

General Page Life-cycle Stages (Courtsy MSDN, CP, UsualDosage, Several Blogs...)
In general terms, the page goes through the stages outlined in the following table. In addition to the page life-cycle stages, there are application stages that occur before and after a request but are not specific to a page.



Putting together an acronym for the page life cycle is easy enough. Since the Page Request technically isn't a part of the life cycle (it only indicates whether we actually will start the cycle or load a cached page) we won't include it in the acronym.
S � Start
I � Initialize
L � Load
V � Validate
E � Event Handling
R � Render
That gives us "SILVER", which is very easy to remember. However, it is important remember that the last part of the cycle is unload. You can remember it as "SILVER-U" or "SILVER-YOU" if that helps !!! Now that it's easy to remember the order of steps for the page lifecycle, we'll summarize exactly what happens and what events are pertinent to each stage.

1. Start
This is where page properties such as Request, Response, IsPostBack and UICulture are set. As a developer, you most likely won't really need to do anything in this stage of the cycle. If you need to access or override behavior for this step, use the PreInit method to create or re-create dynamic controls, set a master page or theme or read or set profile property values. It is important to note that 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.

2. Initialize
This stage can be very important to developers. Here, themes are applied, and unique ids are generated and set for controls. Developers have access to the Init, InitComplete and PreLoad methods in this stage. Microsoft's recommended usage for these methods is as follows:
Init � This event is raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.
InitComplete � This event is raised by the Page object. Use this event for processing tasks that require all initialization be complete.
PreLoad - Use this event if you need to perform processing on your page or control before the Load event. After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

3. Load
This stage is perhaps the most utilized by developers. In this stage controls are loaded with information retrieved from view and control states. The OnLoad is the event method that fires during this stage. This is where you will want to set properties for all of the server controls on your page, request query strings, and establish database connections.

4. Validation
If you have controls that require validation, they are validated here and you can now check the IsValid property of the control. The event associated with this is Validate, which contains one overloaded method that accepts a validation group string. The overloaded method instructs the controls in the specified group to validate.

5. Event Handling
The event handling for server controls occurs during this stage. This means that events such as Click, SelectedIndexChanged, etc are applied to your server controls, and, in the case of a postback, these event handlers are fired by the control. The accessible events of note in this stage are as follows:
LoadComplete � At this step, all of the controls for the page have been loaded.
PreRender � A few things of import happen here. First, the page object will call EnsureChildControls for each control, and finally for the page. Additionally, any data bound control that has a DataSourceID set will call its DataBind method. It is important to note that the PreRender event occurs for each control on the page. At the conclusion of this event, ViewState will be saved for the page and all of the controls.
SaveStateComplete � ViewState has been saved. If you have actions that do not require changes to controls but require ViewState to have been saved, you can handle the SaveStateComplete event.

6. Render
Render is not really an event. Rather, the page object calls this method on each control, which in turn writes out the HTML markup for the control to the browser. This stage is keenly important to developers who create custom controls, because the standard approach is to override the Render method for the control in order to output the custom markup. If your control inherits from a standard ASP.NET server control, you probably won't need to override the Render method unless you want to exhibit a different behavior than the control's default. This is outside the scope of this document, but for more reading, you can reference Microsoft's Developing Custom ASP.NET Server Controls. (http://msdn2.microsoft.com/en-us/library/zt27tfhy.aspx)

7. Unload
This final event occurs first for each control, then, finally, for the page. At this point, all controls have been rendered to the output stream and cannot be changed. During this event any attempt to access the response stream will result in an exception being thrown. This event is primarily for cleanup routines such as closing open database connections and open file streams, or, event logging and other tasks.

Methods
The following methods (which can all be overridden) occur in order during the lifecycle of an ASP.NET page. Please realize that some of these methods are called recursively, and multiple times depending on the content of the page. This list is the generalized order in which methods fire when a page loads. You can test this by creating a default ASP.NET application, overloading each of the below methods, and setting a breakpoint on each.
1. Construct
2. ProcessRequest
3. FrameworkInitialize
4. InitializeCulture
5. If child controls are present:
a. AddParsedSubObject
b. CreateControlCollection
c. AddedControl
d. ResolveAdapter
6. DeterminePostBackMode
7. OnPreInit
8. OnInit
9. TrackViewState
10. OnInitComplete
11. OnPreLoad
12. OnLoad
13. OnLoadComplete
14. EnsureChildControls
a. CreateChildControls
15. OnPreRender
16. OnPreRenderComplete
17. SaveViewState
18. OnSaveStateComplete
19. CreateHtmlTextWriter
20. RenderControl
a. Render
b. RenderChildren
21. VerifyRenderingInServerForm
22. OnUnload
23. Dispose

So, after theory comes the Practical Lab... Here, comes a code stub, which one can very easily use to learn clearly about page life cycle.

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("protected void Page_Load" + "
");
}
protected void Page_PreRender(object sender, EventArgs e)
{
Response.Write("protected void Page_PreRender" + "
");
}
protected void Page_PreInit(object sender, EventArgs e)
{
Response.Write("protected void Page_PreInit" + "
");
}
protected void Page_Init(object sender, EventArgs e)
{
Response.Write("protected void Page_Init" + "
");
}
protected void Page_InitComplete(object sender, EventArgs e)
{
Response.Write("protected void Page_InitComplete" + "
");
}

protected void Page_PreLoad(object sender, EventArgs e)
{
Response.Write("protected void Page_PreLoad" + "
");
}
protected void Page_ControlEvents(object sender, EventArgs e)
{
Response.Write("protected void Page_ControlEvents" + "
");
}
protected void Page_SaveStateComplete(object sender, EventArgs e)
{
Response.Write("protected void Page_SaveStateComplete" + "
");
}
protected void Page_Render(object sender, EventArgs e)
{
Response.Write("protected void Page_Render" + "
");
}
protected void Page_UnLoad(object sender, EventArgs e)
{
//Response is not available in this context.
}
/////////////////////////////////////////////////////////////
protected override void AddedControl(Control control, int index)
{
Response.Write("AddedControl Fired on " + control.ID + "
");
base.AddedControl(control, index);
}
protected override void AddParsedSubObject(object obj)
{
base.AddParsedSubObject(obj);
Response.Write("AddParsedSubObject" + obj.ToString() + "
");
}
public override void ApplyStyleSheetSkin(Page page)
{
base.ApplyStyleSheetSkin(page);
Response.Write("ApplyStyleSheetSkin " + page.ToString() + "
");
}
protected override void Construct()
{
base.Construct();
// No Response Object here yet!
}
protected override void CreateChildControls()
{
base.CreateChildControls();
Response.Write("CreateChildControls
");
}
protected override ControlCollection CreateControlCollection()
{
Response.Write("CreateControlCollection
");
return base.CreateControlCollection();
}
// etc. etc. just type the keyword "override" and select from the list! protected void Page_Load(object sender, EventArgs e)
}

Ref: http://msdn.microsoft.com/en-us/library/ms178472.aspx
http://69.10.233.10/KB/aspnet/ASPNET_Page_Lifecycle.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.page_events.aspx

In depth Pic Analysis: (Courtsy: Léon Andrianarivony)

1 comment:

  1. This is a nice article..
    Its easy to understand ..
    And this article is using to learn something about it..

    c#, dot.net, php tutorial, Ms sql server

    Thanks a lot..!
    ri70

    ReplyDelete