Saving State in Microsoft Silverlight

Saving State in Microsoft Silverlight

Microsoft Silverlight is a platform for creating RIA (Rich Internet Applications). There can be only one page in your application but what if you need to create a whole site or some pages with Silverlight. Or, maybe, your are programming multiform out-of-browser application. This article will provide information about how to save current page information to restore it after or use this information in other pages of Sillverlight application.

You must know that all your created pages are XAML files with markup. Something like this:




Hi to you

But all our pages will be generated dynamically. So all information will be generated to. We cant declare some variable in .cs file of page and use it to store information. To solve this problem we must look at the App.xaml and App.xaml.cs files. Its a configuration files where determined resources for all pages and some events.
We need to create a static container for our information. Static – because we cant create a new instance of App configuration.


For instance, lets create Dictionary where the key will be our page name and value is string:


//In App.xaml.cs

//simple Dictionary with String-String pair
private static Dictionary pagedata = new Dictionary();

Some developers are using UserControl for value. Its a good answer in saving the whole page.

Next, we need to add some lines to OnNavigateTo() event

		//this procedure will be added when you will create new Page in your project
		protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //getting current page name is differs from one version to another. You can use NavigationEventArgs too. The most common is
           string currentPage= this.GetType().Name;
            //if key exists then we take the value
           if (App.pagedata.ContainsKey(currentPage))
            {
                 App.pagedata[currentPage]= textBox1.Text.Trim();  				
            } //else we are adding a new pair
			else
				App.pagedata.Add(currentPage,textBox1.Text);         								
        }

As use see it pretty easy. Don’t forget to save the information before restoring. It can be done before navigating to other pages.

Other very useful method is Cache navigated pages. Each Page has NavigationCacheMode property. It has 3 states: Disabled (no pages will be cached), Enabled (will be cached till count of pages is less then Frame.CacheSize porperty) and Required (when this page must be cached).

You can add this to the Page:

   this.NavigationCacheMode = System.Windows.Navigation.NavigationCacheMode.Required;

This will work only if you are navigating through the pages using Navigate(URI uri) in Frame. Here are some information about this method:

And the last method is Isolated storage of Microsoft Silverlight.
It a virtual file system, which allows to store data. We can create a lot of directories for the application but notice that by default the size of storage is limited to 1MB. But we can increase it easily.
Isolated storage is often used for keeping temporary data, application info and other. They are stored permanently (not like in Cache). Don’t use it to store media files or external images because this storage is for keeping only small portions of data.

How to access the storage?

We need to use IsolatedStorageFile class. More info about it here.
In instance, we want to create a new file:

		using System.IO.IsolatedStorage;
		using System.IO;

		/* other code  */

		  try
		{
		  using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
		{
			//creating a file stream
		   using (IsolatedStorageFileStream stream = store.CreateFile("new.txt"))
		   {
			  //simple StreamWriter
			  StreamWriter writer = new StreamWriter(stream);
			  writer.Write("Some text");
			  writer.Close();
		   }
		}
		}
		catch(Exception ex)
		{
		   MessageBox.Show(ex.Message);
		}  

You can find this file in C:Documents and Settings{Current user}Local SettingsApplication DataMicrosoftSilverlightis{a lot of IDs}.

To access that file we must do the same operations but we need to open existing file and use StreamReader

		using System.IO.IsolatedStorage;
		using System.IO;

		/* other code  */

		  try
		{
		  using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
		{
		   //checking file existance
		   if (store.FileExists("new.txt"))
			{
			  //creating a file stream
			 using (IsolatedStorageFileStream stream = store.OpenFile("new.txt",FileMode.Open))
			 {
				//simple StreamReader
				StreamReader reader = new StreamReader(stream);
				reader.Write("Some text");
				reader.Close();
			 }
			}
		}
		}
		catch(Exception ex)
		{
		   MessageBox.Show(ex.Message);
		}  

But that’s not all :). You can use XMLSerializer to serialize and deserialize objects by creating new XMLSerializer with type of serialized object.

Click here to download the Sample application for Saving State in Microsoft Silverlight.