Tải bản đầy đủ (.pdf) (32 trang)

Quản lý nhà nước trong ứng dụng Web ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (559.56 KB, 32 trang )


Managing State in
Web Applications
Chapter 5

Web pages and ASP.NET Framework use HTTP protocol
to communicate between a Web browser and a Web
server. HTTP is a stateless protocol and cannot
automatically indicate whether the sequential requests are
coming from the same or different clients. Therefore,
when a Web page is posted to the server, a new instance
of the Web page class is created. This results in the loss of
all the information associated with the page and the
controls placed on it.
To overcome this limitation, ASP.NET provides the state
management feature. In addition, it provides a feature
called caching that helps you improve the performance of
your Web application.
This chapter discusses the various client-side and
server-side state management options provided by
ASP.NET. In addition, it discusses how to improve the
performance of a Web application by using caching.

In this chapter, you will learn to:
 Implement client-side state management
 Implement server-side state management
 Manage state by using cross-page posting
 Implement caching

Objectives


NIIT Managing State in Web Applications 5.3
N
ot
e


A new instance of the Web page class is created each time the page is posted to the server.
In traditional Web programming, this would typically mean that all information
associated with the page and the controls on the page would be lost with each round trip.
Consider an example. Suppose a user fills up some personal information on a Web form.
While filling up this information, the user selects a country from a drop-down list on the
Web page. As soon as the user selects a country, the page needs to be posted back to the
server to retrieve a list of state names, which need to be populated in another drop-down
list on the same Web page. When the page is posted to the server, a new instance of the
Web page class will be created, and therefore, all information previously entered on the
Web page will be lost. This problem can be solved by using client-side state management.
Client-side state management allows you to store information either on a Web page or on
a client computer. Such state management improves the performance of a Web
application because it reduces the load on the server. The various options available to
implement client-side state management are:
 Hidden fields
 View state
 Control state
 Cookies
 Query strings



You can store only a limited amount of information by using client-side state
management.




A hidden field is a control similar to a TextBox control. However, unlike a TextBox
control, it does not render in a Web browser. As a result, a user cannot type anything in it.
Hidden fields can be used to store information that needs to be submitted along with the
Web page, but should not be displayed on the page. For example, when the details of a
product are displayed on a Web page, the ID of the product can be stored in a hidden
field. If the user orders the product, the information stored in the hidden field will be sent
to the server and the corresponding product will be added to the shopping cart.
Implementing Client-Side State Management
Hidden Fields
5.4 Managing State in Web Applications NIIT
N
ot
e

Hidden fields can also be used to pass session information to and from forms,
transparently. Consider an example. Suppose the home page of your website asks a user
to specify his or her favorite color. When the user clicks the submit button to move to
another page, say Page1.aspx, the information about the favorite color can be passed on to
a hidden field on Page1.aspx and the information can be used to change the background
color of the page to the specified color. Similarly, when the user moves from Page1.aspx
to another page, say Page2.aspx, the information in the hidden field on Page1.aspx can be
passed on to a hidden field on Page2.aspx. This information, again, can be used to change
the background color of Page2.aspx to the specified color.
To pass the information from one page to another, you can invoke the
Server.Transfer
method on the Click event of a Button control, as shown in the following example:


protected void Button1_Click(object sender, EventArgs e)
{
Server.Transfer("Page2.aspx");
}
The target page can access the passed information by referring to individual controls on
the source page, as shown in the following example:

String name = Request.Form["TextBox1"];
String color = Request.Form["HiddenField1"];


To ensure that the passed values are available to the target page, you must submit the page
by using the HTTP Post method.

A hidden field acts as a repository for any page-specific information that you want to
store directly in a page. The advantages of using hidden form fields are:
 A hidden field can store page-specific information without accessing any Web server
or Web browser resource.
 A hidden field can be easily implemented in an ASP.NET Web form page. You just
need to add the HiddenField control to a Web page and use the Value property of the
control to set its value.
Some limitations of using hidden form fields are:
 You can view the information stored in the hidden field by accessing the source of
the Web page. Therefore, the values stored in hidden form fields are not very secure.
 A hidden field does not support more than a single value field to store information.
 The hidden fields are stored in a page. Therefore, storing large values in hidden form
fields can slow down the processing of the page.
NIIT Managing State in Web Applications 5.5

If you use hidden fields, you must submit your pages to the server using the HTTP

