How to use ConfigurationManager.AppSettings with a custom section? - c#

I need to get "http://example.com" from using App.config file.
But at the moment I am using:
string peopleXMLPath = ConfigurationManager.AppSettings["server"];
I cannot get the value.
Could you point out what I am doing wrong?
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configSections>
<section name="device" type="System.Configuration.SingleTagSectionHandler" />
<section name="server" type="System.Configuration.SingleTagSectionHandler" />
</configSections>
<device id="1" description="petras room" location="" mall="" />
<server url="http://example.com" />
</configuration>

I think you need to get the config section, and access that:
var section = ConfigurationManager.GetSection("server") as NameValueCollection;
var value = section["url"];
And you also need to update your config file:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configSections>
<section name="device" type="System.Configuration.NameValueSectionHandler" />
<section name="server" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<device>
<add key="id" value="1" />
<add key="description" value="petras room" />
<add key="location" value="" />
<add key="mall" value="" />
</device>
<server>
<add key="url" value="http://example.com" />
</server>
</configuration>
Edit: As CodeCaster mentioned in his answer, SingleTagSectionHandler is for internal use only. I think NameValueSectionHandler is the preferred way to define config sections.

The SingleTagSectionHandler documentation says:
This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.
You can retrieve it as a HashTable and access its entries using Configuration.GetSection():
Hashtable serverTag = (Hashtable)ConfigurationManager.GetSection("server");
string serverUrl = (string)serverTag["url"];

string peopleXMLPath = ConfigurationManager.AppSettings["server"];
gets the value from the appSettings part of the app.config file but you are storing your value in
<server url="http://example.com" />
Either put the value in the appSettings section as below or retrieve the value from its current location.
You need to add a key value pair to your config's appSettings section. As below:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="server" value="http://example.com" />
</appSettings>
</configuration>
Your reading code is correct but you should probably check for null. If the code fails to read the config value the string variable will be null.

You're defining a configuration section instead of a value in AppSettings. You can simply add your setting to AppSettings:
<appSettings>
... may be some settings here already
<add key="server" value="http://example.com" />
</appSettings>
Custom config sections are typically used for more complicated configurations (e.g. multiple values per key, non-string values, etc.

If you want to get the value from the app settings your appsetting element in configuration file must have a key.
define your sever value as mentioned below under configuration section:
<configuration>
<appSettings>
<add key="server" value="http://example.com" />
</appSettings>
...
...
...
</configuration>
Now execute below code line to get the server url:
string peopleXMLPath = ConfigurationManager.AppSettings["server"].ToString();

Related

How to solve App config error Configuration system failed to initialize

I came for advice.I'm trying to connect to the database through C#.But I have a problem with the App config file.It keeps throwing the App exception:,,
Configuration system failed to initialize
".I tried to add ,as advised here:Configuration System Failed To Initialize , but with no positive result.
So I wonder,if there is still a problem in the code,but I rather think that the problem is with the App config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<add key="DataSource" value=" My Database'IP adress "/>
<add key="Database" value="My database Name"/>
<add key="Name" value="User name"/>
<add key="Password" value="Password"/>
</configuration>
It seems like you're missing the appSettings element that wraps your key-value collection. It should look more like the following:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DataSource" value=" My Database'IP adress "/>
<add key="Database" value="My database Name"/>
<add key="Name" value="User name"/>
<add key="Password" value="Password"/>
</appSettings>
</configuration>

Saving existing file: empty value attribute is removed

I have a config file like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="key1" value="value1" />
<add key="key2" value="" />
...
</appSettings>
...
</configuration>
I read the config, change the value of key1 and save the config
System.Configuration.Configuration appConfig = ConfigurationManager.OpenExeConfiguration(Configuration.ConfigFile.Replace(".config", string.Empty));
appConfig.AppSettings.Settings["key1].Value = "newvalue1";
appConfig.Save(ConfigurationSaveMode.Minimal);
After this I get the following result:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="key1" value="newvalue1" />
<add key="key2"/>
...
</appSettings>
...
</configuration>
Why is the 'empty' value attribute removed for key "key2"?
When I try it with
appConfig.Save(ConfigurationSaveMode.Modified);
, the attribute is not removed. But I want to know why it's removed in the first case?
Thanks
<add key="key2" value="" />
and
<add key="key2" />
are both functionally equal. The value of key2 with or without that tag is a null string variable which is equivalent to the empty string.
Edit to reflect comment: Simply assign key2 the empty string in the same statement.
System.Configuration.Configuration appConfig = ConfigurationManager.OpenExeConfiguration(Configuration.ConfigFile.Replace(".config", string.Empty));
appConfig.AppSettings.Settings["key1"].Value = "newvalue1";
appConfig.AppSettings.Settings["key2"].Value = "";
appConfig.Save(ConfigurationSaveMode.Minimal);
Second Edit for 2nd comment:
Well, you haven't provided enough information then. All of my answers answer your question. The two values from the first answer are functionally equivalent. Therefore, if you wish to see if the "key2" value = "" then you could simply run the following
if(appConfig.AppSettings.Settings["key2"] == null){
//If this hits, that means <add key="key2" value="" />
}
Please research how to ask a good question and adjust your question to reflect what you are really trying to ask.

How to retrieve the value for the Key in the Web.Config using DictionarySectionHandler

How to fetch the corresponding value of a key that I would get dynamically. I wish to use the system defined DictionarySectionHandler to do the job, of fetching the data from my custom built config section in the Web.config file
Code block in Web.Config
<section name="domainsource" type="System.Configuration.DictionarySectionHandler"/>
<domainSource>
<add key="0" value="170" />
<add key="1" value="171" />
<add key="2" value="172" />
<add key="3" value="173" />
<add key="12" value="174" />
</domainSource>
Sourcecode in the main cs file from where I wish to retrieve the data from the Web.Config
Hashtable statusCodes = ConfigurationManager.GetSection("domainSource") as Hashtable;
vDomainSource = statusCodes[vDomainID];
This is where I am stuck vDomainID would be a value 0/1/2/3/12, based on this value I need to fetch its respective Source from the Web.Config. Any help on this aspect would be really appreciated.
You have a missspelling in the defintion of the section domainsource -> domainSource. Further ensure that the elemnt is defined in an element. Then it should work.
<configuration>
<configSections>
<section name="domainSource" type="System.Configuration.DictionarySectionHandler"/>
</configSections>
<domainSource>
<add key="0" value="170" />
<add key="1" value="171" />
<add key="2" value="172" />
<add key="3" value="173" />
<add key="12" value="174" />
</domainSource>
</configuration>

How to use custom configuration file or app.config in .NET application

I have MVC5 .NET 4.6.1 C# web application
I want to create a custom config file separate from web.config to store some settings my application uses.
I tried to follow this article https://support.microsoft.com/en-us/kb/815786
however the items I set in app.config:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
</system.web>
<appSettings>
<add key="Key0" value="0" />
<add key="Key1" value="1" />
<add key="Key2" value="2" />
</appSettings>
</configuration>
are not seen in my application see , eg. they come as null:
string attr = ConfigurationManager.AppSettings["Key0"];
Why isn't it working? Am I missing something?
Alternatively I would like to create a custom config file eg. mycustom.config to define my global app settings.
EDIT
Solution I used
Follwing this post https://social.msdn.microsoft.com/Forums/vstudio/en-US/11e6d326-c32c-46b1-a9a2-1fbef96f33ee/howto-custom-configuration-files?forum=netfxbcl
In web.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="newAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</configSections>
<newAppSettings file="C:\mycustom.config"/>
</configuration>
Then mycustom.config
<?xml version="1.0" encoding="utf-8" ?>
<newAppSettings>
<add key="OurKey" value="OurValue"/>
</newAppSettings>
And reading the value:
System.Collections.Specialized.NameValueCollection newAppSettings = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("newAppSettings");
string key = Convert.ToDateTime(newAppSettings["OurKey"]);
You can use separate config file for connection strings and app settings:
<appSettings configSource="appSettings.config" />
<connectionStrings configSource="connectionStrings.config"/>
appSettings.config file
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="Setting1" value="App setting 1" />
</appSettings>
connectionStrings.config file
<?xml version="1.0" encoding="utf-8"?>
<connectionStrings>
<add name="MyConnStr1" connectionString="My connection string" />
</connectionStrings>
Usage is same as it was before:
var setting1 = ConfigurationManager.AppSettings["Setting1"];
var connString1 = ConfigurationManager.ConnectionStrings["MyConnStr1"].ConnectionString;
//Helps to open the Root level web.config file.
Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
//Modifying the AppKey from AppValue to AppValue1
webConfigApp.AppSettings.Settings["AppKey"].Value = "AppValue1";
<appSettings>
<add key="AppKey" value="AppValue"/>
</appSettings>

Using ConnectionStrings and custom ConfigSections in the same App.Config

I have a custom configSection that works as expected. However, when I add a 'connectionStrings' section, I receive error:
Configuration system failed to initialize
on line:
StencilObjects so = ConfigurationManager.GetSection( "stencilObjects" ) as StencilObjects;
Here is the config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="connection" connectionString="foo"/>
</connectionStrings>
<configSections>
<section name="stencilObjects" type="Stencil.Configuration.StencilObjects, Stencil.Configuration"/>
</configSections>
<stencilObjects>
<tableData>
<table schema="Auth" name="SecurityQuestion" />
</tableData>
</stencilObjects>
</configuration>
Is there any limitation when using a custom config section? Does this not allow the use of connectionstrings?
Again, when I remove the connectionStrings, the app runs as expected.
Any idea on what is going on?
I haven't found a link to back this up yet with an explicit statement, but I've always used configSections at the top of the file without any problems. Try like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="stencilObjects" type="Stencil.Configuration.StencilObjects, Stencil.Configuration"/>
</configSections>
<connectionStrings>
<add name="connection" connectionString="foo"/>
</connectionStrings>
<stencilObjects>
<tableData>
<table schema="Auth" name="SecurityQuestion" />
</tableData>
</stencilObjects>
</configuration>
configSections definitely doesn't need to be just before the section(s) it describes. connectionStrings can be in between.

Categories

Resources