Created
March 4, 2012 17:57
-
-
Save gjulianm/1974155 to your computer and use it in GitHub Desktop.
Generic Config wrapper C# / WP7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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