I have a customized config section in my web.config like this:
<configSection>
<section name="CustomConfig" type="ConfigSectionRoot" allowLocation="true" allowDefinition="Everywhere"/>
</configSection>
<CustomConfig>
<ConfigRoot>
<add key="DataBase" value="CouchDB"/>
<add key="FrontEnd" value="Asp.Net"/>
<add key="AppName" value="Virtual WorkPlace"/>
</ConfigRoot>
</CustomConfig>
<AppSettings>
<add key="DataBase" value="CouchDB"/>
</AppSettings>
My ConfigSectionRoot.cs is like this:
public class ConfigSectionRoot:ConfigurationSection
{
[ConfigurationProperty("key", DefaultValue = "", IsKey = true, IsRequired = true)]
public string Key
{
get
{
return ((string)(base["key"]));
}
set
{
base["key"] = value;
}
}
[ConfigurationProperty("value", DefaultValue = "", IsKey = false, IsRequired = false)]
public string Value
{
get
{
return ((string)(base["value"]));
}
set
{
base["value"] = value;
}
}
}
If i use AppSettings Instead of Custom Config I could access it like:
string results= ConfigurationManager.AppSettings["Database"];
// results wil contain "CouchDB"
Is there any way to achieve the same thing in Customized Config section ??? Pls help me out
To access these values, there is one static class named ConfigurationManager, which has one getter property named AppSettings. We can just pass the key inside the AppSettings and get the desired value from AppSettings section, as shown below.
it is a .net builtin mechanism to define some settings before the application starts, without recompiling. see msdn configurationmanager.
If your configuration doesn't need to be more than a key-value store, I'd go for a NameValueSectionHandler.
<section name="customConfig" type="System.Configuration.NameValueSectionHandler"/>
<!-- ... -->
<customConfig>
<add key="DataBase" value="CouchDB" />
<add key="FrontEnd" value="Asp.Net" />
<add key="AppName" value="Virtual WorkPlace" />
</customConfig>
You can then read it out, just like the appSettings:
var customConfig = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("customConfig");//i have changed like this and it worked fine
var database = customConfig["DataBase"];
You could also achieve the same with a SingleTagSection:
<section name="customConfig" type="System.Configuration.SingleTagSectionHandler"/>
<!-- ... -->
<customConfig database="CouchDB" frontEnd="Asp.Net" appName="Virtual Workplace" />
And then query it with:
var customConfig = (System.Collections.Hashtable) System.Configuration.ConfigurationManager.GetConfig("customConfig");
var database = customConfig["database"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With