Skip to content

Instantly share code, notes, and snippets.

@yetanotherchris
Created February 11, 2013 22:08
Show Gist options
  • Save yetanotherchris/4758068 to your computer and use it in GitHub Desktop.
Save yetanotherchris/4758068 to your computer and use it in GitHub Desktop.
IConfigurationSectionHandler example
public class ConfigurationHandler : IConfigurationSectionHandler
{
/// <summary>
/// Creates a <see cref="Settings"/> object from the configuration file.
/// </summary>
/// <seealso cref="Settings"/>
public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
if (section == null)
throw new ArgumentNullException("'section' is null. Check your app.config or web.config exists and is valid.");
try
{
Settings settings = new Settings();
// Security
XmlNode node = section.SelectSingleNode("//security");
if (node != null)
Settings.Security = (node.Attributes["enabled"].Value == "true");
else
throw new Exception("No security node could be found in the web/app.config");
// Username
node = section.SelectSingleNode("//username");
if (node != null)
settings.Username = node.Value;
else
throw new Exception("No username could be found in the web/app.config");
return settings;
}
catch (XPathException ex)
{
// Catch From SelectSingleNode,SelectNodes
throw new Exception("XPathException caught when reading config file", ex);
}
}
}
public class Settings
{
public bool Security { get; set; }
public string Username { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment