Skip to content

Instantly share code, notes, and snippets.

@alastairtree
Created June 29, 2017 13:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alastairtree/4cb56a39274ee69b881771d9d5434ade to your computer and use it in GitHub Desktop.
Save alastairtree/4cb56a39274ee69b881771d9d5434ade to your computer and use it in GitHub Desktop.
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