P. 1
ASP .net tutorials

ASP .net tutorials

4.0

|Views: 1,876|Likes:
Published by sinhdeepak2700

More info:

Published by: sinhdeepak2700 on Dec 29, 2008
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

07/20/2013

pdf

text

original

The following are the main ten steps in the ASP.NET page life cycle.

1. Object Initialization

A page's controls (and the page itself) are first initialized in their raw form. By declaring your objects
within the constructor of your C# code-behind file, the page knows what types of objects and how
many to create. Once you have declared your objects within your constructor, you may then access
them from any sub class, method, event, or property. However, if any of your objects are controls
specified within your ASPX file, at this point the controls have no attributes or properties. It is
dangerous to access them through code, as there is no guarantee of what order the control instances
will be created (if they are created at all). The initialization event can be overridden using the OnInit
method.

Figure 1 - Controls are initialized based on their declaration.

2. Load Viewstate Data

After the Init event, controls can be referenced using their IDs only (no DOM is established yet for
relative references). At LoadViewState event, the initialized controls receive their first properties:
viewstate information that was persisted back to the server on the last submission. The page
viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the
server. Viewstate information is saved as a string of name/value pairs and contains information
such as control text or value. The viewstate is held in the value property of a hidden control
that is passed from page request to page request. As you can see, this is a giant leap forward from
the old ASP 3.0 techniques of maintaining state. This event can be overridden using the
LoadViewState method and is commonly used to customize the data received by the control at the
time it is populated.

Figure 2 - When LoadViewState is fired, controls are populated with the appropriate viewstate
data.

11

3. LoadPostData Processes Postback Data

During this phase of the page creation, form data that was posted to the server (termed postback
data in ASP.NET) is processed against each control that requires it. When a page submits a form, the
framework will implement the IPostBackDataHandler interface on each control that submitted data.
The page then fires the LoadPostData event and parses through the page to find each control that
implements this interface and updates the control state with the correct postback data. ASP.NET
updates the correct control by matching the control's unique ID with the name/value pair in the
NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any
given page. Extra steps are taken by the framework to ensure each ID is unique in situations, such
as several custom user controls existing on a single page. After the LoadPostData event triggers, the
RaisePostDataChanged event is free to execute (see below).

4. Object Load

Objects take true form during the Load event. All object are first arranged in the page DOM (called
the Control Tree in ASP.NET) and can be referenced easily through code or relative position (crawling
the DOM). Objects are then free to retrieve the client-side properties set in the HTML, such as width,
value, or visibility. During Load, coded logic, such as arithmetic, setting control properties
programmatically, and using the StringBuilder to assemble a string for output, is also executed. This
stage is where the majority of work happens. The Load event can be overridden by calling OnLoad.

Figure 3 - The OnLoad event is an ideal location to place logic.

5. Raise PostBack Change Events

As stated earlier, this occurs after all controls that implement the IPostBackDataHandler interface
have been updated with the correct postback data. During this operation, each control is flagged
with a Boolean on whether its data was actually changed or remains the same since the previous
submit. ASP.NET then sweeps through the page looking for flags indicating that any object's data
has been updated and fires RaisePostDataChanged. The RaisePostDataChanged event does not fire
until all controls are updated and after the Load event has occurred. This ensures data in another
control is not manually altered during the RaisePostDataChanged event before it is updated with
postback data.

6. Process Client-Side PostBack Event

After the server-side events fire on data that was changed due to postback updates, the object which
caused the postback is handled at the RaisePostBackEvent event. The offending object is usually a
control that posted the page back to the server due to a state change (with autopostback enabled) or
a form submit button that was clicked. There is often code that will execute in this event, as this is
an ideal location to handle event-driven logic. The RaisePostBackEvent event fires last in the series
of postback events due to the accuracy of the data that is rendered to the browser. Controls that are

12

changed during postback should not be updated after the executing function is called due to the
consistency factor. That is, data that is changed by an anticipated event should always be reflected
in the resulting page. The RaisePostBackEvent can be trapped by catching RaisePostBackEvent.

Figure 4 - The RaisePostDataChanged and RaisePostBackEvent events are defined by the
IPostBackDataHandler interface.

7. Prerender the Objects

The point at which the objects are prerendered is the last time changes to the objects can be saved
or persisted to viewstate. This makes the PreRender step a good place to make final modifications,
such as changing properties of controls or changing Control Tree structure, without having to worry
about ASP.NET making changes to objects based off of database calls or viewstate updates. After the
PreRender phase those changes to objects are locked in and can no longer be saved to the page
viewstate. The PreRender step can be overridden using OnPreRender.

8. ViewState Saved

The viewstate is saved after all changes to the page objects have occurred. Object state data is
persisted in the hidden object and this is also where object state data is prepared to be
rendered to HTML. At the SaveViewState event, values can be saved to the ViewState object, but
changes to page controls are not. You can override this step by using SaveViewState.

Figure 5 - Values are set for controls in OnPreRender. During the SaveViewState event, values
are set for the ViewState object.

9. Render To HTML

The Render event commences the building of the page by assembling the HTML for output to the
browser. During the Render event, the page calls on the objects to render them into HTML. The page

13

then collects the HTML for delivery. When the Render event is overridden, the developer can write
custom HTML to the browser that nullifies all the HTML the page has created thus far. The Render
method takes an HtmlTextWriter object as a parameter and uses that to output HTML to be
streamed to the browser. Changes can still be made at this point, but they are reflected to the client
only.

10. Disposal

After the page's HTML is rendered, the objects are disposed of. During the Dispose event, you should
destroy any objects or references you have created in building the page. At this point, all processing
has occurred and it is safe to dispose of any remaining objects, including the Page object. You can
override Dispose, as well as Render by setting the appropriate selection in the object parameter

Figure 6 - The Render event will output custom HTML to the browser through the
HtmlTextWriter object.

The following are the some of the guidelines to create a good ASP.NET application.

Disable session when not using it. This can be done at the application level in the
"machine.config" file or at a page level.
The in-proc model of session management is the fastest of the three options. SQL Server option
has the highest performance hit.
Minimize the amount and complexity of data stored in a session state. The larger and more
complex the data is, the cost of serializing/deserializing of the data is higher (for SQL Server
and State server options).
Use Server.Transfer for redirecting between pages in the same application. This will avoid
unnecessary client-side redirection.
Choose the best suited session-state provider - In-process is the fastest option.
Avoid unnecessary round-trips to the server - Code like validating user input can be handled at
the client side itself.
Use Page.IsPostback to avoid unnecessary processing on a round trip.
Use server controls in appropriate circumstances. Even though are they are very easy to
implement, they are expensive because they are server resources. Sometimes, it is easier to
use simple rendering or data-binding.
Save server control view state only when necessary.
Buffering is on by default. Turning it off will slow down the performance. Don't code for string
buffering - Response.Write will automatically buffer any responses without the need for the
user to do it. Use multiple Response.Writes rather than create strings via concatenation,
especially if concatenating long strings.
Don't rely on exceptions in the code. Exceptions reduce performance. Do not catch the
exception itself before handling the condition.

// Consider changing this...
try { result = 100 / num;}
catch (Exception e) { result = 0;}

14

// to this...
if (num != 0)
result = 100 / num;

else

result = 0;
Use early binding in VB.NET and Jscript code. Enable Option Strict in the page directive to
ensure that the type-safe programming is maintained.
Port call-intensive COM components to managed code. While doing Interop try avoiding lot of
calls. The cost of marshalling the data ranges from relatively cheap (i.e. int, bool) to more
expensive (i.e. strings). Strings, a common type of data exchanged for web applications, can be
expensive because all strings in the CLR are in Unicode, but COM or native methods may
require other types of encoding (i.e. ASCII).
Release the COM objects or native resources as soon as the usage is over. This will allow other
requests to utilize them, as well as reducing performance issues, such as having the GC release
them at a later point.
Use SQL server stored procedures for data access.
Use the SQLDataReader class for a fast forward-only data cursor.
Datagrid is a quick way of displaying data, but it slows down the application. The other
alternative, which is faster, is rendering the data for simple cases. But this is difficult to
maintain. A middle of the road solution could be a repeater control, which is light, efficient,
customizable and programmable.
Cache data and page output whenever possible.
Disable debug mode before deploying the application.
For applications that rely extensively one external resource, consider enabling web gardening
on multiprocessor computers. The ASP.NET process model helps enable scalability by
distributing work to several processes, one on each CPU. If the application is using a slow
database server or calls COM objects that access external resources, web gardening could be a
solution.

Enumerating into collections sometimes is more expensive than index access in a loop. This is
because the CLR can sometimes optimize array indexes and bounds checks away in loops, but
can't detect them in for each type of code.
JScript .NET allows methods within methods - to implement these in the CLR required a more
expensive mechanism which can be much slower, so avoid them by moving inner methods to be
just regular methods of the page.
Do a "pre-batch" compilation. To achieve this, request a page from the site.
Avoid making changes to pages or assemblies that are there in the bin directory of the
application. A changed page will only recompile the page. Any change to the bin directory will
result in recompile of the entire application.
The config file is configured to enable the widest set of features. For a performance boost it is
better to tune it to the requirements. Some key points here are:
Encoding - Request/Response - The default is UTF-8 encoding. If the site is completely ASCII,
change the option to ASCII encoder.
Session State - By default is ON. If session state is not maintained then the value should be
changed to OFF.
ViewState - Default is ON. Turn it off if not being used. If ViewState is being used there are
different levels of security that need to be considered which can impact the performance of the
application.

AutoEventWireup - Turning off AutoEventWireup means that the page will not try and match
up method names to events and hook them up (i.e. Page_Load, etc). Instead, if the application
writer wishes to receive them, they need to override the methods in the base class (i.e. override
OnLoad for the page load event instead of using a Page_Load method). By doing so, the page
will get a slight performance boost by not having to do the extra work itself, but leaving it to the
page author.
For efficient debugging Use ASP.NET trace feature instead of Response.Write.

15

Phase

What a control needs to do

Method or event to override

Initialize

Initialize settings needed during the
lifetime of the incoming Web request.
See Handling Inherited Events.

Init event (OnInit method)

Load view state

At the end of this phase, the
ViewState property of a control is
automatically populated as described
in Maintaining State in a Control. A
control can override the default
implementation of the LoadViewState
method to customize state
restoration.

LoadViewState method

Process postback data

Process incoming form data and
update properties accordingly. See
Processing Postback Data.

Note Only controls
that process postback
data participate in this
phase.

LoadPostData method

(if IPostBackDataHandler is
implemented)

Load

Perform actions common to all
requests, such as setting up a
database query. At this point, server
controls in the tree are created and
initialized, the state is restored, and
form controls reflect client-side data.
See Handling Inherited Events.

Load event

(OnLoad method)

Send postback change
notifications

Raise change events in response to
state changes between the current
and previous postbacks. See
Processing Postback Data.

Note Only controls
that raise postback
change events
participate in this
phase.

RaisePostDataChangedEvent

method

(if IPostBackDataHandler is
implemented)

Handle postback events

Handle the client-side event that
caused the postback and raise
appropriate events on the server. See
Capturing Postback Events.

Note Only controls
that process postback
events participate in
this phase.

RaisePostBackEvent method

(if IPostBackEventHandler is
implemented)

Prerender

Perform any updates before the
output is rendered. Any changes
made to the state of the control in the
prerender phase can be saved, while
changes made in the rendering phase
are lost. See Handling Inherited
Events.

PreRender event

(OnPreRender method)

Save state

The ViewState property of a control is
automatically persisted to a string
object after this stage. This string
object is sent to the client and back

SaveViewState method

16

as a hidden variable. For improving
efficiency, a control can override the
SaveViewState method to modify the
ViewState property. See Maintaining
State in a Control.

Render

Generate output to be rendered to the
client. See Rendering an ASP.NET
Server Control.

Render method

Dispose

Perform any final cleanup before the
control is torn down. References to
expensive resources such as database
connections must be released in this
phase. See Methods in ASP.NET
Server Controls.

Dispose method

Unload

Perform any final cleanup before the
control is torn down. Control authors
generally perform cleanup in Dispose
and do not handle this event.

UnLoad event (On UnLoad
method)

Note To override an EventName event, override the OnEventName method (and call
base. OnEventName).

The methods and events in the third column are inherited from System.Web.UI.Control, with the
following exceptions: LoadPostData and RaisePostDataChangedEvent are methods of the
IPostBackDataHandler interface, and RaisePostBackEvent belongs to the
IPostBackEventHandler interface. If your control participates in postback data processing you
must implement IPostBackDataHandler. If your control receives postback events you must
implement IPostBackEventHandler.

The CreateChildControls method is not listed in the table because it is called whenever the
ASP.NET page framework needs to create the controls tree and this method call is not limited to a
specific phase in a control's lifecycle. For example, CreateChildControls can be invoked when
loading a page, during data binding, or during rendering.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->