|
Normally, a web application is stateless. This means that no data is kept as the user navigates between one page and another in a website. In a thick client, such as a Windows application, the client remains running and data the application needs is stored in memory until the client is closed. However, with a web-based application, a connection is made to the website, the page content is downloaded, and the connection is ended. So, there's no constantly running client to maintain state. However, there are workarounds we can utilize to let our web application work as if it can maintain state.
The first technique is cookies. Cookies are name-value pairs that get sent to and from the browser with each HTTP request. They contain information about your visit that the developer of the website you're visiting wishes to track. They can either be designed to be volatile, lasting only for the duration of your current visit to the website, or they can be persistent, lasting for an extended period of time, which is determined by the developer. We're going to use cookies below to remember a user's name.
Cookies have gotten a bad reputation as being insecure. Many say that a user's privacy will be compromised if they allow sites to place cookies on their computer. The most important things to know about cookies are:
They only contain data. They aren't programs, and can't run programs, so they aren't going to delete files, or mail your credit card details back to the authors.
The only site that can access a cookie is the site from which it was created . So, someone can't create a malicious site and read all of your cookie data at will. This makes cookies relatively secure.
Note | There have been some browser bugs that do allow this sort of unauthorized cookie access between sites. Patches exist, but keep in mind that some of your users may not have applied these patches, and also that new bugs to exploit could be found in the future. |
Now, if your browser stores cookies in files, and someone can gain access to the cookie file on your computer, they could view the data contained within, or possibly copy it to another computer and utilize it there. The best strategy is to use cookies only to store information that isn't overly sensitive. Many websites use cookies to recognize a user, but still require the user to log on in order to view their sensitive data. This is a good compromise.
Different operating systems store cookies in different ways. With Windows XP, they are stored as files in a directory specific to each user of the system. Most of the time, the path will be C:\Documents and Settings\username\Cookies, where username is the logon name you use to log onto your operating system. The cookie files on XP are named as username@domainname[uniquenumber].txt. The domain name is the URL domain you accessed the site with. The unique number is used in the case where a site has more than
one cookie.
Note | Cookies are limited to 4,096 bytes in size. |
ASP.NET provides two accessible collections of cookies, both returned as type HttpCookieCollection. The first one is accessible via the HttpRequest.Cookies property. This collection contains all of the cookies returned from the browser with each request. This collection is used to read cookies. The second collection is accessible via the HttpResponse.Cookies property. This collection is sent to the browser with each request. This is the collection you use to create cookies.
The HttpCookieCollection contains objects of type HttpCookie. The HttpCookie object has the following commonly used properties. For other properties, refer to the documentation:
Property | Description |
---|---|
Domain | The name of the domain with which the cookie is to be associated. By default, it's the name of the current domain. The domain is the root of the URL you're accessing. So the domain for http://www.msn.com/news would be www.msn.com. |
Expires | The date and time when the cookie should expire. |
Name | The name of the cookie. By default, it's set to Nothing. |
Path | This is the URL virtual path where the cookie originates. In the example http://www.msn.com/news, the path is /news. If no path is specified, this cookie will be sent to all pages on the server. If it is specified, this cookie will only be sent to pages under the /news path. |
Value | The value of the cookie. A simple example is: |
MyCookie.Value = "abc" | |
Values | A NameValueCollection of values for the current cookie. This is convenient if you want to store more than one value within the current cookie. An example is: |
MyCookie.Values("FirstValue") = "abc" | |
MyCookie.Values("SecondValue") = "def" |
Here's some example code that creates a cookie and sends it along with the page to the browser.
First, you create a new HttpCookie instance, with the name FavoriteBand:
Dim MyCookie as New HttpCookie("FavoriteBand")
Set the value of the cookie to Cornflakes at Midnight:
MyCookie.Value = "Cornflakes at Midnight"
Set the cookie to expire 30 days from now:
MyCookie.Expires = today.AddDays(30)
Add the cookie to the response object's cookie collection so that it will be sent to the browser along with the rest of the page:
Response.Cookies.Add(MyCookie)
As mentioned above, different browsers will store these cookies in different ways. Regardless of how the browser stores them, it will return them each time a request to the site is located, as long as the cookie is determined to be valid for the domain and path of the URL the user is requesting. To use the cookie value on our page, here is the kind of code we need:
If Request.Cookies("FavoriteBand") Is Nothing Then txtField.Text = "" Else txtField.Text = Request.Cookies("FavoriteBand").Value End If
If it is Nothing, then the cookie doesn't exist and if it doesn't exist then set the text field to nothing. Otherwise, set the text field to the value of the cookie name FavoriteBand.
Cookie values are always stored and returned as strings, so you'll need to cast your types appropriately when setting and returning non-string values.
OK. Now that you've seen a quick example, let's implement cookies in our band's website. The perfect place for it is on the page where fans can make a guest book entry. Instead of making them type their name in each time, we'll remember their name after they post their first entry. After that, we'll pre-populate the name textbox from the cookie's value.
Open the GuestBook.aspx page we created in Chapter 13 and add the following method to the code:
Sub SaveNameToCookie() Dim MyCookie As New HttpCookie("Name") MyCookie.Value = txtAuthor.Text MyCookie.Expires = Today.AddDays(30) Response.Cookies.Add(MyCookie) End Sub
In the btnOK_Click event handler, add the following line:
Sub btnOK_Click(sender As Object, e As EventArgs) Dim NumRecords As Integer = 0 If IsValid Then NumRecords = _ InsertGuestBookEntry(txtAuthor.text, txtSubject.text, txtMessage.text) If NumRecords = 0 Then lblStatusMsg.visible = True lblStatusMsg.text = _ "An error occurred while trying to create the entry." Else lblStatusMsg.text = "Entry created successfully. " & _ "Thanks for letting us know what you think." SaveNameToCookie() InitPostForm() End If BindGrid() End If End Sub
Now, when the entry is saved successfully, the user's name will be stored in the cookie.
Next, change the InitPostForm() method as follows:
Sub InitPostForm() If Request.Cookies("Name") Is Nothing Then txtAuthor.Text = "" Else txtAuthor.Text = Request.Cookies("Name").Value End If txtSubject.text = "" txtMessage.text = "" End Sub
We check to see if the cookie named Name contains a value. If it does, we set the txtAuthor to the value of the cookie. Otherwise, we set it to an empty string.
Change the Page_Load event handler to initialize the post form:
Sub Page_Load(Sender As Object, E As EventArgs) If Not Page.IsPostBack Then ' Databind the data grid on the first request only ' (on postback, rebind only in paging and sorting commands) InitPostForm() BindGrid() End If End Sub
This causes the name to be loaded from the cookie when the page is first loaded.
Now, after you create your first entry, the name you entered for yourself should be pre populated into the Your name: field. If you haven't used the site for 30 days, however, the cookie will be deleted and you'll have to enter your name again. I created an entry with the name of Art Edwards, closed the browser, opened it up and navigated back to the guest book.
To test the cookie's deletion after a certain time, you can always set the expiration date to say 1 day and then go back to the site a couple of days later to see if the page still remembers you.
This is pretty simple code. First we created a SaveNameToCookie routine, so save the user name into a cookie:
Sub SaveNameToCookie() Dim MyCookie As New HttpCookie("Name") MyCookie.Value = txtAuthor.Text MyCookie.Expires = Today.AddDays(30) Response.Cookies.Add(MyCookie) End Sub
This simply stores the user's name (txtAuthor.Text) into a cookie named, appropriately enough, Name. Their name will be stored for 30 days.
We now need to call this routine, and the best time to do this is when the guest book entry is saved successfully. We don't want to store it if the save fails, because for all we know, it could be the name itself that caused the failure. So, if the entry was successfully written to the database, we just call the above routine:
SaveNameToCookie()
What we next need to do is modify the InitPostForm routing, which resets the Subject and Message textboxes. Instead of just clearing the name, we check to see if the cookie has a value, and if so we use that value as the value for the author name textbox:
If Request.Cookies("Name") Is Nothing Then txtAuthor.Text = "" Else txtAuthor.Text = Request.Cookies("Name").Value End If
Finally we make sure this routine is called when the page is first loaded, so that their name will be filled in when they return to the site at a later date. We simply added a call to InitPostForm() in the Page_Load event:
InitPostForm()
|