Sunday, September 5, 2010

Cookies in silverlight

Hi all,

here i demonstrate how to set the cookies and get the values of the cookies and set the values of the cookies in the silverlight. for that i am making 2 function named GetCookie() and SetCookie().

in my project i have 2 textbox for the key and the value of the cookies then 1 button that set the value of the cookies by the key and then one button that show the cookies value by the key.

Note : For using the cookie, you have to add namespance “System.Windows.Browser”.

Step 1 : Create new silverlight project.

Step 2 : in mainpage.xaml file





Step 3 : my mainpage.xaml.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
namespace SilverlightCookies

{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}

private void SetCookie(string key, string value)

{

DateTime expireDate = DateTime.Now + TimeSpan.FromHours(1);

string newCookie = key + "=" + value + ";expires=" + expireDate.ToString("R");
HtmlPage.Document.SetProperty("cookie", newCookie);
}

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().Trim() == key.Trim())
return keyValue[1];
}
}
return null;
}

private void Button_Click(object sender, RoutedEventArgs e)

{
SetCookie(txtCookieskey.Text.Trim(), txtCookiesValue.Text.Trim());
LblCookies.Text = "Cookes has been Created";
}

private void Button_Click_1(object sender, RoutedEventArgs e)

{
LblDisplayCookies.Text = GetCookie(txtCookieskey.Text.Trim());
LblCookies.Text = "Display Cookies of " + txtCookieskey.Text;
}
}
}



Step 4 : Run the application…

for this you get 2 textbox and 2 button.

when i input the key and value in the textbox and press button of “Set Cookies”, it set the key of cookies by that value and when i click on “get Cookies” by typing key value in key textbox, it show me the value of the key in cookie.

No comments:

Post a Comment