Created
June 29, 2017 13:33
-
-
Save alastairtree/4cb56a39274ee69b881771d9d5434ade to your computer and use it in GitHub Desktop.
This file contains hidden or 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
using System; | |
using System.Configuration; | |
namespace Util | |
{ | |
public static class Config | |
{ | |
public static string GetSetting(string key) => ConfigurationManager.AppSettings[key]; | |
public static bool HasSetting(string key) => !string.IsNullOrEmpty(GetSetting(key)); | |
public static string GetSettingOrDefault(string key, string defaultValue) => HasSetting(key) | |
? GetSetting(key) | |
: defaultValue; | |
public static bool IsTrue(string key) | |
{ | |
bool enabled; | |
return GetSetting(key) != null && bool.TryParse(GetSetting(key), out enabled) && enabled; | |
} | |
public static int GetSettingAsIntOrDefault(string key, int defaultValue) | |
{ | |
try | |
{ | |
return HasSetting(key) ? int.Parse(GetSetting(key)) : defaultValue; | |
} | |
catch (FormatException fomatException) | |
{ | |
throw new FormatException($"Invalid format for setting {key}, expected an int", fomatException); | |
} | |
} | |
public static string GetSettingOrError(string key) | |
{ | |
if (!HasSetting(key)) | |
throw new ConfigurationErrorsException($"Unable to find required config value with key {key}"); | |
return GetSetting(key); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment