WP7 Tip: tombstoning simplified

In order to prepare your phone app to go into tombstone mode (to make it tomb-worthy) it is necessary to save off state data associated with your app.  My preference is to simply save off view models – but you may want to also save off model objects or even individual field values.

There are two dictionaries for doing this. 

IsolatedStorageSettings.ApplicationSettings is available to save persistent data between runs of the application (whether the application gets tombstoned or simply gets closed down).

PhoneApplicationService.Current.State allows one to save and restore data when the application gets tombstoned.  It is handy if we only want to save off data temporarily – for instance if we do not need it for a fresh run of the application. 

Since State and ApplicationSettings are both dictionaries that automatically handle serialization and deserialization for us, much of the underlying code we are required to write when using them is also very similar.

In my own applications, I use a set of utility classes to ease saving and restoring my application state.

Since I generally only want to use State and ApplicationSettings to save and restore data, I encapsulate the plumbing behind a very simple interface.

    public interface IDataStorage
    {
        bool Backup(string token, object value);
        T Restore<T>(string token);
    }

The concrete classes aren’t particularly sophisticated.  I use this for transient data storage:

    public class TransientDataStorage: IDataStorage
    {

        public bool Backup(string token, object value)
        {
            if (null == value)
                return false;

            var store = PhoneApplicationService.Current.State;
            if (store.ContainsKey(token))
                store[token] = value;
            else
                store.Add(token, value);

            return true;
        }

        public T Restore<T>(string token)
        {
            var store = PhoneApplicationService.Current.State;
            if (!store.ContainsKey(token))
                return default(T);

            return (T) store[token];
        }
    }

And this for isolated storage:

    public class PersistentDataStorage: IDataStorage
    {

        public bool Backup(string token, object value)
        {
            if(null == value)
                return false;

            var store = IsolatedStorageSettings.ApplicationSettings;
            if (store.Contains(token))
                store[token] = value;
            else
                store.Add(token,value);

            store.Save();
            return true;
        }

        public T Restore<T>(string token)
        {
            var store = IsolatedStorageSettings.ApplicationSettings;
            if (!store.Contains(token))
                return default(T);

            return (T) store[token];
        }
    }

You’ll notice that the only real difference between these two code segments is that I need to call Save for isolated storage but do not have to for State updates.

Now when I need to save to isolated storage I simply call:

    var store = new PersistentDataStorage();  
    store.Backup("token", myObject);

While a transient save to State is simply:

    var store = new TransientDataStorage();  
    store.Backup("token", myObject);

No sticky kids mess afterwards.

I like having an interface as it allows me to throw some methods on the VMs themselves:

public static bool Backup(IDataStorage store)
{
    return store.Backup("MainViewModel", this._instance);
}

public static void Restore(IDataStorage store)
{
    this._instance = store.Restore<MainViewModel>("MainViewModel");
}

In this case, each VM is responsible for what actually gets saved to storage: for instance, we might want to save off the VM as well as the  associated model object. 

Whether this state is saved off to IsolatedStorage or State, however, gets determined elsewhere – generally in the ApplicationService lifecycle events: Launching, Closing, Activated and Deactivated.

WP7 Tombstoning Pattern Tip

Customizing App.xaml.cs

If you are familiar with tombstoning on Windows Phone, you know there are four events in the Windows Phone application lifecycle that can be handled: PhoneApplicationService.Launching, PhoneApplicationService.Closing, PhoneApplicationService.Activated and PhoneApplicationService.Deactivated.  The first two are for normal app startup and shutdown, while the latter two are for tombstoning scenarios.

Along with these events are two different property bags that application data can be saved to. 

IsolatedStorageSettings.ApplicationSettings  is typically used for backing up persistent data that you want available every time the application starts up. 

PhoneApplicationService.Current.State is used for transient data that you only want persisted if your Silverlight application gets tombstoned.  It is the equivalent of session data in an ASP.NET web application.

In the Launching and Closing event handlers you would typically save to Isolated Storage, while in handlers for Activated and Deactivated you would want to use Current.State.  The former coding artifacts are for persistent data while the latter are for transient data.

These categories are imperfect, however.  It is possible to go through the Deactivated event but never have Activated called.  This occurs if for memory management reasons your application is permanently terminated (a permanent death scenario rather than the temporary death that tombstoning is supposed to trigger).  This can also happen, of course, if the user for whatever reason just decides not to return to your app after it gets tombstoned.

Another way to look at this is that your application is permanently terminated without ever invoking the PhoneApplication.Closing event.

In order to handle this common scenario, you must save any persistent data in the Deactivated event as well as the Closing event.

A simple pattern for structuring your code to cover all these possibilities is to make sure the code fragment for saving persistent data is called in both the Dectivated and Closing event handlers.  Similarly, the fragment for restoring persistent data should be called in both the Activated and Launching handlers.  We do this by taking care of persistent data backup and restores in two new methods: BackupPersistentData and RestorePersistentData. Those who remember the IDisposible pattern in C# will recognize some of the same coding idioms being used here.

The following code goes in App.xaml.cs:

private void BackupPersistentData()
{
    var store = IsolatedStorageSettings.ApplicationSettings;
    //save persistent data
    store.Save();
}
private void RestorePersistentData()
{
    var store = IsolatedStorageSettings.ApplicationSettings;
    //restore persistent data
}

private void Application_Closing(object sender
    , ClosingEventArgs e)
{
    BackupPersistentData();
}

private void Application_Launching(object sender
    , LaunchingEventArgs e)
{
    RestorePersistentData();
}

private void Application_Deactivated(object sender
    , DeactivatedEventArgs e)
{
    BackupPersistentData();
    var store = PhoneApplicationService.Current.State;
    //save transient data
}

private void Application_Activated(object sender
    , ActivatedEventArgs e)
{
    RestorePersistentData();
    var store = PhoneApplicationService.Current.State;
    //restore transient data
}

Sticking to this pattern has helped me to avoid a lot of unforeseen mistakes in my own phone apps.