Skip to content

Instantly share code, notes, and snippets.

@ianoxley

ianoxley/Config.cs

Created Mar 7, 2012
Embed
What would you like to do?
A dynamic config object to access <appSettings>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Dynamic;
using System.Collections.Specialized;
namespace Ox.Models
{
public class Config : DynamicObject
{
private NameValueCollection settings;
public Config(NameValueCollection s)
{
this.settings = s;
}
public Config() : this(ConfigurationManager.AppSettings) {}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
string key = binder.Name.ToLower();
result = settings[key];
return result != null;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NSpec;
using Ox.Models;
using System.Collections.Specialized;
using Microsoft.CSharp.RuntimeBinder;
namespace Ox.Tests.Models
{
public class describe_Config : nspec
{
void given_app_settings()
{
var settings = new NameValueCollection();
settings.Add("foo", "foo");
settings.Add("bar", "bar");
settings.Add("empty", "");
dynamic config = new Config(settings);
context["when key exists"] = () =>
{
it["then value returned should be non null"] = () =>
{
string value = config.Foo;
value.should_not_be_null();
value.should_be("foo");
};
it["then value returned should be empty string if empty string in app settings"] = () =>
{
string value = config.Empty;
value.should_be(string.Empty);
};
it["then case sensitivity should not affect returned value"] = () =>
{
string value1 = config.Foo;
string value2 = config.foo;
value1.should_not_be_null();
value2.should_not_be_null();
value1.should_be(value2);
};
};
context["when key does not exist"] = () =>
{
it["then should throw a RuntimeBinderException"] = expect<RuntimeBinderException>(() => config.FooBar());
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.