Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 24

Managing State

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
logon information: information:
First Name First Name
John John
Last Name Last Name
Chen Chen

Submit Submit Web Server


Submit Web Server Submit
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 • Text file stores information to
users of a Web application maintain state

Session state ViewState and Control State


• Information is available only to • Retains values between multiple
a user of a specific session requests for the same page

Database Query strings


• In some cases, use database
• Information appended to the end
support to maintain state on
of a URL
your 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

• ASP.NET session is identified by the SessionID string

Web Server
Client Computer
Application and Session variables

SessionID
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

Sub Application_Start(s As Object,e As EventArgs)


Application("NumberofVisitors") = 0
End Sub

protected void Application_Start(Object


sender,EventArgs e)
{
Application["NumberofVisitors"] = 0;
}

 The Session object stores information for a particular


user session
Accessing Application and Session Variables

• Set session and application variables

Session("BackColor") = "blue"
Application.Lock()
Application("NumberOfVisitors") += 1
Application.UnLock()

Session["BackColor"] = "blue";
Application.Lock();
Application["NumberOfVisitors"] =
(int)Application["NumberOfVisitors"] + 1;
Application.UnLock();

• Read session and application variables


strBgColor = Session("BackColor")
lblNbVisitor.Text = Application("NumberOfVisitors")

strBgColor = (string)Session["BackColor"];
lblNbVisitor.Text = 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
Client

Session and Application variables


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• Then, configure the 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:

HttpCookie
HttpCookie objCookie
objCookie == new
new HttpCookie("myCookie");
HttpCookie("myCookie");
HttpCookie
DateTime now
HttpCookie
DateTime objCookie
now = DateTime.Now;
objCookie = new
= DateTime.Now;HttpCookie("myCookie");
= new HttpCookie("myCookie");
DateTime now = DateTime.Now;
DateTime now = DateTime.Now;
objCookie.Values.Add("Time",
objCookie.Values.Add("Time", now.ToString());
now.ToString());
objCookie.Values.Add("Time",
objCookie.Values.Add("ForeColor",now.ToString());
objCookie.Values.Add("ForeColor", "White");
objCookie.Values.Add("Time", now.ToString());
"White");
objCookie.Values.Add("ForeColor",
objCookie.Values.Add("BackColor",
objCookie.Values.Add("BackColor", "White");
"Blue");
objCookie.Values.Add("ForeColor", "Blue");
"White");
objCookie.Values.Add("BackColor", "Blue");
objCookie.Values.Add("BackColor", "Blue");
objCookie.Expires
objCookie.Expires == now.AddHours(1);
now.AddHours(1);
Response.Cookies.Add(objCookie);
Response.Cookies.Add(objCookie);
Response.Cookies.Add(objCookie);
Response.Cookies.Add(objCookie);
To create a persistent
cookie, 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


Dim objCookie As HttpCookie = Request.Cookies("myCookie")

HttpCookie objCookie = Request.Cookies["myCookie"];

• Retrieve values from the cookie


lblTime.Text = objCookie.Values("Time")
lblTime.ForeColor = System.Drawing.Color.FromName _
(objCookie.Values("ForeColor"))
lblTime.BackColor = System.Drawing.Color.FromName _
(objCookie.Values("BackColor"))

lblTime.Text = objCookie.Values["Time"];
lblTime.ForeColor = System.Drawing.Color.FromName
(objCookie.Values["ForeColor"]);
lblTime.BackColor = System.Drawing.Color.FromName
(objCookie.Values["BackColor"]);
Cookieless Sessions

• Each active session is identified and tracked using


session IDs
• Session IDs are communicated across client-server
requests using an HTTP cookie or included 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
• Set cookieless = true

<sessionState cookieless="true" />


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_14
User name Student
Password Pa$$w0rd

Estimated time: xx minutes


Lab Scenario

Logon Page
Login.aspx
Benefits
Coho Home Page Page Header ASPState
Winery Default.aspx Header.ascx
Menu
Registration Component
Register.aspx Class1.vb or Class1.cs Web.
tempdb
config

Life Insurance Retirement Medical Dental


Life.aspx Retirement.aspx Medical.aspx Dental.aspx

Prospectus Doctors User Control XML Web


Lab Web Prospectus.aspx Doctors.aspx namedate.ascx Service
Application dentalService1.asmx

XML
Doctors Dentists
Files
Lab Review
Module Review and Takeaways
Review Questions
• How do you set up a Web application to use cookieless
sessions?
• What are the three categories of events that are handled
in the global.asax file?
• Where is the global.asax file of an application located?

• Can there be more than one global.asax file for a single


Web application?
Review for Alpha
• Is there any topic or specific content item in the module
that seemed unclear or unnecessary?
• Is there any content item/related subject area that was
not covered and could be included?
• Did you observe any issues with the technical accuracy of
the content?
• Is the content in the module presented in a manner that
encourages learning? Did the flow of topics seem right?
• Does the lab outline indicate the expected scope of tasks
to be covered? Would you like to suggest any tasks that
could be removed or added?

You might also like