21.6.2. Session Tracking with HttpSessionState
C# provides session-tracking capabilities in the Framework Class Library's HttpSessionState class. To demonstrate basic session-tracking techniques, we modified Fig. 21.26 so that it uses HttpSessionState objects. Figure 21.28 presents the ASPX file, and Fig. 21.29 presents the code-behind file. The ASPX file is similar to that presented in Fig. 21.23, except Fig. 21.28 contains two additional Labels (lines 3536 and lines 3839), which we discuss shortly.
Figure 21.28. ASPX file that presents a list of programming languages.
1 <%-- Fig. 21.28: Options.aspx --%>2 <%-- Allows client to select programming languages and access --%>
3 <%-- book recommendations. --%>
4 <%@ Page Language="C#" AutoEventWireup="true"
5 CodeFile="Options.aspx.cs" Inherits="Options" %>
6
7 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
8 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"
9
10 <html xmlns="http://www.w3.org/1999/xhtml"
11 <head runat="server"
12 <title>Sessions</title>
13 </head>
14 <body>
15 <form id="form1" runat="server"
16 <div>
17 <asp:Label ID="promptLabel" runat="server" Font-Bold="True"
18 Font-Size="Large" Text="Select a programming language:"
19 </asp:Label>
20
21 <asp:RadioButtonList ID="languageList" runat="server"
22 <asp:ListItem>Visual Basic 2005</asp:ListItem>
23 <asp:ListItem>Visual C# 2005</asp:ListItem>
24 <asp:ListItem>C</asp:ListItem>
25 <asp:ListItem>C++</asp:ListItem>
26 <asp:ListItem>Java</asp:ListItem>
27 </asp:RadioButtonList>
28
29 <asp:Button ID="submitButton" runat="server" Text="Submit" />
30
31 <asp:Label ID="responseLabel" runat="server" Font-Bold="True"
32 Font-Size="Large" Text="Welcome to sessions!"
33 Visible="False"</asp:Label<br /<br />
34
35 <asp:Label ID="idLabel" runat="server" Visible="False"
36 </asp:Label<br /<br />
37
38 <asp:Label ID="timeoutLabel" runat="server" Visible="False"
39 </asp:Label>br /<br />
40
41 <asp:HyperLink ID="languageLink" runat="server"
42 Visible="False" NavigateUrl="~/Options.aspx"
43 Click here to choose another language
44 </asp:HyperLink<br /<br />
45
46 <asp:HyperLink ID="recommendationsLink" runat="server"
47 Visible="False" NavigateUrl="~/Recommendations.aspx"
48 Click here to get book recommendations</asp:HyperLink>
49 </div>
50 </form>
51 </body>
52 </html>
(a)
(b)
(c)
(d)
Every Web Form includes an HttpSessionState object, which is accessible through property Session of class Page. Throughout this section, we use property Session to manipulate our page's HttpSessionState object. When the Web page is requested, an HttpSessionState object is created and assigned to the Page's Session property. As a result, we often refer to property Session as the Session object.
Adding Session Items
When the user presses Submit on the Web Form, submitButton_Click is invoked in the code-behind file (Fig. 21.29). Method submitButton_Click responds by adding a keyvalue pair to our Session object, specifying the language chosen and the ISBN number for a book on that language. These keyvalue pairs are often referred to as session items. Next, a postback occurs. Each time the user clicks Submit, submitButton_Click adds a new session item to the HttpSessionState object. Because much of this example is identical to the last example, we concentrate on the new features.
Figure 21.29. Creates a session item for each programming language selected by the user on the ASPX page.
1 // Fig. 21.29: Options.aspx.cs2 // Processes user's selection of a programming language
3 // by displaying links and writing a cookie to the user's machine.
4 using System;
5 using System.Data;
6 using System.Configuration;
7 using System.Web;
8 using System.Web.Security;
9 using System.Web.UI;
10 using System.Web.UI.WebControls;
11 using System.Web.UI.WebControls.WebParts;
12 using System.Web.UI.HtmlControls;
13 public partial class Options : System.Web.UI.Page
14 {
15 // stores values to represent books as cookies
16 private System.Collections.Hashtable books =
17 new System.Collections.Hashtable();
18
19 //initializes the Hashtable of values to be stored as cookies
20 protected void Page_Init( object sender, EventArgs e )
21 {
22 books.Add( "Visual Basic 2005", "0-13-186900-0" );
23 books.Add( "Visual C# 2005", "0-13-152523-9" );
24 books.Add( "C", "0-13-142644-3" );
25 books.Add( "C++", "0-13-185757-6" );
26 books.Add( "Java", "0-13-148398-6" );
27 } // end method Page_Init
28
29 // if postback, hide form and display links to make additional
30 // selections or view recommendations
31 protected void Page_Load( object sender, EventArgs e )
32 {
33 if ( IsPostBack )
34 {
35 // user has submitted information, so display appropriate labels
36 // and hyperlinks
37 responseLabel.Visible = true;
38 idLabel.Visible = true;
39 timeoutLabel.Visible = true;
40 languageLink.Visible = true;
41 recommendationsLink.Visible = true;
42
43 // hide other controls used to make language selection
44 promptLabel.Visible = false;
45 languageList.Visible = false;
46 submitButton.Visible = false;
47
48 // if the user made a selection, display it in responseLabel
49 if ( languageList.SelectedItem != null )
50 responseLabel.Text += " You selected " +
51 languageList.SelectedItem.Text.ToString();
52 else
53 responseLabel.Text += " You did not select a language.";
54
55 // display session ID
56 idLabel.Text = "Your unique session ID is: " + Session.SessionID;
57
58 // display the timeout
59 timeoutLabel.Text = "Timeout: " + Session.Timeout + " minutes.";
60 } // end if
61 } // end method Page_Load
62
63 // write a cookie to record the user's selection
64 protected void submitButton_Click( object sender, EventArgs e )
65 {
66 // if the user made a selection
67 if ( languageList.SelectedItem != null )
68 {
69 string language = languageList.SelectedItem.ToString();
70
71 // get ISBN number of book for the given language
72 string ISBN = books[ language ].ToString();
73
74 Session.Add( language, ISBN ); // add name/value pair to Session
75 } // end if
76 } // end method submitButton_Click
77 } // end class Options
Like a cookie, an HttpSessionState object can store namevalue pairs. These session items are placed in an HttpSessionState object by calling method Add. Line 74 calls Add to place the language and its corresponding recommended book's ISBN number in the HttpSessionState object. If the application calls method Add to add an attribute that has the same name as an attribute previously stored in a session, the object associated with that attribute is replaced.
The application handles the postback event (lines 3360) in method Page_Load. Here, we retrieve information about the current client's session from the Session object's properties and display this information in the Web page. The ASP.NET application contains information about the HttpSessionState object for the current client. Property SessionID (line 56) contains the unique session IDa sequence of random letters and numbers. The first time a client connects to the Web server, a unique session ID is created for that client. When the client makes additional requests, the client's session ID is compared with the session IDs stored in the Web server's memory to retrieve the HttpSessionState object for that client. Property Timeout (line 59) specifies the maximum amount of time that an HttpSessionState object can be inactive before it is discarded. Figure 21.30 lists some common HttpSessionState properties.
Figure 21.30. HttpSessionState properties.
/Properties / Description /
Count / Specifies the number of keyvalue 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.
Displaying Recommendations Based on Session Values
As in the cookies example, this application provides a link to Recommendations.aspx (Fig. 21.31), which displays a list of book recommendations based on the user's language selections. Lines 2122 define a ListBox Web control that is used to present the recommendations to the user.
Figure 21.31. Session-based book recommendations displayed in a ListBox.
1 <%-- Fig. 21.31: Recommendations.aspx --%>2 <%-- Displays book recommendations using sessions. --%>
3 <%@ Page Language="C#" AutoEventWireup="true"
4 CodeFile="Recommendations.aspx.cs" Inherits="Recommendations" %>
5
6 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
7 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"
8
9 <html xmlns="http://www.w3.org/1999/xhtml"
10 <head runat="server"
11 <title>Book Recommendations</title>
12 </head>
13 <body>
14 <form id="form1" runat="server"
15 <div>
16 <asp:Label ID="recommendationsLabel"
17 runat="server" Text="Recommendations"
18 Font-Bold="True" Font-Size="X-Large"
19 </asp:Label<br /<br />
20
21 <asp:ListBox ID="booksListBox" runat="server" Height="125px"
22 Width="450px"</asp:ListBox<br /<br />
23
24 <asp:HyperLink ID="languageLink" runat="server"
25 NavigateUrl="~/Options.aspx"
26 Click here to choose another language
27 </asp:HyperLink>
28 </div>
29 </form>
30 </body>
31 </html>
Code-Behind File That Creates Book Recommendations from a Session
Figure 21.32 presents the code-behind file for Recommendations.aspx. Event handler Page_Init (lines 1747) retrieves the session information. If a user has not selected a language on Options.aspx, our Session object's Count property will be 0. This property provides the number of session items contained in a Session object. If Session object's Count property is 0 (i.e., no language was selected), then we display the text No Recommendations and update the Text of the HyperLink back to Options.aspx.
Figure 21.32. Session data used to provide book recommendations to the user.
1 // Fig. 21.32: Recommendations.aspx.cs2 // Creates book recommendations based on a session object.
3 using System;
4 using System.Data;
5 using System.Configuration;
6 using System.Collections;
7 using System.Web;
8 using System.Web.Security;
9 using System.Web.UI;
10 using System.Web.UI.WebControls;
11 using System.Web.UI.WebControls.WebParts;
12 using System.Web.UI.HtmlControls;
13
14 public partial class Recommendations : System.Web.UI.Page
15 {
16 // read cookies and populate ListBox with any book recommendations
17 protected void Page_Init( object sender, EventArgs e )
18 {
19 // stores a key name found in the Session object
20 string keyName;
21
22 // determine whether Session contains any information
23 if ( Session.Count != 0 )
24 {
25 for ( int i = 0; i < Session.Count; i++ )
26 {
27 keyName = Session.Keys[ i ]; // store current key name
28
29 // use current key to display one
30 // of session's name-value pairs
31 booksListBox.Items.Add( keyName +
32 " How to Program. ISBN#: " +
33 Session[ keyName ].ToString() );
34 } // end for
35 } // end if
36 else
37 {
38 // if there are no session items, no language was chosen, so
39 // display appropriate message and clear and hide booksListBox
40 recommendationsLabel.Text = "No Recommendations";
41 booksListBox.Items.Clear();
42 booksListBox.Visible = false;
43
44 // modify languageLink because no language was selected
45 languageLink.Text = "Click here to choose a language";
46 } // end else
47 } // end method Page_Init
48 } // end class Recommendations
If the user has chosen a language, the for statement (lines 2534) iterates through our Session object's session items, temporarily storing each key name (line 27). The value in a keyvalue pair is retrieved from the Session object by indexing the Session object with the key name, using the same process by which we retrieved a value from our Hashtable in the preceding section.
Line 27 accesses the Keys property of class HttpSessionState, which returns a collection containing all the keys in the session. Line 27 indexes this collection to retrieve the current key. Lines 3133 concatenate keyName's value to the string " Howto Program. ISBN#: " and the value from the Session object for which keyName is the key. This string is the recommendation that appears in the ListBox.