For one of the apps I have been working on, I needed to persist a List<T> of T objects across sessions. They are simple objects with simple properties, so I decided to use XML. However, since WP7 is a new platform, there’s not a lot of information out there on what is a good best practice.
It turns out for simple situations like mine, serializing objects into XML and writing that to file is by far the easiest way to do it.
Let’s examine a scenario.
This is not an app I am working on, but it is basically the same thing.
Let’s say that you want to track your jogs. Starting simple, you decide to track the following properties:
Of course, we won’t attempt to build all of this here, but rather, focus on the storage aspect of it.
You will persist a list of these objects to be able to view them historically. This is what a Jog object might look like. Note the extra property, DurationXml, with its special attributes – this exists because XmlSerializer does not properly serialize TimeSpan objects.
Note the hackery around the Duration and DurationXml properties.
For the purposes of this app, you’d have a List of Jog objects: List<Jog> which you keep as a static on the App class and maintain it there. You’d then create some methods in the App class that would help out with storage, and then call them from Application_Closing, Application_Launching, and Activated/Deactivated as you handle tombstoning and deactivation.
Then, you might write a class like this which helps with storage, and keep it statically on the App class. All you have to do is call XmlSerializer.Serialize(object) and XmlHelper.Deserialize(xml) to manage the saving/loading of your object list. Put together, it looks like this:
One thing to note here is that several of the Xml classes won’t magically work with IntelliSense. You need to add references to System.Xml and System.Xml.Serialization for all this good stuff to work.
I’ll be posting an example Jog Tracker application that uses isolated storage in the coming weeks, but for now, this should be enough to get you started.