wtorek, 3 stycznia 2012

ASP.NET Page Life Cycle

ASP.NET Page Events Lifecycle


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.

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.

The page life cycle phases are:
  • initialization, 
  • instantiating controls, 
  • restoring and maintaining state, 
  • running event handler code
  • rendering.

ASP.Net Page STAGE Life Cycle


Some parts of the life cycle occur only when a page is processed as a postback. For postbacks, the page life cycle is the same during a partial-page postback (as when you use an UpdatePanel control) as it is during a full-page postback.

Stage Description
Page request
  • The page request occurs before the page life cycle begins. 
  • When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.
Start
  • In the start stage, page properties such as Request and Response are set. 
  • At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. 
  • The page also sets the UICulture property.
Initialization
  • During page initialization, controls on the page are available and each control's UniqueID property is set. 
  • A master page and themes are also applied to the page if applicable. 
  • For a new request postback data is loaded and the control properties are restored to the view-state values.
  • If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.
Load
  • Control properties are set using the view state and control state values.
  • During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.
Postback event handling
  • If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called .
    (There is an exception to this sequence: the handler for the event that caused validation is called after validation.)
Validation
  • Validate method of the validation control is called and if it runs successfully, the IsValid property of the page is set to true.
Rendering
  • Before rendering, view state is saved for the page and all controls. 
  • During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property.
  • View state for the page and all controls are saved.
Unload
  • The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. 
  • At this point, page properties such as Response and Request are unloaded and cleanup is performed.




ASP.NET Page Life-Cycle Events

At each stage of the page life cycle, the page raises some events, which could be coded.
For control events, you bind the event handler to the event, either declaratively using attributes such as onclick, or in code.


Pages also support automatic event wire-up, meaning that ASP.NET looks for methods with particular names and automatically runs those methods when certain events are raised.
Page Events

Page Event Typical Use
PreInit
  • PreInit is the first event in page life cycle.
  • This event can be handled by overloading the OnPreInit method or creating a Page_PreInit handler.
  • 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. 
  • 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.