POST method instead of requesting the page using the page URL. You cannot take
advantage of hidden fields if a page is processed in response to a link or the HTTP
GET method.


Each Web page and controls on the page have a property called
ViewState. This property
is used to automatically save the values of the Web page and each control on the Web
page prior to rendering the page. This, in turn, enables you to retain the page and
control-specific values between round trips to the server.
The view state is implemented with the help of a hidden form field called
__VIEWSTATE.
This hidden form field is automatically created in every Web page.
When ASP.NET executes a Web page on the Web server, the values stored in the
ViewState property of the page and controls on it are collected and formatted into a
single encoded string. This encoded string is then assigned to the
Value attribute of the
hidden form field,
__VIEWSTATE, and is sent to the client as part of the Web page.
During postback of a Web page to itself, one of the tasks performed by ASP.NET is to
restore the values in
__VIEWSTATE. When the page is initialized during postback,
ASP.NET Framework parses the view state string to restore the information displayed on
the page.
The view state of a Web page or a control consists of the cumulative property values of
the page or the control. To preserve these values across stateless HTTP requests, Web
pages and controls in ASP.NET use an instance of the
StateBag class.
The
StateBag class is the primary storage mechanism for HTML and server controls.

This class works like a dictionary object and allows you to store items as a key/value pair
in it. It accepts a string as a key and an object as its value. Items added to this class are
automatically added to the hidden
__VIEWSTATE form variable.
Storing Information in View State
Information in the form fields on a Web page is automatically added to the view state. In
addition to the information contained in form fields, the view state can be used to store
some additional information. For example, you can store a key-value pair,
Counter=1, in
the view state by using the following code:

ViewState["Counter"] = 1;

V
iew State
5.6 Managing State in Web Applications NIIT
In the preceding code snippet, a key by the name Counter is stored in the view state and
the value
1 is assigned to the key. If currently no key has the name Counter, a new key
will be added automatically. If a key with the name
Counter already exists, it will be
replaced.
Retrieving Information from View State
A value stored in view state can be retrieved by using code. For example, you can retrieve
the value of the key,
Counter, from view state by using the following code snippet:

int counter;
counter = (int) ViewState["Counter"];
In the preceding code snippet, the value stored in the key, Counter is converted to an

integer before storing it into an integer variable.
Enabling and Disabling View State
By default, the ViewState property of a Web page and the controls on the Web page is
enabled. However, you can disable this property for a Web page or any particular control
on the Web page. This is required when you have a large volume of information to
maintain. However, maintaining large volume of information leads to a significantly
slower rendering of a Web page. Therefore, disabling the
ViewState property is
important when users are accessing a Web page with limited bandwidth.
You also need to disable the
ViewState property for users using mobile devices. This is
because mobile devices may not have enough storage space for storing large volumes of
information.
You can enable or disable the
ViewState property of a Web page or an individual control
by setting the
EnableViewState property of the Web page or the control to True or
False. You can set the EnableViewState property of a Web page by using the @Page
directive, as shown in the following example:

<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="false"
CodeFile="Page1.aspx.cs" Inherits="Page1" %>
To determine the effect of enabling and disabling the ViewState property of a control,
consider an example. Add a Label and a Button control to a Web page and type the
following code in the
Page_Load event handler:

if(!IsPostBack)
{
Label1.Text="Hello World";

}
NIIT Managing State in Web Applications 5.7
N
ot
e
N
ot
e


By default, a Button Web server control submits a page back to itself.
When this page is loaded for the first time, the message, Hello World, is displayed in the
Label control. When the user clicks the button, the message is still displayed on the Label
control. This is because the default value of the
EnableViewState property of the Label
control is
True.
To see the effect of disabling the
ViewState property, set the EnableViewState property
of the Label control to
False and execute the application. When this page is loaded for
the first time, the message, Hello World, is displayed in the Label control. However, when
the button is clicked, the Label control displays the default text, Label. This is because the
Label control does not maintain its state when its
EnableViewState property is set to
False.



If the EnableViewState property of a Web page is set to False, viewstate is not

maintained for any control on that Web page, even if the
EnableViewState property
of a control on the Web page is set to
True.

The advantages of using view state are:
 The values in view state are stored in a standard HTML format as part of a Web
page. Therefore, no Web server resource is required to maintain it.
 The view state can be easily implemented on the ASP.NET Web page. You just need
