Asp.Net Page Life Cycle – an understanding using msdn

Typical Asp.net page life cycle : Standalone page , with User Control Embedded , As Content Page within Master Page , As when User Control &  Content Page both on Master Page

What can be best source for understanding the asp.net page life cycle other than MSDN itself…? I am just going to refer the same and mentioned key points of for simple to understand and remember. Let’s start with Standalone aspx page… Then rest scenarios will be just change in the sequence of the events while getting called.

Typical Asp.net page life cycle: Standalone page

Page Life Cycle Events with calling sequence

·         PreInit

·         Init

·         InitComplete

·         PreLoad

·         Load

·         Control events

·         LoadComplete

·         PreRender

·         PreRenderComplete

·         SaveStateComplete

·         Render

·         Unload

Along with the events mentioned above, there some methods which are being called before and after the Events to facilitate functionality. Most of the times developers not aware ( don’t care !! ) about these methods other than other than specific cases like setting something before or after the method call or overloading them, so not covered in detailed.

Also please note that some of these methods are called recursively multiple times depending on the content of the page (e.g. postback  or not etc)

Event

When is getting called

Page Methods getting called Before or during this event call

 

Typical use /Functionality handled by

PreInit

Raised after the start stage is complete and
before the page initialization stage begins

Construct()

ProcessRequest()

InitializeCulture()

DeterminePostBackMode()

OnPreInit()

 

 

Check IsPostBack property to determine
whether this is the first time the page is being processed

(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.
)

 

Typically event is useful for –

Create or re-create dynamic controls ;

Set a master page dynamically.

Set the Theme property dynamically.

Read or set profile property values.

 

Init

Raised after all controls have been initialized and any skin
settings have been applied

 

OnInit()

 

To read or initialize control properties.

 

The Init event of individual controls
occurs before the Init event of the page.

 

InitComplete

Raised at the end of the page’s initialization stage.

TrackViewState()

OnInitComplete()

 

Only one operation takes place between the Init and InitComplete
events which is tracking of view state changes is turned on.

 

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.

 

Use this event to make changes to view state that
you want to make sure are persisted after the next postback.

PreLoad

Raised after the page loads view state for itself and all
controls after it processes postback data that is included with the Request instance.

 

LoadPageStateFromPersisteceMedium ( Postback Only)

 

LoadControlState(Postback only)

 

LoadViewState ( Postback Only)

 

ProcessPostData ( Postback Only)

IsPostBackDataHandler.

 

LoadPostData

     (Postback
only – first try)

 

OnPreLoad()

 

The OnPreLoad method is called after all
postback data returned from the user is loaded.

 

At this stage in the page’s life cycle, view-state
information and postback data for declared controls and controls created
during the initialization stage are loaded into the page’s controls.

 

Controls created in the OnPreLoad method
will also be loaded with view-state and postback data.

Load

The Page object calls the OnLoad method on the Page object, and then recursively does the same for each
child control until the page and all controls are loaded.

 

The Load event of individual controls occurs after the Load event of
the page

OnLoad()

 

Use the OnLoad event method to set
properties in controls and to establish database connections.

Control events

TextChanged()  or Click() etc

 

 

RaisePostBackEvent()

Validate()

 

Use these events to handle specific control
events, such as a Button control’s Click event or a TextBox 
control’s TextChanged event.

 

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

Raised at the end of the event-handling stage.

OnLoadComplete()

 

 

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

 

The PreRender event of individual
controls occurs after the PreRender event of the page.

EnsureChildControls()

OnPreRender()

 

Use the event to make final changes to the
contents of the page or its controls before the rendering stage begins.

PreRenderComplete

Raised after each data bound control whose DataSourceID property
is set calls its DataBind method.

Data Binding Events

OnPreRenderComplete()

 

 

SaveStateComplete

Raised after view state and control state have been saved for
the page and for all controls

SaveViewState()

 

SavePageStateToPersistenceMedium

 

OnSaveStateComplete

 

Any changes to the page or controls at this point affect
rendering, but the changes will not be retrieved on the next postback.

Render

It is the processing Stage, not an event, Page
Object call this method on each control. All asp.net server controls have a
Render method, which
writes out the control’s markup to send to the
browser.

RenderControl()

Render()

RenderChildren()

 

 

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. 

A user control (an .ascx file) automatically incorporates
rendering, so you do not need to explicitly render the control in code

Unload

Raised for each control and then for the page.

OnUnload()

Dispose()

 

For Controls – use this event to do final cleanup for specific
controls, such as closing control-specific database connections.

 

For Page – 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.

 

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.

 

For those who don’t know View State Tracking

Control.TrackViewState Method It Causes tracking of view-state changes to the server control so they can be stored in the server control's StateBag object.  This object is accessible through the Control.ViewState property.Use this method when you have to develop template data-bound controls.

