Isolated Storage

Windows Phone From Scratch #30

 

An essential ingredient in storing the state of your application, especially when IsoStorage your application may be tombstoned or, even more extreme, closed, is the ability to create persistent storage – that is to write to the disk so that you can retrieve your data when the application resumes or is restarted.

This is the purpose of Isolated Storage.   The term is nearly self-explanatory; this is persistent storage that is isolated from the storage used by all other applications, and further, it is isolated from the operating system itself. It is therefore very safe.

[ Click on image for full size ]

There are a number of ways to store data to Isolated Storage.  In keeping with the previous posting, we’ll focus on the mechanism for storing the state of your page or application.  In this case what we want to store is key/value pairs. 

You can store these pairs in the ApplicationSettings collection of the IsolatedStorageSettings object.  This is, essentially, a dictionary that is unique to your application and that is stored on the device securely isolated from all other similar storage.

To see this at work, create a new application with a couple text boxes and a button and a list box as shown in the illustration above.  The first text box will capture the key, the second the value. 

To begin, you’ll need a member variable to represent Isolated Storage,

private IsolatedStorageSettings _isoSettings;

You’ll need to add the appropriate using statement for IsolatedStorageSettings to be recognized,

using System.IO.IsolatedStorage;

 

There are two events you want to capture:

  • The click of the Save button
  • The SelectionChanged event on the list box

The Save Button saves new key/value pairs or updates existing key/value pairs.

Clicking an entry in the list raises SelectionChanged, which makes the selected key current and populates the Key and Value TextBoxes

Let’s start with the Save_Click event handler.  The tasks here are

  1. Make sure we have both a key and a value to add
  2. See if the key exists, if so update it
  3. If the key does not exist, add it

Here is the code for the event handler,

void Save_Click( object sender, RoutedEventArgs e )
{
   if ( String.IsNullOrEmpty( Key.Text ) || 
      String.IsNullOrEmpty( Value.Text ) )
      return;

   if ( _isoSettings.Contains( Key.Text ) )
      _isoSettings[Key.Text] = Value.Text;
   else
      _isoSettings.Add( Key.Text, Value.Text );
   RebindKeys();
}

Adding to or updating the isolated storage itself is as simple as managing a dictionary; the actual business of writing to disk is handled for you by the IsolatedStorageSettings object.

Notice that the method ends with a call to RebindKeys – the job of that method is just to rebuild the list box,

private void RebindKeys()
{
   Value.Text = Key.Text = String.Empty;
   Keys.Items.Clear();
   foreach ( string key in _isoSettings.Keys )
   {
      ListBoxItem lbi = new ListBoxItem();
      string newKey = key + ": " + _isoSettings[key];
      Keys.Items.Add( newKey );
   }
}

I’ve chosen to list both the key and its value.  This makes the workings of the project a bit easier to understand but it does complicate, slightly, the handler for clicking on an entry in the list box,

void Keys_SelectionChanged( object sender, 
   SelectionChangedEventArgs e )
{
   if ( e.AddedItems.Count < 1 )
      return;
   string selected = e.AddedItems[0].ToString();
   string key = selected.Substring( 
      0, selected.IndexOf( ":" ) );
   Key.Text = key;
   Value.Text = _isoSettings[key].ToString();
}

The small amount of extra work is to isolate the key from the colon and the value; with this in hand we can proceed to populate the Key TextBox as well as the Value TextBox. 

Persistance

Notice that after you add a key/value pair, you can change applications or stop debugging altogether and then restart to find the values have been saved (persisted) and are restored just as you left them.

 

The complete source code is available here

Share

About Jesse Liberty

Jesse Liberty is an independent consultant and programmer with three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight courses, and has been a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP, Microsoft MVP and Telerik MVP.
This entry was posted in Patterns & Skills. Bookmark the permalink.

4 Responses to Isolated Storage

  1. ilham says:

    thanks for your tutorial …
    but i have 3 textbox here and i try to implent it to event Save_Click()
    and it’s not work i’ve an error …
    ‘No Overload for method ‘Add’ takes 3 argument’

    void Save_Click_Income(object sender, RoutedEventArgs e)
    {
    var toDate = Convert.ToString(incomedate.Value);
    string income = toDate + ” : ” + incomedate.Value;
    if (String.IsNullOrEmpty(inputamount.Text) || String.IsNullOrEmpty(deskripsi.Text))
    return;
    if (isoSettings.Contains(inputamount.Text) && isoSettings.Contains(toDate))
    isoSettings[inputamount.Text] = deskripsi.Text = toDate;
    else
    isoSettings.Add(income, deskripsi.Text, toDate); //here’s the error come
    RebindKeysIncome();
    }

    i hope you can help
    thanks before

  2. Samuel Blanchard says:

    Hi Jesse,

    Thanks for your very clear article.

    I’ve created a small, free and opensource tool to explore IsolatedStorage without installing anything on the phone. It’s very easy ton ensure a file is well written in Isolated Storage.
    http://isostorespy.codeplex.com/

  3. henry tomas says:

    Isolatedstoragesettings is very slow to my experience (atleast on the phone). I would rather suggest using as less overhead as possible because performance is a big issue on wp7. I mostly use Binarystreams.

    Cheers!

  4. Pingback: Tweets that mention Isolated Storage | Jesse Liberty -- Topsy.com

Leave a Reply

Your email address will not be published.