Updated PersistHelper for #Win8Dev #WinRT

A while back I posted some persistence helper class. It was hardcoded to use LocalFolder and LocalSettings. I eventually updated it. Now it requires you the developer to specify a folder and settings object. Hope it is helpful.

public class PersistHelper
{
    //private static StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.RoamingFolder;
    //private static ApplicationDataContainer storageSettings = ApplicationData.Current.LocalSettings;

    public async static Task<bool> FileExisits(StorageFolder folder, string fileName)
    {
        try
        {
            StorageFile file = await folder.GetFileAsync(fileName);
            return file != null;
        }
        catch
        {
            return false;
        }
    }

    private async static Task<StorageFile> GetFileIfExistsAsync(StorageFolder folder, string fileName)
    {
        try
        {
            return await folder.GetFileAsync(fileName);
        }
        catch
        {
            return null;
        }
    }


    public static async Task<T> LoadObjectFromStorage<T>(Windows.Storage.StorageFolder storageFolder)
    {
        T ObjToLoad = default(T);

        try
        {
            StorageFile storageFile = await storageFolder.CreateFileAsync(GetFileName<T>(), 
                CreationCollisionOption.OpenIfExists);

            using (Stream inStream = await storageFile.OpenStreamForReadAsync())
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                ObjToLoad = (T)serializer.Deserialize(inStream);
            }
        }
        catch (Exception error)
        {
            throw new NotImplementedException(error.Message);
        }

        return ObjToLoad;
    }

    public static async void SaveObjectToStorage<T>(T ObjectToSave, Windows.Storage.StorageFolder storageFolder)
    {
        string filename = GetFileName<T>();
                
        using (Stream fs = await storageFolder.OpenStreamForWriteAsync(filename, CreationCollisionOption.ReplaceExisting))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                XmlSerializer ser = new XmlSerializer(typeof(T));
                ser.Serialize(sw, ObjectToSave);
            }
        }
    }

    public static string GetFileName<T>()
    {
        return typeof(T).FullName + ".xml";
    }

    public async static Task<bool> IsObjectPersisted<T1>(Windows.Storage.StorageFolder storageFolder)
    {
        string file = GetFileName<T1>();

        StorageFile storageFile = await GetFileIfExistsAsync(storageFolder, file);

        return (storageFile != null);
    }

    public static T LoadSetttingFromStorage<T>(string Key, Windows.Storage.ApplicationDataContainer storageSettings)
    {
        T ObjToLoad = default(T);

        if (storageSettings.Values.ContainsKey(Key))
        {
            using (StringReader sr = new StringReader((string)storageSettings.Values[Key]))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                ObjToLoad = (T)serializer.Deserialize(sr);
            }
        }

        return ObjToLoad;
    }

    public static void SaveSettingToStorage(string Key, object Setting, Windows.Storage.ApplicationDataContainer storageSettings)
    {
        StringBuilder sb = new StringBuilder();
        using (StringWriter sw = new StringWriter(sb))
        {
            XmlSerializer ser = new XmlSerializer(Setting.GetType());
            ser.Serialize(sw, Setting);
        }

        if (!storageSettings.Values.ContainsKey(Key))
        {
            storageSettings.Values.Add(Key, sb.ToString());
        }
        else
        {
            storageSettings.Values[Key] = sb.ToString();
        }
    }

    public static bool IsSettingPersisted(string Key, Windows.Storage.ApplicationDataContainer storageSettings)
    {
        return storageSettings.Values.ContainsKey(Key);
    }
}
About these ads

One thought on “Updated PersistHelper for #Win8Dev #WinRT

  1. Pingback: Updated PersistHelper for #Win8Dev #WinRT

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s