Tuesday, November 5, 2013

ASP.NET Page Life Cycle In Detail

ASP.NET Page Life Cycle In Detail

When a page is requested, it is loaded into the server memory, processed and sent to the browser. Then it is unloaded from the memory. At each of this steps, methods and events are available, which could be overridden according to the need of the application. In other words, you can write your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the components on the page, except the directives are part of this control tree. You can see the control tree by adding trace= "true" to the Page directive. We will cover page directives and tracing under 'directives' and 'error handling'.
The page life cycle phases are:

  • Initialization
  • Instantiation of the controls on the page
  • Restoration and maintenance of the state
  • Execution of the event handler codes
  • Page rendering
Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the page life cycle. It also helps in writing custom controls and initializing them at right time, populate their properties with view-state data and run control behavior code.
Following are the different stages of an ASP.Net page:

  • Page request . when ASP.Net gets a page request, it decides whether to parse and compile the page or there would be a cached version of the page; accordingly the response is sent
  • Starting of page life cycle . at this stage, the Request and Response objects are set. If the request is an old request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page is also set.
  • Page initialization . at this stage, the controls on the page are assigned unique ID by setting the UniqueID property and themes are applied. For a new request postback data is loaded and the control properties are restored to the view-state values.
  • Page load . at this stage, control properties are set using the view state and control state values.
  • Validation . Validate method of the validation control is called and if it runs successfully, the IsValid property of the page is set to true.
  • Postback event handling . if the request is a postback (old request), the related event handler is called.
  • Page rendering . at this stage, view state for the page and all controls are saved. The page calls the Render method for each control and the output of rendering is written to the OutputStream class of the Page's Response property.
  • Unload . the rendered page is sent to the client and page properties, such as Response and Request are unloaded and all cleanup done.
At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is basically a function or subroutine, bound to the event, using declarative attributes like Onclick or handle.Event are described at last.

 Let  Us Understand in More Detail

When a visitor first requests an .aspx page on your server, the server sends it to the HTTP Pipeline. 
(HTTP Pipeline is a chain of managed objects that sequentially process the request and convert it to plain HTML text content.)
The HTTP Pipeline handles all processes involved in converting all of the application code into HTML to be interpreted by the browser. 

The first class initiated is called HttpRuntime. This class finds a free HttpApplication object to start processing the request. The HttpApplication object then runs the appropriate handler assigned in the web.config and machine.config files for the requested extension.

The extension .aspx can be handled by the HandlerClass or HandlerFactory class. The HttpApplication objects starts the IHttpHandler interface which begins processing the application code by calling the processRequest() method.

The processRequest() method then calls the FrameworkInitialize() method which begins building the control trees for the requested page. 
(You can see the Control tree of any aspx page by giving Trace="true" in Page Directive)

Request(.aspx) --> IIS --> HTTPPipeLine --> HttpRuntime -->HttpApplication -->Handler(HandlerClass/HandlerFactory) --> Process Application by processRequest() -->
FrameworkInitialize() 


Now the processRequest() method cycles through the page’s life cycle in the order listed below.

Following are the page life cycle events:

  • PreInit . PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the page is a postback. It sets the themes and master pages, creates dynamic controls and gets and sets profile property values. This event can be handled by overloading the OnPreInit method or creating a Page_PreInit handler.
  • Init . Init event initializes the control property and the control tree is built. This event can be handled by overloading the OnInit method or creating a Page_Init handler.
  • InitComplete . InitComplete event allows tracking of view state. All the controls turn on view-state tracking.
  • LoadViewState . LoadViewState event allows loading view state information into the controls.
  • LoadPostData . during this phase, the contents of all the input fields defined with the <form> tag are processed.
  • PreLoad . PreLoad occurs before the post back data is loaded in the controls. This event can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.
  • Load . the Load event is raised for the page first and then recursively for all child controls. The controls in the control tree are created. This event can be handled by overloading the OnLoad method or creating a Page_Load handler.
  • LoadComplete . the loading process is completed, control event handlers are run and page validation takes place. This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler.
  • PreRender . the PreRender event occurs just before the output is rendered. By handling this event, pages and controls can perform any updates before the output is rendered.
  • PreRenderComplete . as the PreRender event is recursively fired for all child controls, this event ensures the completion of the pre-rendering phase.
  • SaveStateComplete . state of control on the page is saved. Personalization, control state and view state information is saved. The HTML markup is generated. This stage can be handled by overriding the Render method or creating a Page_Render handler.
  • UnLoad . the UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.

Short Forms:
PreIn->In->Incomp
LoadVstate->LoadPostData
PreLoad->Load->Loadcomplete
PreRender->PreRendComplete->SaveStatecomplete
UnLoad


Now Let Us Come to Programming Stuff- How to Handle Above Events:
Below is the Code where I handled each event Try and Enjoy...

   StringBuilder sb = new StringBuilder();
    protected void Page_PreInit(object o, EventArgs e)
    {
        sb.Append("<b>Page Pre_Init</b> - Occurs at the begining of the Page Initialization <br />");
    }
    protected void Page_Init(object sender, EventArgs e)
    {
        sb.Append("<b>Page Init </b>- Occurs when the Server Control is Initialized. It is the first step in the ASP.NET Page Life Cycle <br />");
    }
    public void Page_InitComplete(object sender, EventArgs e)
    {
        sb.Append("<b>Page Init Complete </b>- Occurs when the Page Initialization is Complete <br />");
    }


   
    public void Page_PreLoad(object sender, EventArgs e)
    {
        sb.Append("<b>Page Pre Load </b>- Occurs before the Load Event <br />");
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        sb.Append("<b>Page Load </b>- Occurs when the Server Control is Loaded in the Page Object <br />");
    }
    void Page_LoadComplete(object sender, EventArgs e)
    {
        sb.Append("<b>Page Load Complete </b>- Occurs at the end of Load Stage of the Page Life Cycle. <br />");
    }



    void Page_PreRender(object sender, EventArgs e)
    {
        sb.Append("<b>Page Pre Render </b>- Occurs after the Server Controls is Loaded in the Page but before the Rendering</div> <br />");
    }
    void Page_PreRenderComplete(object sender, EventArgs e)
    {
        sb.Append("<b>Page Pre Render Complete </b>- Occurs before the Page Content is Rendered <br />");
        Response.Write(sb.ToString());
    }
   
      /// This is the event when the page is unloaded from the server memory and ready to be returned to the client,
    /// Here the response is not available, so you cannot modify the Response

   
    void Page_Unload(object sender, EventArgs e)
    {
    }
   
 
 

No comments: