Cookies provide web developers with a tool for identifying and tracking web users. A cookie is a piece of data stored in a small text file on the user’s computer. A cookie main-tains information about the client during and between browser sessions. The first time a user visits the website, the user’s computer might receive a cookie; this cookie is then re-trieved 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 us-ers. 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 per-form any necessary processing.
In addition to identifying users, cookies also can indicate users’ shopping preferences. When a web server receives a request from a client, the server can examine the cookie(s) it sent to the client during previous communications, identify the users’s preferences and immediately return products of interest to the client.
Every HTTP-based interaction between a client and a server includes a header con-taining 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 server 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 infor-mation 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 main-tains 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.
Using Cookies to Provide Book Recommendations
The ASPX file in Fig. 25.20 contains five radio buttons (lines 20–26) 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 32–35), and the other requests Recommendations.aspx (lines 37–40). 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 website ( 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.
1 <%-- Fig. 25.20: 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" %>
7 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
10 <html xmlns="http://www.w3.org/1999/xhtml" >
11 <head runat="server">
15 <form id="form1" runat="server">
17 <asp:Label ID="promptLabel" runat="server" Font-Bold="True"
18 Font-Size="Large" Text="Select a programming language:">
20 <asp:RadioButtonList ID="languageList" runat="server">
21 <asp:ListItem>Visual Basic 2005</asp:ListItem>
22 <asp:ListItem>Visual C# 2005</asp:ListItem>
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"
39 Click here to get book recommendations
Fig. 25.20 | ASPX file that presents a list of programming languages.
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 Recommen-dations.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
Figure 25.21 presents the code-behind file for Options.aspx (Fig. 25.20). This file con-tains the code that writes a cookie to the client machine when the user selects a program-ming language. The code-behind file also modifies the appearance of the page in response to a postback.
1 ' Fig. 25.21: 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()
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
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
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
31 ' hide other controls used to make language selection
32 promptLabel.Visible = False
33 languageList.Visible = False
34 submitButton.Visible = False
36 ' if the user made a selection, display it in responseLabel
If languageList.SelectedItem IsNot Nothing Then
38 responseLabel.Text &= " You selected " & _
41 responseLabel.Text &= " You did not select a language."
41 End If
42 End If
43 End Sub ' Page_Load
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()
53 ' get ISBN number of book for the given language
54 Dim ISBN As String = books(language).ToString()
56 ' create cookie using language-ISBN name-value pair
57 Dim cookie As New HttpCookie(language, ISBN)
59 ' add cookie to response to place it on the user's machine
61 End If
62 End Sub ' submitButton_Click
63 End Class ' Options
Fig. 25.21 | Code-behind file that writes a cookie to the client.
Line 7 creates variable books as a Hashtable (namespace System.Collections)—a data structure that stores key–value 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 argu-ments 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 deter-mined by indexing the Hashtable with that value’s key. The expression
returns the value in the key–value pair in which keyName is the key. For example, the ex-pression books(language) in line 54 returns the value that corresponds to the key contained in language.
Clicking the Submit button creates a cookie if a language is selected and causes a post-back to occur. In the submitButton_Click event handler (lines 47–62), 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 27–42 execute. Lines 27–29 reveal the initially hidden controls responseLabel, languageLink and recommendationsLink.
Lines 32–34 hide the controls used to obtain the user’s language selection. Line 37 deter-mines whether the user selected a language. If so, that language is displayed in response-Label (lines 38–39). 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. 25.22) to display the recommendations based on the user’s language selections.
1 <%-- Fig. 25.22: Recommendations.aspx --%>
2 <%-- Displays book recommendations using cookies. --%>
3 <%@ Page Language="VB" AutoEventWireup="false"
4 CodeFile="Recommendations.aspx.vb" Inherits="Recommendations" %>
6 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
9 <html xmlns="http://www.w3.org/1999/xhtml" >
10 <head runat="server">
11 <title>Book Recommendations</title>
14 <form id="form1" runat="server">
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"
25 Click here to choose another language
26 </asp:HyperLink> </div>
Fig. 25.22 | ASPX file that displays book recommendations based on cookies.
Recommendations.aspx contains a Label (lines 16–18), a ListBox (lines 20–21) and a HyperLink (lines 23–26). 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 (Fig. 25.23). The Hyper-Link 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 (Fig. 25.23), method Page_Init (lines 7–28) retrieves the cookies from the client, using the Request object’s Cookies property (line 10). This returns a col-lection of type HttpCookieCollection, containing cookies that have previously been writ-ten to the client. Cookies can be read by an application only if they were created in the domain in which the application is running—a 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 14–17 add the informa-tion 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 lan-guage and corresponding ISBN, respectively, are concatenated with " How to Program.
1 ' Fig. 25.23: Recommendations.aspx.vb
2 ' Creates book recommendations based on cookies.
3 Partial Class Recommendations
4 Inherits System.Web.UI.Page
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
12 ' if there are cookies, list the appropriate books and ISBN numbers
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)
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"
23 booksListBox.Visible = False
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
Fig. 25.23 | Reading cookies from a client to determine book recommendations.
ISBN# " and added to the ListBox. Lines 21–26 execute if no language was selected. We summarize some commonly used HttpCookie properties in Fig. 25.24.
Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.