Advertisement
Guest User

Untitled

a guest
Aug 5th, 2015
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. public class Settings
  2. {
  3. public Settings()
  4. {
  5. SomeString = Helpers.GetSetting("SomeString", "DefaultString");
  6. SomeInt = Helpers.GetSetting("SomeInt", 9, int.TryParse);
  7. SomeTimeSpan = Helpers.GetSetting("SomeTimeSpan", new TimeSpan(60), Helpers.TimeSpanParser);
  8. }
  9.  
  10. public string SomeString { get; set; }
  11.  
  12. public int SomeInt { get; set; }
  13.  
  14. public TimeSpan SomeTimeSpan { get; set; }
  15. }
  16.  
  17. public static class Helpers
  18. {
  19. public static T GetSetting<T>(string appSetting, T @default, TryParseHandler<T> handler) where T : struct
  20. {
  21. var value = ConfigurationManager.AppSettings[appSetting];
  22.  
  23. if (string.IsNullOrEmpty(value))
  24. {
  25. return @default;
  26. }
  27.  
  28. T result;
  29.  
  30. if (handler(value, out result))
  31. {
  32. return result;
  33. }
  34.  
  35. throw new Exception(); // Swap to something better :)
  36. }
  37.  
  38. public static string GetSetting(string appSetting, string @default)
  39. {
  40. return ConfigurationManager.AppSettings[appSetting];
  41. }
  42.  
  43. public static bool TimeSpanParser(string value, out TimeSpan result)
  44. {
  45. result = TimeSpan.FromSeconds(double.Parse(value));
  46. return true;
  47. }
  48.  
  49. public delegate bool TryParseHandler<T>(string value, out T result);
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement