Вы находитесь на странице: 1из 34

EVOCATION

Session Tracking
Session Tracking
 Session Tracking
 Tracking individual clients
 The request/response system on which the Web
operates is facilitated by HTTP
 HTTP is a stateless protocol
Does not support persistent connections
 Web servers cannot maintain state information regarding
particular clients
 A session represents a unique client on a Web site
 The client will still be recognized as the same user if the client leaves a
site and returns later
Each client must identify itself to the server
 Help the server distinguish among clients

3
Cookies
 Cookies
 Piece of data stored in a small text file on the user’s computer
 Maintains information about the client during and between browser sessions
 Are sent and received as a collection of type HttpCookieCollection
 Web Forms can examine the cookies it sent to the client during previous
communications
 The expiration date determines how long the cookie remains on the client’s
computer
 The Web browser maintains the cookie for the duration of the browsing session if
there is no expiration date
 Response object’s Cookies property
 Used to write cookies to a client
 Used to access cookies

 Can be read by an application only if they were created in the domain in


which the application is running

4
1 <%-- Fig. 25.20: Options.aspx --%>
2 <%-- Allows client to select programming languages and access --%> Outline
3 <%-- book recommendations. --%>
4 <%@ Page Language="VB" AutoEventWireup="false"
5 CodeFile="Options.aspx.vb" Inherits="Options" %>
6
Options.aspx
7 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
8 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
(1 of 3)
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:">
Declare a
19 </asp:Label>
RadioButtonList with
20 <asp:RadioButtonList ID="languageList" runat="server"> 5 elements
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>

5
27
27 <asp:Button ID="submitButton"
<asp:Button runat="server"
ID="submitButton" Text="Submit"
runat="server" />
Text="Submit" />
28
28
<asp:Label ID="responseLabel" runat="server" Font-Bold="True"
<asp:Label ID="responseLabel" runat="server" Font-Bold="True" Outline
29 Font-Size="Large" Text="Welcome to cookies!" Visible="False">
29
30 Font-Size="Large"
</asp:Label><br /> Text="Welcome to cookies!" Visible="False">
31
30 <br />
</asp:Label><br /> Does not cause a postback to
32 <asp:HyperLink ID="languageLink" runat="server" Options.aspx
occur
31 <br />
33 NavigateUrl="~/Options.aspx" Visible="False">
32
34 <asp:HyperLink ID="languageLink"
Click here to choose another language runat="server" (2 of 3)
33
35 NavigateUrl="~/Options.aspx"
</asp:HyperLink><br /> Visible="False">
Declare two hyperlinks
36 <br />
34 Click here to choose another language
37 <asp:HyperLink ID="recommendationsLink" runat="server"
35
38 </asp:HyperLink><br />
NavigateUrl="~/Recommendations.aspx" Visible="False">
36
39 <br />here
Click to get book recommendations
40 </asp:HyperLink>
37 <asp:HyperLink ID="recommendationsLink" runat="server"
41 </div>
38
42 </form> NavigateUrl="~/Recommendations.aspx" Visible="False">
39 </body>
43 Click here to get book recommendations
44 </html>
40 </asp:HyperLink>
41 </div>
42 </form>
43 </body>
44 </html>

6
Outline

Options.aspx

(3 of 3)

7
1 ' Fig. 25.21: Options.aspx.vb
2 ' Processes user's selection of a programming language Outline
3 ' by displaying links and writing a cookie to the user's machine.
4 Partial Class Options
5 Inherits System.Web.UI.Page
A data structure to hold
Options.aspx.vb
book representations
6 ' stores values to represent books as cookies
7 Private books As New System.Collections.Hashtable()
8
(1 of 3)
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
Add each book element
12 books.Add("Visual Basic 2005", "0-13-186900-0")
13 books.Add("Visual C# 2005", "0-13-152523-9")
into the hash table
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

8
26 ' and appropriate hyperlinks
27 responseLabel.Visible = True Outline
28 languageLink.Visible = True
29 recommendationsLink.Visible = True
30 Options.aspx.vb
31 ' hide other controls used to make language selection
32 promptLabel.Visible = False (2 of 3)
33 languageList.Visible = False
34 submitButton.Visible = False Determine whether
35 user selected a
36 language
' if the user made a selection, display it in responseLabel
Display the
37 If languageList.SelectedItem IsNot Nothing Then
appropriate
38 responseLabel.Text &= " You selected " & _
output
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