to set the
EnableViewState property of a Web page and server controls.
 The values in view state are hashed, compressed, and encoded for Unicode
implementations. Therefore, values in view state are more secure than the values
stored in hidden fields.
View state also has the following limitations:
 Storing large values can cause a page to slow down when users display it or post it
because view state is stored in the Web page.
 View state is stored in a hidden field on a Web page. Although view state stores data
in a hashed format, it can be tampered with. The information in the hidden field can
be seen if the page output source is viewed directly, creating a potential security
issue.

5.8 Managing State in Web Applications NIIT

You can use the
ViewState property to preserve page and control values between round
trips to the Web server. If you disable the
ViewState property of a page, the ViewState
of the controls on that page is not maintained. This can lead to improper functioning of
some controls on the page. For example, the state of the selected node in a TreeView

control needs to be maintained for the control to function properly across postbacks.
To enable persistence of property information that is specific to a control, ASP.NET
allows you to store the state of a control by using a client-side state maintenance
mechanism called control state. Unlike view state, the control state cannot be disabled at
the page level. Therefore, if your Web page contains controls whose state must be
maintained, you can use the control state mechanism to store their state.
You can implement control state on a custom Web control by overriding the following
methods of the base class:
 OnInit: This method should contain the following lines of code:
Page.RegisterRequiresControlState(this);
base.OnInit(e);
 SaveControlState
: This method should return a public property of the control
(whose state needs to be saved) or an object array containing the values of all the
public properties of the control.
 LoadControlState: This method should set the value of the public properties to the
values contained in the object passed to the
LoadControlState method as an
argument.


Task 5.1: Implementing control state on a Custom Web control


Cookies are used to store small pieces of information related to a user’s computer, such as
its IP address, browser type, operating system, and Web pages last visited. The purpose of
storing this information is to offer a personalized experience to the user. For example, if a
user has logged on to your website for the first time, the name of the user can be stored in
a cookie. This information can be retrieved later on when the same user visits the website
again to greet the user with his/her name.

Cookies are sent to a client computer along with the page output. These Cookies are
stored on the client’s computer. When a browser requests the same page the next time, it
sends the cookie along with the request information. The Web server reads the cookie and
Cookies
Control State
NIIT Managing State in Web Applications 5.9
extracts its value. It then process the Web page according to the information contained in
the cookie and renders it on the Web browser.
Types of Cookies
Cookies can either be temporary or persistent. Temporary cookies exist in the memory
space of a browser. When the browser is closed, all temporary cookies added to the
browser are lost. Temporary cookies are also known as session cookies.
A temporary cookie is useful for storing information required for only a short time or that
should not be written to disk on the client computer for security reasons. For example, a
temporary cookie can be created to store the user name. The user name stored in the
cookie can be retrieved and displayed on every page of the website.
A persistent cookie is saved as a text file in the file system of the client computer.
Persistent cookies are used when you want to store information for a longer period. For
example, persistent cookies can be used to store customized user settings for a website.
This helps in customizing the website when the user visits the website again.
While creating a persistent cookie, you can set the expiration date of the cookie, which
defines the duration for which the cookie will be stored on the client computer. If you do
not set the expiration date of a cookie, the cookie is maintained as a temporary cookie, as
part of the user's session information. Once the user session is finished, the cookie is
discarded.
Persistent cookies can be created as shown in the following example:

Response.Cookies["userName"].Value = "Peter";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(2);
Response.Cookies["lastVisited"].Value = DateTime.Now.ToString();

Response.Cookies["lastVisited"].Expires = DateTime.Now.AddDays(2);
In the preceding example, two cookies, username and lastVisited, are created. The user
name
Peter is stored in the first cookie and the date and time when the user, Peter, last
visited the site is stored in the second cookie. The expiry period for both the cookies is set
as
2 days. If you do not set the expiry period for the cookies, the cookies will be created
as temporary cookies.
You can also store multiple values in a single cookie. For example, instead of creating
separate cookies for storing the user name and last visited information, you can create a
single cookie that can hold both the values. Such a cookie can be created as shown in the
following example:

Response.Cookies["userInfo"]["userName"] = "Peter";
Response.Cookies["userInfo"]["lastVisited"] =
DateTime.Now.ToString();
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(2);
5.10 Managing State in Web Applications NIIT
In the preceding example, the cookie, userInfo, with two subkeys, userName and
lastVisited, is created.
Reading Cookies
You can access the value of a cookie by using the Request built-in object. However, if
you want to modify a cookie, you need to use the
Response built-in object of ASP.NET.
The following example reads the value of a cookie that stores a single value:

if (Request.Cookies["userName"].Value != null)
{
Label1.Text = Request.Cookies["userName"].Value;
}

In the preceding example, the value in the cookie, userName, is checked for null. If the
value is not null, the value is assigned to the
Text property of the Label control.
Similarly, you can read the values from a cookie that stores multiple values. The
following example reads values from a cookie that stores multiple values:

if (Request.Cookies["userInfo"] != null)
{
Label1.Text = Request.Cookies["userInfo"]["userName"]);
Label2.Text = Request.Cookies["userInfo"]["lastVisited"]);
}
In the preceding example, the value in the cookie, userInfo, is checked for null. If the
value is not null, the value of the subkeys,
userName and lastVisited, is assigned to the
Text properties of the Label controls.
Advantages and Disadvantages of Cookies
Cookies provide several advantages. Some advantages of using cookies are:
 A cookie is stored on the client computer and can be read by the server after a
request for a page is posted. Therefore, no server resource is involved in maintaining
the cookie.
 A cookie is a text-based data structure that contains key-value pairs. Therefore, it is
easy to create and manipulate cookies.
 A cookie can either expire when the browser session ends or exist indefinitely on the
client computer, subject to the expiration rules on the client.
NIIT Managing State in Web Applications 5.11
However, cookies also have the following limitations:
 Cookies that are stored on the client computers have a limited size. Most browsers
allow cookies to be up to 4096 bytes in size. Therefore, you cannot store a large
amount of data in a cookie.
 Users can disable cookies to prevent them from being stored on the hard disk of their

computer. If a user denies permission for cookies, an ASP.NET Web application
cannot store cookies on the client computer.
 Users can tamper with cookies because cookies are stored on the client computer.


Sometimes, it is required to transfer information from one page to another. For example,
on an online book shopping website, a Web form displays the list of categories of books.
When the user selects a category, another page with detailed information about the
selected category is displayed. This process requires you to transfer the information about
the selected category to the other page so that the relevant details can be displayed. You
can perform this task by using a query string.
A query string provides a simple way to pass information from one page to another. It is
the part of a URL that appears after the Question mark (?) character. Consider the
following URL:

In the preceding URL, the query string defines a variable, category, which contains the
string, fiction.
You can pass data from one page to another page in the form of a query string by using
the
Response.Redirect method, as shown in the following example:

Response.Redirect("BooksInfo.aspx?Category=fiction");
In the preceding example, the string fiction is stored in the variable Category and is
sent to the
BooksInfo.aspx page. The information stored in the variable Category can be
retrieved on the
BooksInfo.aspx page by using the following syntax:

String cat = Request.QueryString["Category"];
The preceding example returns the string fiction.

You can pass multiple values from one page to another by using a query string. For this,
the values must be separated with the ampersand (&) symbol, as shown in the following
example:

Response.Redirect("BooksInfo.aspx?Category=fiction&Publisher=Sams");
Query String
5.12 Managing State in Web Applications NIIT
N
ot
e

N
ot
e



There should be no blank space before and after the ampersand (&) symbol.

In the preceding example, the strings,
fiction and Sams, are stored in the variables,
Category and Publisher, respectively. The information stored in these variables can be
retrieved on the
BooksInfo.aspx page by using the following syntax:

String cat = Request.QueryString["Category"];
String pub = Request.QueryString["Publisher"];




To ensure that the query string values are available during page processing, you must
submit the page by using the HTTP Get method.

Advantages and Disadvantages of Query Strings
The advantages of using query strings are:
 A query string is contained in the HTTP request for a specific URL. Therefore, no
server resource is involved in processing a query string.
 Many Web browsers support passing values in a query string. Therefore, if you
create a Web application that passes information from one page to another using a
query string, it will be processed in most of the browsers.
Query strings have the following limitations:
 They can be used only with the HTTP GET method.
 The information in a query string is directly visible to the users in the browser
window. Therefore, you need to encrypt this information to ensure that any
confidential information is not exposed. This causes an additional overhead to Web
application development. In addition, query strings are not useful for storing
sensitive data.
 There is a limit to the amount of information that you can pass from one page to
another using query strings because most browsers support up to 255 characters of
URL.

NIIT Managing State in Web Applications 5.13
N
ot
e

There are situations where you need to store the state information at the server-side. One
such situation is when you want to know the number of users logged on to the Web
application. Server-side state management enables you to manage application and
session-related information on the server. This reduces the amount of information to be

sent to the client to preserve state.
ASP.NET provides the following options to manage state at the server side:
 Application state
 Session state
 Profile properties


ASP.NET provides application state as a means of storing application-specific
information such as objects and variables. The information in the application state is
stored in a key-value pair and is used to maintain data consistency between server round
trips and between pages.
Application state is created the first time a user accesses any URL resource in an
application. After an application state is created, the application-specific information is
stored in it. All the information stored in the application state is shared among all the
pages of the Web application by using the
HttpApplicationState class. The
HttpApplicationState class is accessed by using the Application property of the
HttpContext object.



Application state variables are global for an ASP.NET application. However, the values
s
tored in the application state variables are accessible only from the code running within the
context of the originating application. Other applications running in the system cannot
access or modify the values.





A
pplication State
Implementing Server-Side State Management
5.14 Managing State in Web Applications NIIT
Storing Information in Application State
You can add application-specific information to an application state by creating variables
and objects and adding them to the application state. Variables and objects added to the
application state are global to an ASP.NET application. For example, you can create a
variable called
MyVariable with the value Hello and store it in the application state by
using the following code snippet:

Application ["MyVariable"] = "Hello";
After the application in which you declared MyVariable is executed, any page in the
application can retrieve the value of
MyVariable. To read the value of MyVariable, you
can use the following code snippet:

string val = (string) Application["MyVariable"];
You can also add complex objects, such as a Collection or a Dataset, in the application
state. For example, you can add a dataset to an application state by using the following
code snippet:

DataSet ds = new DataSet();
Application ["DataSet"] = ds;
Removing Information from Application State
In addition to adding variables and objects to application state, you can remove an
existing object or variable from application state. For example, you can remove the
application variable
MyVariable from the application state, by using the following code

snippet:

Application.Remove(["MyVariable"]);
You can also remove all the application state variables and objects by using the following
code snippet:

Application.RemoveAll();
After an object is added to an application state, it remains in the application state until the
application is shut down, the Global.asax file is modified, or the item is explicitly
removed from the application state.


NIIT Managing State in Web Applications 5.15
Handling Application Events
Application state has the following events that you can capture to manipulate an
ASP.NET Web application:
 Application.Start: This event is raised when the application receives the first
request for a Web page. It is also raised on the next request after the server, Web
service, or website has been restarted. The event handler for this event usually
contains code for initializing the application variables.
 Application.End: This event is raised the server, Web service, or website is stopped
or restarted. The event handler for this event usually contains code to clean up the
resources that the application has used.
 Application.Error: This event is raised when an unhandled error occurs.
You can handle the preceding events by adding subroutines in the Global.asax file. The
Global.asax file contains the event handlers for all the application and session events.
Considerations While Using Application State
The application state variables are global to an application. Therefore, it is important to
consider the following issues while storing any value in an application state variable:
 The memory occupied by variables stored in an application state is not released until

the value is either removed or replaced. Therefore, the number of variables and
objects in an application state should be minimum. Otherwise, it will be an overhead
on the Web server and the server response will be slow.
 Multiple pages within an application can simultaneously access the values stored in
an application state. Therefore, explicit synchronization methods need to be used to
avoid deadlocks and access violations.
Synchronizing Application State
Multiple pages within an ASP.NET Web application can simultaneously access the values
stored in an application state. This can result in conflicts and deadlocks. For example, you
can add a variable named
PageCounter in the application state to keep track of the
number of times a page has been requested. If two users access a Web page
simultaneously, there will be an attempt to update the value of the variable
PageCounter
by both the users which could result in data inconsistency. To avoid such situations, the
HttpApplicationState class provides two methods, Lock() and Unlock(). These
methods allow only one thread at a time to access application state variables and objects.



5.16 Managing State in Web Applications NIIT
N
ot
e

N
ot
e

N

ot
e



Each browser’s request for a Web page initiates a new thread on the Web server.

Calling the
Lock() method on an Application object causes ASP.NET to block attempts
by the code running on other worker threads to access anything in the application state.
These threads are unblocked only when the thread that called the
Lock() method calls the
corresponding
Unlock() method on the Application object. Consider the following
example:

Application.Lock();
if (Application["PageCounter"] == null)
{
Application["PageCounter"]=1;
}
else
{
Application["PageCounter"]=(int)Application["PageCounter"
]+1;
Response.Write(Application["PageCounter"]);
}
Application.UnLock();

In the preceding example, the Lock() method is called before accessing the value of the

PageCounter variable. This ensures that the variable cannot be modified simultaneously
by any other thread. After calling the
Lock() method, the value of the PageCounter
variable is modified. After the modification is done, the
UnLock() method is called to
release the imposed lock on the
PageCounter application state variable. Then, the
variable can be modified by other threads.


It is not required to call the Unlock() method explicitly because the .NET Framework
automatically removes the lock when the request completes or times out, or when an
unhandled error occurs during request execution and causes the request to fail.



The Lock() method locks all the items in the application state object. In other words,
you cannot selectively lock items in an application state.


NIIT Managing State in Web Applications 5.17
The advantages of using the application state are:
 Application state is easy to use and is consistent with other .NET Framework classes.
 Storing information in application state involves maintaining only a single copy of
the information.
Application state has the following limitations:
 The data stored in an application state is lost when the Web server containing the
application state fails due to a server crash, upgrade, or shutdown.
 Application state requires server memory and can affect the performance of the
server and the scalability of the Web application, if it occupies too much memory

space.
You can implement application state to increase the performance of the Web application.
For example, storing relatively static dataset in an application state can enhance Website
performance by reducing the overall number of data requests to a database. However, it is
important to remember that application state variables containing large blocks of
information can reduce Web server performance as server load increases. In addition, the
memory occupied by a variable stored in an application state is not released until the
value is either removed or replaced. Therefore, it is preferred to use application state
variables with small, and less frequently changed datasets.


Activity 5.1: Implementing Application State



In ASP.NET, session state is used to store session-specific information for a Web
application. Unlike application state, the scope of session state is limited to the current
browser session. If multiple users are accessing a Web application, each will have a
different session state. If a user exits from a Web application and returns later, the user
will have a different session state.
Session state is structured as a key-value pair for storing session-specific information that
needs to be maintained between server round trips and between requests for pages.
The session state has a built-in support in ASP.NET. The built-in session state feature
automatically performs the following actions:
 Identify and classify requests coming from a browser into a logical application
session on the server.
Session State
5.18 Managing State in Web Applications NIIT

Store session-specific data on the server for use across multiple browser requests.

 Raise session lifetime-related events, such as Session.Start and Session.End,
which can be handled in the Global.asax file.
 Automatically release session data if a browser does not access an application within
a specified timeout period.
When a user first requests a page from an ASP.NET website, the website automatically
adds a session cookie to the client browser. This cookie is named
ASP.NET_SessionID
cookie. This cookie is used for the remainder of the user’s visit to the website.
Identifying a Session
Each active ASP.NET session is identified and tracked by a unique 120-bit SessionID
string containing American Standard Code for Information Interchange (ASCII)
characters. The SessionID strings are communicated across client/server requests either
by means of an HTTP cookie or by using a modified URL with the embedded SessionID
string. The
SessionStateModule class is responsible for generating or obtaining
SessionID strings.
Similar to the application state, you can store objects and variables in a session state. By
default, a session variable is active for 20 minutes without any user interaction. In an
ASP.NET Web application, the objects stored in the session state are stored on the server.
Using the Session State
The syntax for adding and retrieving items from the session state is basically the same as
for adding items to a page’s view state. The following example adds the variable,
MyVariable, with value HELLO in the session state:

Session["MyVariable"]="HELLO";
You can retrieve the value of the variable, MyVariable, by using the following statement:

String val = (string) Session["MyVariable"];
The preceding statement returns the value of the variable, MyVariable.
You need to consider the following issues when adding variables and objects to a session

state:
 Any variable or object that you add to a session state is available only until the user
closes the browser window. The variables and objects are automatically removed
from session state if the user does not request a page for more than 20 minutes
because it is the default value.
NIIT Managing State in Web Applications 5.19

Any variable or object added to a session state is related to a particular user. For
example, you can store different values for
MyVariable for two different users
accessing the Web page and each user can access only the value that is assigned to
him/her.
 Any object that supports serialization can be added to the session state. The objects
stored in session state are stored on the server. Therefore, session objects are not
subject to the same size limitations as cookies.
Session state is global to the entire application for the current user. Session state is not lost
if the user revisits a Web page by using the same browser window. However, session state
can be lost in the following ways:
 When the user closes and restarts the browser.
 When the user accesses the same Web page through a different browser window.
 When the session times out because of inactivity.
 When the Session.Abandon() method is called within the Web page code.
Similar to an application state, you can remove an object or a variable added to the
session state by using either the
Remove() method, or the RemoveAll() method based on
the requirement.
Handling Session Events
Session state has the following events that you can capture to manipulate an ASP.NET
Web application:
 Session.Start: This event is raised when a user requests the first page from a

website, and is useful for initializing session variables.
 Session.End: This event is raised when a user session expires or when the
Session.Abandon method is called.
You can capture both these events by adding subroutines in the Global.asax file. The
Global.asax file contains the event handlers for all the application and session events.
Configuring Session State
Session state can be configured through the web.config file for the application. The
web.config file allows you to set advanced options such as the timeout and the session
state mode. The following markup shows some important options that can be set for the
<sessionState> element:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<sessionState
5.20 Managing State in Web Applications NIIT
cookieless="UseCookies" cookieName="ASP.NET_SessionId"
timeout="20"
mode="InProc" />
</system.web>
</configuration>
The preceding markup uses the following session state attributes:
 Cookieless
 timeout
 mode

The cookieless Attribute
The
cookieless attribute specifies whether a cookie should be used or not. The following
table lists the values that the

cookieless attribute can have with their description.

Value Description
UseCookies
Specifies that cookies are always used, even if the browser or device
does not support cookies or cookies are disabled. It is the default
value. If the device does not support cookies, the session information
will be lost over subsequent requests, because each request will get a
new ID.
UseUri
Specifies that cookies are never used.
UseDeviceProfile
Specifies ASP.NET to choose whether to use cookies by examining the
BrowserCapabilities object. It does not take into account that the user
may have disabled cookies in a browser that supports them.
AutoDetect
Specifies that cookies should be used if the browser supports them.
ASP.NET determines whether the browser supports cookies by
attempting to set and retrieve a cookie.
Values of the Cookieless Attribute
The timeout Attribute
The
timeout attribute is an important attribute of the <sessionState> element. It
specifies the number of minutes that ASP.NET will wait, without receiving a request,
before abandoning the session.
The value for the
timeout attribute should be set such that it is short enough to allow the
server to reclaim valuable memory after a client stops using the application. At the same
time, the value should be long enough to allow a client to pause and continue a session
without losing it.

NIIT Managing State in Web Applications 5.21
The timeout attribute can also be set programmatically, as shown in the following code
snippet:

Session.Timeout = 15;
The mode Attribute
The
mode attribute specifies where the session state values are to be stored. The mode
attribute can have the following values:
 Custom: Specifies custom data store to store session-state information.
 InProc: Specifies that the information is to be stored in the same process as the
ASP.NET worker threads. This is the only mode in which the
Session.End event is
raised.
 Off: Specifies that the session state is disabled.
 SQLServer: Specifies that the session state is to be stored by using an out-of-process
SQL Server database to store state information.
 StateServer: Specifies that the session state is to be stored in an out-of-process
ASP.NET state service.
Disabling the Session State
By default, session state is enabled for all the pages in a Web application. If you need to
improve the performance of the Web application, you can disable session state for Web
pages. This can be done by using the
EnableSessionState attribute in the page directive,
as shown in the following code:

<%@ Page EnableSessionState=”False” %>
You can also disable session state for all pages of a Web application by setting the mode
attribute to
Off in the web.config file, as shown in the following figure.


Mode Attributes in a Web.config File
5.22 Managing State in Web Applications NIIT
N
ot
e

If you want to retrieve objects from session state but do not want to add objects to it, you
can set the
EnableSessionState attribute to ReadOnly.



In ASP.NET, the mode attribute is case-sensitive.


Activity 5.2: Storing and Retrieving Session State


Many Web applications provide users with the option to personalize the application. This
can be done by storing and using information that is unique to a user. This information
can be used to present the user with a personalized version of the Web application.
Consider an example. Suppose, you have created a website for online shopping of books.
A user has used the website to purchase books from the IT category. This information can
be stored as a profile property for that user. When the same user visits the website again,
you can use the information stored in the profile properties to display the latest books in
the IT category to the user.
ASP.NET provides the profiles feature to implement personalization in Web applications.
Although it is possible to store user preferences without using profiles, using it enables
developers to store preferences without writing much code. These preferences are stored

as named properties in profiles. The preferences can be stored in the form of simple data
types, complex data structures, or .NET Framework classes.
The profile information is stored in the aspnetdb.mdf file. It is created automatically when
you use any membership or profiles features for the first time. However, this automatic
creation of the aspnetdb.mdf file relies on SQL Server 2005 Express. If you’re using
another version of SQL Server, you need to modify the profile configuration and create
the database manually.





Profile Properties
NIIT Managing State in Web Applications 5.23
N
ot
e


The membership feature will be discussed later in this course.


Task 5.2: Creating the Aspnetdb.mdf File Manually
By default, the connection string in the profile configuration is named as LocalSqlServer.
You can modify this connection string in the machine.config file. The machine.config
settings apply to all the ASP.NET applications. Therefore, if you have to modify the
connection string for a single application, it is advisable to use the web.config file.
To modify the connection string by using the web.config file, you need to use the markup
as shown in the following example:


<configuration>
<connectionStrings>
<clear />
<add name="LocalSqlServer" providerName="System.Data.SqlClient"
connectionString="Data Source=localhost;Integrated Security=SSPI;
Initial Catalog=aspnetdb" />
</connectionStrings>

</configuration>
The <clear/> element clears all the existing connection strings. After clearing the
existing connection strings, you can specify the new connection string.
Configuring Profile Properties
The properties that need to be stored in each user profile for an application can be
configured in the web.config file. You can configure the profile properties by using the
markup shown in the following example:

<system.web>
<profile>
<properties>
<add name="UserName" />
<add name="BirthDate" type="System.DateTime" />
</properties>
</profile>
<system.web>
5.24 Managing State in Web Applications NIIT
N
ot
e

In the preceding example, two profile properties, UserName and BirthDate, are defined.

The name attribute is used to define the name of the profile properties and the type
attribute is used to specify the data type. If the data type for a profile property is
not defined, it takes the default data type, which is String. Therefore, the data type
of the UserName property is String. The data type for the BirthDate property is
defined as
DateTime. The properties UserName and BirthDate can be set only by the
logged-on users. Anonymous users cannot set these properties.
You can also create profile properties that can be set by all users including anonymous
users. To configure such profile properties, you need to use the markup as shown in the
following example:

<system.web>
<anonymousIdentification enabled="true"/>
<profile>
<properties>
<add name="UserName" type ="System.String" allowAnonymous=
"true"/>
<add name="BirthDate" type="System.DateTime" allowAnonymous=
"true"/>
</properties>
</profile>
<system.web>
Getting and Setting Profile Properties
After configuring the profile properties in the web.config file, you can access them by
using the
Profile object. The value of the Profile property can be set, as shown in the
following code snippet:

Profile.UserName = TextBox1.Text;
In the preceding code snippet, the UserName profile property is set to the Text property of

the
TextBox1 control. Similarly, the value of the profile property can be retrieved, as
shown in the following code snippet:

String uname = Profile.UserName;
The preceding code snippet returns the value of the Username profile property.


When you store profile properties, ASP.NET identifies the user who has set the
property.
NIIT Managing State in Web Applications 5.25
N
ot
e

By default, a Button control on a Web page submits the page back to itself. However,
sometimes, you may want to post one page to another. In such a case, you can set the
PostBackUrl property of the Button control to the URL of the target page. This posting of
information from one page to another page is called cross-page posting.
When the source page is posted to the target page, the target page must be able to access
the information stored in the controls on the source page. In addition, the target page must
be able to identify whether the page was loaded as a result of a cross-page postback.


To make a control submit the page back to itself, you can set the AutoPostBack
property of the control to true.



The

Page class exposes a public property named PreviousPage. If the source and target
pages are in the same application, the
PreviousPage property contains a reference to the
source page. However, if the pages are in different applications, or if the page is not the
target of a cross-page posting, the
PreviousPage property is not initialized.
You can access the values in the controls on the source page by using the
FindControl
method, as shown in the following example:

if (PreviousPage != null)
{
TextBox t = (TextBox) PreviousPage.FindControl
("TextBox1");
if (t != null)
{
Response.Write(t.Text);
}
}
In the preceding example, the value of the TextBox1 control, which is on the source page,
is accessed in the target page.




Managing State by Using Cross-Page Posting
A
ccessing Information Stored in Controls on the Source Page

×