This method alerts ASP.NET to monitor changes to a server control's view state, which is required when you override the Control.DataBind method. The control then uses the IsTrackingViewState property to determine whether view-state change tracking is enabled  for the control. If it is not enabled, the TrackViewState method is called.

Ref – MSDN

Some important Event Methods in above Page Life cycle :

LoadControlState(postback only): The page recursively calls the LoadControlState method of those controls in its Controls collections that have called the RegisterRequiresControlState method of the page class to express interest in using their control states.

LoadViewState(postback only): The page first calls its own LoadViewState method and then recursively calls the LoadViewState method of the controls in its Controls collection to allow them to load their saved view states.

LoadPostData(postback only – first try): The page calls the LoadPostData method of the controls that implement the IPostBackDataHandler interface and passes the posted data into it. The LoadPostData method of each control must access the posted data and update the respective property of the control accordingly. For example, the LoadPostData method of the TextBox control assigns the new value of the text box to the Text property of the TextBox control.

LoadPostData(postback only second try): The page calls the LoadPostData method of those controls that where programmatically added to its Controls collection in the Load phase if they implement the IPostBackDataHandler interface.

RaisePostDataChangedEvent(Postback only): The page calls the RaisePostDataChangedEvent method of those controls whose LoadPostData method returned true. The RaisePostDataChangedEvent method raises post data changed event. For example, TextBox control raises this event when the new value of the text box is different from the old value.

RaisePostbackEvent (postback only): The page calls the RaisePostBackEvent method of the control whose associated HTML element submitted the form. For example, the Button control's associated HTML element posts the page back to the server. The RaisePostBackEvent method of a control must map the postback event to one or more server-side events. For example, the RaisePostBackEvent method of the Button control maps the postback event to the Command and Click server-side events.

Overall Page life cycle with the Events & methods

  • PreInit
  • Init
  • InitComplete
  • LoadControlState (Postback only)
  • LoadViewState (Postback only)
  • LoadPostData (Postback only – first try)
  • PreLoad
  • Load
  • LoadPostData (Postback only – second try)
  • RaisePostDataChangedEvent (Postback only)
  • RaisePostbackEvent (Postback only)
  • LoadComplete
  • RaiseCallbackEvent (Postback and Callback only)
  • PreRender
  • PreRenderComplete
  • SaveControlState
  • SameViewState
  • SaveStateComplete
  • Render

 

Now let’s say we have User Control on the asp.net webpage then Asp.net Page life cycle will be as follows

  • PreInit – Page
  • Init – UserControl
  • Init – Page
  • InitComplete – Page
  • LoadPageStateFromPersistenceMedium – Page 
  • ProcessPostData (first try) – Page
  • PreLoad – Page
  • Load – Page
  • Load – UserControl
  • ProcessPostData (second try) – Page
  • RaiseChangedEvents – Page
  • RaisePostBackEvent – Page
  • Control Events – Page
  • Control Event – UserControl
  • DataBinding – Page
  • DataBinding – UserControl
  • LoadComplete – Page
  • PreRender – Page
  • PreRender – UserControl
  • PreRenderComplete – Page
  • SaveViewState – Page
  • SavePageStateToPersistenceMedium – Page
  • SaveStateComplete – Page
  • Unload – UserControl
  • Unload – Page

Please refer to previous post for the Asp.net Life Cycle details

 

There can be the case that you have one Master page in which you asp.net web page is content page , in that case Asp.net LifeCycle will be as follows

  • PreInit – Page
  • Init – MasterPage
  • Init – Page
  • InitComplete – Page
  • LoadPageStateFromPersistenceMedium – Page 
  • LoadControlState (Postback only) – Page
  • LoadViewState (Postback only) – Page
  • ProcessPostData (first try) – Page
  • LoadPostData (Postback only – first try) – Page
  • PreLoad – Page
  • Load – Page
  • Load – MasterPage
  • ProcessPostData (second try) – Page
  • RaiseChangedEvents – Page
  • RaisePostBackEvent – Page
  • Control Events – OnClick,TextChanged,GridView Events  followed by DataBinding
  •     DataBinding – Page
  •     DataBinding – MasterPage
  •     DataBinding – UserControl
  •     DataBinding – ChildUserControl
  • LoadComplete – Page
  • PreRender – Page
  • PreRender – MasterPage
  • PreRenderComplete – Page
  • SaveViewState – Page
  • SavePageStateToPersistenceMedium – Page
  • SaveStateComplete – Page
  • Unload – MasterPage
  • Unload – Page

