Cookie in Silverlight Through JavaScript

In this process we follow, we will be accessing JavaScript's function from silverlight. This sometime becomes headache for most developers, but you should not worry, you are reading “my post.”

My doggie love cookies, I love my doggie, this implies I love cookies. Ah! Bad joke is it? Never mind, you will be reading more about me and my bad jokes throughout my articles. That doesn't mean you should stop reading them and go away…after all they are very informative and cool. Anyways, over with the jokes.

Cookies are data stored by the web browser, as simple as that. You can save anything; yes I said anything, in cookies. We can also do this through Silverlight itself, but for fun let's try doing it with JavaScript. In this process we follow, we will be accessing JavaScript's function from Silverlight. This sometime becomes a headache for most developers, but you should not worry, you are reading "my article".

The First Step

The first step towards setting cookies through JavaScript, is to call the JavaScript function from Silverlight. Calling a JavaScript function from Silverlight is very easy. To understand this, and more forthcoming things, create a new Silverlight application "JavaScriptTweaks". Open JavaScriptTweaksTestpage.aspx, and add the following code somewhere inside the <head> tag:

<script type="text/javascript">
  
 function SayHello()
   {
        alert(
"Hello!");
   }

</script>

Now in the mainpage.cs inside the constructor add the following line:

HtmlPage.Window.Invoke("SayHello");

Okay, what we have done so far is, we have created a JavaScript function SayHello and called it from Silverlight. When you run the application, what you will see is a message box that pops up saying Hello at the very beginning of the application. Congratulations! You've just learned how to call a JavaScript function from Silverlight.

The Second Step

You might be so happy after completing the first step. And that's no problem indeed. The actual problem is that the next step is a little bit complex. It's the Cookie functions.

Setting Cookie

Remove the SayHello function from the JavaScript we wrote previously and add the following function instead.
 

function SetCookie(cookieName, cookieValue, Days)

{           

    var todayDate = new Date();

    var expireDate = new Date();

    if (Days == null || Days == 0) Days = 1;

    expire.setTime(todayDate.getTime() + 3600000 * 24 * Days);

    document.cookie = cookieName + ":" + cookieValue

    + ";expires=" + expireDate.toGMTString();          

}

And instead of calling SayHello from the mainpage, call the function SetCookie as:

HtmlPage.Window.Invoke("SetCookie", "Name", "Neelma", 5);

Here's the description. What the code above does is to call the function SetCookie with the parameters cookieName "Name", cookieValue "Neelma" and validity, in other words Days as "5".

Line #5 of the function will set the expiry time period of cookies, which is in milliseconds and is about 432000000 for 5 days. Line #6 of the function will set the cookie's information like, its Name, Value and Expiry date. So, our cookie is set to give information.

Getting Cookie

Next is the retrieval of information. Well, let's do one thing. Create 3 buttons in the XAML of the main page, one for each setcookie, getcookie and deletecookie.

Cookies-in-Silverlight.jpg

Copy the function written on the main page to the click event of the SetCookie Button.

Now for retrieving the cookie here is the code:
 

function GetCookie(cookieName)

{

   var allcookies = document.cookie;

   // Get all the cookies in an array

   var cookiearray = allcookies.split(';');

   for (var i = 0; i < cookiearray.length; i++)

   {

       var nameOfCookie = cookiearray[i].split('=')[0];

       if (cookieName == nameOfCookie)

       {

           return cookiearray[i];

    }

 }

           return null;

}

Just pass in the cookie name (which in our case is "Name") and the function will return the entire cookie. In the GetCookie button click event of course, we need to call this function. Here's what I have in my code.
 

private void ButtonGet_OnClick(object sender, RoutedEventArgs e)

{

    var cookie = HtmlPage.Window.Invoke("GetCookie", "Name");

    if (cookie == null)

    {

        MessageBox.Show("No cookie found");

        return;

    }

    MessageBox.Show(cookie.ToString().Split('=').LastOrDefault());

}


This will pop up a message box, showing the value of the cookie specified. Since I have my cookie as "name=Neelma" it shows me "Neelma".

Deleting Cookie

Finally comes the deletion of a cookie. Which is pretty simple, you just need to set the expiry date to a previous date; that can be done thorugh JavaScript's function as follows:

function DeleteCookie(cookieName)

{

    var exp = new Date();

    exp.setTime(exp.getTime() - 1);

    document.cookie = cookieName + "=;expires=" + exp.toGMTString();

}


In the delete button click event call this function as:

private void ButtonDelete_OnClick(object sender, RoutedEventArgs e)

{

    HtmlPage.Window.Invoke("DeleteCookie", "Name");

}

Pass in the name of the cookie you want to delete and bang! It will be deleted. Now just try this. Click on SetCookie, it will set the cookie for you. Now click on GetCookie to verify whether it did set a cookie or not, you should see the value of the cookie in the message box. Click on Deletecookie to delete the cookie. Finally click on Getcookie button again, if everything worked fine then you should see a message in the message box saying: "No cookie found".