Channels ▼


Building Line-of-Business Apps with Silverlight 2

Application Settings and Storage

With authentication fresh in your minds, it's not a far stretch to start thinking about how to store user defined settings. In web applications, whether the user runs the application from their desktop, laptop, or even a co-worker's computer, user defined should always available. Silverlight applications should be no different. To preserve this idiom, personalization settings should be stored on the server rather than the client. Storing settings on the server is as easy as adding a service reference to the ProfileService. Just like in a classic ASP.NET application, the ProfileService can be used to save and load settings via a String Dictionary, as demonstrated in Listing Three. While server-side storage of user defined settings provides the user with a sort of "roaming profile", the disadvantage of using a server-side service is the latency associated with the request/response cycle. In most cases the additional wait time required should not be enough that it creates a negative experience. However, if you know that your application is going to be run on a slow network or over an intra-office VPN, you should think about caching a copy of the profile settings in IsolatedStorage.

ProfileServiceReference.ProfileServiceClient profileClient = new ProfileServiceReference.ProfileServiceClient();
  profileClient.GetPropertiesForCurrentUserCompleted += new EventHandler<Tracker.ProfileServiceReference.GetPropertiesForCurrentUserCompletedEventArgs>(profileClient_GetPropertiesForCurrentUserCompleted);
  profileClient.GetPropertiesForCurrentUserAsync(props, true);
void profileClient_GetPropertiesForCurrentUserCompleted(object sender, Tracker.ProfileServiceReference.GetPropertiesForCurrentUserCompletedEventArgs e)
Listing Three


Included with every Silverlight 2 application is a 100KB store that can be used to save settings on the client. The 100KB limit can be increased, but first requires approval from the end user. In most cases though, 100KB should be more than enough room to store settings. If you've worked with IsolatedStorage in WindowsForms applications, the code in Listing Four should look familiar as the API is almost identical. The main difference on the Silverlight side, is the additional requirements around space limits. Almost half of the code in Listing Four is dedicated to simply asserting space requirements, something that can easily be factored out and re-used. Once factored out, persisting items to IsolatedStorage is as simple as writing to a FileStream.

Aside from user defined settings, IsolatedStorage serves another key role. You've probably noticed by now that I used "cache" as my local variable name for the IsolatedStorageFile in Listing Four. In a client-centric application, reducing calls to the server and data transfers is the key to creating a usable, responsive application. IsolatedStorage is a perfect candidate for a client-side cache. Any time you're dealing with large lists of mainly static content, you should think about storing that content in IsolatedStorage. If your data maps directly to a database table, you can use a Timestamp column to determine whether your client-side cache is stale or not.

using (IsolatedStorageFile cache = IsolatedStorageFile.GetUserStoreForApplication())
    // Create our Settings object
    Settings settings = new Settings() { Size = new Point(1024, 768), ShowCloseConfirmDialog = true, Theme = "Blue" };
    // Use a StringBuilder/StringWriter combo since our desired
    // datatype is a string
    StringBuilder buffer=new StringBuilder();
    StringWriter writer =new StringWriter(buffer);

    // Serialize Settings object as a string
    XmlSerializer serializer = new XmlSerializer(typeof(Settings));
    serializer.Serialize(writer, settings);

    // Get underlying string representation of Settings
    // and determine file size using Unicode encoding
    string serializedSettings = buffer.ToString();
    byte[] serializedSettingsBuffer = System.Text.Encoding.Unicode.GetBytes(serializedSettings);
    int maxSize = serializedSettingsBuffer.Length;
    Int64 availableSize = cache.AvailableFreeSpace;

    // IsolatedStorage limit is 100kb by default
    // but can be increased with the user's approval
    // check required size, and request increase if necessary
    if (maxSize > availableSize)
        // Request additional space
        // If user denies request, we'll quit loading settings
        if (!cache.IncreaseQuotaTo(maxSize))

    // Now that we have the string and enough space
    // we can write contents to IsolatedStorage
    using (IsolatedStorageFileStream storeFileStream = cache.OpenFile("Settings.xml", FileMode.OpenOrCreate, FileAccess.Write))
        // Don't need to close stream since we're scoped in the using block
Listing Foure

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.