Skip to content

Instantly share code, notes, and snippets.

@JerryNixon
Last active May 15, 2020 00:07
Show Gist options
  • Select an option

  • Save JerryNixon/c81b708906d9d7daca0589c34495cfbb to your computer and use it in GitHub Desktop.

Select an option

Save JerryNixon/c81b708906d9d7daca0589c34495cfbb to your computer and use it in GitHub Desktop.
UWP Settings Helper
using Newtonsoft.Json;
using System;
using Windows.Foundation.Collections;
namespace Client.Helpers
{
public class SettingsHelper
{
private readonly IPropertySet _settings;
public SettingsHelper(IPropertySet settings)
{
_settings = settings;
}
public string ReadCascade(string key, string otherwise)
{
if (!TryReadSetting<string>(key, out var result))
{
if (!TryReadEnvironment(key, out result))
{
result = otherwise;
}
}
return result;
}
public string ReadEnvironment(string key, string otherwise)
{
if (!TryReadEnvironment(key, out var result))
{
result = otherwise;
}
return result;
}
public bool TryReadEnvironment(string key, out string value)
{
value = default;
var result = true;
try
{
if (Environment.GetEnvironmentVariables().Contains(key))
{
value = Environment.GetEnvironmentVariable(key);
}
else
{
result = false;
}
}
catch
{
result = false;
}
return result;
}
public T ReadSetting<T>(string key, T otherwise)
{
if (!TryReadSetting<T>(key, out var result))
{
result = otherwise;
}
return result;
}
public bool TryReadSetting<T>(string key, out T value)
{
value = default;
var result = true;
try
{
if (_settings.ContainsKey(key))
{
var json = _settings[key].ToString();
value = JsonConvert.DeserializeObject<T>(json);
}
else
{
result = false;
}
}
catch
{
result = false;
}
return result;
}
public bool WriteSetting<T>(string key, T value)
{
var result = true;
if (TryReadSetting<T>(key, out var setting) && Equals(setting, value))
{
result = false;
}
else
{
var json = JsonConvert.SerializeObject(value);
_settings[key] = json;
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment