How to retrieve a custom section from an app.config in .NET? - c#

I have a .NET Framework 4.7.2 library project, inside there's an App.config file like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="NewDocumentMetadata" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<NewDocumentMetadata>
<add key="Type" value="principal"/>
<add key="IsActive" value="true"/>
</NewDocumentMetadata>
<appSettings>
<add key="Entity" value="9"/>
<add key="Flux" value="pdf"/>
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<!-- [...] -->
</assemblyBinding>
</runtime>
</configuration>
As you can see, I have some standard settings, but also a custom section. I have no problems with the settings, but when I retrieve the section, it works, but there I'm stuck, when I try to cast it to NameValueCollection or AppSettingsSection it gives me a null value, I'm stuck with a ConfigurationOption object I am not able to work with.
var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
flux = appConfig.AppSettings.Settings["Flux"].Value; //Works
entity = appConfig.AppSettings.Settings["Entity"].Value; //Works
var metadataSection = appConfig.GetSection("NewDocumentMetadata"); //What do I do with this boy?
I need to retrieve the settings within the NewDocumentMetadata section, how to proceed?

You should try this :
var metadataSection = ConfigurationManager.GetSection("NewDocumentMetadata") as NameValueCollection;
// Get all the value foreach key
foreach(var key in metadataSection.AllKeys)
{
string value = metadataSection.GetValues(key).FirstOrDefault()
}

I just found out that the problem was with this line :
<section name="NewDocumentMetadata" type="System.Configuration.NameValueSectionHandler" />.
I changed the type and went for this :
<section name="NewDocumentMetadata" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
Now I just have to do this kind of code to retrieve the values I want :
var metadataSection = (AppSettingsSection)appConfig.GetSection("NewDocumentMetadata");
foreach (var key in metadataSection.Settings.AllKeys)
{
string value = metadataSection.Settings[key].Value;
}

Related

I need to set the value of <add key="FileSystemResourcePath" value="abc.config"/> at runtime in code behind

My Web.Config looks something like below:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="EAFramework">
<section name="ConfigurationFile" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</sectionGroup>
</configSections>
<EAFramework>
<ConfigurationFile>
<add key="FileSystemResourcePath" value="abc.config"/>
</ConfigurationFile>
</EAFramework>
<appSettings>
<add key="RecordUpdateNotifyString" value="Set records updated with date printed "/>
<add key="RecordUpdateFailString" value="Failed to Print Records."/>
</appSettings>
.
.
.
for key="FileSystemResourcePath" i need to set value at run time to default directory from where application is running.
For eg : Say my application runs from C:/MyFolder, value for above key should hold C:/MyFolder/abc.config.
This always works for me (at least for web.config files)
//get the path of the website
string path = HttpContext.Current.Request.ApplicationPath;
//create a webconfiguration instance
System.Configuration.Configuration cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(path);
//add the new keyvalue to the web.config, remove the old one if necessary
cfg.AppSettings.Settings.Remove("myAppKey");
cfg.AppSettings.Settings.Add("myAppKey", "myAppValue");
//save the new value
cfg.Save();
Try this code, it will definitely work for custom configuration sections
string filename = "abc.config";
string fullpath = MapPath(filename);
var xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
xmlDoc.SelectSingleNode("//EAFramework/ConfigurationFile/add[#key='FileSystemResourcePath']").Attributes["value"].Value = fullpath;
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
ConfigurationManager.RefreshSection("//EAFramework/ConfigurationFile");

How to programmatically read the custom config files in asp.net mvc

