Section 21.6. Session Tracking


21.6. Session Tracking

Originally, critics accused the Internet and e-business of failing to provide the kind of customized service typically experienced in "brick-and-mortar" stores. To address this problem, e-businesses began to establish mechanisms by which they could personalize users' browsing experiences, tailoring content to individual users while enabling them to bypass irrelevant information. Businesses achieve this level of service by tracking each customer's movement through the Internet and combining the collected data with information provided by the consumer, including billing information, personal preferences, interests and hobbies.

Personalization

Personalization makes it possible for e-businesses to communicate effectively with their customers and also improves users' ability to locate desired products and services. Companies that provide content of particular interest to users can establish relationships with customers and build on those relationships over time. Furthermore, by targeting consumers with personal offers, recommendations, advertisements, promotions and services, e-businesses create customer loyalty. Web sites can use sophisticated technology to allow visitors to customize home pages to suit their individual needs and preferences. Similarly, online shopping sites often store personal information for customers, tailoring notifications and special offers to their interests. Such services encourage customers to visit sites more frequently and make purchases more regularly.

Privacy

A trade-off exists, however, between personalized e-business service and protection of privacy. Some consumers embrace the idea of tailored content, but others fear the possible adverse consequences if the info they provide to e-businesses is released or collected by tracking technologies. Consumers and privacy advocates ask: What if the e-business to which we give personal data sells or gives that information to another organization without our knowledge? What if we do not want our actions on the Interneta supposedly anonymous mediumto be tracked and recorded by unknown parties? What if unauthorized parties gain access to sensitive private data, such as credit-card numbers or medical history? All of these are questions that must be debated and addressed by programmers, consumers, e-businesses and lawmakers alike.

Recognizing Clients

To provide personalized services to consumers, e-businesses must be able to recognize clients when they request information from a site. As we have discussed, the request/response system on which the Web operates is facilitated by HTTP. Unfortunately, HTTP is a stateless protocolit does not support persistent connections that would enable Web servers to maintain state information regarding particular clients. This means that Web servers cannot determine whether a request comes from a particular client or whether the same or different clients generate a series of requests. To circumvent this problem, sites can provide mechanisms by which they identify individual clients. A session represents a unique client on a Web site. If the client leaves a site and then returns later, the client will still be recognized as the same user. To help the server distinguish among clients, each client must identify itself to the server. Tracking individual clients, known as session tracking, can be achieved in a number of ways. One popular technique uses cookies (Section 21.6.1); another uses ASP.NET's HttpSessionState object (Section 21.6.2). Additional session-tracking techniques include the use of input form elements of type "hidden" and URL rewriting. Using hidden form elements, a Web Form can write session-tracking data into a form in the Web page that it returns to the client in response to a prior request. When the user submits the form in the new Web page, all the form data, including the "hidden" fields, is sent to the form handler on the Web server. When a Web site performs URL rewriting, the Web Form embeds session-tracking information directly in the URLs of hyperlinks that the user clicks to send subsequent requests to the Web server.

Note that our previous examples set the Web Form's EnableSessionState property to False. However, because we wish to use session tracking in the following examples, we keep this property's default settingtrue.

21.6.1. Cookies

Cookies provide Web developers with a tool for personalizing Web pages. A cookie is a piece 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. The first time a user visits the Web site, the user's computer might receive a cookie; this cookie is then reactivated each time the user revisits that site. The collected information is intended to be an anonymous record containing data that is used to personalize the user's future visits to the site. For example, cookies in a shopping application might store unique identifiers for users. When a user adds items to an online shopping cart or performs another task resulting in a request to the Web server, the server receives a cookie containing the user's unique identifier. The server then uses the unique identifier to locate the shopping cart and perform any necessary processing.

In addition to identifying users, cookies also can indicate users' shopping preferences. When a Web Form receives a request from a client, the Web Form can examine the cookie(s) it sent to the client during previous communications, identify the users's preferences and immediately display products of interest to the client.

Every HTTP-based interaction between a client and a server includes a header containing information either about the request (when the communication is from the client to the server) or about the response (when the communication is from the server to the client). When a Web Form receives a request, the header includes information such as the request type (e.g., Get) and any cookies that have been sent previously from the server to be stored on the client machine. When the server formulates its response, the header information contains any cookies the server wants to store on the client computer and other information, such as the MIME type of the response.

The expiration date of a cookie determines how long the cookie remains on the client's computer. If you do not set an expiration date for a cookie, the Web browser maintains the cookie for the duration of the browsing session. Otherwise, the Web browser maintains the cookie until the expiration date occurs. When the browser requests a resource from a Web server, cookies previously sent to the client by that Web server are returned to the Web server as part of the request formulated by the browser. Cookies are deleted when they expire.

Portability Tip 21.3

Users may disable cookies in their Web browsers to ensure that their privacy is protected. Such users will experience difficulty using Web applications that depend on cookies to maintain state information.


Using Cookies to Provide Book Recommendations

The next Web application demonstrates the use of cookies. The example contains two pages. In the first page (Figs 21.23 21.24), users select a favorite programming language from a group of radio buttons and submit the XHTML form to the Web server for processing. The Web server responds by creating a cookie that stores a record of the chosen language, as well as the ISBN number for a book on that topic. The server then returns an XHTML document to the browser, allowing the user either to select another favorite programming language or to view the second page in our application (Figs. 21.25 and 21.26), which lists recommended books pertaining to the programming language that the user selected previously. When the user clicks the hyperlink, the cookies previously stored on the client are read and used to form the list of book recommendations.

Figure 21.23. ASPX file that presents a list of programming languages.

  1  <%-- Fig. 21.23: Options.aspx --%>  2  <%-- Allows client to select programming languages and access --%>  3  <%-- book recommendations. --%>  4  <%@ Page Language="VB" AutoEventWireup="false"  5     CodeFile="Options.aspx.vb" Inherits="Options" %>  6  7  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  8     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  9 10  <html xmlns="http://www.w3.org/1999/xhtml" > 11  <head runat ="server" > 12      <title>Cookies </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        <asp:RadioButtonList ID="languageList" runat="server"> 21           <asp:ListItem>Visual Basic 2005 </asp:ListItem>     22           <asp:ListItem>Visual C# 2005 </asp:ListItem>        23           <asp:ListItem>C </asp:ListItem>                     24           <asp:ListItem>C++</asp:ListItem>                    25           <asp:ListItem>Java </asp:ListItem>                  26        </asp:RadioButtonList>                                 27        <asp:Button ID="submitButton" runat="server" Text="Submit" /> 28        <asp:Label ID="responseLabel" runat="server" Font-Bold="True" 29           Font-Size="Large" Text="Welcome to cookies!" Visible="False"> 30        </asp:Label><br /> 31        <br /> 32        <asp:HyperLink ID="languageLink" runat="server"  33           NavigateUrl="~/Options.aspx" Visible="False"> 34           Click here to choose another language         35        </asp:HyperLink><br />                           36         <br /> 37        <asp:HyperLink ID="recommendationsLink" runat="server"   38           NavigateUrl="~/Recommendations.aspx" Visible="False"> 39           Click here to get book recommendations                40        </asp:HyperLink>                                         41     </div> 42     </form> 43  </body> 44  </html> 

(a)

(b)

(c)

(d)

Figure 21.24. Code-behind file that writes a cookie to the client.

  1  ' Fig. 21.24: Options.aspx.vb  2  ' Processes user's selection of a programming language  3  ' by displaying links and writing a cookie to the user's machine.  4  Partial Class Options  5     Inherits System.Web.UI.Page  6     ' stores values to represent books as cookies        7     Private books As New System.Collections.Hashtable()  8  9     ' initializes the Hashtable of values to be stored as cookies 10     Protected Sub Page_Init(ByVal sender As Object, _ 11        ByVal e As System.EventArgs) Handles Me.Init 12        books.Add("Visual Basic 2005", "0-13-186900-0") 13        books.Add("Visual C# 2005", "0-13-152523-9")    14        books.Add("C", "0-13-142644-3")                 15        books.Add("C++", "0-13-185757-6")               16        books.Add("Java", "0-13-148398-6")              17     End Sub ' Page_Init 18 19     ' if postback, hide form and display links to make additional 20     ' selections or view recommendations 21     Protected Sub Page_Load(ByVal sender As Object, _ 22        ByVal e As System.EventArgs) Handles Me.Load 23 24        If IsPostBack Then 25           ' user has submitted information, so display message 26           ' and appropriate hyperlinks 27           responseLabel.Visible = True 28           languageLink.Visible = True 29           recommendationsLink.Visible = True 30 31           ' hide other controls used to make language selection 32           promptLabel.Visible = False 33           languageList.Visible = False 34           submitButton.Visible = False 35 36           ' if the user made a selection, display it in responseLabel 37           If languageList.SelectedItem IsNot Nothing Then             38              responseLabel.Text &= " You selected " & _               39                 languageList.SelectedItem.Text.ToString()             40           Else                                                        41              responseLabel.Text &= " You did not select a language."  42           End If                                                      43        End If 44     End Sub ' Page_Load 45 46     ' write a cookie to record the user's selection 47     Protected Sub submitButton_Click(ByVal sender As Object, _ 48        ByVal e As System.EventArgs) Handles submitButton.Click 49        ' if the user made a selection 50        If languageList.SelectedItem IsNot Nothing Then 51           Dim language As String = languageList.SelectedItem.ToString() 52 53           ' get ISBN number of book for the given language 54           Dim ISBN As String = books(language).ToString()  55 56           ' create cookie using language-ISBN name-value pair 57           Dim cookie As New HttpCookie(language, ISBN)        58 59           ' add cookie to response to place it on the user's machine 60           Response.Cookies.Add(cookie)                               61        End If 62     End Sub ' submitButton_Click 63  End Class ' Options 

Figure 21.25. ASPX file that displays book recommendations based on cookies.

  1  <%-- Fig. 21.25: Recommendations.aspx --%>  2  <%-- Displays book recommendations using cookies. --%>  3  <%@ Page Language="VB" AutoEventWireup="false"  4     CodeFile="Recommendations.aspx.vb" Inherits= "Recommendations" %>  5  6  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  7     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.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" runat= "server" 17            Font-Bold="True" Font-Size="X-Large" Text="Recommendations"> 18         </asp:Label><br /> 19         <br /> 20         <asp:ListBox ID="booksListBox" runat="server" Height="125px" 21            Width="450px"></asp:ListBox><br />                        22         <br /> 23         <asp:HyperLink ID="languageLink" runat="server" 24            NavigateUrl="~/Options.aspx"> 25            Click here to choose another language 26         </asp:HyperLink> </div> 27      </form> 28  </body> 29  </html> 

Figure 21.26. Reading cookies from a client to determine book recommendations.

  1  ' Fig. 21.26: Recommendations.aspx.vb  2  ' Creates book recommendations based on cookies.  3  Partial Class Recommendations  4     Inherits System.Web.UI.Page  5  6     ' read cookies and populate ListBox with any book recommendations  7     Protected Sub Page_Init(ByVal sender As Object, _  8        ByVal e As System.EventArgs) Handles Me.Init  9        ' retrieve client's cookies                           10        Dim cookies As HttpCookieCollection = Request.Cookies 11 12        ' if there are cookies, list the appropriate books and ISBN numbers 13        If cookies.Count <> 0 Then 14           For i As Integer = 0 To cookies.Count - 1 15              booksListBox.Items.Add(cookies(i).Name & _        16                 " How to Program. ISBN#: " & cookies(i).Value) 17           Next 18        Else 19           ' if there are no cookies, then no language was chosen, so 20           ' display appropriate message and clear and hide booksListBox 21           recommendationsLabel.Text = "No Recommendations" 22           booksListBox.Items.Clear() 23           booksListBox.Visible = False 24 25           ' modify languageLink because no language was selected 26           languageLink.Text = "Click here to choose a language" 27        End If 28     End Sub ' Page_Init 29  End Class ' Recommendations 

The ASPX file in Fig. 21.23 contains five radio buttons (lines 2026) with the values Visual Basic 2005, Visual C# 2005, C, C++, and Java. Recall that you can set the values of radio buttons via the ListItem Collection Editor, which you open either by clicking the RadioButtonList's Items property in the Properties window or by clicking the Edit Items… link in the RadioButtonList Tasks smart tag menu. The user selects a programming language by clicking one of the radio buttons. When the user clicks Submit, we'll create a cookie containing the selected language. Then, we'll add this cookie to the HTTP response header, so the cookie will be stored on the user's computer. Each time the user chooses a language and clicks Submit, a cookie is written to the client. Each time the client requests information from our Web application, the cookies are sent back to the server.

When the postback occurs, certain controls are hidden and others are displayed. The Label, RadioButtonList and Button used to select a language are hidden. Toward the bottom of the page, a Label and two HyperLinks are displayed. One link requests this page (lines 3235), and the other requests Recommendations.aspx (lines 3740). Clicking the first hyperlink (the one that requests the current page) does not cause a postback to occur. The file Options.aspx is specified in the NavigateUrl property of the hyperlink. When the hyperlink is clicked, a new request for this page occurs. Recall that earlier in the chapter, we set NavigateUrl to a remote Web site (http://www.deitel.com). To set this property to a page within the same ASP.NET application, click the ellipsis button next to the NavigateUrl property in the Properties window to open the Select URL dialog. Use this dialog to select a page within your project as the destination for the HyperLink.

Adding and Linking to a New Web Form

Setting the NavigateUrl property to a page in the current application requires that the destination page exist already. Thus, to set the NavigateUrl property of the second link (the one that requests the page with book recommendations) to Recommendations.aspx, you must first create this file by right clicking the project location in the Solution Explorer and selecting Add New Item… from the menu that appears. In the Add New Item dialog, select Web Form from the Templates pane and change the name of the file to Recommendations.aspx. Finally, check the box labeled Place code in separate file to indicate that the IDE should create a code-behind file for this ASPX file. Click Add to create the file. (We discuss the contents of this ASPX file and code-behind file shortly.) Once the Recommendations.aspx file exists, you can select it as the NavigateUrl value for a HyperLink in the Select URL dialog.

Writing Cookies in a Code-Behind File

Fig. 21.24 presents the code-behind file for Options.aspx (Fig. 21.23). This file contains the code that writes a cookie to the client machine when the user selects a programming language. The code-behind file also modifies the appearance of the page in response to a postback.

Line 7 creates variable books as a Hashtable (namespace System.Collections)a data structure that stores keyvalue pairs. A program uses the key to store and retrieve the associated value in the Hashtable. In this example, the keys are strings containing the programming languages' names, and the values are strings containing the ISBN numbers for the recommended books. Class Hashtable provides method Add, which takes as arguments a key and a value. A value that is added via method Add is placed in the Hashtable at a location determined by the key. The value for a specific Hashtable entry can be determined by indexing the Hashtable with that value's key. The expression

 HashtableName(keyName) 

returns the value in the keyvalue pair in which keyName is the key. For example, the expression books(language) in line 54 returns the value that corresponds to the key contained in language. Class Hashtable is discussed in detail in Section 26.4.3

Clicking the Submit button creates a cookie if a language is selected and causes a postback to occur. In the submitButton_Click event handler (lines 4762), a new cookie object (of type HttpCookie) is created to store the language and its corresponding ISBN number (line 57). This cookie is then Added to the Cookies collection sent as part of the HTTP response header (line 60). The postback causes the condition in the If statement of Page_Load (line 24) to evaluate to true, and lines 2742 execute. Lines 2729 reveal the initially hidden controls responseLabel, languageLink and recommendationsLink. Lines 3234 hide the controls used to obtain the user's language selection. Line 37 determines whether the user selected a language. If so, that language is displayed in responseLabel (lines 3839). Otherwise, text indicating that a language was not selected is displayed in responseLabel (line 41).

Displaying Book Recommendations Based on Cookie Values

After the postback of Options.aspx, the user may request a book recommendation. The book recommendation hyperlink forwards the user to Recommendations.aspx (Fig. 21.25) to display the recommendations based on the user's language selections.

Recommendations.aspx contains a Label (lines 1618), a ListBox (lines 2021) and a HyperLink (lines 2326). The Label displays the text Recommendations if the user selects one or more languages; otherwise, it displays No Recommendations. The ListBox displays the recommendations specified by the code-behind file (21.26). The HyperLink allows the user to return to Options.aspx to select additional languages.

Code-Behind File That Creates Book Recommendations From Cookies

In the code-behind file (21.26), method Page_Init (lines 728) retrieves the cookies from the client, using the Request object's Cookies property (line 10). This returns a collection of type HttpCookieCollection, containing cookies that have previously been written to the client. Cookies can be read by an application only if they were created in the domain in which the application is runninga Web server can never access cookies created outside the domain associated with that server. For example, a cookie created by a Web server in the deitel.com domain cannot be read by a Web server in any other domain. [Note: Depending on the settings in web.config and whether other pages store cookies, other cookie values may be displayed by this Web application.]

Line 13 determines whether at least one cookie exists. Lines 1417 add the information in the cookie(s) to the booksListBox. The loop retrieves the name and value of each cookie using i, the loop's control variable, to determine the current value in the cookie collection. The Name and Value properties of class HttpCookie, which contain the language and corresponding ISBN, respectively, are concatenated with " How to Program. ISBN#" and added to the ListBox. Lines 1826 execute if no language was selected. We summarize some commonly used HttpCookie properties in Fig. 21.27.

Figure 21.27. 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 to the client. 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.

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 Boolean 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.


21.6.2. Session Tracking with HttpSessionState

Session-tracking capabilities are provided by the FCL class HttpSessionState. To demonstrate basic session-tracking techniques, we modified the example of 21.2321.26 to use HttpSessionState objects. Figures 21.2821.29 present the ASPX file and code-behind file for Options.aspx. Figures 21.3121.32 present the ASPX file and code-behind file for Recommendations.aspx. Options.aspx is similar to the version presented in Fig. 21.23, but Fig. 21.28 contains two additional Labels (lines 3233 and lines 3536), 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= "VB" AutoEventWireup="false"  5     CodeFile="Options.aspx.vb" Inherits="Options" %>  6  7  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  8     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  9 10  <html xmlns="http://www.w3     .org/1999     /xhtml" > 11  <head id="Head1" 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        <asp:RadioButtonList ID= "languageList" runat="server"> 21           <asp:ListItem>Visual Basic 2005</asp:ListItem> 22           <asp:ListItem>Visual C# 2005</asp:ListItem> 23           <asp:ListItem>C </asp:ListItem> 24           <asp:ListItem>C++</asp:ListItem> 25           <asp:ListItem>Java </asp:ListItem> 26        </asp:RadioButtonList> 27        <asp:Button ID="submitButton" runat="server" Text="Submit" /> 28        <asp:Label ID="responseLabel" runat= "server" Font-Bold= "True" 29           Font-Size="Large" Text= "Welcome to sessions!" Visible= "False"> 30        </asp:Label><br /> 31        <br /> 32        <asp:Label ID="idLabel" runat= "server" Visible="False"> 33        </asp:Label><br />                                       34        <br /> 35        <asp:Label ID="timeoutLabel" runat= "server" Visible="False"> 36        </asp:Label><br />                                            37        <br /> 38        <asp:HyperLink ID="languageLink" runat="server" 39           NavigateUrl="~/Options.aspx" Visible="False"> 40           Click here to choose another language 41        </asp:HyperLink><br /> 42        <br /> 43        <asp:HyperLink ID="recommendationsLink" runat="server" 44           NavigateUrl="~/Recommendations.aspx" Visible="False"> 45           Click here to get book recommendations 46        </asp:HyperLink> 47     </div> 48     </form> 49  </body> 50  </html> 

(a)

(b)

(c)

(d)

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.vb  2  ' Processes user's selection of a programming language  3  ' by displaying links and writing information in a Session object.  4  Partial Class Options  5     Inherits System.Web.UI.Page  6     ' stores values to represent books  7     Private books As New System.Collections.Hashtable()  8  9     ' initializes the Hashtable of values to be stored in a Session 10     Protected Sub Page_Init(ByVal sender As Object, _ 11        ByVal e As System.EventArgs) Handles Me.Init 12        books.Add("Visual Basic 2005", "0-13-186900-0") 13        books.Add("Visual C# 2005", "0-13-152523-9") 14        books.Add("C" , "0-13-142644-3") 15        books.Add("C++", "0-13-185757-6") 16        books.Add("Java" , "0-13-148398-6") 17     End Sub ' Page_Init 18 19     ' if postback, hide form and display links to make additional 20     ' selections or view recommendations 21     Protected Sub Page_Load(ByVal sender As Object, _ 22        ByVal e As System.EventArgs) Handles Me.Load 23 24        If IsPostBack Then 25           ' user has submitted information, so display message 26           ' and appropriate hyperlinks 27           responseLabel.Visible = True 28           idLabel.Visible = True 29           timeoutLabel.Visible = True 30           languageLink.Visible = True 31           recommendationsLink.Visible = True 32 33           ' hide other controls used to make language selection 34           promptLabel.Visible = False 35           languageList.Visible = False 36           submitButton.Visible = False 37 38           ' if the user made a selection, display it in responseLabel 39           If languageList.SelectedItem IsNot Nothing Then 40              responseLabel.Text &= " You selected " & _ 41                 languageList.SelectedItem.Text.ToString() 42           Else 43              responseLabel.Text &= " You did not select a language." 44           End If 45 46           ' display session ID                                             47           idLabel.Text = "Your unique session ID is: " & Session.SessionID 48 49           '  display the timeout                                          50           timeoutLabel.Text = "Timeout: " & Session.Timeout & " minutes." 51        End If 52     End Sub ' Page_Load 53 54     ' record the user's selection in the Session 55     Protected Sub submitButton_Click(ByVal sender As Object, _ 56        ByVal e As System.EventArgs) Handles submitButton.Click 57        ' if the user made a selection 58        If languageList.SelectedItem IsNot Nothing Then 59           Dim language As String= languageList.SelectedItem.ToString() 60 61           ' get ISBN number of book for the given language 62           Dim ISBN As String = books(language).ToString() 63 64           Session.Add(language, ISBN) ' add name/value pair to Session 65        End If 66     End Sub ' submitButton_Click 67  End Class ' Options 

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.

Software Engineering Observation 21.1

A Web Form should not use instance variables to maintain client state information, because each new request or postback is handled by a new instance of the page. Instead, maintain client state information in HttpSessionState objects, because such objects are specific to each client.


Like a cookie, an HttpSessionState object can store namevalue pairs. These session items are placed in an HttpSessionState object by calling method Add. Line 64 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.

Software Engineering Observation 21.2

A benefit of using HttpSessionState objects (rather than cookies) is that HttpSessionState objects can store any type of object (not just Strings) as attribute values. This provides you with increased flexibility in determining the type of state information to maintain for clients.


The application handles the postback event (lines 2451) 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 47) 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 and a temporary cookie is written to the client so the server can identify the client on subsequent requests. When the client makes additional requests, the client's session ID from that temporary cookie is compared with the session IDs stored in the Web server's memory to retrieve the client's HttpSessionState object. Recall that clients may disable cookies in their Web browsers to ensure that their privacy is protected. Such clients will experience difficulty using Web applications that depend on HttpSessionState objects to maintain state information. Property Timeout (line 50) specifies the maximum amount of time that an HttpSessionState object can be inactive before it is discarded. Fig. 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 2021 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 a Session object. --%>  3  <%@ Page Language="VB" AutoEventWireup="false"  4     CodeFile="Recommendations.aspx.vb" Inherits="Recommendations" %>  5  6  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  7     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  8  9  <html xmlns="http://www.w3.org/1999/xhtml" > 10  <head id="Head1" runat="server"> 11      <title>Book Recommendations</title> 12  </head> 13  <body> 14     <form id="form1" runat="server"> 15     <div> 16        <asp:Label ID="recommendationsLabel" runat="server" 17           Font-Bold="True" Font-Size="X-Large" Text="Recommendations"> 18        </asp:Label><br /> 19        <br /> 20        <asp:ListBox ID="booksListBox" runat="server" Height="125px" 21           Width="450px"></asp:ListBox><br /> 22        <br /> 23        <asp:HyperLink ID="languageLink" runat="server" 24           NavigateUrl="~/Options.aspx"> 25           Click here to choose another language 26        </asp:HyperLink> </div> 27     </form> 28  </body> 29  </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 730) 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.vb  2  ' Creates book recommendations based on a Session object.  3  Partial Class Recommendations  4     Inherits System.Web.UI.Page  5  6     ' read Session items and populate ListBox with any book recommendations  7     Protected Sub Page_Init(ByVal sender As Object, _  8        ByVal e As System.EventArgs) Handles Me.Init  9        ' determine whether Session contains any information 10        If Session.Count <> 0 Then 11           For i As Integer = 0 To Session.Count - 1 12              ' get current key name from Session object 13              Dim keyName As String = Session.Keys(i)    14 15              ' use keyName to display one of Session's name-value pairs 16              booksListBox.Items.Add(keyName & _                         17                 " How to Program. ISBN#: " & _                          18                 Session(keyName).ToString())                            19           Next 20        Else 21           ' if there are no session items, no language was chosen, so 22           ' display appropriate message and clear and hide booksListBox 23           recommendationsLabel.Text = "No Recommendations" 24           booksListBox.Items.Clear() 25           booksListBox.Visible = False 26 27           ' modify languageLink because no language was selected 28           languageLink.Text = "Click here to choose a language" 29        End If 30     End Sub ' Page_Init 31  End Class ' Recommendations 

If the user has chosen a language, the loop in lines 1119 iterates through our Session object's session items, temporarily storing each key name (line 13). 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 13 accesses the Keys property of class HttpSessionState, which returns a collection containing all the keys in the session. Line 13 indexes this collection to retrieve the current key. Lines 1618 concatenate keyName's value to the String " How to 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.



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net