If you are developing an enterprise Silverlight application you will typically need to cache your business entities in the isolated storage. There are two apparent choices for this:
1. Use the powerful Linq-To-XML API from System.Xml.Linq namespace. This method is to be used when you want to have a fine grain control over serialization (e.g. you want to store some properties of the data objects).
2. Use the built-in DataContractSerializer class. This method is very simple and the only thing it requires is that our business objects need to have the [DataContract] and [DataMember] attributes. In this post, I am going to discuss this second method.
In an enterprise LOB (line of business) application, our business objects will typically be retrieved via WCF service and hence will already have the [DataContract] and [DataMember] attributes marked on them. So we can directly use the built-in DataContractSerializer to store them to, and later retrieve them from, the isolated storage. Here’s a generic class to simplify the process:
public static class IsolatedStorageCacheManager<T>
{
public static void Store(string filename, T obj)
{
IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream fileStream = appStore.OpenFile(filename, FileMode.Create))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(fileStream, obj);
}
}
public static T Retrieve(string filename)
{
T obj = default(T);
IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication();
if (appStore.FileExists(filename))
{
using (IsolatedStorageFileStream fileStream = appStore.OpenFile(filename, FileMode.Open))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
obj = (T)serializer.ReadObject(fileStream);
}
}
return obj;
}
}
Using the above code is really simple. Just add the class to your project and use it like this:
//for storing and retrieving a single object
Person myPersonObj = GetPerson();
IsolatedStorageCacheManager<Person>.Store("myfile.xml", myPersonObj);
Person myPersonObj2 = IsolatedStorageCacheManager<Person>.Retrieve("myfile.xml");
//for storing and retrieving a collection of objects
List<Person> myPersonList = GetPersonList();
IsolatedStorageCacheManager<List<Person>>.Store("myfile.xml", myPersonList);
List<Person> myPersonList2 = IsolatedStorageCacheManager<List<Person>>.Retrieve("myfile.xml");
Hope you will find this implementation useful.