Session Management in ASP.NET IT533 Lectures

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 protocol—it 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.NET’s 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 user’s




4
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 client’s 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.
Most browsers allow 20 cookies per server.
The size of a cookie is not more than 4096 bytes or 4 KB.
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.
Outline
Options.aspx.cs
(1 of 3 )
1
2
3
4
5
6
7
8
// Options.aspx.cs
// 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;
public partial class Options : System.Web.UI.Page
9 {
10
11
12
13
private Dictionary< string, string > books =
new Dictionary< string, string >();
14
15
16
17
// initializes the Dictionary when the Page initializes
protected void Page_Init( object sender, EventArgs e )
{
books.Add( "Visual Basic 2008", "0-13-606305-X" );
18
7
// stores values to represent books as cookies
books.Add( "Visual C# 2008", "0-13-605322-X" );
Figure. | Code-behind file that writes a cookie to
the client. (Part 1 of 3.)
For adding new entries,
class Dictionary
provides method Add,
which takes a key and a
value as arguments.
Outline
19
books.Add( "C", "0-13-240416-8" );
20
21
books.Add( "C++", "0-13-615250-3" );
books.Add( "Java", "0-13-222220-5" );
(2 of 3 )
22
23
} // end method Page_Init
24
// hide and display links to make additional selections or view
25
// recommendations, and write a cookie to record the user's selection
26
27
28
29
// when the form is submitted
protected void submitButton_Click ( object sender, EventArgs e )
{
// display appropriate message and hyperlinks
For
30
31
32
33
34
responseLabel.Visible = true;
languageLink.Visible = true;
recommendationsLink.Visible = true;
35
36
37
38
promptLabel.Visible = false;
languageList.Visible = false;
submitButton.Visible = false;
// hide controls for selecting a language
Fig. | Code-behind file that writes a cookie to
the client. (Part 2 of 3.)
8
Options.aspx.cs
adding new
entries, class
Dictionary
provides method
Add, which takes a
key and a value as
arguments.
Outline
39
40
// if the user made a selection
if ( languageList.SelectedItem != null )
Options.aspx.cs
41
42
43
44
45
46
{
(3 of 3 )
// get value of user's selection
string language = languageList.SelectedItem.Value;
string ISBN = books[ language ]; // get ISBN for given language
47
48
49
// create cookie using language-ISBN name-value pair
HttpCookie cookie = new HttpCookie( language, ISBN );
50
51
// add cookie to response to place it on the user's machine
Response.Cookies.Add( cookie );
52
53
54
55
// display user's selection in responseLabel
responseLabel.Text += " You selected " + language + ".";
} // end if
56
else
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
9
Fig. | Code-behind file that writes a cookie to
the client. (Part 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.
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
Create Recommendations.aspx file with:

Add a Label “Recommendations“
2. Add a Listbox
3. Add a Hyperlink that goes back to Options.aspx.
1.
Outline
Code-Behind File That Creates Book Recommendations
From Cookies
Recommendations
.aspx.cs
(1 of 2 )
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
// read cookies and populate ListBox with any book recommendations
9
10
protected void Page_Init(object sender, EventArgs e)
{
11
12
// retrieve client's cookies
HttpCookieCollection cookies = Request.Cookies;
13
12
Retrieve the cookies from
the client using the
Request object’s
Cookies property.
Fig. | Reading cookies from a client to determine book
recommendations. (Part 1 of 2.)
17
18
19
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 );
20
} // end if
21
22
else
{
14
15
16
23
24
25
26
27
28
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 object’s 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:
15
Properties
Description
Domain
Returns a string containing the cookie’s 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.
Expires
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.)
Session Tracking
16
Properties
Description
Name
Returns a string containing the cookie’s name.
Path
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.
Secure
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.
Value
Returns a string containing the cookie’s value.
Fig. | HttpCookie properties. (Part 2 of 2.)
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
 Let’s modify the Cookies example to use Session
 Use HttpSessionState instead of Cookies
Outline
a)
b)
Options.aspx
c)
19
d)
Session Tracking
 We keep the EnableSessionState property’s default





