when some external indicator changes, but that kind of task is a little beyond the
scope of this discussion.
Later in the code, we could use the cached object as follows:
Visual Basic
employeesTable = Cache("Employees")
C#
employeesTable = Cache["Employees"];
Objects in the cache can expire, so its good practice to verify that the object
youre expecting does actually exist, to avoid any surprises:
Visual Basic
employeesTable = Cache("Employees")
If employeesTable Is Nothing Then
' Read the employees table from another source
Cache("Employees") = employeesTable
End If
C#
employeesTable = Cache["Employees"];
if (employeesTable == null)
{
// Read the employees table from another source
Cache["Employees"] = employeesTable;
}
This sample code checks to see if the data youre expecting exists in the cache.
If not, it means that this is the first time the code has been executed, or that the
item has been removed from the cache. Thus, we can populate employeesTable
from the database, remembering to store the retrieved data into the cache. The
trip to the database server is made only if the cache is empty or not present.
Using Cookies
If you want to store data related to a particular user, you could use the Session
object, but this approach has an important drawback: its contents are lost when
the user closes the browser window.
To store user data for longer periods of time, you need to use cookies. Cookies
are pieces of data that your ASP.NET application can save on the users browser,
to be read later by your application. Cookies arent lost when the browser is
183
Using Cookies
closed (unless the user deletes them), so you can save data that helps identify
your user in a cookie.
In ASP.NET, a cookie is represented by the HttpCookie class. We read the users
cookies through the Cookies property of the Request object, and we set cookies
though the Cookies property of the Response object. Cookies expire by default
when the browser window is closed (much like session state), but their points of
expiration can be set to dates in the future; in such cases, they become persistent
cookies.
Lets do a quick test. First, open Default.aspx and remove the text surrounding
myLabel:
File: Default.aspx (excerpt)
<form id="form1" runat="server">
<div>
<asp:Label ID="myLabel" runat="server" />
</div>
</form>
Then, modify Page_Load in the code-behind file as shown:
Visual Basic File: Default.aspx.vb (excerpt)
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
' Declare a cookie variable
Dim userCookie As HttpCookie
' Try to retrieve user's ID by reading the UserID cookie
userCookie = Request.Cookies("UserID")
' Verify if the cookie exists
If userCookie Is Nothing Then
' Display message
myLabel.Text = "Cookie doesn't exist! Creating a cookie now."
' Create cookie
userCookie = New HttpCookie("UserID", "JoeBlack")
' Set cookie to expire in one month
userCookie.Expires = DateTime.Now.AddMonths(1)
' Save the cookie on the client
Response.Cookies.Add(userCookie)
Else
' Display message
myLabel.Text = "Welcome back, " & userCookie.Value
End If
End Sub
184
Chapter 5: Building Web Applications
C# File: Default.aspx.cs (excerpt)
protected void Page_Load(object sender, EventArgs e)
{
// Declare a cookie variable
HttpCookie userCookie;
// Try to retrieve user's ID by reading the UserID cookie
userCookie = Request.Cookies["UserID"];
// Verify if the cookie exists
if (userCookie == null)
{
// Display message
myLabel.Text =
"Cookie doesn't exist! Creating a cookie now.";
// Create cookie
userCookie = new HttpCookie("UserID", "JoeBlack");
// Set cookie to expire in one month
userCookie.Expires = DateTime.Now.AddMonths(1);
// Save the cookie on the client
Response.Cookies.Add(userCookie);
}
else
{
// Display message
myLabel.Text = "Welcome back, " + userCookie.Value;
}
}
The first time you load the page, youll be notified that the cookie doesnt exist,
and that a new cookie is being created, via a message like the one shown in Fig-
ure 5.31.
Figure 5.31. Creating a new cookie
185
Using Cookies

Get Build Your Own ASP.NET 2.0 Web Site Using C# & VB, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.