IsolatedStorage and managed JavaScript

Michael Schwarz on Thursday, May 31, 2007

Today I tried to use the IsolatedStorage in managed JavaScript with Silverlight 1.1 [1]. The IsolatedStorage can be used to store data on the client. Currently the alpha version supports 1MB, which is more than storing data in cookies, but maybe will be changed in the future. Perhaps there will be a setting in a future options dialog where you can specify how much you will allow to store locally.

I used the files from my last post and modified the test.jsx. I added two methods: SetData(key, s) and GetData(key), both could be used to store up to 1MB.

function SetData(key, s) {

var isf = IsolatedStorageFile.GetUserStoreForApplication(); var fsm = <span class="kwrd">new</span> IsolatedStorageFileStream(key, FileMode.OpenOrCreate, isf);

fsm.SetLength(System.Int64.Parse(<span class="str">"0"</span>));

var sw = <span class="kwrd">new</span> StreamWriter(fsm); sw.Write(s);

sw.Close(); fsm.Close(); isf.Close(); }

function GetData(key) {

var isf = IsolatedStorageFile.GetUserStoreForApplication(); var fsm = <span class="kwrd">new</span> IsolatedStorageFileStream(key, FileMode.Open, isf);

var sr = <span class="kwrd">new</span> StreamReader(fsm); var s = sr.ReadToEnd();

sr.Close(); fsm.Close(); isf.Close();

<span class="kwrd">return</span> s; }</pre>

Problems with data types

During writing this small example I stumbled on some problems. Because there is no File.Delete method I tried to set the length of the file to zero.

<pre class="csharpcode"><span class="kwrd">if</span>(fsm.length &gt; 0) fsm.SetLength(System.Int64.Parse(<span class="str">"0"</span>));</pre>

Invoking this method throws an error that double could not be converter to Int64 (long). Hm, seems that Silverlight DLR is converting JavaScript numbers to double. Ok, then I used Int64.Parse("0") instead and it is working.

My second problem was how to decode the byte array back to a string. Encoding.Default.GetString needs a byte array (System.Byte[]) as first argument value. How to create a System.Byte[]? In the SetData method I looked at what I get back from the GetByte method, and it is really System.Byte[]. I searched around but couldn't get any help on how to create a new instance of an byte array.

To get a working demo I used String.fromCharCode instead, I know it is not the same, I need some more time to get the trick. Maybe it is not yet working in the alpha version.

Updated: I'm using now the StreamWriter and StreamReader... and I'm very happy that it is working as expected. But I'd like to know how to create a byte[] array, generics in JavaScript are not supported until now.

Example Files

Download files here [2].