20
setting—True.
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 Page’s Session
property.
A distinct HttpSessionState resides on the server,
whereas a cookie is stored on the user’s 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.
Outline
Adding Session Items
1
// Options.aspx.cs
2
3
// Processes user's selection of a programming language by displaying
// links and writing information in a Session object.
4
5
6
using System;
using System.Collections.Generic;
7
8
9
public partial class Options : System.Web.UI.Page
{
// stores values to represent books
10
11
private Dictionary< string, string > books =
new Dictionary< string, string >();
Options.aspx.cs
(1 of 3 )
12
13
14
15
// initializes the Dictionary when the Page initializes
protected void Page_Init( object sender, EventArgs e )
{
16
books.Add( "Visual Basic 2008", "0-13-606305-X" );
17
books.Add( "Visual C# 2008", "0-13-605322-X" );
18
19
20
21
21
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
Fig. | Creates a session item for each programming language
selected by the user on the ASPX page. (Part 1 of 3.)
22
23
24
// hide and display links to make additional selections or view
// recommendations, and record the user's selection in the Session
25
26
27
28
29
// when the form is submitted
protected void submitButton_Click ( object sender, EventArgs e )
{
// display appropriate message and hyperlinks
responseLabel.Visible = true;
30
idLabel.Visible = true;
31
32
33
34
35
36
timeoutLabel.Visible = true;
languageLink.Visible = true;
recommendationsLink.Visible = true;
37
38
39
40
41
42
languageList.Visible = false;
submitButton.Visible = false;
Outline
Options.aspx.cs
(2 of 3 )
// hide controls for selecting a language
promptLabel.Visible = false;
// if the user made a selection
if ( languageList.SelectedItem != null )
{
Fig. | Creates a session item for each programming language
selected by the user on the ASPX page. (Part 2 of 3.)
22
Outline
43
// get value of user's selection
44
45
string language = languageList.SelectedItem.Value;
46
string ISBN = books[ language ]; // get ISBN for given language
Options.aspx.cs
(3 of 3 )
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
 Requires no code changes to app
 All relative links continue to work
<configuration>
<sessionstate cookieless=“true”/>
</configuration>
Session Tracking
 Some common HttpSessionState properties:
27
Properties
Description
Count
Specifies the number of key/value pairs in the Session object.
IsNewSession
Indicates whether this is a new session (i.e., whether the session
was created during loading of this page).
IsReadOnly
Indicates whether the Session object is read-only.
Keys
Returns a collection containing the Session object’s keys.
SessionID
Returns the session’s unique ID.
Timeout
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.
Code-Behind File That Creates Book
Recommendations from a Session
1
// Recommendations.aspx.cs
2
3
4
// Creates book recommendations based on a Session object.
using System;
5
6
public partial class Recommendations : System.Web.UI.Page
{
7
8
9
10
11
12
13
14
15
16
Outline
Recommendations
.aspx.cs
(1 of 2 )
Use the Session
object’s Count
// read Session items and populate ListBox with recommendations property to
protected void Page_Init(object sender, EventArgs e)
determine if the
{
user has selected
// if there are Session items, list the appropriate books and
ISBNs
any
languages.
if ( Session.Count > 0 )
{
The Keys property
foreach ( string keyName in Session.Keys )
of class
{
HttpSessionSta
// use current key to display one of the session’s te returns a
// name/value pairs
collection containing
all the keys in the
session.
Fig. | Session data used to provide book recommendations
to the user. (Part 1 of 2.)
28
Outline
17
18
19
20
21
22
booksListBox.Items.Add( keyName + " How to Program. ISBN: " +
Session[ keyName ] );
} // end foreach
} // end if
else
{
23
24
// if there are no items, then no language was chosen, so
// display appropriate message and clear and hide booksListBox
25
26
27
28
recommendationsLabel.Text = "No Recommendations";
booksListBox.Visible = false;
29
30
// modify languageLink because no language was selected
languageLink.Text = "Click here to choose a language.";
} // end else
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
Recommendations
.aspx.cs
(2 of 2 )
The value in a
key/value pair is
retrieved from the
Session object
by indexing the
Session object
with the key name.
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
 Can’t 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 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)