There is one scenario given by mbanavige on Asp.net Forums(http://forums.asp.net/t/1191194.aspx)  I am just going to refer the same ,

Our test setup is composed of a Page, MasterPage, UserControl, Nested UserControl and Button control as follows: The Page is tied to the MasterPage,The UserControl is on the Page,The Nested UserControl is on the UserControl,The Button is on the Nested UserControl.,Clicking the Button calls the Page.DataBind method

Then in above mentioned case asp.net page life cycle will be as follows

  • PreInit – Page
  • Init – Nested ChildUserControl
  • Init – UserControl
  • Init – MasterPage
  • Init – Page
  • InitComplete – Page
  • LoadPageStateFromPersistenceMedium – Page 
  • ProcessPostData (first try) – Page
  • PreLoad – Page
  • Load – Page
  • Load – MasterPage
  • Load – UserControl
  • Load – Nested ChildUserControl
  • ProcessPostData (second try) – Page
  • RaiseChangedEvents – Page
  • RaisePostBackEvent – Page
  • Click – Button – Nested ChildUserControl
  •    DataBinding – Page
  •    DataBinding – MasterPage
  •    DataBinding – UserControl
  •    DataBinding – Nested ChildUserControl
  • LoadComplete – Page
  • PreRender – Page
  • PreRender – MasterPage
  • PreRender – UserControl
  • PreRender – Nested ChildUserControl
  • PreRenderComplete – Page
  • SaveViewState – Page
  • SavePageStateToPersistenceMedium – Page
  • SaveStateComplete – Page
  • Unload – Nested ChildUserControl
  • Unload – UserControl
  • Unload – MasterPage
  • Unload – Page

 

Interview quickies:

1)    If we have a page called "Default" and a Master page called "DefaultMaster".
Both contain Page Load events. When a page request comes to Default page, which Page Load event will call first

Ans : Default.aspx Page load

 

2)    If we have a page called "Default" and a Master page called "DefaultMaster".
For both Page.Init events is handled. When a page request comes to Default page, which Page Init () event will call first

 

Ans:- DefaultMaster.Master page init event followed by Default.aspx

In Case of Nested Master Pages –

Main Master Page Init ===> Nested/Sub Master page Init ===>

Content Page Init /Requester Page.aspx

 

If you are still unsatisfied with asp.net life cycle events

Reference :

http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx

http://blogs.thesitedoctor.co.uk/tim/2006/06/30/Complete+Lifecycle+Of+An+ASPNet+Page+And+Controls.aspx

Typed DataSet and Untyped DataSet

It’s been Long time since I used Typed Datasets, so just wanted refresh the basics differences between ‘Ordinary’ and Typed Datasets

 

Typed DataSet :

 

  • A typed DataSet is a class that derives from a DataSet. As such, it inherits all the methods, events, and properties of a DataSet. Additionally, a typed DataSet provides strongly typed methods, events, and properties.

 

  • The typed dataset is binded with the database tables(s) at design time and you have all the schema information at design time in your code. It is added as .xsd file in your application.

 

  •  This means you can access tables and columns by name, instead of using collection-based methods. 

 

  •  Aside from the improved readability of the code, a typed DataSet also allows the Visual Studio .NET code editor to automatically complete lines as you type.

 

  •  Additionally, the strongly typed DataSet provides access to values as the correct type at compile time. With a strongly typed DataSet, type mismatch errors are caught when the code is compiled rather than at run time.

 

  •  Access to tables and columns in a typed dataset is also slightly faster at run time because access is determined at compile time, not through collections at run time.

 

 UnTyped DataSet :

  •  Untyped dataset is an object of class System.Data.DataSet.
  • It is binded with the tables at runtime.
  • You are not aware of the schema of the dataset at design time. There are a variety of circumstances under which an untyped dataset is useful. The most obvious scenario is that no schema is available for the dataset. This might occur, for example, if your application is interacting with a component that returns a dataset, but you do not know in advance what its structure is. Similarly, there are times when you are working with data that does not have a static, predictable structure; in that case, it is impractical to use a typed dataset, because you would have to regenerate the typed dataset class with each change in the data structure.
  • You can access the tables and columns using index no.
  • More generally, there are many times when you might create a dataset dynamically without having a schema available. In that case, the dataset is simply a convenient structure in which you can keep information, as long as the data can be represented in a relational way.
  • At the same time, you can take advantage of the dataset’s capabilities, such as the ability to serialize the information to pass to another process, or to write out an XML file

 

// This accesses the Name column in the first row of the Employee table.

string s = dsEmployee.Employee[0].Name;

The same call using the UnTyped Dataset as follows

string s = (string) dsEmployee.Tables[“Employee “].Rows[0][“Name”];

Useful References –

http://msdn.microsoft.com/en-us/library/esbykkzb(v=vs.100).aspx

http://aspalliance.com/1367_Typed_Dataset_and_its_Usages.all