class SuspensionManager
{
static private Dictionary sessionState_ = new Dictionary();
static private List knownTypes_ = new List();
private const string filename = "_sessionState.xml";
// Provides access to the currect session state
static public Dictionary SessionState
{
get { return sessionState_; }
}
// Allows custom types to be added to the list of types that can be serialized
static public List KnownTypes
{
get { return knownTypes_; }
}
// Save the current session state
static async public Task SaveAsync()
{
// Get the output stream for the SessionState file.
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
IRandomAccessStream raStream = await file.OpenAsync(FileAccessMode.ReadWrite);
using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
{
// Serialize the Session State.
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary), knownTypes_);
serializer.WriteObject(outStream.AsStreamForWrite(), sessionState_);
await outStream.FlushAsync();
}
}
// Restore the saved sesison state
static async public Task RestoreAsync()
{
// Get the input stream for the SessionState file.
try
{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
if (file == null) return;
IInputStream inStream = await file.OpenSequentialReadAsync();
// Deserialize the Session State.
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary), knownTypes_);
sessionState_ = (Dictionary)serializer.ReadObject(inStream.AsStreamForRead());
}
catch (Exception)
{
// Restoring state is best-effort. If it fails, the app will just come up with a new session.
}
}