Developing Web
Applications Using
Microsoft® Visual
Studio® 2008
Module 14: Managing State
• State Management
• Application and Session Variables
• Cookies and Cookieless Sessions
Lesson: State Management
• What Is State Management?
• Types of State Management
• Server-Side State Management
• Client-Side State Management
• The Global.asax File
What Is State Management?
Without State With State
Management Management
Login.aspx Login.aspx
Please enter your Please enter your
logon information: logon information:
First Name First Name
John John
Last Name Last Name
Chen Chen
Submit
Submit Web Server Submit
Submit Web Server
Greetings.aspx Greetings.aspx
Hello Hello John Chen
I forget who
you are!!
Types of State Management
Server-Side State Client-Side State
Management Management
Application state Cookies
• Information is available to all • Plain text file that stores
users of a Web application information to maintain state
Session state ViewState and Control State
• Information is available only to a • Retains values between multiple
user of a specific session requests for the same page
Database
Query strings
• In some cases, use database
support to maintain state on your • Information appended to the end
of a URL
Web site
Server-Side State Management
• Application state is a global storage mechanism accessible
from all pages in the Web application
• Session state is limited to the current browser session:
Values are preserved through the use of application and
session variables
Scalability
• An ASP.NET session is identified by the SessionID string
Web Server
Client Computer
SessionID Application and
Session variables
Client-Side State Management
• Uses cookies to maintain state:
Persistent cookies
Temporary / non-persistent cookies
• Less reliable than server-side state management options:
User can delete cookies
• Less secure than server-side state management options
• Limited amount of information:
Client-side restrictions on file sizes Web Server
Client Computer
Cookies
The Global.asax File
• Only one Global.asax file per Web application
• Stored in the virtual root of the Web application
• Used to handle application and session events
• The Global.asax file is optional
Lesson: Application and Session Variables
• Initializing Application and Session Variables
• Accessing Application and Session Variables
• Application and Session Variable Duration
• Scalable Storage of Application and Session Variables
• Saving Application and Session Variables in a Database
Initializing Application and Session Variables
• Variables are initialized in Global.asax
The Application object shares information among all
users of a Web application
[Visual C#]
protected void Application_Start(Object
sender,EventArgs e)
{
Application["NumberofVisitors"] = 0;
}
[Visual Basic]
Sub Application_Start(s As Object,e As EventArgs)
Application("NumberofVisitors") = 0
End Sub
The Session object stores information for a particular
user session
Accessing Application and Session Variables
• Set session and application variables
[Visual C#]
[Visual Basic]
Session["BackColor"] = "blue";
Session("BackColor") = "blue"
Application.Lock();
Application.Lock()
Application["NumberOfVisitors"] =
Application("NumberOfVisitors") += 1
(int)Application["NumberOfVisitors"] + 1;
Application.UnLock()
Application.UnLock();
• Read session and application variables
[Visual C#]
[Visual Basic]
bgColor = (string)Session["BackColor"];
bgColor = Session("BackColor")
visitorLabel.Text =
visitorLabel.Text = Application("NumberOfVisitors")
Application["NumberOfVisitors"].ToString();
Application and Session Variable Duration
• Session variables have a set duration after last access:
Default is 20 minutes
• Session duration can be changed in web.config
<configuration>
<system.web>
<sessionState timeout="10" />
</system.web>
</configuration>
• Application variables persist until the Application_End
event is fired
Scalable Storage of Application and Session Variables
• By default, the session state is managed in-process
• Disadvantage of in process storage:
Not Scalable
• ASP.NET provides out of process storage of session state
State can be stored in a SQL Server database or a state server
• Advantages of out-of-process storage:
Scalable State server
Web farm
Session and
Application variables
-Or-
SQL
Session and
Application variables
Client
Saving Application and Session Variables in
a Database
11 Configure the session state in Web.config:
• Mode is set to SqlServer or StateServer
<sessionState mode="SQLServer"
sqlConnectionString="data source=SQLServerName;
Integrated security=true" />
22 Configure SQL server by using the Aspnet_regsql.exe tool
Lesson: Cookies and Cookieless Sessions
• Storing Session Date by Using Cookies
• Retrieving Information from a Cookie
• Cookieless Sessions
• Setting Up Cookieless Sessions
Storing Session Date by Using Cookies
• Creating a cookie
[Visual C#]
[Visual C#]
HttpCookie getCookie = new HttpCookie("myCookie");
HttpCookie getCookie = new HttpCookie("myCookie");
DateTime now = DateTime.Now;
DateTime now = DateTime.Now;
getCookie.Values.Add("Time", now.ToString());
getCookie.Values.Add("Time", now.ToString());
getCookie.Values.Add("ForeColor", "White");
getCookie.Values.Add("ForeColor", "White");
getCookie.Values.Add("BackColor", "Blue");
getCookie.Values.Add("BackColor", "Blue"); To create a
getCookie.Expires = now.AddHours(1);
Response.Cookies.Add(getCookie); persistent cookie,
Response.Cookies.Add(getCookie); specify the
expiration time
• Cookie contains information about the domain name
Set-Cookie:
Set-Cookie: Username=John+Chen;
Username=John+Chen; path=/;
path=/;
domain=microsoft.com;
domain=microsoft.com;
Expires=Tuesday,
Expires=Tuesday, 01-Feb-05
01-Feb-05 00.00.01
00.00.01 GMT
GMT
Retrieving Information from a Cookie
• Read the cookie
[Visual C#] [Visual Basic]
HttpCookie myCookie = Dim myCookie As HttpCookie = _
Request.Cookies["cookieName"]; Request.Cookies("cookieName")
• Retrieve values from the cookie
[Visual C#]
timeLabel.Text = myCookie.Values["Time"];
timeLabel.ForeColor = System.Drawing.Color.FromName
(myCookie.Values["ForeColor"]);
timeLabel.BackColor = System.Drawing.Color.FromName
(myCookie.Values["BackColor"]);
[Visual Basic]
timeLabel.Text = myCookie.Values("Time")
timeLabel.ForeColor = System.Drawing.Color.FromName _
(myCookie.Values("ForeColor"))
timeLabel.BackColor = System.Drawing.Color.FromName _
(myCookie.Values("BackColor"))
Cookieless Sessions
• Each active session is identified and tracked by using a
session IDs
• Session IDs are communicated across client-server
requests by using an HTTP cookie or including it in the URL
• Cookieless sessions
Session ID information is encoded into URLs
http://server/(h44a1e55c0breu552yrecobl)/page.aspx
Cannot use absolute URLs
Most browsers limit the URL size to 255 characters, which limits
use of cookieless session IDs
Setting Up Cookieless Sessions
• Session state is configured in the <sessionState>
section of web.config
• To enable a cookieless session, set the cookieless
attribute to "true"
<sessionState cookieless="true" />
Lab: Storing Application and Session Data
• Exercise 1: Implementing Session Variables
• Exercise 2: Implementing Cookies
• Exercise 3: Implementing Application Variables
• Exercise 4: Storing Session Variables in a Database
Logon information
Virtual machine 2310C-LON-DEV-14
User name Student
Password Pa$$w0rd
Estimated time: 90 minutes
Lab Scenario
Logon Page Master Page
login.aspx Lab Web benefitsMaster.master
Benefits Application
Home Page ASPState
Default.aspx Page Header
header.ascx
Registration Menu Component
register.aspx Benefits.cs or Benefits.vb
TempDB
Web.
config
Life Insurance Retirement Medical Dentists
life.aspx retirement.aspx medical.aspx dental.aspx
Prospectus XML Web
prospectus.aspx Doctors User Control
LINQ to SQL doctors.aspx nameDate.ascx Service
Classes DentalService1.asmx
Doctors.dbml
Doctors Dentists
XML Files
Lab Review
Review Questions
• How do you set session variables?
• How can you check if a cookie exists?
• When you modify an application variable, why must you
lock it?
• How can you store the session variables in a SQL Server
database?
Module Review and Takeaways
• Review Questions
• Best Practices
• Tools