Silverlight Tips of the Day - Blog by Mike Snow

Game Programming with Silverlight

Silverlight Tip of the Day #18: How to Set Browser Cookies.

Cookies are strings of text that the server can store on the client side. These cookies can then be sent back by the client to the server each time the client accesses that server again. Cookies are commonly used for session tracking, authentication, site preferences and maintaining specific information about users.  For example, items a client stores in a shopping cart can be stored on the client side as cookies so that they can leave the online store and return later to check out.

So, how do we set cookies from within a Silverlight application? To accomplish this we turn again to the HtmlPage.Document object. To use this object you must add a using statement to reference the System.Windows.Browser namespace.

To set a cookie we need to call SetProperty() with a string in the following format: “Key=Value;expires=ExpireDate.”

For example:

private void SetCookie(string key, string value)
{
    // Expire in 7 days
    DateTime expireDate = DateTime.Now + TimeSpan.FromDays(7);
 
    string newCookie = key + "=" + value + ";expires=" + expireDate.ToString("R");
    HtmlPage.Document.SetProperty("cookie", newCookie);
}

Now, to get the cookie we split up and iterate through all the cookies returned through the property HtmlPage.Document.Cookies.

For example:

private string GetCookie(string key)
{
    string[] cookies = HtmlPage.Document.Cookies.Split(';');
 
    foreach (string cookie in cookies)
    {
        string [] keyValue = cookie.Split('=');
        if (keyValue.Length == 2)
        {
            if(keyValue[0].ToString() == key)
                return keyValue[1];
        }
    }
    return null;
}

For more details on additional properties you can set when creating cookies please see MSDN.

Thank you,
--Mike Snow

 Subscribe in a reader

Comments

Microsoft Weblogs said:

Cookies are strings of text that the server can store on the client side. These cookies can then be sent

# July 15, 2008 6:34 PM

BenHayat said:

Mike, firstly I like to thank you for these great Tips you provide. They are very valuable!

Secondly, what would be the advantage of using Cookies v.s. IsolatedStorage, whereas the cookies can be cleared by the user!

Thanks!

..Ben

# July 15, 2008 8:58 PM

chrisaswain said:

Wish you'd had this post up a couple of days ago.  I just had to use code very much like this to get/set a username cookie for my Tank Wars game.  I'm using the AuthenticationServices to handle my silverlight security, but you can't register through the services.  So I had to redirect the users to a new aspx page that uses the registration control, then redirects them back to the silverlight page.  The problem I ran into was that the silverlight app could see that the user was logged in, but I could find a way to get the username.  That's where the username cookie comes in.  

# July 15, 2008 9:06 PM

mike.snow said:

BenHayat- Cookies are good for small sets of data since they are more straight forward to use. For larger sets of data I would use IsolatedStorage (IS). I'll do a blog next on the adv. and disadvantages of IS but one example is that with IS administrators can set quoates whichs means there is no guarantee of the size available.

# July 15, 2008 11:22 PM

itsmallmouse said:

Thanks! But how to set cookies with Unicode character in Silverlight?

# July 16, 2008 2:56 AM

jhoffa said:

So after you use SetProperty to set "cookie", should you see your cookie in HtmlPage.Document.Cookies?

Any idea how you'd be able to see the resulting cookie in a self hosted WCF service?

# July 16, 2008 10:44 AM

Dew Drop - July 16, 2008 | Alvin Ashcraft's Morning Dew said:

Pingback from  Dew Drop - July 16, 2008 | Alvin Ashcraft's Morning Dew

# July 16, 2008 11:05 AM

mike.snow said:

Itsmallmouse - There is no Unicode support sorry.

Jhoffa - Yes, after you set it it should show up in HtmlPage.Document.Cookies. Make certain you set the expiration date.

From a WCF service, check out the class HttpCookie: msdn.microsoft.com/.../system.web.httpcookie.aspx

# July 16, 2008 12:08 PM

jackbond said:

Life is better with a little LINQ.

return (from z in cookies

let y = z.Split('=')

where y.Length == 2 && y[0] == key

select y[1]).FirstOrDefault();

Some additional cookie info here as well:

silverlight.net/.../38621.aspx

# July 16, 2008 1:58 PM

Mike Snows Silverlight Blog said:

Silverlight uses Isolated Storage as a virtual file system to store data in a hidden folder on your machine

# July 16, 2008 2:08 PM

Mirrored Blogs said:

Post: Approved at: Jul-16-2008 File Dialog and more! Here is a great screencast on Channel 9 showing

# July 16, 2008 2:12 PM

Visual Web Developer Team Blog said:

6 new Silverlight tutorials are completed! Tip of the Day #15 - Communicating between JavaScript &

# July 17, 2008 5:19 PM

Visual Web Developer Team Blog said:

6 new Silverlight tutorials are completed! Tip of the Day #15 - Communicating between JavaScript &

# July 17, 2008 5:19 PM

Pietro Brambati Blog said:

Updated 18/7/2008 Percorso formativo in italiano Aggiornamento del percorso formativo su Silverlight

# July 18, 2008 8:21 AM

Pietro Brambati Blog said:

Updated 18/7/2008 Percorso formativo in italiano Aggiornamento del percorso formativo su Silverlight

# July 18, 2008 8:27 AM

Silverlight - Tip of the Day by Mike Snow at Blog von J??rgen Ebner said:

Pingback from  Silverlight - Tip of the Day by Mike Snow at Blog von J??rgen Ebner

# July 28, 2008 7:06 AM

Deepak's WebLog said:

When you create a Silverlight application the App.xaml.cs code behind file has the Application event

# August 11, 2008 5:35 PM

tzahis said:

Is the cookies saved in the browser relating to the current page? for example, what happens if I call HtmlPage.Document.Cookies from a difernet page, will I see the cookies set by the former one?

Thanks,

Tzahi.

# August 17, 2008 12:15 PM