Rants and Raves

Thanks for visiting my blog!

Using Isolated Storage Settings in Silverlight 2
Using Isolated Storage Settings in Silverlight 2
October 21, 2008

Silverlight Logo
Here is a quick but fun tip for working with Silverlight 2. I found that many people are using Isolated Storage for saving user preferences or other small pieces of information. When I look at the code, I am surprised by how much trouble they are going through to save small bits of data.  That’s where Isolated Storage Settings come in.

For example, let’s assume you want to be able to store a FavoriteColor for a user.  You could cruft up a bunch of code to save a file and handle the serialization, or you could use the IsolatedStorageSetting class. This class supports being able to store arbitrary objects in a settings file in Isolated Storage. The IsolatedStorageSettings class supports two keyed collections, ApplicationSettings and SiteSettings. ApplicationsSettings is specific to your .xap file, while SiteSettings are specific to your domain.  Here is an example of a property that uses the IsolatedStorageSettings to store a nullable Color for FavoriteColor:

const string FAVCOLORNAME = "favoriteColor";
public Color? FavoriteColor
{
  get
  {
    if (IsolatedStorageSettings.ApplicationSettings[FAVCOLORNAME] != null)
    {
      Color? colorSetting = 
        IsolatedStorageSettings.ApplicationSettings[FAVCOLORNAME] as Color?;
      if (colorSetting != null) return colorSetting;
    }

    // If we can't find a favorite color, return a null color
    return new Color?();
  }
  set
  {
    IsolatedStorageSettings.ApplicationSettings[FAVCOLORNAME] = value;
  }
}

```csharp

If you are familiar with ASP.NET, you'll probably see that the pattern here is similar to Cache or Session data.  The idea is the same.  You should always code this defensively as Isolated Storage maybe cleared or could be disabled by the user. In addition, you should be careful \*not\* to store sensitive data as the user can get access to files in Isolated Storage (though its hidden in a deep directory structure). So avoid saving sensitive data like connection strings or other sensitive information that you want to keep from the user.

HTH