I am trying to create a custom configuration section to store some API credentials after the tutorial at: http://devlicio.us/blogs/derik_whittaker/archive/2006/11/13/app-config-and-custom-configuration-sections.aspx . I added the following to the Web.config file:
<section name="providers" type="EmailApiAccess.Services.ProviderSection, EmailApiAccess.Services"/> <providers> <add name="ProviderName" username="" password ="" host="" /> </providers>
and created the following classes:
public class ProviderSection: ConfigurationSection { [ConfigurationProperty("providers")] public ProviderCollection Providers { get { return ((ProviderCollection)(base["providers"])); } } } [ConfigurationCollection(typeof(ProviderElement))] public class ProviderCollection : ConfigurationElementCollection { public ProviderElement this[int index] { get { return (ProviderElement) BaseGet(index); } set { if (BaseGet(index) != null) BaseRemoveAt(index); BaseAdd(index, value); } } protected override object GetElementKey(ConfigurationElement element) { return ((ProviderElement)(element)).name; } protected override ConfigurationElement CreateNewElement() { return new ProviderElement(); } } public class ProviderElement: ConfigurationElement { public ProviderElement() { } [ConfigurationProperty("name", DefaultValue="", IsKey=true, IsRequired=true)] public string name { get { return (string)this["name"]; } set { this["name"] = value; } } [ConfigurationProperty("username", DefaultValue = "", IsRequired = true)] public string username { get { return (string)this["username"]; } set { this["username"] = value; } } [ConfigurationProperty("password", DefaultValue = "", IsRequired = true)] public string password { get { return (string)this["password"]; } set { this["password"] = value; } } [ConfigurationProperty("host", DefaultValue = "", IsRequired = false)] public string host { get { return (string)this["host"]; } set { this["host"] = value; } } }
However, when I try to implement code using this:
var section = ConfigurationManager.GetSection("providers"); ProviderElement element = section.Providers["ProviderName"]; var creds = new NetworkCredential(element.username, element.password);
I get a message that "Object" does not contain a definition for "Providers" ....
Any help would be greatly appreciated.
source share