0% found this document useful (0 votes)
31 views15 pages

3 Events in The Life Cycle of A Web Application - Page Liffe Cycle Events

Uploaded by

Jesica D'cruz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views15 pages

3 Events in The Life Cycle of A Web Application - Page Liffe Cycle Events

Uploaded by

Jesica D'cruz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Events in the life cycle of a web application

In a web application, events can occur at 3 levels

1. At the Application Level(Example: Application Start)


2. At the Page Level(Example: Page Load)
3. At the Control Level (Example: Button Click)

● ViewState variables are used to preserve data across page post back.
● By default, ViewState of one webform is not available in another webform.
For example, if you define ViewState["MyData"] = "View State Example" in WebForm1.
ViewState["MyData"] is only available in WebForm1.
● ViewState["MyData"] will be null on any other web form in the application.

● To make data available on multiple web forms, there are several techniques in ASP.NET:
1. Query Strings
2. Cookies
3. Session State
4. Application State

Session state variables are available across all pages, but only for a given single session.
Only the current session has access to its Session state.

Application State variables are available across all pages and across all sessions.
All sessions can read and write Application State variables.

Cookies and Sessions are used to store information. Cookies are only stored on the
client-side machine, while sessions get stored on the client as well as a server.

In an ASP.NET web application, Global.asax file contains the application level events.
.asax stands for Active Server Application Extended.

void Application_Start(object sender, EventArgs e)


{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the session state mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}

Session-State Modes

ASP.NET session state supports different storage options for session data. Each option is
identified by a value in the SessionStateMode enumeration. The following list describes the
available session state modes:

● InProc mode, (In-Process) which stores session state in memory on the Web server. This
is the default.
● StateServer mode, which stores session state in a separate process called the ASP.NET
state service. This ensures that session state is preserved if the Web application is
restarted and also makes session state available to multiple Web servers in a Web farm
(A web farm is a group of two or more web servers (or nodes) that host multiple instances
of an app).
● SQLServer mode stores session state in a SQL Server database. This ensures that
session state is preserved if the Web application is restarted and also makes session state
available to multiple Web servers in a Web farm.
● Custom mode, which enables you to specify a custom storage provider.
● Off mode, which disables session state.

You can specify which mode you want ASP.NET session state to use by assigning
a SessionStateMode value to the mode attribute of the sessionState element in your application's
Web.config file.

In-Process Mode
In-process mode is the default session state mode and is specified using
the InProc SessionStateMode enumeration value. In-process mode stores session state values
and variables in memory on the local Web server. It is the only mode that supports
the Session_End event.

In general,
Application events are used to initialize data that needs to be available to all the current
sessions of the application
And
Session events are used to initialize data that needs to be available only for a given
individual session, but not between multiple sessions

What is a Session, in a web application?


A session is a unique instance of the browser.
A single user can have multiple sessions, by visiting your application, with multiple instances
of the browser running with a different session-id.

Example using session and application level events.

Create a new asp.net web application, and copy paste the following code in Global.asax file.
1. Application_Start() event gets fired, when a first request is made, and if the application is
not already running.
2. Session_Start() event is fired every time a new browser instance, with a different session-
id, visits the application.
3. Session_End() event is fired when the user session times out. The default is 20 minutes.
This can be configured in the web.config file.

One word of caution……..do not use the already existing webform or delete the
existing webform and add a new webform, always add a new webform by right clicking
the name of the web application and then click add and then click on webform.

void Application_Start(object sender, EventArgs e)


{
// Create Application state variables
Application["TotalApplications"] = 0;
Application["TotalUserSessions"] = 0;
// Increment TotalApplications by 1
Application["TotalApplications"] = (int)Application["TotalApplications"] + 1;
}
void Session_Start(object sender, EventArgs e)
{
// Increment TotalUserSessions by 1
Application["TotalUserSessions"] = (int)Application["TotalUserSessions"] + 1;
}
void Session_End(object sender, EventArgs e)
{
// Decrement TotalUserSessions by 1
Application["TotalUserSessions"] = (int)Application["TotalUserSessions"] - 1;
}
Copy and paste the following code in WebForm1.aspx.
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Number of Applications: " + Application["TotalApplications"]);
Response.Write("<br/>");
Response.Write("Number of Users Online: " + Application["TotalUserSessions"]);
}

Now, when you run the application, you get the following output:
Number of Applications: 1
Number of Users Online: 1

Note ;
If you run the web application the no. of users online will be
incremented by 1 for every run because a new session id is created
for every run.

To check this add the below code in Web.Config file.

<system.web>
<sessionState mode="InProc"
cookieless="true"></sessionState>
// just add the above line of code inside <system.web>
</system.web>

Copy the URL and open a new instance of the browser (new tab in the same browser).
Paste the URL and press enter. In the new instance of the browser, we still see the same
output.

We expected the Number of Users Online to be 2.

The new instance of the browser, is treated as part of the same session, because, by default
the browser uses cookies to store session id.

The session id is read from the same cookie when you opened the new browser window.
Hence, Number of Users Online is not incremented.
How to get a new session-id and force the Session_Start() event to execute?
1. Close the browser:
Close the existing browser window, which automatically deletes the session cookie.
Now, open a new browser instance.
Since, the existing session cookie associated with the previous browser instance is deleted.
The new instance of the browser, will get a new session-id and a session cookie.
Now, if you navigate to WebForm1.aspx, Session_Start() event gets fired and Number of
Users Online is incremented to 2……………..some issue sometimes

2. Open a new instance of a different browser:


For example, if you first visited the application with Google Chrome, now try accessing the same
page with internet explorer, Session_Start() event gets fired and Number of Users Online is
incremented to 2.

3. Use Cookie-less Sessions: To use cookie-less sessions set the cookieless attribute to true in
web.config as shown below.

<system.web>
<sessionState mode="InProc"
cookieless="true"></sessionState>
// just add the above line of code inside <system.web>
</system.web>

Make these changes in web.config file and the run the web application.
You will see

https://localhost:44325/(S(0w2sxz2vdac04d1yscyhzuzo))/WebForm1.aspx

(Notice the session id seen in the URL it’s not stored in cookie now…it is carried along
with the URL and posted to the web server and the server identifies that there is a new user)
Copy the URL and paste it in another instance of the browser, you see user sessions
increased by 1.
Now, here
https://localhost:44325/WebForm1.aspx remove the session id and paste the URL in new
window and you will see a new session is created meaning a new user)
See the Pic below:
ASP.NET Page Life Cycle Events

Events occur at the page level also.

We have learnt that, web applications work on a stateless protocol. Every time a request is made
for a webform, the following sequence of events occur.
1. Web Application creates an instance of the requested webform.
2. Processes the events of the webform.
3. Generates the HTML, and sends the HTML back to the requested client(Browser).
4. The webform gets destroyed and removed from the memory.

ASP.NET Life Cycle Events

Page Event Typical Use

PreInit This event is raised after the start stage is complete and before the
initialization stage.

Init This event occurs after all controls have been initialized.
We can use this event to read or initialize control properties.

InitComplete This event occurs at the end of the page's initialization stage.
We can use this event to make changes to view state that we want to
make sure are persisted after the next post back.
PreLoad This event is occurs before the post back data is loaded in the controls.

Load This event is raised for the page first time and then recursively for all
child controls.

Control events This event is used to handle specific control events such as Button
control' Click event.

LoadComplete This event occurs at the end of the event-handling stage.


We can use this event for tasks that require all other controls on the
page be loaded.

PreRender This event occurs after the page object has created all controls that are
required in order to render the page.

PreRenderComplete This event occurs after each data bound control whose DataSourceID
property is set calls its DataBind method. (GridView)

SaveStateComplete It is raised after view state and control state have been saved for the
page and for all controls.

Render This is not an event; instead, at this stage of processing, the Page
object calls this method on each control.

Unload This event raised for each control and then for the page.

To see the events execution order, create a new asp.net web project, and copy the
following code.
protected void Page_PreInit(object sender, EventArgs e)
{ Response.Write("Page_PreInit" + "<br/>"); }

protected void Page_Init(object sender, EventArgs e)


{ Response.Write("Page_Init" + "<br/>"); }

protected void Page_InitComplete(object sender, EventArgs e)


{ Response.Write("Page_InitComplete" + "<br/>"); }

protected void Page_PreLoad(object sender, EventArgs e)


{ Response.Write("Page_PreLoad" + "<br/>"); }

protected void Page_LoadComplete(object sender, EventArgs e)


{ Response.Write("Page_LoadComplete" + "<br/>"); }

protected void Page_PreRender(object sender, EventArgs e)


{ Response.Write("Page_PreRender" + "<br/>"); }

protected void Page_PreRenderComplete(object sender, EventArgs e)


{ Response.Write("Page_PreRenderComplete" + "<br/>"); }

protected void Page_Unload(object sender, EventArgs e)


{
//Response.Write("Page_Unload" + "<br/>");
}

Run the project and you should see the following output.
Page_PreInit
Page_Init
Page_InitComplete
Page_PreLoad
Page_LoadComplete
Page_PreRender
Page_PreRenderComplete

Note: If you uncomment, Response.Write() method call in Page_Unload() event, you


get System.Web.HttpException stating - Response is not available in this context.
This makes sense because, the Unload event is raised after the page has been fully rendered,
and the HTML is already sent to the client.
At this stage, the webform instance is ready to be discarded.
So, at this point, page properties such as Response and Request are unloaded and clean up is
performed.

ASP.NET Server control events

ASP.NET server controls, such as TextBox, Button, and DropDownList has their own events.
For example, Button has a click event. TextBox has TextChanged event,
and DropDownList has SelectedIndexChanged event.

We have a set of asp.net validation controls, that has validation events.

The events that all these controls expose, can be broadly divided into 3 categories.

Postback events - These events submit the Web page, immediately to the server for
processing. Click event of a button control is an example for PostBack event.

Cached events - These events are saved in the page’s view state to be processed when a
postback event occurs.

TextChanged event of TextBox control, and SelectedIndexChanged event of


a DropDownList control are examples of cached events.

Cached events can be converted into postback events, by setting the AutoPostBack property of
the control to true.

Validation events - These events occur on the client(browser), before the page is posted back to
the server. All validation controls use these type of events.

Control events are processed after the PageLoad event.

The picture below depicts the same.


Among the control events, Cached events happen before PostBack events.

To understand the order in which Page and Server control events execute, add a Web form
with a TextBox, RequiredFieldValidator, and a Button control.

WebForm1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"


Inherits="WebApplication8.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Name : <asp:TextBox ID="TextBox1" runat="server"
OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
&nbsp&nbsp&nbsp&nbsp
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Name is Mandatory"
ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
&nbsp&nbsp
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>

Set AutoPostBack property of TextBox to True

You can find RequiredFieldValidator under Validation tab, in the ToolBox.

Double click the TextBox control on the WebForm, and the event
handler TextBox1_TextChanged() will be automatically generated.
Along the same lines, double click the Button control, Button1_Click() event handler will be
generated.

Right Click the RequiredFieldValidator control on the webform and select Properties.

From the Properties window, Set ControlToValidate property to TextBox1.


At this stage copy and paste the following code in WebForm1.aspx.cs.

A word of Caution

Add protected void TextBox1_TextChanged(object sender, EventArgs e) { }

And protected void Button1_Click(object sender, EventArgs e) { }

By double clicking on the TextBox control and Button control respectively seen in the
WebForm.aspx[Design]
Do no type

protected void Page_PreInit(object sender, EventArgs e)


{
Response.Write("Page_PreInit" + "<br/>");
}
protected void Page_Init(object sender, EventArgs e)
{
Response.Write("Page_Init" + "<br/>");
}
protected void Page_InitComplete(object sender, EventArgs e)
{
Response.Write("Page_InitComplete" + "<br/>");
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Page_Load" + "<br/>");
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
Response.Write("Page_LoadComplete" + "<br/>");
}
protected void Page_PreRender(object sender, EventArgs e)
{
Response.Write("Page_PreRender" + "<br/>");
}
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
Response.Write("Page_PreRenderComplete" + "<br/>");
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Response.Write("Text Changed Event"+ "<br/>");
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("Button Click"+ "<br/>");
}

Now, run the project, and when the webform renders, the page level events occur in the
following order. Notice that, TextChanged and ButtonClick events are not fired that is because
it is the initial get request of the page. So only web page related events are fired.
Page_PreInit
Page_Init
Page_InitComplete
Page_Load
Page_LoadComplete
Page_PreRender
Page_PreRenderComplete

Don't type anything in the TextBox, and click the button control.

The RequiredFieldValidator message is displayed.(Validation done at the client side – the client is
the browser we are using)

No other events get processed and the page is not posted back to the server.

Now enter some data in the textbox , immediately you see textchanged event triggeres
Now click the button and see click event of button triggered

Set AutoPostBack property of TextBox to False to convert it to cached event.

Now, enter some text, into the TextBox and Click the button.

Notice that, Text Changed Event and Button Click, execute after Page Load and Before Page
Load Complete events.

Among the control events, TextChanged event is fired before the click event.

Do not enter anything in textbox and click button


Now enter some text in textbox and click the button

And see both events triggered

Page Load events

cached event

Post back event

Page Complete events

The execution order is shown below.


Page_PreInit
Page_Init
Page_InitComplete
Page_Load
Text Changed Event
Button Click
Page_LoadComplete
Page_PreRender
Page_PreRenderComplete

You might also like