Tips and Tricks for C# Windows 8 developer: Read and write roamed application settings

Windows 8 offers a really cool tool to save and load settings for your application: the roaming settings. It is a dictionary container where the name of each setting can be 255 characters in length at most. Each setting can be up to 8K bytes in size.

For more information about the roaming, you can go there:

https://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx

The today’s code is about creating a set of tools to handle application settings. With the following code you can save and retrieve typed settings. If a roamed version exists it will be used else a local version will be used:

public static bool GetSerializedBoolValue(string name, bool defaultValue = false, bool roaming = true)
{
    var value = GetSerializedStringValue(name, roaming);
    if (value == null)
        return defaultValue;

    bool result;
    if (bool.TryParse(value, out result))
        return result;

    return defaultValue;
}

public static int GetSerializedIntValue(string name, int defaultValue = 0, bool roaming = true)
{
    var value = GetSerializedStringValue(name, roaming);
    if (value == null)
        return defaultValue;

    int result;
    if (int.TryParse(value, out result))
        return result;

    return defaultValue;
}

public static double GetSerializedDoubleValue(string name, double defaultValue = 0, bool roaming = true)
{
    var value = GetSerializedStringValue(name, roaming);
    if (value == null)
        return defaultValue;

    double result;
    if (double.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out result))
        return result;

    return defaultValue;
}

public static string GetSerializedStringValue(string name, bool roaming = true)
{
    if (roaming && ApplicationData.Current.RoamingSettings.Values.ContainsKey(name))
    {
        return ApplicationData.Current.RoamingSettings.Values[name].ToString();
    }

    if (ApplicationData.Current.LocalSettings.Values.ContainsKey(name))
    {
        return ApplicationData.Current.LocalSettings.Values[name].ToString();
    }

    return null;
}



public static void SetSerializedValue(string name, object value, bool roaming = true)
{
    string valueToStore;

    if (value is double)
        valueToStore = ((double)value).ToString(CultureInfo.InvariantCulture);
    else
        valueToStore = value.ToString();

    if (roaming)
        ApplicationData.Current.RoamingSettings.Values[name] = valueToStore;
    ApplicationData.Current.LocalSettings.Values[name] = valueToStore;
}