Cookie in Silverlight Through JavaScript


My doggie love cookies, I love my doggie, this implies I love cookies. Ah! A 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 sometimes 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:
  1. <script type="text/javascript">    
  2. function SayHello() {    
  3.     alert("Hello!");    
  4. }    
  5. </script>    
Now on the mainpage.cs inside the 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 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.
  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 the mainpage, call the function SetCookie as:
  1. 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.
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 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.
  1. private void ButtonGet_OnClick(object sender, RoutedEventArgs e) {    
  2.   var cookie = HtmlPage.Window.Invoke("GetCookie""Name");    
  3.   if (cookie == null) {    
  4.     MessageBox.Show("No cookie found");    
  5.     return;    
  6.   }    
  7.   MessageBox.Show(cookie.ToString().Split('=').LastOrDefault());    
  8. }    
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 through 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 calls this function as:
  1. private void ButtonDelete_OnClick(object sender, RoutedEventArgs e) {  
  2.   HtmlPage.Window.Invoke("DeleteCookie""Name");  
  3. }  
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".