9
46 ' write a cookie to record the user's selection
47 Protected Sub submitButton_Click(ByVal sender As Object, _
Outline
48 ByVal e As System.EventArgs) Handles submitButton.Click
49 ' if the user made a selection Options.aspx.vb
50 If languageList.SelectedItem IsNot Nothing Then
Retrieve (3
theofvalue
3) that
51 Dim language As String = languageList.SelectedItem.ToString()
corresponds to the key
52 contained in
53 ' get ISBN number of book for the given language language
A new cookie object is
54 Dim ISBN As String = books(language).ToString() created to store the
55 language and its
56 ' create cookie using language-ISBN name-value pair corresponding ISBN
The cookie is added to the number
57 Dim cookie As New HttpCookie(language, ISBN)
Cookies collection sent as
58 part of the HTTP response
59 ' add cookie to response to place it on the user's
headermachine
60 Response.Cookies.Add(cookie)
61 End If
62 End Sub ' submitButton_Click
63 End Class ' Options

10
1 <%-- Fig. 25.22: Recommendations.aspx --%>
2 <%-- Displays book recommendations using cookies. --%> Outline
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" Recommendations
7 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> .aspx
8
9 <html xmlns="http://www.w3.org/1999/xhtml" > (1 of 2)
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 />
Display the recommendations
23 <asp:HyperLink ID="languageLink" runat="server"
24 NavigateUrl="~/Options.aspx"> created by the code-behind
25 Click here to choose another language file
26 </asp:HyperLink>&nbsp;</div>
27 </form>
28 </body>
29 </html>

11
Outline

Recommendations
.aspx

(2 of 2)

12
1 ' Fig. 25.23: Recommendations.aspx.vb
2 ' Creates book recommendations based on cookies. Outline
3 Partial Class Recommendations
4 Inherits System.Web.UI.Page
5
6 Recommendations
' read cookies and populate ListBox with any book recommendations
7 Protected Sub Page_Init(ByVal sender As Object, _ .aspx.vb
8 ByVal e As System.EventArgs) Handles Me.InitRetrieves the cookies from the
9 ' retrieve client's cookies
10 Dim cookies As HttpCookieCollection = Request.Cookies
client
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 Add the information in
15 booksListBox.Items.Add(cookies(i).Name & _ the cookie(s) to the
16 " How to Program. ISBN#: " & cookies(i).Value) booksListBox
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
13
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.

| HttpCookie properties. (Part 1 of 2.)

14
Properties Description

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.

| HttpCookie properties. (Part 2 of 2.)

15
Session Tracking with HttpSessionState
 Class HttpSessionState
 Provides session-tracking
 Every Web Form includes an HttpSessionState
object
 Accessible through property Session of class Page
 Can store name–value pairs using method Add
 When adding an attribute that has the same name, the object
associated with that attribute is replaced

16
Session Tracking with HttpSessionState
 Property SessionID
 Contains the unique session ID
 A sequence of random letters and numbers

 The first time a client connects to server, a unique session ID is created


for that client
 Property Timeout
 Specifies the maximum amount of time that an HttpSessionState
object can be inactive before it is discarded
 Property Count
 Provides the number of session items contained in a Session object
 Property Keys
 Returns a collection containing all the session’s keys

17
1 <%-- Fig. 25.25: Options.aspx --%>
2 <%-- Allows client to select programming languages and access --%> Outline
3 <%-- book recommendations. --%>
4 <%@ Page Language="VB" AutoEventWireup="false"
5 CodeFile="Options.aspx.vb" Inherits="Options" %>
Options.aspx
6
7 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
8 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
(1 of 3)
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>

18
26 </asp:RadioButtonList>
27 <asp:Button ID="submitButton" runat="server" Text="Submit" /> Outline
28 <asp:Label ID="responseLabel" runat="server" Font-Bold="True"
29 Font-Size="Large" Text="Welcome to sessions!" Visible="False">
30 </asp:Label><br /> Options.aspx
31 <br />
32 <asp:Label ID="idLabel" runat="server" Visible="False"> (2 of 3)
33 </asp:Label><br />
34 <br />
35 <asp:Label ID="timeoutLabel" runat="server" Visible="False">
36 </asp:Label><br /> Hidden labels to
37 <br /> display tracking
38 <asp:HyperLink ID="languageLink" runat="server" information
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>

19
Outline

Options.aspx

(3 of 3)

20
1 ' Fig. 25.26: Options.aspx.vb
2 ' Processes user's selection of a programming language Outline
3 ' by displaying links and writing information in a Session object.
4 Partial Class Options
5 Inherits System.Web.UI.Page Options.aspx.vb
6 ' stores values to represent books
7 Private books As New System.Collections.Hashtable() (1 of 3)
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

21
24 If IsPostBack Then
25 ' user has submitted information, so display message Outline
26 ' and appropriate hyperlinks
27 responseLabel.Visible = True
28 idLabel.Visible = True
Options.aspx.vb
29 timeoutLabel.Visible = True
30 languageLink.Visible = True (2 of 3)
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 " & _ Returns the unique session
41 languageList.SelectedItem.Text.ToString() ID
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

22
49 ' display the timeout
50 Outline
timeoutLabel.Text = "Timeout: " & Session.Timeout & " minutes."
51 End If
Returns the maximum
52 End Sub ' Page_Load amount of time that an
Options.aspx.vb
53 HttpSessionStat
54 ' record the user's selection in the Session e object(3can
of 3)
be
55 Protected Sub submitButton_Click(ByVal sender As Object,inactive
_ before it is
56 ByVal e As System.EventArgs) Handles submitButton.Click discarded
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
Place the language and its
67 End Class ' Options
corresponding ISBN number in
the HttpSessionState
object
23
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.

| HttpSessionState properties.

24
1 <%-- Fig. 25.28: Recommendations.aspx --%>
2 <%-- Displays book recommendations using a Session object. --%> Outline
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" Recommendations
7 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> .aspx
8
9 <html xmlns="http://www.w3.org/1999/xhtml" > (1 of 2)
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 /> Used to present the
22 <br /> recommendations to the
23 <asp:HyperLink ID="languageLink" runat="server" user
24 NavigateUrl="~/Options.aspx">
25 Click here to choose another language
26 </asp:HyperLink>&nbsp;</div>
27 </form>
28 </body>
29 </html>
25
Outline

Recommendations
.aspx

(2 of 2)

26
1 ' Fig. 25.29: Recommendations.aspx.vb
2 ' Creates book recommendations based on a Session object.
Outline
Provides the number of
3 Partial Class Recommendations session items contained
4 Inherits System.Web.UI.Page in a Session object
Recommendations
5 .aspx.vb

6 ' read Session items and populate ListBox with any book recommendations
(1 of 2)
7 Protected Sub Page_Init(ByVal sender As Object, _
8 ByVal e As System.EventArgs) Handles Me.Init Indexes the collection
9 ' determine whether Session contains any information containing all the keys in the
10 If Session.Count <> 0 Then session to receive the
current key
11 For i As Integer = 0 To Session.Count - 1
12 ' get current key name from Session object Concatenate and display the
13 Dim keyName As String = Session.Keys(i)
string that is the
recommendation in the
14
ListBox
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())

27
19 Next
Outline
20 Else
21 ' if there are no session items, no language was chosen, so
Recommendations
22 ' display appropriate message and clear and hide booksListBox
.aspx.vb

23 recommendationsLabel.Text = "No Recommendations" (2 of 2)


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

28
PUZZLES
 Rob and Bob are arch enemies. They decide to have a
fight to the death one day when a fairy appears. The
fairy says it will give them both one wish. Bob wishes,
"I wish for twice whatever Rob asks for."

What can Rob ask for to ensure he wins the fight?

 He should wish to be beaten half to death in the


fight.
PUZZLES
 Smell me, buy me, and deliver me.
I won't change.

What am I?

 Scent, Cent, and Sent.


GUIDED READING AND DISCUSSION
MINDMAP
SUMMARY

 ASP.NET
Session Tracking
Cookies
Session Tracking with HttpSessionState
FRAMING QUESTIONS

Вам также может понравиться