In the root folder of my ASP.NET MVC 5 I have two config files. one is the default web.config file and the second one is department.config.
The content of the department.config file is:
<department>
<add key="dept1" value="xyz.uvw.rst" />
<add key="dept2" value="abc.def.ghi" />
<department>
How to read the department.config file ?
I want to get a collection of values under <department> in this config file.
Edit: Web.config has <department configSource="reports.config" />
so, how to read the configSource file in asp.net mvc ?
Edit:
<configuration>
<configSections>
<section name="departments"
type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
restartOnExternalChanges="false"
requirePermission="false" />
In your web.config, you can specify other files that the built-in ConfigurationManager can easily access. For example, we decided that we wanted to separate connection strings and application setting into separate files. You can do this by putting this in your web.config:
<appSettings configSource="appsettings.config" />
Then you can access these values in the 'regular' way
ConfigurationManager.AppSettings["KeyHere"]
Same thing with connection strings...
Why not use the appSettings section in your web.config? These are easy to read using ConfigurationManager object.
In your web.config, find the appSettings section:
<appSettings>
<add key="dept1" value="xyz.uvw.rst"/>
Then in your class where you want to read it, import the correct namespace:
using System.Configuration;
And then read the value easily, like so:
var dept1 = ConfigurationManager.AppSettings.Get("dept1");
If you have to have it in a separate config, you might consider creating a class for it, I'll post up an example of that shortly.
edit1: here is a quick example of how to do your own custom config
first, define the config class:
using System;
using System.Configuration;
namespace WebApplication2
{
public class MyConfig : ConfigurationSection
{
private static readonly MyConfig ConfigSection = ConfigurationManager.GetSection("MyConfig") as MyConfig;
public static MyConfig Settings
{
get
{
return ConfigSection;
}
}
[ConfigurationProperty("Dept1", IsRequired = true)]
public string Dept1
{
get
{
return (string)this["Dept1"];
}
set
{
this["Dept1"] = value;
}
}
[ConfigurationProperty("Dept2", IsRequired = true, DefaultValue = "abc.def.ghi")]
public string Dept2
{
get
{
return (string)this["Dept2"];
}
set
{
this["Dept2"] = value;
}
}
// added as example of different types
[ConfigurationProperty("CheckDate", IsRequired = false, DefaultValue = "7/3/2014 1:00:00 PM")]
public DateTime CheckDate
{
get
{
return (DateTime)this["CheckDate"];
}
set
{
this["CheckDate"] = value;
}
}
}
}
Then, set it up in your web.config file:
<configuration>
<configSections>
<section name="MyConfig" type="WebApplication2.MyConfig, WebApplication2" />
</configSections>
<MyConfig Dept1="xyz.uvw.rst" Dept2="abc.def.ghi" />
...
</configuration>
And then you can call it very easily, along with strong-typing and support for many types:
var dept1 = MyConfig.Settings.Dept1;
var dept2 = MyConfig.Settings.Dept2;
// strongly-typed
DateTime chkDate = MyConfig.Settings.CheckDate;
That's how I would do it. Use the built-in stuff and create a class for it. Easy to do config transforms with, easy to read, and easy to use.
This is an old question but in the event someone needs to know... First geekzsters answer lays out how to write a config class. Then you specify a custom Config Section and give it a configSource in a separate file.
<configuration>
<configSections>
<section name="myCustomSection" type="MyNamespace.MyCustomType" requirePermission="false" />
</configSections>
</configuration>
<myCustomSection configSource="myConfigDir\myFile.config" />
Then in your custom config file you write a normal xml config
<?xml version="1.0" encoding="utf-8"?>
<myCustomSection>
<myCustomType>
<add name="pro1" value="abc" />
<add name="prop2" value="cde" />
<add name="prop3" value="efg" />
</myCustomType>
</myCustomSection>
The simplest way to read configuration File other then Web config is to define file you want to read as follows:
webConfig
<appSettings file="TestFile.config">
<add key="webpages:Version" value="3.0.0.0"/>
<add key="webpages:Enabled" value="false"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
TestFile.Config
<appSettings>
<add key="test" value="testData"/>
</appSettings>
Above we define the file we want to read configuration from in Webconfig. thus using ConfigurationManager.AppSettings['test'] you can read the value from your newly created custom config file.

How to use ConfigurationManager.AppSettings with a custom section?

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();

Storing settings in configFile

Try to save all data in to config file, and then read it and apply to my program during running - as user preference.
Whats done: create new config file (using Add new element-> add congif file). In this file put simple code
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSetting>
<add Key="Volume" value="100" />
</appSetting>
</configuration>
After it create method
public int GetVolumeFromConfigFile()
{
return Convert.ToInt32(ConfigurationManager.AppSettings.Get("Volume"));
}
and in main programm call it like
Value = (MyClass.GetVolumeFromConfigFile());
But it's not work. (During debaggin it's return nothing)
Think it can be few reason:
I need to add (I don't now in what way) what config file to use, because i have few files *.config - one as default (App.exe.config, and another - that i created)
I use incorrect method to get value from config file
Also I read about some another way to store app settings, like store it in *.settings file
What I'm doing wrong and what method prefered?
Additional information - use net 4.0
EDIT
Remove my config file, and add to existed few lines (in strong>)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="PlayDemo.SettingsPlayIt" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<userSettings>
<PlayDemo.SettingsPlayIt>
<setting name="Volume" serializeAs="String">
<value>10</value>
</setting>
</PlayDemo.SettingsPlayIt>
</userSettings>
Here I add my key
<appSetting>
<add key="Volume" value="100" />
</appSetting>
</configuration>
try this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Volume" value="100" />
</appSettings>
</configuration>
and
return Convert.ToInt32(ConfigurationManager.AppSettings["Volume"]);
the appSettings are key value pairs, so you can access it like you would a value in a Dictionary
If you want to use a separate config file, try this:
Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
config.AppSettings.File = "yourFileName"'tell Configuration what file to read
config.Save(ConfigurationSaveMode.Modified) ' save the Configuration setting
ConfigurationManager.RefreshSection("appSettings") ' update just the <appSettings> node
I really like the following technique, using ConfigurationSection. This allows you for painless manipulation of your configuration. But it is more specific upfront.
http://msdn.microsoft.com/en-us/library/2tw134k3%28v=vs.90%29.aspx

Reading keyvalue pairs into dictionary from app.config configSection

I currently have an app.config in an application of mine set up like so:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="DeviceSettings">
<section name="MajorCommands" type="System.Configuration.DictionarySectionHandler"/>
</sectionGroup>
</configSections>
<appSettings>
<add key="ComPort" value="com3"/>
<add key="Baud" value="9600"/>
<add key="Parity" value="None"/>
<add key="DataBits" value="8"/>
<add key="StopBits" value="1"/>
<add key="Ping" value="*IDN?"/>
<add key="FailOut" value="1"/>
</appSettings>
<DeviceSettings>
<MajorCommands>
<add key="Standby" value="STBY"/>
<add key="Operate" value="OPER"/>
<add key="Remote" value="REMOTE"/>
<add key="Local" value="LOCAL"/>
<add key="Reset" value="*RST" />
</MajorCommands>
</DeviceSettings>
</configuration>
My current objective is to foreach or simply read all values from MajorCommands into a Dictionary<string, string> formatted as Dictionary<key, value>. I've tried several different approaches using System.Configuration but none seem to work and I haven't been able to find any details out there for my exact question. Is there any proper way to do this?
using ConfigurationManager class you can get whole section from app.config file as Hashtable which you can convert to Dictionary if you want to:
var section = (ConfigurationManager.GetSection("DeviceSettings/MajorCommands") as System.Collections.Hashtable)
.Cast<System.Collections.DictionaryEntry>()
.ToDictionary(n=>n.Key.ToString(), n=>n.Value.ToString());
you'll need to add reference to System.Configuration assembly
You are almost there - you just have nested your MajorCommands a level too deep. Just change it to this:
<configuration>
<configSections>
<section
name="MajorCommands"
type="System.Configuration.DictionarySectionHandler" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<MajorCommands>
<add key="Standby" value="STBY"/>
<add key="Operate" value="OPER"/>
<add key="Remote" value="REMOTE"/>
<add key="Local" value="LOCAL"/>
<add key="Reset" value="*RST" />
</MajorCommands>
</configuration>
And then the following will work for you:
var section = (Hashtable)ConfigurationManager.GetSection("MajorCommands");
Console.WriteLine(section["Reset"]);
Note that this is a Hashtable (not type safe) as opposed to a Dictionary. If you want it to be Dictionary<string,string> you can convert it like so:
Dictionary<string,string> dictionary = section.Cast<DictionaryEntry>().ToDictionary(d => (string)d.Key, d => (string)d.Value);
I would probably treat the config file as an xml file.
Dictionary<string, string> myDictionary = new Dictionary<string, string>();
XmlDocument document = new XmlDocument();
document.Load("app.config");
XmlNodeList majorCommands = document.SelectNodes("/configuration/DeviceSettings/MajorCommands/add");
foreach (XmlNode node in majorCommands)
{
myDictionary.Add(node.Attributes["key"].Value, node.Attributes["value"].Value)
}
If document.Load doen't work, try converting your config file to xml file.

Categories

Resources