Skip to content

Instantly share code, notes, and snippets.

@NikolajDL
Created February 6, 2014 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NikolajDL/8845534 to your computer and use it in GitHub Desktop.
Save NikolajDL/8845534 to your computer and use it in GitHub Desktop.
A dynamic object to wrap WebConfigurationManager.AppSettings to access the settings "prettily". Great in combination with a custom ASP.NET MVC WebViewPage for easy access in views.
public abstract class MyWebViewPage<TModel> : WebViewPage<TModel>
{
public dynamic Settings
{
get { return SettingsHelper.Instance; }
}
}
public abstract class MyWebViewPage : WebViewPage
{
}
public class SettingsHelper : DynamicObject
{
private static dynamic instance = new SettingsH();
private static object syncRoot = new object();
private SettingsHelper() { }
public static dynamic Instance
{
get {
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new SettingsHelper();
}
}
return instance;
}
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (WebConfigurationManager.AppSettings.AllKeys.Contains(binder.Name))
{
result = WebConfigurationManager.AppSettings[binder.Name];
return true;
}
result = null;
return false;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
var key = binder.Name;
if (WebConfigurationManager.AppSettings.AllKeys.Contains(key))
WebConfigurationManager.AppSettings.Set(key, value.ToString());
else
WebConfigurationManager.AppSettings.Add(key, value.ToString());
return true;
}
public override string ToString()
{
StringWriter message = new StringWriter();
foreach (var item in WebConfigurationManager.AppSettings.AllKeys)
message.WriteLine("{0}:\t{1}", item, WebConfigurationManager.AppSettings[item]);
return message.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment