You are on page 1of 32

Session Management in ASP.

NET
IT533 Lectures

Session Tracking
Personalization
Personalization makes it possible for e-businesses to

communicate effectively with their customers. Online shopping sites often store personal information for customers, tailoring notifications and special offers to their interests.

Privacy
A trade-off exists, however, between personalized e-business

service and protection of privacy. Some consumers fear the possible adverse consequences if the info they provide to e-businesses is released or collected by tracking technologies.
2

Session Tracking
Recognizing Clients
To provide personalized services to consumers, e-businesses

must be able to recognize clients when they request information from a site.
HTTP is a stateless protocolit does not support persistent

connections that would enable web servers to maintain state information between requests.
Tracking individual clients, known as session tracking, can be

achieved in a number of ways.


Using cookies. Using ASP.NETs HttpSessionState object. Using hidden form elements. Embedding session-tracking information directly in URLs.
3

Session Tracking - Cookies


Cookies are pieces of data stored in a small text file on the users

computer. A cookie maintains information about the client during and between browser sessions. Every HTTP-based interaction between a client and a server includes a header containing information about the request or response. When a web server receives a request, the header includes any cookies that have been stored on the client machine by that server. When the server formulates its response, the header contains any cookies the server wants to store on the client computer.

Session Tracking - Cookies


The expiration date of a cookie determines how long the

cookie remains on the clients computer. If no expiration date is set, web browser maintains the cookie for the duration of the browsing session. Otherwise, the web browser maintains the cookie until the expiration date occurs. Cookies are deleted when they expire.

Portability Tip
Users may disable cookies in their web browsers to help ensure their privacy. Such users will experience difficulty using web applications that depend on cookies to maintain state information.
5

Example using Cookies


Create Options.aspx file with:
1. 2. 3. 4. 5.

A Label "Select a programming language:" 5 radio buttons with the values Visual Basic 2008, Visual C# 2008, C, C++, and Java. A Submit button A Hyperlink that navigates to "~/Options.aspx A Hyperlink that navigates to "~/Recommendations.aspx

Writing Cookies in a Code-Behind File The code-behind file for Options.aspx.


1 2 3 4 5 6 7 8 public partial class Options : System.Web.UI.Page 9 { 10 // stores values to represent books as cookies 11 12 13 14 15 16 17 18 private Dictionary< string, string > books = new Dictionary< string, string >(); // initializes the Dictionary when the Page initializes protected void Page_Init( object sender, EventArgs e ) { books.Add( "Visual Basic 2008", "0-13-606305-X" ); books.Add( "Visual C# 2008", "0-13-605322-X" ); // Options.aspx.cs

Outline
Options.aspx.cs (1 of 3 )

// Processes user's selection of a programming language by displaying // links and writing a cookie to the user's machine. using System; using System.Web; using System.Collections.Generic;

For adding new entries, class Dictionary provides method Add, which takes a key and a value as arguments.

Figure. | Code-behind file that writes a cookie to the client. (Part 1 of 3.)

Outline
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 // hide and display links to make additional selections or view // recommendations, and write a cookie to record the user's selection // when the form is submitted protected void submitButton_Click ( object sender, EventArgs e ) { // display appropriate message and hyperlinks responseLabel.Visible = true; languageLink.Visible = true; recommendationsLink.Visible = true; // hide controls for selecting a language promptLabel.Visible = false; languageList.Visible = false; submitButton.Visible = false; books.Add( "C", "0-13-240416-8" ); books.Add( "C++", "0-13-615250-3" ); books.Add( "Java", "0-13-222220-5" ); } // end method Page_Init

Options.aspx.cs (2 of 3 )

For adding new entries, class Dictionary provides method Add, which takes a key and a value as arguments.

Fig. | Code-behind file that writes a cookie to the client. (Part 2 of 3.)
8

Outline
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 // if the user made a selection if ( languageList.SelectedItem != null ) { // get value of user's selection string language = languageList.SelectedItem.Value; string ISBN = books[ language ]; // get ISBN for given language // create cookie using language-ISBN name-value pair HttpCookie cookie = new HttpCookie( language, ISBN ); // add cookie to response to place it on the user's machine Response.Cookies.Add( cookie ); // display user's selection in responseLabel responseLabel.Text += " You selected " + language + "."; } // end if else

Options.aspx.cs (3 of 3 )

Create an HttpCookie object, passing a name and a value as arguments. Add the HttpCookie to the Cookies collection sent as part of the HTTP response header.

57 { 58 // inform user that no selection was made 59 responseLabel.Text += " You didn't make a selection."; 60 } // end else 61 } // end method submitButton_Click 62 } // end class Options

Fig. | Code-behind file that writes a cookie to the client. (Part 3 of 3.)

Session Tracking
This code writes a cookie to the client machine when the

user selects a programming language. A Dictionary is a data structure that stores key/value pairs. For adding new entries, class Dictionary provides method Add, which takes a key and a value as arguments. The expression dictionaryName[ keyName ] returns the value corresponding to key keyName.
Create an HttpCookie object, passing a name and a value

as arguments. Add the HttpCookie to the Cookies collection sent as part of the HTTP response header.
10

Example using Cookies

1.

Create Recommendations.aspx file with:


Add a Label Recommendations 2. Add a Listbox 3. Add a Hyperlink that goes back to Options.aspx.

Outline

Code-Behind File That Creates Book Recommendations From Cookies


1 // Recommendations.aspx.cs 2 // Creates book recommendations based on cookies. 3 using System; 4 using System.f; 5 6 public partial class Recommendations : System.Web.UI.Page 7 { 8 9 10 11 12 13

Recommendations .aspx.cs
(1 of 2 )

// read cookies and populate ListBox with any book recommendations protected void Page_Init(object sender, EventArgs e) { // retrieve client's cookies HttpCookieCollection cookies = Request.Cookies;

Retrieve the cookies from the client using the Request objects Cookies property.

12

Fig. | Reading cookies from a client to determine book recommendations. (Part 1 of 2.)

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

Outline // if there are cookies, list the appropriate books and ISBNs if ( cookies.Count > 0 ) Recommendations { .aspx.cs for ( int i = 0; i < cookies.Count; i++ ) (2 of 2 ) booksListBox.Items.Add( cookies[ i ].Name + " How to Program. ISBN: " + cookies[ i ].Value );
} // end if else {

Use the Name and Value properties of an HttpCookie to // if there are no cookies, then no language was chosen, so access its data.
// display appropriate message and clear and hide booksListBox recommendationsLabel.Text = "No Recommendations"; booksListBox.Visible = false; // modify languageLink because no language was selected

29 languageLink.Text = "Click here to choose a language."; 30 } // end else 31 } // end method Page_Init 32 } // end class Recommendations

Fig.
13

Reading cookies from a client to determine book recommendations. (Part 2 of 2.)

Session Tracking
Retrieve the cookies from the client using the

Request objects Cookies property. This returns an HttpCookieCollection containing cookies that were previously written to the client. Cookies can be read by an application only if they were created in the domain in which the application is running. Use the Name and Value properties of an HttpCookie to access its data.
14

Session Tracking
Some commonly used HttpCookie properties:

Properties
Domain

Description
Returns a string containing the cookies domain (i.e., the domain of the web server running the application that wrote the cookie). This determines which web servers can receive the cookie. By default, cookies are sent to the web server that originally sent the cookie. Changing the Domain property causes the cookie to be returned to a web server other than the one that originally wrote it. Returns a DateTime object indicating when the browser can delete the cookie. You can delete a cookie by setting this property to be a DateTime in the past.
Fig. | HttpCookie properties. (Part 1 of 2.)

Expires

15

Session Tracking
Properties
Name Path

Description
Returns a string containing the cookies name. Returns a string containing the path to a directory on the server (i.e., the Domain) to which the cookie applies. Cookies can be targeted to specific directories on the web server. By default, a cookie is returned only to applications operating in the same directory as the application that sent the cookie or a subdirectory of that directory. Changing the Path property causes the cookie to be returned to a directory other than the one from which it was originally written. Returns a bool value indicating whether the cookie should be transmitted through a secure protocol. The value true causes a secure protocol to be used. Returns a string containing the cookies value.
Fig. | HttpCookie properties. (Part 2 of 2.)

Secure

Value

16

Session
What is a session? Context in which a user communicates with a server over multiple HTTP requests Within the scope of an ASP.NET Application HTTP is a stateless, sessionless protocol ASP.NET adds the concept of session Session identifier: 120 bit ASCII string Session variables: store data across multiple requests

Example for Session


Lets modify the Cookies example to use Session
Use HttpSessionState instead of Cookies

Outline
a) b)

Options.aspx (4 of 4 )

c)

d)

19

Fig. 22.29 | ASPX file that presents a list of programming languages. (Part 4 of 4.)

Session Tracking
We keep the EnableSessionState propertys default

settingTrue. Every Web Form includes an HttpSessionState object, which is accessible through property Session of class Page. When the web page is requested, an HttpSessionState object is created and assigned to the Pages Session property. A distinct HttpSessionState resides on the server, whereas a cookie is stored on the users client. Like a cookie, an HttpSessionState object can store name/value pairs. The name/value pairs stored in a Session object are often referred to as session items.

20

Adding Session Items


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // Options.aspx.cs using System; using System.Collections.Generic;

Outline

// Processes user's selection of a programming language by displaying // links and writing information in a Session object.

Options.aspx.cs (1 of 3 )

public partial class Options : System.Web.UI.Page { // stores values to represent books private Dictionary< string, string > books = new Dictionary< string, string >(); // initializes the Dictionary when the Page initializes protected void Page_Init( object sender, EventArgs e ) { books.Add( "Visual Basic 2008", "0-13-606305-X" ); books.Add( "Visual C# 2008", "0-13-605322-X" ); books.Add( "C", "0-13-240416-8" ); books.Add( "C++", "0-13-615250-3" ); books.Add( "Java", "0-13-222220-5" ); } // end method Page_Init

21

Fig. | Creates a session item for each programming language selected by the user on the ASPX page. (Part 1 of 3.)

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

// hide and display links to make additional selections or view // recommendations, and record the user's selection in the Session // when the form is submitted protected void submitButton_Click ( object sender, EventArgs e ) { // display appropriate message and hyperlinks responseLabel.Visible = true; idLabel.Visible = true; timeoutLabel.Visible = true; languageLink.Visible = true; recommendationsLink.Visible = true; // hide controls for selecting a language promptLabel.Visible = false; languageList.Visible = false; submitButton.Visible = false; // if the user made a selection if ( languageList.SelectedItem != null ) {

Outline
Options.aspx.cs (2 of 3 )

Fig. | Creates a session item for each programming language selected by the user on the ASPX page. (Part 2 of 3.)
22

Outline
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 // get value of user's selection string language = languageList.SelectedItem.Value;

Options.aspx.cs (3 of 3 )

string ISBN = books[ language ]; // get ISBN for given language Session.Add( language, ISBN ); // add name/value pair to Session

Call Add to place a session item in the responseLabel.Text += " You selected " + language + "."; HttpSessionState } // end if object.
// display user's selection in responseLabel

else { Property SessionID contains // inform user that no selection was made responseLabel.Text += " You didn't make a selection."; the unique session ID, which identifies } // end else

each unique client.


idLabel.Text = "Your unique session ID is: " + Session.SessionID + "."; // display session ID

62 // display amount of time before session times out 63 timeoutLabel.Text = "Timeout: " + Session.Timeout + " minutes."; 64 } // end method submitButton_Click Property Timeout 65 } // end class Options specifies the amount of

23

Fig. | Creates a session item for each programming language selected by the user on the ASPX page. (Part 3 of 3.)

time that an HttpSessionState object can be inactive before it is discarded.

Session Tracking
Call Add to place a session item in the

HttpSessionState object. If you add an attribute that has the same name as an attribute previously stored in a session, the object associated with that attribute is replaced. Another common syntax for placing a session item in the HttpSessionState object is Session[ name ] = value.

24

Session Tracking
Property SessionID contains the unique session

ID, which identifies each unique client. Property Timeout specifies the amount of time that an HttpSessionState object can be inactive before it is discarded. By default, a session times out after twenty minutes.

25

Session Identifier
By default, session id is stored in a cookie

Can optionally track session id in URL


New in ASP.NET

Requires no code changes to app


All relative links continue to work
<configuration> <sessionstate cookieless=true/> </configuration>

Session Tracking
Some common HttpSessionState properties:
Properties
Count IsNewSession IsReadOnly Keys SessionID Timeout

Description
Specifies the number of key/value pairs in the Session object. Indicates whether this is a new session (i.e., whether the session was created during loading of this page). Indicates whether the Session object is read-only. Returns a collection containing the Session objects keys. Returns the sessions unique ID. Specifies the maximum number of minutes during which a session can be inactive (i.e., no requests are made) before the session expires. By default, this property is set to 20 minutes.

27

Code-Behind File That Creates Book Recommendations from a Session


1 2 3 4 5 // Recommendations.aspx.cs // Creates book recommendations based on a Session object. using System; public partial class Recommendations : System.Web.UI.Page

Outline

Recommendations .aspx.cs (1 of 2 )

Use the Session 6 { objects Count 7 // read Session items and populate ListBox with recommendations property to 8 protected void Page_Init(object sender, EventArgs e) determine if the 9 { user has selected 10 // if there are Session items, list the appropriate books and ISBNs any languages.
11 12 13 14 15 16 if ( Session.Count > 0 ) {

Fig. | Session data used to provide book recommendations to the user. (Part 1 of 2.)
28

The Keys property foreach ( string keyName in Session.Keys ) of class { HttpSessionSta // use current key to display one of the sessions te returns a // name/value pairs collection containing all the keys in the session.

Outline
17 18 19 20 21 22 23 24 25 26 27 28 29 30 booksListBox.Items.Add( keyName + " How to Program. ISBN: " + Session[ keyName ] ); } // end foreach } // end if else { // if there are no items, then no language was chosen, so // display appropriate message and clear and hide booksListBox recommendationsLabel.Text = "No Recommendations"; booksListBox.Visible = false; // modify languageLink because no language was selected languageLink.Text = "Click here to choose a language."; } // end else
(2 of 2 ) Recommendations .aspx.cs

The value in a key/value pair is retrieved from the Session object by indexing the Session object with the key name.

31 } // end method Page_Init 32 } // end class Recommendations

Fig. | Session data used to provide book recommendations to the user. (Part 2 of 2.)

29

Session Tracking
The Keys property of class HttpSessionState

returns a collection containing all the keys in the session. The value in a key/value pair is retrieved from the Session object by indexing the Session object with the key name.

30

Session Variables
ASP stores session state in IIS process
State is lost if IIS crashes

Cant use session state across machines

ASP.NET stores session state:


In another process: ASP State NT service In SQL Server database

Session Variables
Live objects are are not stored in session state
Instead, ASP.NET serializes objects out between requests

ASP.NET approach provides:


Ability to recover from application crashes Ability to recover from IIS crash/restart Can partition an application across multiple processes

(called a Web Garden) Can partition an application across multiple machines (called a Web Farm)

You might also like