Download an AVR for .NET 8x example
(The example provided is for AVR 8.x only, but the code shown in this article also works with AVR for .NET 7.x)
Cookies provide a way to store user-specific information on a user's computer. Cookie values persist across sessions so that any cookie values you write for a user will be available the next time the user starts the browser. For example, it's built into ASP.NET's forms authentication to create a cookie to optionally persist user sign-in information. In this case, the cookie creation is implicit--the forms authenticate engine creates it for you. It's also possible, though, to create your own cookie values to persist other information for the user. For example, you may persist the starting customer number of a list so that when the user returns to app, the list starts displaying customers from where the user last listed customers. This article shows how to read and write cookie values.
Cookie considerations
Note that cookies support must be enabled by the user. If a user's browser isn't set to allow cookies, the user won't be able to read your cookies. For that reason, cookies use in your applications should be an option to make the application flow better; you should not use cookies to persist important data that drives application logic. If you do, your application won't work correctly for users who don't have cookies enabled. Cookie enablement is a user choice! You can't enable cookies from your application. Remember, too, that users can disable cookies at any time. Don't ever assume cookie values are available!
Beware also that cookies provide a potential sercurity issue. Cookie contents are stored as plain text on the client computer. Don't ever put anything in a cookie that could compromise security.
Most browsers allow 20 cookies per site--if you try to store more cookies than a browser supports, the oldest cookies are discarded. Keep an eye on content size as well. Most browsers support a maximum cookie length of 4K.
Cookies are very handy and can add to the quality of your application's user experience. Use them prudently though, be mindful of the amounts of data you are attempting to store, and always onsider their existence optional. Make sure that your application runs fine in the absense of cookie values.
Cookies two ways
There are two kinds of cookies: single value cookies, which are cookies that store a single value per cookie and multi-value, or dictionary, cookies. These are cookies that store multiple values per cookie. First let's take a look at single- value cookies.
Writing a single-value cookie
The code below shows how to write a single-value cookie. To write to a cookie, you first instance an HttpCookie object. Then you need to set, at a minimum, two properties: Value and Expires. The Value property sets the value for the cookie to persist and the Expires property specifies how long the persisted cookie should last. Setting the Expires property is very important! If you don't set it, the cookie will not persist across browser sessions. The data type of the Expires property is *TimeStamp (DateTime in the .NET Framework). You can set its expiration with any level of granularity you want, minutes, hours, days, weeks, etc. Typically, the value is set in days. The code below shows a way to specify a cookie that expires 30 days from the day the cookie is written.
BegSr WriteSingleValueCookie
DclFld DaysToExpire Type( *Integer4 )
DclFld Cookie Type( HttpCookie )
DaysToExpire = 30
Cookie = *New HttpCookie( "barney" )
Cookie.Value = txtDino.Text
Cookie.Expires = DateTime.Now.AddDays( DaysToExpire )
Response.Cookies.Add( Cookie )
EndSr
The code above creates a cookie named "barney" and then sets its Value property with a value from a textbox and its Expires property to expire in 30 days. Cookie names don't appear to be case-sensitive in IE, but it's probably prudent to write all code as though cookie names are case senstive. It would probably be a good practice to use constants for cookie names.
After creating the cookie, the last thing to do is to add it to the Response.Cookies collection with its Add method. If you forget this line, all of your work is for nought! Don't forget this important step!
If a user's browser has cookies disabled, the code above finishes normally as though the cookie were written. You'll see in in a moment that when you attempt to read a cookie value, you'll want to ensure the read was successful.
Reading a single-value cookie
Reading a single-value is also very easy. To do so, you attempt to assign an HttpCookie instance from a previously created named cookie. The code below attempts to fetch a cookie named "barney."
BegSr ReadSingleValueCookie
DclFld Cookie Type( HttpCookie )
Cookie = Request.Cookies[ "barney" ]
If ( Cookie <> *Nothing )
txtDino.Text = Cookie.Value
EndIf
EndSr
If the fetch is succesful, that is, if the user has cookies enabled and the cookie had previously been written, the Cookie instance variable will not be *Nothing and you can fetch its value. If the Cookie instance value is *Nothing, there isn't a cookie value available. Always test fetched cookies for returning *Nothing to ensure you're actually able to read the cookie value. In the case of single-value cookies, after ensuring the cookie exists, you can fetch the cookie value with its Value property.
Writing dictionary cookies
Dictionary cookies let you associate multiple keys and values with a single cookie. Dictionary cookies are especially handing for saving several values that have a related function. The code below creates a single cookie named fred and then populates it with two key values, wilma and betty. The wilma and betty keys are assined a value from two different textboxes. You can have as many value pair associated with a dictionary cookie as necessary.
The cookie is then added to the Response.Cookie collection. Just a like a single-value key, you must specify the Expires property to persist the cookie across browser sessions.
BegSr WriteDictionaryCookie
DclFld DaysToExpire Type( *Integer4 )
DclFld Cookie Type( HttpCookie )
DaysToExpire = 30
Cookie = *New HttpCookie( "fred" )
Cookie.Expires = DateTime.Now.AddDays( DaysToExpire )
Cookie.Values[ "wilma" ] = txtWilma.Text
Cookie.Values[ "betty" ] = txtBetty.Text
Response.Cookies.Add( Cookie )
EndSr
Reading dictionary cookies
Reading dictionary cookies is similar to reading a single-value cookie. The difference is that after you fetch the cookie instance, you must then fetch each key/value pair seperately. Note also that even though a dictionary cookie exists, you're never guaranteed what key/value pairs it contains. Thus, you should always a dictionary cookie's value against *Nothing to ensure it exists. Notice below that both cookie keys, wilma and betty are checked against *Nothing before using them.
BegSr ReadDictionaryCookie
DclFld Cookie Type( HttpCookie )
Cookie = Request.Cookies[ "fred" ]
If ( Cookie <> *Nothing )
If ( Cookie.Values[ "wilma" ] <> *Nothing )
txtWilma.Text = Cookie[ "wilma" ].ToString()
EndIf
If ( Cookie.Values[ "betty" ] <> *Nothing )
txtBetty.Text = Cookie[ "betty" ].ToString()
EndIf
EndIf
EndSr
Additional properties
There are a couple of HttpCookie properties that you should be familar with:
- The HttpOnly property is a boolean value that determines if a cookie is accessible by client-side scripting. If HttpOnly is true, the cookie cannot be accessed with client-side scripting (such as JavaScript). This setting can help mitigate the possibility of stealing cookie value with malicious client code. Note that even if HttpOnly is true, a hacker still has potential access to the network channel. If security is an utmost concern with your cookies, consider securing the pages on which they are used with HTTPS. See this MSDN article for more on malicious cross-site scripting. The default is false.
- The Secure property is a boolean value that indicates whether the cookie should be transmitted only over HTTPS. The default is false.
Here is an example of writing a single-value cookie using these properties. In this case, the cookie is not available to JavaScript and is only transmitted over HTTPS.
BegSr WriteSingleValueCookie
DclFld DaysToExpire Type( *Integer4 )
DclFld Cookie Type( HttpCookie )
DaysToExpire = 30
Cookie = *New HttpCookie( "barney" )
//Cookie is not available to JavaScript.
Cookie.HttpOnly = *True
// Cookie is transmitted only over HTTPS.
Cookie.Secure = *True
Cookie.Value = txtDino.Text
Cookie.Expires = DateTime.Now.AddDays( DaysToExpire )
Response.Cookies.Add( Cookie )
EndSr
What do cookies look like?
Internet Explorer stores cookies as text files in the c:\documents and settings\[user]\cookies folder. An example IE cookie file is shown below. The first cookie written to this file is a single-value cookie; the other is a dictionary cookie. Notice that a cookie file's contents are clearly visible. Don't put sensitive data in a cookie!
barney
Lead guitar
localhost/
1024
390308736
29886109
521850096
29880074
*
fred
wilma=Neil&betty=Young
localhost/
1024
380308736
29886109
512320096
29880074
*
Cookies checklist
- Don't persist senstive data in cookies.
- Be sure to specify the Expires property--cookies don't persist without it.
- Don't forget to add cookies you create to the Response.Cookies collection--cookies don't persist until you do this.
- Cookie space is finite--limit cookie values to small, scalar values.
- Always check to see if a cookie and, for dictionary cookies, its values were read before attempting to use its values.
- Users control cookie availability and that control can't be changed programatically.
- Always write your code so that cookie use is optional--don't base program logic on cookies.
- Cookies are persisted on a per-user basis. Multiple browser instances on the same PC, using the same browser type (ie, IE or FireFox), share cookies.
- Prevent errors by using constants for cookie names and dictionary cookie key names.
For more information
Read more about cookies in this MSDN article.