Note
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.
    Init
    • This event can be handled by overloading the OnInit method or creating a Page_Init handler.
    • Raised after all controls have been initialized and any skin settings have been applied. 
    • Init event initializes the control property and the control tree is built. 
    • The Init event of individual controls occurs before the Init event of the page.
    • Viewstate information is not available at this stage.
    Use this event to read or initialize control properties.
    InitComplete
    • This event can be handled by overloading the OnInitComplete method or creating a Page_InitComplete handler. 
    • Raised at the end of the page's initialization stage. 
    • Only one operation takes place between the Init and InitComplete events: tracking of view state. All the controls turn on view-state tracking.
      View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.
      This event is used to processing tasks that require all initialization be complete.
      Use this event to make changes to view state that you want to make sure are persisted after the next postback. 
      PreLoad
       
      • This event can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.
      • PreLoad occurs before the post back data is loaded in the controls.
      • 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.
      This event is used before Perform any processing that should occur before Load.
      Use this event if you need to perform processing on your page or control before the Load event.
        Load
        • This event can be handled by overloading the OnLoad method or creating a Page_Load handler. 
        • The Load event is raised for the page first and then recursively for all child controls.
        • The controls in the control tree are created. 
        • Note that the control is stable at this time; it has been initialized and its state has been reconstructed. 
        • Allows actions that are common to every request to be placed here.
        Use the OnLoad event method to set properties in controls and to establish database connections. 
        Control events Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
        Note 
        Note
        In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.
        LoadComplete
        • This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler.  
        • Raised at the end of the event-handling stage.
        • The loading process is completed, control event handlers are run and page validation takes place.
        Use this event for tasks that require that all other controls on the page be loaded.
        PreRender
        • 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.
        • By handling this event, pages and controls can perform any updates before the output is rendered.  
        • Every controls whose datasource/databind property is set calls for its databind method.
        Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.
        PreRenderComplete
        SaveStateComplete
        • This stage can be handled by overriding the Render method or creating a Page_Render handler. 
        • Raised after view state and control state have been saved for the page and for all controls. 
        • Personalization, control state and view state information is saved.
        • The HTML markup is generated.
        • Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.
        Render
        • 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.
        • Every ASP.NET control has render method and the page instance calls this method to output the control’s markup, after this event any changes to the page or controls are ignored.
        • 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.
          Unload
          • The UnLoad phase is the last phase of the page life cycle.
          • This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.
          • It raises the UnLoad event for all controls recursively and lastly for the page itself.
          • In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.
          • Unload event used to do cleanup task like closing the database connections, closing of the open files, completing logging or other requested tasks.
          • Unload events occurs for each control on page control tree first and after that page.
          For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

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


          Controls Life-Cycle Events

          Individual ASP.NET server controls have their own life cycle that is similar to the page life cycle.
          If you develop custom controls, you must be familiar with the page life cycle in order to correctly initialize controls, populate control properties with view-state data, and run control behavior code. The life cycle of a control is based on the page life cycle, and the page raises many of the events that you need to handle in a custom control.For example, a control's Init and Load events occur during the corresponding page events.
          Master pages behave like child controls on a page: the master page Init event occurs before the page Init and Load events, and the master page Load event occurs after the page Init and Load events.

          If controls are created dynamically at run time or declaratively within templates of data-bound controls, their events are initially not synchronized with those of other controls on the page. 
          For example, for a control that is added at run time, the Init and Load events might occur much later in the page life cycle than the same events for controls created declaratively.

          The following illustration shows some of the most important methods of the Page class that you can override in order to add code that executes at specific points in the page life cycle.
          The illustration also shows how these methods relate to page events and to control events.




          Data Binding Events for Data-Bound Controls

          To help you understand the relationship between the page life cycle and data binding events, the following table lists data-related events in data-bound controls such as the GridView, DetailsView, and FormView controls.

          Control Event Typical Use
          DataBinding
          • Raised after the control's PreRender event, which occurs after the page's PreRender event.
            (This applies to controls whose DataSourceID property is set declaratively. Otherwise the event happens when you call the control's DataBind method.)
          This event marks the beginning of the process that binds the control to the data. Use this event to manually open database connections, if required, and to set parameter values dynamically before a query is run.
          RowCreated (GridView only) or ItemCreated (DataList, DetailsView, SiteMapPath, DataGrid, FormView, Repeater, and ListView controls) Use this event to manipulate content that is not dependent on data binding. For example, at run time, you might programmatically add formatting to a header or footer row in a GridView control.
          RowDataBound (GridView only) or ItemDataBound (DataList, SiteMapPath, DataGrid, Repeater, and ListView controls)
          • Raised after the control's RowCreated or ItemCreated event.
          When this event occurs, data is available in the row or item, so you can format data or set the FilterExpression property on child data source controls in order to display related data within the row or item.
          DataBound
          • Raised at the end of data-binding operations in a data-bound control. 
          • In a GridView control, data binding is complete for all rows and any child controls.
          Use this event to format data-bound content or to initiate data binding in other controls that depend on values from the current control's content.

          If a child control has been data bound, but its container control has not yet been data bound, the data in the child control and the data in its container control can be out of sync. 
          This is true particularly if the data in the child control performs processing based on a data-bound value in the container control. (see Binding to Data Using a Data Source Control)

          Login Control Events

          The Login control can use settings in the Web.config file to manage membership authentication automatically. However, if your application requires you to customize how the control works, or if you want to understand how Login control events relate to the page life cycle, you can use the events listed in the following table.

          Control Event Typical Use
          LoggingIn
          • Raised during a postback, after the page's LoadComplete event has occurred. 
          • This event marks the beginning of the login process.
          Use this event for tasks that must occur prior to beginning the authentication process.
          Authenticate Use this event to override or enhance the default authentication behavior of a Login control.
          LoggedIn
          • Raised after the user name and password have been authenticated.
          Use this event to redirect to another page or to dynamically set the text in the control. This event does not occur if there is an error or if authentication fails.
          LoginError
          • Raised if authentication was not successful.
          Use this event to set text in the control that explains the problem or to direct the user to a different page.








          When using  master pages, the normal page event lifecycle is a little different. Here is the actual order:
          1. Page.OnPreInit
          2. MasterPageControl.OnInit (for each control on the master page)
          3. Control.OnInit (for each contol on the page)
          4. MasterPage.OnInit
          5. Page.OnInit
          6. Page.OnInitComplete
          7. Page.LoadPageStateFromPersistenceMedium
          8. Page.LoadViewState
          9. MasterPage.LoadViewState
          10. Page.OnPreLoad
          11. Page.OnLoad
          12. MasterPage.OnLoad
          13. MasterPageControl.OnLoad (for each control on the master page)
          14. Control.OnLoad (for each control on the page)
          15. OnXXX (control event)
          16. MasterPage.OnBubbleEvent
          17. Page.OnBubbleEvent
          18. Page.OnLoadComplete
          19. Page.OnPreRender
          20. MasterPage.OnPreRender
          21. MasterPageControl.OnPreRender (for each control on the master page)
          22. Control.OnPreRender (for each control on the page)
          23. Page.OnPreRenderComplete
          24. MasterPageControl.SaveControlState (for each control on the master page)
          25. Control.SaveControlState (for each control on the page)
          26. Page.SaveViewState
          27. MasterPage.SaveViewState 
          28. Page.SavePageStateToPersistenceMedium
          29. Page.OnSaveStateComplete
          30. MasterPageControl.OnUnload (for each control on the master page)
          31. Control.OnUnload (for each control on the page)
          32. MasterPage.OnUnload
          33. Page.OnUnload

          The table below shows the list, and whether the method is active at all times, or only on PostBack.

          Method Active
          Constructor Always
          Construct Always
          TestDeviceFilter Always
          AddParsedSubObject Always
          DeterminePostBackMode Always
          OnPreInit Always
          LoadPersonalizationData Always
          InitializeThemes Always
          OnInit Always
          ApplyControlSkin Always
          ApplyPersonalization Always
          OnInitComplete Always
          LoadPageStateFromPersistenceMedium PostBack
          LoadControlState PostBack
          LoadViewState PostBack
          ProcessPostData1 PostBack
          OnPreLoad Always
          OnLoad Always
          ProcessPostData2 PostBack
          RaiseChangedEvents PostBack
          RaisePostBackEvent PostBack
          OnLoadComplete Always
          OnPreRender Always
          OnPreRenderComplete Always
          SavePersonalizationData Always
          SaveControlState Always
          SaveViewState Always
          SavePageStateToPersistenceMedium Always
          Render Always
          OnUnload Always


          The sequence of methods and events that each Page, MasterPage, and Control processes during the ASP.Net life cycle has been a recurring topic in this blog:












          Synchronous vs. Asynchronous Page Processing









          Materiały:
          ASP.NET Page Life Cycle - PLAKAT
          ASP.NET Page and Control Life Cycle - PLAKAT
          Microsoft ASP.NET AJAX Client Life-Cycle Events - PLAKAT
          ASP.NET Page Life Cycle1 - PLAKAT
          ASP.NET Page Life Cycle2 - PLAKAT
          ASP.NET Request + Page LifeCycle diagram
          ASP.NET Request + Page LifeCycle diagram
          ASP.NET Page Life Cycle - PREZENTACJA

          Page Life Cycle with a Page Base Class, a Master Page, and a Master Page Base Class
          aspnet-life-cycles-events.pdf
          ASP.Net 4 Page Life Cycle
          ASP.NET Page Life Cycle Overview
          ASP.NET Page Life Cycle
          ASP.NET Page Life Cycle
          ASP.NET 2.0 page and control life-cycle diagram
          Complete Lifecycle of an ASP.Net page and controls
          The ASP.NET Page Life Cycle
          ASP.NET Application and Page Life Cycle
          ASP.NET Application Life Cycle Overview for IIS 7.0
          The ASP.NET Page Lifecycle – A Basic Approach
          ASP.NET Page Events Lifecycle
          ASP.NET Page Events Lifecycle
          Master Page Events Lifecycle
          ASP.NET WebPage Lify Cycle
          ASP.NET Page life cycle events
          Control Execution Lifecycle
          NET Framework 4 - ASP.NET Page Life Cycle Overview
          Application, Page and Control lifecycle
          ASP.NET Application Life Cycle
          ASP.NET Web Parts Life Cycle
          ASP.NET 2.0 Page LifeCycle
          What is the life cycle of asp.net
          Understanding ASP.NET View State
          .NET Page Life Cycle with Events
          Chapter 5: Event-Based Programming
          ASP.NET Page Lifecycle
          ASP.NET Page Lifecycle - CodeAsp.net
          The ASP.NET page life cycle - DotNetFunda.com
          Explain the page life cycle in ASP.NET 2.0 - DotNetUncle.com
          ASP.NET Page Life Cycle - TheWebWithAsp.blogspot.com
          Page Life Cycle - RandyConnolly.com
          ASP.NET Page Life Cycle - Data.bangtech.com
          ASP.NET Page Life Cycle demystified by CatchCode
          asp.net life cycle
          The ASP.NET Page Life Cycle
          The ASP.NET Application Life Cycle, Page Life Cycle and Control Life Cycle
          ASP.NET Page Life Cycle
          State and life cycle
          ASP.NET Page Life Cycle Overview
          ASP.NET - Life Cycle

          AJAX Client Life-Cycle Events
          ASP.NET Internals : Visualizing ASP.NET Page Life Cycle using IntelliTrace
          AJAX and the ASP.NET 2.0 Callback Framework
          ASP.Net MVC Page Life Cycle
          ASP.NET Application, Page and Control Life Cycle
          Control life cycle

          1 komentarz:

          1. Hi, I have read the related articles. They did not mention the "Unload" step but they used the "Close Connection" phrase. Are they similar? Thank you

            OdpowiedzUsuń