Cookies in Silverlight, through JavaScript

Cookie in silverlight, through JavaScript

My doggie love cookies, I love my doggie, this implies I love cookies. Ah! bad joke is it? Never mind, you will be reading a lot of me and my bad jokes through out the posts on my blog. That doesn't mean you should stop reading them and go away…after all they are very informative and cool. Winking smile Anyways jokes apart.

Cookies are the data stored in 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 headache for most developers, but you should not worry, you are reading “my post.”

The First Step:

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

   1: <script type="text/javascript">
   2:         function SayHello() {
   3:             alert("Hello!");
   4:         }
   5: </script>

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

   1: 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 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 real man's thing, the Cookie functions.

Setting Cookie

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

   1: function SetCookie(cookieName, cookieValue, Days) {            
   2:    var todayDate = new Date();
   3:    var expireDate = new Date();
   4:    if (Days == null || Days == 0) Days = 1;
   5:    expire.setTime(todayDate.getTime() + 3600000 * 24 * Days);
   6:    document.cookie = cookieName + ":" + cookieValue
   7:         + ";expires=" + expireDate.toGMTString();           
   8: }

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

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

Here's the description. What above code do, is to call function SetCookie with the parameters cookieName as “Name”,cookieValue as “Neelma”, and validity i.e. 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 comes then 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.

image


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:

   1: function GetCookie(cookieName) {
   2:     var allcookies = document.cookie;
   3:     // Get all the cookies in an array
   4:     var cookiearray = allcookies.split(';');
   5:     for (var i = 0; i < cookiearray.length; i++) {
   6:         var nameOfCookie = cookiearray[i].split('=')[0];
   7:         if (cookieName == nameOfCookie) {
   8:             return cookiearray[i];
   9:         }
  10:     }
  11:     return null;
  12: }

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

   1: private void ButtonGet_OnClick(object sender, RoutedEventArgs e)
   2: {
   3:    var cookie =  HtmlPage.Window.Invoke("GetCookie", "Name");
   4:     if (cookie == null)
   5:     {
   6:         MessageBox.Show("No cookie found");
   7:         return;
   8:     }
   9:     MessageBox.Show(cookie.ToString().Split('=').LastOrDefault());
  10: }

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 cookie. Which is pretty simple, you just need to set the expiry date to previous date which can be done thorugh javascript's function as follows:


   1: function DeleteCookie(cookieName) {
   2:    var exp = new Date();
   3:    exp.setTime(exp.getTime() - 1);
   4:    document.cookie = cookieName + "=;expires=" + exp.toGMTString();
   5: }

In the delete button click event call this function as:

   1: private void ButtonDelete_OnClick(object sender, RoutedEventArgs e)
   2: {
   3:    HtmlPage.Window.Invoke("DeleteCookie", "Name");
   4: }

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 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, you should see a message in the message box saying – “No cookie found”.

Next Recommended Reading Clock in Silverlight With C#