Often times when I am building a web application, I am presented with instances in the application that require the user to input the same set of information. Typically this consists of data that is non-sensitive in nature, such as the user's name, address, email address and so on. One of the easiest ways to store this information is in a cookie. In this month's column, I will demonstrate how to create a class in C# that will maintain a cookie within an ASP.NET application.
If you are new to web programming, a cookie is a text file that is stored in the user's browser and can be updated or created by the programmer. A cookie is also domain specific. This means that a cookie written by an application at http://www.grannet.net cannot be read or manipulated by an application at http://www.designstudiomag.com . In ASP.NET, cookies are represented by the HttpCookie object that is defined in the System.Web namespace of the .NET Framework. Each ASP.NET page has a collection of HttpCookie objects available to it that can be manipulated at runtime. The data inside of a cookie is essentially a large string that has key/value pairs of data delimited by the ampersand character. In our simple cookie example, the string would look similar to this:
As you can see, it is not difficult to decipher the data that is contained in a cookie. The data is stored in plain text an easily readable to the human eye. As you may also be able to see, the simple structure of the data stored in a cookie can prove very useful for certain applications. To illustrate some common uses for cookies, consider the following scenarios:
1. Common User Input You have an application that consists of several ASP.NET Web Forms that will require user input. Some of the Web Forms in this application are typical "Contact Us" forms, while other forms are used to request service for products. There are several pieces of information that these forms share in common, such as name, email address, mailing address and so on. The visitor's information is not stored in the database under an account, due to the fact that a log on mechanism is not necessary.
2. Unique Visitor Settings You are developing a web application that will support multiple languages. The settings for the application will be determined by the user. The user will select a culture format (i.e. "en-US") as well as a skin or theme. These settings will be user specific.
3. Shopping Cart You are developing an e-commerce enabled web application. As users browse your online store, they can add or remove items from their shopping carts. The checkout process will be secured by a login and the cart should remain on the site for shopping across sessions.
Each of the above mentioned scenarios are prime examples for the use of a cookie. The first example would benefit by storing the non-sensitive user data, such as name, email address and so on, in a cookie. The second scenario would benefit from a cookie because the application settings are user specific. Rather than add the overhead of storing these settings for each user in a database, simply write a cookie containing the settings to each user's browser and read the settings from the cookie at runtime. And finally, our third scenario would benefit by using a cookie to store the unique ID of the cart. This way, when a user adds an item to their cart, the program would read the cart ID from the cookie and add the item to their cart (as determined by the cart ID) in the database. As you can see, there are many applications for cookies in web development.
A Simple Cookie
In our example we are going to use a combination of pieces from two of the aforementioned scenarios. We are going to use ASP.NET and C# to construct a cookie that will store the following pieces of information:
·First Name ·Last Name ·Email Address ·Shopping Cart ID ·LanguageCulture
HttpCookie is a sealed class in C# and thus, we cannot derive a class from it. So, to create our own cookie class we need to define the class that has a private field that is of type HttpCookie, and then define properties and methods to access and modify the data stored in this HttpCookie field. When you are using the Cookies collection of an ASP.NET Page object, the executing context of the cookies is the Page class. Since our class will not have the context of the Page class that is executing, we must capture the context of the current HttpRequest and add or read our cookies from this object. This is available to us from the static Current property that is a member of the System.Web.HttpContext class
For my example, I will define a class named AppCookie as follows.
As you can see from the comments in the code, the AppCookie class defines two private fields; one for the cookie and one for the name of the cookie. The AppCookie constructor checks the current request to see if a cookie by the specified name exists. If a cookie by that name does not exist, a new instance of an HttpCookie object is created for the HttpCookie field, and the values of the cookie are set to default empty strings. If a cookie by the specified name does exist, the HttpCookie field is set to the value of the cookie from the request. The properties of the class provide access to the key/value pairs of the HttpCookie field. Finally, the Save() method of the class sets the cookie to expire 30 days from the current date and then adds the cookie to the outgoing response.
To test our cookie object, we will create an ASP.NET Web Form that will accept user input for the values of the cookie; however the Cart ID will be generated by the .NET Framework at runtime. The TextBox for the Cart ID will be disabled by default since this value will be generated by the system. To generate the Cart ID, we will ask the system for a GUID (Globally Unique Identifier) and use the Page_Load event to populate the control using the following line of code:
The Click event of the Button server control will be used to create an instance of our AppCookie object and save the cookie with the data input by the user. The Web Form will contain TextBox controls, a Button control and a Label. The figure below shows the orientation of the controls on the Web Form:
Once the "Save Cookie" button has been clicked, our btnSaveCookie_Click event handler method will be invoked. The event handler definition is shown below:
This event handler method simply creates a new instance of an AppCookie object, then assigns the values of the input from the TextBox controls to the property values of the AppCookie, and finally saves the cookie to the user's browser.
To verify that the cookie was written, we're going to navigate to another Web Form within the application and read the data from the cookie. The figure below shows the orientation of the controls on the Web Form:
We will show this data to the user by creating a new instance of an AppCookie object from within the Page_Load event handler of the above mentioned Web Form, and then use that AppCookie instance to populate the Text properties of the Label controls on the Web Form. The code to accomplish this task is shown below:
We now have a class that can be invoked from anywhere in our application and use this class to manage a cookie that contains user data that will create a convenience for users.
A Note on Cookie Security
Due to the nature in which data is stored in a cookie, you must use discretion when choosing what types of data to store in cookies. As mentioned earlier, cookies store information as plain text that is easily decipherable. Since the data is easily readable, sensitive information should never be stored in a cookie. Some types of information that should never be stored in a cookie include the following:
Generally speaking, you shouldn't use cookies to store any kind of information that can be considered confidential or could cause any type of fraud if the cookie was read by a malevolent viewer. So, be diligent and carefully choose the types of data you store in a cookie for your application.