Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2015
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. using System;
  2. using System.Configuration;
  3.  
  4. namespace Successful.Misc
  5. {
  6. public static class AppSettingsHelper
  7. {
  8. private static bool ThrowException { get; set; }
  9. private static object DefaultValue { get; set; }
  10. public static TResult Get<TResult>(string key, Func<TResult> defaultValue = null, bool throwException = false)
  11. {
  12. ThrowException = throwException;
  13. DefaultValue = defaultValue;
  14.  
  15. var result = default(TResult);
  16. var valueOfKey = ConfigurationManager.AppSettings[key];
  17.  
  18. if (string.IsNullOrWhiteSpace(valueOfKey))
  19. {
  20. if (ThrowException && DefaultValue == null)
  21. {
  22. throw new ArgumentNullException(valueOfKey,
  23. $"Failed to get a value for the key {key} in the App.config file.");
  24. }
  25.  
  26. result = GetDefaultValue(defaultValue);
  27. }
  28. else
  29. {
  30. result = ConvertToResult<TResult>(key, valueOfKey);
  31. }
  32.  
  33. return result;
  34. }
  35.  
  36. private static TResult ConvertToResult<TResult>(string key, string valueOfKey)
  37. {
  38. TResult result;
  39.  
  40. try
  41. {
  42. result = (TResult)Convert.ChangeType(valueOfKey, typeof(TResult));
  43. }
  44. catch (Exception ex)
  45. {
  46. if (ThrowException && DefaultValue == null)
  47. {
  48. throw new Exception($"Failed to convert {valueOfKey} from type {valueOfKey.GetType()} to the type {typeof (TResult)}", ex);
  49. }
  50.  
  51. result = GetDefaultValue((Func<TResult>)Convert.ChangeType(DefaultValue, typeof(Func<TResult>)));
  52. }
  53.  
  54. return result;
  55. }
  56.  
  57. private static TResult GetDefaultValue<TResult>(Func<TResult> defaultValue)
  58. {
  59. var result = default(TResult);
  60.  
  61. if (defaultValue != null)
  62. {
  63. try
  64. {
  65. result = defaultValue.Invoke();
  66. }
  67. catch (Exception ex)
  68. {
  69. if (ThrowException)
  70. {
  71. throw new Exception($"Failed to to invoke delegate {defaultValue} of type {defaultValue.GetType()}", ex);
  72. }
  73. }
  74. }
  75.  
  76. return result;
  77. }
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement