Tip: operate cookies in a Silverlight Application

Source: Internet
Author: User
Tags setcookie
Overview

Many of my friends wrote to ask me how to operate cookies in Silverlight 2. Here I will write a special article to introduce it. To implement Cookie operations in the Silverlight application, we need to use the HtmlPage. Document Object.

Before using HtmlPage. Document, add the System. Windows. Browser namespace. This article describes how to operate on cookies in a Silverlight application, and provides a public class to operate on cookies. You can use them directly in your own application.

Write Cookie

In the Silverlight application, we can use the HtmlPage. Document. SetProperty method to set the Cookie or use the Cookie attribute of the HtmlPage. Document Object (as described later). The following code is used:

void btnSet_Click(object sender, RoutedEventArgs e){    DateTime expir = DateTime.UtcNow + TimeSpan.FromDays(7);    String cookie = String.Format("{0}={1};expires={2}",    this.txtKey.Text,    this.txtValue.Text,     expir.ToString("R"));    HtmlPage.Document.SetProperty("cookie", cookie);}

Set the Cookie expiration time to one week. In addition to setting the expiration time, you can also set domain and path. You will see this in the help class below.

For example, use the following interface to write a Cookie:

 

Read Cookie

We can use HtmlPage. document. the GetProperty method is used to obtain all Cookies. In addition, the Cookie attribute is defined in HtmlDocument. The GetProperty method has been encapsulated for us and can be directly used. Its definition is as follows:

public sealed class HtmlDocument : HtmlObject{    public string Cookies    {        get{            HtmlPage.VerifyThread();            String property = this.GetProperty("cookie") as String;            if (property != null)            {                return property;            }            return String.Empty;        }        set{            HtmlPage.VerifyThread();            String str = value;            if (String.IsNullOrEmpty(str))            {                str = string.Empty;            }            this.SetProperty("cookie", str);        }    }}

Use the following code to obtain the Cookie value of a specified Key:

void btnRetrieve_Click(object sender, RoutedEventArgs e){    String[] cookies = HtmlPage.Document.Cookies.Split(';');    foreach (String cookie in cookies)    {        String[] keyValues = cookie.Split('=');        if (keyValues.Length == 2)        {            if (keyValues[0].Trim() == this.txtKey.Text.Trim())            {                this.txtValue.Text = keyValues[1];            }        }    }}

As shown in:

Delete Cookie

It is very easy to delete a Cookie. Clear the Cookie value and set its expiration time, as shown in the following code:

void btnDelete_Click(object sender, RoutedEventArgs e){    DateTime expir = DateTime.UtcNow - TimeSpan.FromDays(1);    string cookie = String.Format("{0}=;expires={1}",        this.txtKey.Text, expir.ToString("R"));    HtmlPage.Document.SetProperty("cookie", cookie);}
Cookie help class

Since we may often use Cookie operations during development, I have summarized a simple Silverlight help class for Cookie operations, which can be directly used in our own projects, it has the following functions:

1. Write Cookie

2. Read Cookie

3. delete a Cookie

4. Determine whether the Cookie exists

Of course, if you have other requirements, you can further improve the Code. The complete code is as follows:

public class CookiesUtils{    public static void SetCookie(String key, String value)    {        SetCookie(key, value, null, null, null, false);    }    public static void SetCookie(String key, String value, TimeSpan expires)    {        SetCookie(key, value, expires, null, null, false);    }    public static void SetCookie(String key, String value, TimeSpan? expires,        String path, String domain, bool secure)    {        StringBuilder cookie = new StringBuilder();        cookie.Append(String.Concat(key, "=", value));        if (expires.HasValue)        {            DateTime expire = DateTime.UtcNow + expires.Value;            cookie.Append(String.Concat(";expires=", expire.ToString("R")));        }        if (!String.IsNullOrEmpty(path))        {            cookie.Append(String.Concat(";path=", path));        }        if (!String.IsNullOrEmpty(domain))        {            cookie.Append(String.Concat(";domain=", domain));        }        if (secure)        {            cookie.Append(";secure");        }        HtmlPage.Document.SetProperty("cookie", cookie.ToString());     }    public static string GetCookie(String key)    {        String[] cookies = HtmlPage.Document.Cookies.Split(';');        String result = (from c in cookies                        let keyValues = c.Split('=')                        where keyValues.Length == 2 && keyValues[0].Trim() == key.Trim()                        select keyValues[1]).FirstOrDefault();        return result;    }    public static void DeleteCookie(String key)    {        DateTime expir = DateTime.UtcNow - TimeSpan.FromDays(1);        string cookie = String.Format("{0}=;expires={1}",            key, expir.ToString("R"));        HtmlPage.Document.SetProperty("cookie", cookie);    }    public static bool Exists(String key, String value)    {        return HtmlPage.Document.Cookies.Contains(String.Format("{0}={1}", key, value));    }}

Summary

This article describes how to operate cookies in Silverlight applications.

Download the sample code and CookiesUtils code in this article:

For more information about Silverlight 2, see Silverlight 2.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.