it533 lectures session management in asp.net. session tracking 2 personalization personalization...
TRANSCRIPT
IT533 Lectures
Session Managementin ASP.NET
Session Tracking
2
PersonalizationPersonalization 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.
PrivacyA 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.
Session Tracking
3
Recognizing ClientsTo 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.
Session Tracking - Cookies
4
Cookies are pieces of data stored in a small text file on the user’s 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
5
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 TipUsers 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.
Example using CookiesCreate Options.aspx file with:
1. A Label "Select a programming language:"2. 5 radio buttons with the values Visual Basic, Visual C#, C,
C++, and Java.3. A Submit button4. A Hyperlink that navigates to "~/Options.aspx“5. A Hyperlink that navigates to "~/Recommendations.aspx“
7
1 // Options.aspx.cs
2 // Processes user's selection of a programming language by displaying
3 // links and writing a cookie to the user's machine.
4 using System;
5 using System.Web;
6 using System.Collections.Generic;
7
8 public partial class Options : System.Web.UI.Page
9 {
10 // stores values to represent books as cookies
11 private Dictionary< string, string > books =
12 new Dictionary< string, string >();
13
14 // initializes the Dictionary when the Page initializes
15 protected void Page_Init( object sender, EventArgs e )
16 {
17 books.Add( "Visual Basic 2008", "0-13-606305-X" );
18 books.Add( "Visual C# 2008", "0-13-605322-X" );
OutlineOptions.aspx.cs
(1 of 3 )
Writing Cookies in a Code-Behind File• The code-behind file for Options.aspx.
Figure. | Code-behind file that writes a cookie tothe client. (Part 1 of 3.)
For adding new entries, class Dictionary provides method Add, which takes a key and a value as arguments.
8
19 books.Add( "C", "0-13-240416-8" );
20 books.Add( "C++", "0-13-615250-3" );
21 books.Add( "Java", "0-13-222220-5" );
22 } // end method Page_Init
23
24 // hide and display links to make additional selections or view
25 // recommendations, and write a cookie to record the user's selection
26 // when the form is submitted
27 protected void submitButton_Click ( object sender, EventArgs e )
28 {
29 // display appropriate message and hyperlinks
30 responseLabel.Visible = true;
31 languageLink.Visible = true;
32 recommendationsLink.Visible = true;
33
34 // hide controls for selecting a language
35 promptLabel.Visible = false;
36 languageList.Visible = false;
37 submitButton.Visible = false;
38
OutlineOptions.aspx.cs
(2 of 3 )
Fig. | Code-behind file that writes a cookie tothe client. (Part 2 of 3.)
For adding new entries, class Dictionary provides method Add, which takes a key and a value as arguments.
9
39 // if the user made a selection
40 if ( languageList.SelectedItem != null )
41 {
42 // get value of user's selection
43 string language = languageList.SelectedItem.Value;
44
45 string ISBN = books[ language ]; // get ISBN for given language
46
47 // create cookie using language-ISBN name-value pair
48 HttpCookie cookie = new HttpCookie( language, ISBN );
49
50 // add cookie to response to place it on the user's machine
51 Response.Cookies.Add( cookie );
52
53 // display user's selection in responseLabel
54 responseLabel.Text += " You selected " + language + ".";
55 } // 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
OutlineOptions.aspx.cs
(3 of 3 )
Fig. | Code-behind file that writes a cookie tothe 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
10
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.
Example using Cookies Create Recommendations.aspx file with:
1. Add a Label “Recommendations“2. Add a Listbox3. Add a Hyperlink that goes back to Options.aspx.
12
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 protected void Page_Init(object sender, EventArgs e)
10 {
11 // retrieve client's cookies
12 HttpCookieCollection cookies = Request.Cookies;
13
Outline
Recommendations.aspx.cs
(1 of 2 )
Code-Behind File That Creates Book Recommendations From Cookies
Fig. | Reading cookies from a client to determine book recommendations. (Part 1 of 2.)
Retrieve the cookies from the client using the Request object’s Cookies property.
13
14 // if there are cookies, list the appropriate books and ISBNs
15 if ( cookies.Count > 0 )
16 {
17 for ( int i = 0; i < cookies.Count; i++ )
18 booksListBox.Items.Add( cookies[ i ].Name +
19 " How to Program. ISBN: " + cookies[ i ].Value );
20 } // end if
21 else
22 {
23 // if there are no cookies, then no language was chosen, so
24 // display appropriate message and clear and hide booksListBox
25 recommendationsLabel.Text = "No Recommendations";
26 booksListBox.Visible = false;
27
28 // 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
Outline
Recommendations.aspx.cs
(2 of 2 )
Fig. | Reading cookies from a client to determine book recommendations. (Part 2 of 2.)
Use the Name and Value properties of an HttpCookie to access its data.
Session Tracking
14
Retrieve the cookies from the client using the Request object’s Cookies property.
This returns an HttpCookieCollection containing cookies that were previously writtento the client.
Cookies can be read by an application only if they were created in the domain in which the applicationis running.
Use the Name and Value properties of an HttpCookie to access its data.
Session Tracking
15
Some commonly used HttpCookie properties:
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.)
SessionWhat is a session?
Context in which a user communicates with a server over multiple HTTP requests
Within the scope of an ASP.NET ApplicationHTTP is a stateless, sessionless protocolASP.NET adds the concept of “session”
Session identifier: 120 bit ASCII stringSession variables: store data across multiple requests
Example for SessionLet’s modify the Cookies example to use Session
Use HttpSessionState instead of Cookies
19
Outline
Options.aspx
a)b)
c) d)
Session Tracking
20
We keep the EnableSessionState property’s default 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.
21
1 // Options.aspx.cs
2 // Processes user's selection of a programming language by displaying
3 // links and writing information in a Session object.
4 using System;
5 using System.Collections.Generic;
6
7 public partial class Options : System.Web.UI.Page
8 {
9 // stores values to represent books
10 private Dictionary< string, string > books =
11 new Dictionary< string, string >();
12
13 // initializes the Dictionary when the Page initializes
14 protected void Page_Init( object sender, EventArgs e )
15 {
16 books.Add( "Visual Basic 2008", "0-13-606305-X" );
17 books.Add( "Visual C# 2008", "0-13-605322-X" );
18 books.Add( "C", "0-13-240416-8" );
19 books.Add( "C++", "0-13-615250-3" );
20 books.Add( "Java", "0-13-222220-5" );
21 } // end method Page_Init
Outline
Options.aspx.cs
(1 of 3 )
Adding Session Items
Fig. | Creates a session item for each programming language selected by the user on the ASPX page. (Part 1 of 3.)
22
22
23 // hide and display links to make additional selections or view
24 // recommendations, and record the user's selection in the Session
25 // when the form is submitted
26 protected void submitButton_Click ( object sender, EventArgs e )
27 {
28 // display appropriate message and hyperlinks
29 responseLabel.Visible = true;
30 idLabel.Visible = true;
31 timeoutLabel.Visible = true;
32 languageLink.Visible = true;
33 recommendationsLink.Visible = true;
34
35 // hide controls for selecting a language
36 promptLabel.Visible = false;
37 languageList.Visible = false;
38 submitButton.Visible = false;
39
40 // if the user made a selection
41 if ( languageList.SelectedItem != null )
42 {
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.)
23
43 // get value of user's selection
44 string language = languageList.SelectedItem.Value;
45
46 string ISBN = books[ language ]; // get ISBN for given language
47
48 Session.Add( language, ISBN ); // add name/value pair to Session
49
50 // display user's selection in responseLabel
51 responseLabel.Text += " You selected " + language + ".";
52 } // end if
53 else
54 {
55 // inform user that no selection was made
56 responseLabel.Text += " You didn't make a selection.";
57 } // end else
58
59 idLabel.Text = "Your unique session ID is: " + Session.SessionID +
60 "."; // display session ID
61
62 // display amount of time before session times out
63 timeoutLabel.Text = "Timeout: " + Session.Timeout + " minutes.";
64 } // end method submitButton_Click
65 } // end class Options
OutlineOptions.aspx.cs
(3 of 3 )
Fig. | Creates a session item for each programming language selected by the user on the ASPX page. (Part 3 of 3.)
Call Add to place a session item in the HttpSessionState object.
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.
Session Tracking
24
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 inthe HttpSessionState object is Session[ name ] = value.
Session Tracking
25
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.
Session Identifier
By default, session id is stored in a cookieCan optionally track session id in URLRequires no code changes to app
All relative links continue to work
<configuration> <sessionstate cookieless=“true”/></configuration>
Session Tracking
27
Some common HttpSessionState properties:
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.
28
1 // Recommendations.aspx.cs
2 // Creates book recommendations based on a Session object.
3 using System;
4
5 public partial class Recommendations : System.Web.UI.Page
6 {
7 // read Session items and populate ListBox with recommendations
8 protected void Page_Init(object sender, EventArgs e)
9 {
10 // if there are Session items, list the appropriate books and ISBNs
11 if ( Session.Count > 0 )
12 {
13 foreach ( string keyName in Session.Keys )
14 {
15 // use current key to display one of the session’s
16 // name/value pairs
Outline
Recommendations.aspx.cs
(1 of 2 )
Code-Behind File That Creates Book Recommendations from a Session
Fig. | Session data used to provide book recommendationsto the user. (Part 1 of 2.)
Use the Session object’s Count property to determine if the user has selected any languages.
The Keys property of class HttpSessionState returns a collection containing all the keys in the session.
29
17 booksListBox.Items.Add( keyName + " How to Program. ISBN: " +
18 Session[ keyName ] );
19 } // end foreach
20 } // end if
21 else
22 {
23 // if there are no items, then no language was chosen, so
24 // display appropriate message and clear and hide booksListBox
25 recommendationsLabel.Text = "No Recommendations";
26 booksListBox.Visible = false;
27
28 // 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
OutlineRecommendations.aspx.cs
(2 of 2 )
Fig. | Session data used to provide book recommendationsto the user. (Part 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
30
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.
Session VariablesASP stores session state in IIS process
State is lost if IIS crashesCan’t use session state across machines
ASP.NET stores session state:In another process: ASP State NT serviceIn SQL Server database
Session Variables
“Live” objects are not stored in session stateInstead, ASP.NET serializes objects out between
requestsASP.NET approach provides:
Ability to recover from application crashesAbility to recover from IIS crash/restartCan partition an application across multiple processes
(called a Web Garden)Can partition an application across multiple machines
(called a Web Farm)