Skip to content

Instantly share code, notes, and snippets.

@gjulianm
Created March 4, 2012 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gjulianm/1974155 to your computer and use it in GitHub Desktop.
Save gjulianm/1974155 to your computer and use it in GitHub Desktop.
Generic Config wrapper C# / WP7
public static class Config
{
private static readonly string SomeConfigElementKey = "MYKEY";
private static string _someConfigElement;
public string SomeConfigElement {
get {
return GenericGetFromConfig<string>(SomeConfigElementKey, ref _someConfigElement);
}
set {
GenericSaveToConfig<string>(SomeConfigElementKey, ref _someConfigElement, value);
}
}
private static T GenericGetFromConfig<T>(string Key, ref T element) where T : new()
{
if (element != null)
return element;
IsolatedStorageSettings config = IsolatedStorageSettings.ApplicationSettings;
try
{
if (!config.TryGetValue<T>(Key, out element))
{
element = new T();
config.Add(Key, element);
config.Save();
}
}
catch (InvalidCastException)
{
config.Remove(Key);
}
catch (Exception)
{
}
if (element == null)
element = new T();
return element;
}
private static void GenericSaveToConfig<T>(string Key, ref T element, T value) where T : new()
{
if (value == null)
return;
IsolatedStorageSettings conf = IsolatedStorageSettings.ApplicationSettings;
try
{
element = value;
if (conf.Contains(Key))
conf[Key] = value;
else
conf.Add(Key, value);
conf.Save();
}
catch (Exception)
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment