Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Session Tracking with HttpSessionState - ASP.NET

Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Server Technologies - ASP.NET 2.0 and ASP.NET Ajax

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Session Tracking with HttpSessionState - ASP.NET

Session-tracking capabilities are provided by the FCL class HttpSessionState.

Session Tracking with HttpSessionState

 

Session-tracking capabilities are provided by the FCL class HttpSessionState. To dem-onstrate basic session-tracking techniques, we modified the example of Figs. 25.20–25.23 to use HttpSessionState objects. Figures 25.25–25.26 present the ASPX file and code-behind file for Options.aspx. Figures 25.28–25.29 present the ASPX file and code-be-hind file for Recommendations.aspx. Options.aspx is similar to the version presented in

 

Fig. 25.20, but Fig. 25.25 contains two additional Labels (lines 32–33 and lines 35–36), which we discuss shortly.

 

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. 25.26, lines 55–66). Method submitButton_Click responds by adding a key–value pair to our Session object, specifying the language chosen and the ISBN number for a book on that language. These key–value 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.

 

1    <%-- Fig. 25.25: 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>

 

</html>


 

Fig. 25.25 | ASPX file that presents a list of programming languages.

 

Like a cookie, an HttpSessionState object can store name–value 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.

1    ' Fig. 25.26: 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

 

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

 

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

 

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

 

 

 

The application handles the postback event (lines 24–51) 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 con-tains information about the HttpSessionState object for the current client. Property SessionID (line 47) contains the unique session ID—a 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 ses-sion 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 and cookies to maintain state information. The HttpSessionStrate property IsCookieless indicates whether URL rewriting or cookies are used for session tracking. Property Timeout (line 50) specifies the maximum amount of time that an Http-SessionState object can be inactive before it is discarded. Figure 25.27 lists some common HttpSessionState properties.

 

Displaying Recommendations Based on Session Values

As in the cookies example, this application provides a link to Recommendations.aspx (Fig. 25.28), which displays a list of book recommendations based on the user’s language selections. Lines 20–21 define a ListBox web control that is used to present the recom-mendations to the user.

 

 

1    <%-- Fig. 25.28: 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>&nbsp;</div>

 

27           </form>

 

28   </body>

 

29   </html>


 

 

Fig. 25.28 | Session-based book recommendations displayed in a ListBox.

 

Code-Behind File That Creates Book Recommendations from a Session

 

Figure 25.29 presents the code-behind file for Recommendations.aspx. Event handler Page_Init (lines 7–30) retrieves the session information. If a user has not selected a lan-guage on Options.aspx, our Session object’s Count property will be 0. This property pro-vides 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.

 

1    ' Fig. 25.29: 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

 

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

Fig. 25.29 | Session data used to provide book recommendations to the user.

 

If the user has chosen a language, the loop in lines 11–19 iterates through our Session object’s session items, temporarily storing each key name (line 13). The value in a key– value 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 col-lection containing all the keys in the session. Line 13 indexes this collection to retrieve the current key. Lines 16–18 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.

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.