Created
March 7, 2012 17:38
-
-
Save ianoxley/1994588 to your computer and use it in GitHub Desktop.
A dynamic config object to access <appSettings>
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.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; | |
} | |
} | |
} |
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.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