Monday, September 27, 2010

Cookies in ASP.NET

Cookies :

Web applications often need to track users between page requests. These applications need to ensure that the user making the fi rst request is the same user making subsequent requests. This type of common tracking is done with what are called cookies.


A cookie is a small amount of data that you write to the client to be stored and then passed with requests to your site. You write persistent cookies to a text fi le on the client machine. These cookies are meant to survive the user shutting down the browser and reopening it at a later time. You can also write temporary cookies to the memory of the client’s browser. These cookies are used only during the given Web session. They are lost when the browser closes. Again, the most common use of cookies is to identify a single user as he or she visits multiple Web pages within your site. However, you can also use cookies to store state information or other user preferences.


Cookies are the most fl exible and reliable way of storing data on the client. However, users can delete cookies on their computers at any time. You can set cookies to have long expiration times but that does not stop users from deleting all their cookies and thus wiping out any settings you might have stored in them. In addition, cookies do not solve the issue of a user moving from computer to computer. In these cases, users’ preferences do not always go along with them. Therefore, if you allow a lot of personalization for users of your site, you need to allow them to log in and reset their cookies. Doing so should then reenable their customizations provided you have them stored elsewhere.


Reading and Writing Cookies :

A Web application creates a cookie by sending it to the client as a header in an HTTP response. Of course, ASP.NET makes writing to and reading from the cookie collection a relatively straight forward task. To add a cookie to the cookies collection and have it written out to the browser, you call the Response.Cookies.Add method. The Cookies property of the Page.Response property is of the type HttpCookieCollection. You add instances of HttpCookie to this collection. The HttpCookie object simply contains a Name property and a Value property. The following code shows how you might add an item to the cookies collection:



Response.Cookies.Add(New HttpCookie("userId", userId))

To retrieve a cookie sent back by the Web browser, you read the values in the Request. Cookies collection. The following shows an example of this code:

Request.Cookies("userId").Value

As a larger example, the following sample code in a Page_Load event handler demonstrates both defining and reading cookie values by setting a cookie named lastVisit to the current time. If the user already has the cookie set, the code displays in the Label1 control the time the user last visited the page.

//check if cookie exists, and display it if it does
if (Request.Cookies["lastVisit"] != null)
//encode the cookie in case the cookie contains client-side script
Label1.Text = Server.HtmlEncode(Request.Cookies["lastVisit"].Value);
else
Label1.Text = "No value defined";
//define the cookie for the next visit

Response.Cookies["lastVisit"].Value = DateTime.Now.ToString();
Response.Cookies["lastVisit"].Expires = DateTime.Now.AddDays(1);

The first time the user visits the page in the previous example, the code displays “No value defi ned” because the cookie has not yet been set. However, if you refresh the page, it displays the time of the fi rst visit.
Note that the code sample defi nes the Expires property for the cookie. You must defi ne the Expires property and set it for the time period you would like the client to store the cookie if you want the cookie to persist between browser sessions. If you do not defi ne the Expires property, the browser stores the cookie in memory and the cookie is lost if the user closes his or her browser. To delete a cookie, you overwrite the cookie and set an expiration date in the past. You cannot directly delete cookies because they are stored on the client’s computer.


Controlling Cookie Scope :

Cookies should be specifi c to a given Web site’s domain or a directory within that domain.The information in cookies is typically specifi c to that site and often private. For this reason a browser should not send your cookie to another site. By default, browsers will not send your cookie to a Web site with a different host name (although, in the past, vulnerabilities in
browsers have allowed attackers to trick a browser into submitting another Web site’s cookie).

You have control over a cookie’s scope. You can limit the scope to either a specifi c directory on your Web server or expand the scope to the entire domain. The scope of your cookie determines which pages have access to the information embedded in the cookie. If you limit the scope to a directory, only pages in that directory will have access to the cookie. You control cookie scope on a per-cookie basis. To limit the scope of a cookie to a directory, you
set the Path property of the HttpCookie class. The following shows sample code for doing just that:

Response.Cookies["lastVisit"].Value = DateTime.Now.ToString();
Response.Cookies["lastVisit"].Expires = DateTime.Now.AddDays(1);
Response.Cookies["lastVisit"].Path = "/MyApplication";

With the scope limited to “/MyApplication”, the browser submits the cookie to any page in the /MyApplication folder. However, pages outside of this folder do not get the cookie, even if they are on the same server.
To expand the scope of a cookie to an entire domain, set the Domain property of the HttpCookie class. The following code demonstrates:

Response.Cookies["lastVisit"].Value = DateTime.Now.ToString();
Response.Cookies["lastVisit"].Expires = DateTime.Now.AddDays(1);
Response.Cookies["lastVisit"].Domain = "contoso.com";

Setting the Domain property to “contoso.com” causes the browser to submit the cookie to any page in the contoso.com domain. This might include those pages that belong to the sites www.contoso.com, intranet.contoso.com, or private.contoso.com. Similarly, you can use the Domain property to specify a full host name, limiting the cookie to a specific server.


Storing Multiple Values in a Cookie :

The size of your cookie is dependent on the browser. Each cookie can be up to a maximum of 4 KB in length. In addition, you can typically store up to 20 cookies per site. This should be more than sufficient for most sites. However, if you need to work around the 20-cookie limit, you can store multiple values in a single cookie by setting the given cookie’s name and its key value. The key value is usually not used when storing just a single value. However, if you need multiple values in a single named cookie, you can add multiple keys. The following code shows an example:

Response.Cookies["info"]["visit"].Value = DateTime.Now.ToString();
Response.Cookies["info"]["firstName"].Value = "Tony";
Response.Cookies["info"]["border"].Value = "blue";
Response.Cookies["info"].Expires = DateTime.Now.AddDays(1);

Running this code sends a single cookie to the Web browser. However, that cookie is parsed to form three values. ASP.NET then reads these three values back in when the cookie is submitted back to the server. The following shows the value sent to the Web browser:

Cookie properties, such as Expires, Domain, and Path, apply for all the values within a single cookie. You cannot control these at the individual key value. Rather, they are controlled at the cookie (or name) level. You can access the individual values of a cookie using Request.Cookies in the same way you define the values (using both name and key).

User Control in ASP.NET

User Control in ASP.NET :

Definition :
A user control is a file you create that contains a set of other ASP.NET controls and code grouped together to provide common functionality.
The user control can then be used on different pages within a Web site.
User controls in ASP.NET are created as .ascx fi les. An .ascx fi le is similar to the Web page’s .aspx fi le and can have its own code-behind page.


Create User Control :

Step 1:
First Create a new Web site called SampleUserControl using your C# programming language.

Step 2:
Add a user control to the site: Right-click the Web site and choose Add New Item. In the Add New Item dialog box, select Web User Control. Name the user control addressusercontrol.ascx.

Step 3:
Open the user control and add input elements for address, city, state, and zip code.
Your control markup should look similar to the following:

<div>
Address
<br />
< asp:TextBox ID=”TextBoxAddress” runat=”server” Width=”275px”
Height=”80px” TextMode=”MultiLine”></asp:TextBox>
<div style=”width: 280px”>
<div style=”float: left; margin-right: 3px”>
City
<br />
<asp:TextBox ID=”TextBoxCity” runat=”server” Width=”150”></asp:TextBox>
</div>
<div style=”float: left; margin-right: 3px”>
State
<br />
<asp:TextBox ID=”TextBoxState” runat=”server” Width=”30”></asp:TextBox>
</div>
<div style=”float: left”>
Zip
< br />
<asp:TextBox ID=”TextBoxZip” runat=”server” Width=”70”></asp:TextBox>
</div>
</div>
<asp:Button ID=”ButtonSave” runat=”server” Text=”Save” />
</div>


Step 4:
Open the code-behind fi le and add properties to expose the Text property of the user control’s TextBox controls. Your code should look similar to the following:

public string Address
{
get { return TextBoxAddress.Text; }
set { TextBoxAddress.Text = value; }
}
public string City
{
get { return TextBoxCity.Text; }
set { TextBoxCity.Text = value; }
}
public string State
{
get { return TextBoxState.Text; }
set { TextBoxState.Text = value; }
}
public string Zip
{
get { return TextBoxZip.Text; }
set { TextBoxZip.Text = value; }
}

Step 5:
Next, you will defi ne the event handler for the Save button. This event will raise an event to the host of the user control. Given that the user control already exposes properties for reading its values, the event will not pass them as an argument; it will simply raise a generic event.
If using C#, start by adding a delegate to the user control. Add the delegate to the code-behind file but outside the class. Your delegate should look as follows:

public delegate void SaveButtonClickHandler(object sender, EventArgs e);

Next, add the event declaration to the user control’s code-behind class file. This codeshould read as follows:

public event SaveButtonClickHandler SaveButtonClick;

Finally, add code to the button’s click event that raises this event. The following is an example:

protected void ButtonSave_Click(object sender, EventArgs e)
{
if (SaveButtonClick != null)
{
SaveButtonClick(this, new EventArgs());
}
}

Step 5:
Compile your code and make sure there are no errors.

Use the User Control on Web Page :

Step 1:
Continue editing the project you created in the previous exercise.

Step 2:
Open the Default.aspx page in Design view. While in Design view, drag AddressUser-Control.ascx to the page from Solution Explorer.
Review the page’s source. Notice that you can initialize the control’s custom properties through markup. The properties are also available in the Properties window when in Design view.

Step 3:
Add an event handler to trap the event fi red by the user control when a user clicks the Save button. Open the Default.aspx page’s code-behind file.

In C#, you need to fi rst add a method to the page. This method should have the same signature as the event exposed by the user control. You then need to wire up the event from the user control to the newly defi ned method. You can do this inside the page’s Init method.

The following code shows an example:

protected void Page_Init(object sender, EventArgs e)
{
AddressUserControl1.SaveButtonClick += this.AddressSave_Click;
}
protected void AddressSave_Click(object sender, EventArgs e)
{

}

Step 4:
You now need to add code to the intercepted event. For this example, this code will simply take the user’s input and write it out to the debug window.
The following shows an example:


protected void AddressSave_Click(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine(“Address: " +
AddressUserControl1.Address +
" City: " + AddressUserControl1.City +
" State: " + AddressUserControl1.State +
" Zip: " + AddressUserControl1.Zip);
}






Step 5:
Finally, run the application in debug mode to view the results. (You must enable script debugging in your browser.) Enter address information in the user control.
Click the Save button. Return to Visual Studio and view the Output window to see the results of the trapped Save button’s event.