Archive for the ‘ CSS ’ Category

Create and Read Cookies in ASP.NET


Cookies are small pieces of text which are created by websites and stored by the Internet browser in its cache for later use. Typically a cookie would contain information related to a surfer’s session in a particular website, such as the user name, items in a shopping cart, page layout preferences, etc.

When a surfer visits a website, a cookie would be created with his details, and when he returns to the site his details are loaded from the cookie and sent to the website. This can for example, allow the website to identify who the surfer is and load his last session back.

Cookies can be very useful but they are also easily accessible so it’s advisable to never store sensitive data, such as passwords or credit card numbers, in cookies.

In this short article I am going to show you how to create a cookie in ASP.NET, obviously using C#, and then I will also show you how to read your cookie’s value.

First you must create an ASP.NET Web Application, and once that’s done add two buttons and a label to your Default.aspx web form. The first button we will call“Save Cookie” and the second one “Load Cookie”. The label will be used to display the status on-screen.

In the event handler for the “Save Cookie” button we will create a cookie and add astring value to it. The code should look like this:

protected void btnSave_Click(object sender, EventArgs e)
{
    // Create a cookie object
    HttpCookie cookie = new HttpCookie("TestCookie");

    // Set the cookie's value
    cookie.Value = "Paul Mercieca";

    // Set the cookie's expiration date
    cookie.Expires = DateTime.Now.AddDays(7);

    // Add the cookie to the cookie collection
    Response.Cookies.Add(cookie);

    // Display the status
    lblStatus.Text = "Cookie has been created.";
}

The above code is quite simple. We are creating a cookie called “TestCookie” and assigning it my name as a value. Then we are setting an expiry date of 7 days for the cookie. This means that the cookie will remain valid for 7 days from creation. When that period expires the cookie will be deleted by the web browser. Finally we are adding our new cookie to the Response.Cookies collection which is actually an instance of HttpCookieCollection, and we are setting the status label’s text.

Now to read the cookie. To do this we need to access the HttpCookieCollection instance again by calling Request.Cookies as can be seen in the below code:

protected void btnLoad_Click(object sender, EventArgs e)
{
    // Retrieve the cookie from the cookie collection
    HttpCookie cookie = Request.Cookies["TestCookie"];

    // Verify the cookie exists
    if (cookie != null)
    {
        lblStatus.Text = string.Format("Hello {0}", cookie.Value.ToString());
    }
    else
    {
        lblStatus.Text = "Cookie not found.";
    }
}

Again, this code is very straight forward. All we are doing here is retrieving the “TestCookie” and verifying it exists. If it exists we are displaying the cookie’s value, which in this case is my name – “David Azzopardi”, and if it does not exist we are displaying “Cookie not found”.

And there you have it – creating and reading cookies with C# in ASP.NET.

Dynamically Setting a Style at Run-Time in ASP.NET


Trolling the ASP.NET forums this week I came across a good question, “setting the background on a master page div at run-time?”. Even though the person posted he found an acceptable solution before I posted my response, I think the user has a complicated solution. Mostly because he is using themes, but nonetheless. I posted my answer and thought I would share it here.

A nice feature of CSS is the ability to assign multiple classes to can DOM element via the class attribute. This opens up the possibility to dynamically set a class assignment based on some logic as the page is being rendered. The example below demonstrates having a common style rule and a rule added at run-time. Of course you are not limited to this methodology, there are many ways to apply styles to an element.

<div class="contentBox bkg1">...</div>

I find the easiest way to set something like a dynamic style at run-time is to define a public method in the page class to return the desired rule. For my demonstration I will return a style rule name based on a QueryString parameter, but you can use all sorts of criteria. I also chose to apply the rule to the Body tag.

public string GetBackgroundClass()
{
    switch ( Request.QueryString["bkg"])
    {
        case "1":
            return "bkg1";
        case "2":
            return "bkg2";
        case "3":
            return "bkg3";
        default:
            return "bkg1";
    }
}

The style rules just set the color as follows, a nice egg shell (at least that is what I call it), red and blue.

.bkg1
{
    background-color: #FFFFCC;
}

.bkg2
{
    background-color: #C30000;
}

.bkg3
{
    background-color: #0000CC;
}

Finally I just inline the call to the method in the HTML markup:

<body class="<%=GetBackgroundClass() %>">

The result as I pass in different values to the page:

Egg Shell:

Red:

Blue: