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

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.

Related

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

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;
}

How to read app.config file programmatically

I have config file for my app, my app.config is as below
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
</configSections>
<appSettings>
<add key="log4net.Config" value="log4netConfig.xml" />
<add key="proxyaddress" value="192.168.130.5"/>
</appSettings>
<system.net>
<defaultProxy enabled ="true" useDefaultCredentials = "true">
<proxy autoDetect="false"
bypassonlocal="true"
proxyaddress="192.168.130.6"
scriptLocation="https://ws.mycompany.com/proxy.dat"
usesystemdefault="true"
/>
</defaultProxy>
</system.net>
</configuration>
var proxy= ConfigurationManager.AppSettings["proxyaddress"];
will get "192.168.130.5",
How to get all proxy settings in system.net section in c#?
Updated: I changed my config to the following and get it:
string proxyURLAddr = ConfigurationManager.AppSettings["proxyaddress"];
Config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
</configSections>
<appSettings>
<add key="log4net.Config" value="log4netConfig.xml" />
<add key="proxyaddress" value=""/>
</appSettings>
<system.net>
<defaultProxy enabled ="true" useDefaultCredentials = "true">
<proxy usesystemdefault ="True" bypassonlocal="False"/>
</defaultProxy>
</system.net>
</configuration>
toosensitive, your app.config when built and deployed will be renamed to : name of of your assembly + (.exe or .dll) + ".config". The answer above is valid for web applications, but not for console ones, libraries and windows services. You can't put app.config alongside with any assembly and expect this assembly to start reading the appSettings section, the same way IIS reads web.config files. I think this is why you receive null.
Update 2:
You can read the values like described here but for local app settings configuration file:
var proxy = System.Configuration.ConfigurationManager.GetSection("system.net/defaultProxy") as System.Net.Configuration.DefaultProxySection
if (proxy != null)
{ /* Check Values Here */ }
For custom sections you can use the following steps:
You have define a custom configsection class derived from ConfigurationSection:
public class ProxyConfiguration : ConfigurationSection
{
private static readonly ProxyConfiguration Config = ConfigurationManager.GetSection("proxy") as ProxyConfiguration;
public static ProxyConfiguration Instance
{
get
{
return Config;
}
}
[ConfigurationProperty("autoDetect", IsRequired = true, DefaultValue = true)]
public bool AutoDetect
{
get { return (bool)this["autoDetect"]; }
}
// all other properties
}
After that you can use the class instance to access the values:
ProxyConfiguration.Instance.AutoDetect
You can find an example in MSDN

Can I create custom method for ConfigurationManager class

My web config is as follows:
<appSettings>
<add key="One" value="1" xdt:Transform="Insert"/>
</appSettings>
If I need to access the value 1, I can write the below code:
ConfigurationManager.AppSettings("One");
But if the web config is like,
<countryAppSettings>
<add key="Two" value="2" xdt:Transform="Insert"/>
</countryAppSettings>
can I access the value in the following form, using a helper class for ConfigurationManager class
ConfigurationManager.CountryAppSettings("Two");
Is this possible in c#?
Yes you can do this, although you do also need to include a custom config section in your configuration file. There's an MSDN article here describing how to do it.
So you'll need to add in your custom configuration section first:
<configuration>
<configSections>
<sectionGroup name="countrySettings">
<section name="countrySetting" type="Custom.CountrySettingSection" allowLocation="true" allowDefinition="Everywhere" />
</sectionGroup>
</configSections>
</configuration>
You'd then typically define your settings more like this, which is great if you've got a really rich object:
<countrySetting customKey="2">
<richerObject>2</richerObject>
</countrySetting>
You'd then need a backing object constructed like so:
namespace Custom
{
public class CountrySettingSection : ConfigurationSection
{
// Create a "customKey" attribute.
[ConfigurationProperty("customKey", DefaultValue = "0", IsRequired = false)]
public int CustomKey
{
get
{
return (int)this["customKey"];
}
set
{
this["customKey"] = value;
}
}
}
You can't create that way. maybe should visit this link
https://msdn.microsoft.com/en-us/library/bb383977.aspx
ConfigurationManager.AppSetting is property ,no method. This
property type is NameValueCollection you can use like this
ConfigurationManager.AppSettings["One"] or
ConfigurationManager.AppSettings.GetValues("One")
You can customize your web.config
https://msdn.microsoft.com/en-us/library/2tw134k3.aspx

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

My config file for dll or why cannot parse Section..?

I encountered a problem that I have no way to parse a document standard configurations.
For example:
private string GetConfigKey(string param)
{
Configuration dllConfig = ConfigurationManager.OpenExeConfiguration(this.GetType().Assembly.Location);
AppSettingsSection dllConfigAppSettings = (AppSettingsSection)dllConfig.GetSection("appSettings");
return dllConfigAppSettings.Settings[param].Value;
}
As a result, I get the settings from the file in a form:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="host" value="mail.ololo.by"/>
</appSettings>
<configSections>
<section name="provideConfig" type="System.Configuration.DictionarySectionHandler"/>
<section name="provideMailStatus" type="System.Configuration.DictionarySectionHandler" />
</configSections>
<provideConfig>
<add key="post#gate.ololo.by" value="Mail Subject 1"/>
<add key="guga#gate.ololo.by" value="Mail Subject 2"/>
</provideConfig>
<provideMailStatus>
<add key="status1" value="send"/>
<add key="status2" value="draft"/>
<add key="status2" value="other"/>
</provideMailStatus>
</configuration>
but
Hashtable hashtable =
(Hashtable)ConfigurationManager.GetSection("provideConfig");
foreach (DictionaryEntry dictionaryEntry in hashtable)
{
Console.WriteLine(dictionaryEntry.Key+" "+dictionaryEntry.Value);
}
but that's unfortunately a configSections have a problem. I can not seem to get it.
MB, I go in the wrong direction?
P.S. Config file cannot be named "app.config" - only project dll name
Config file should be named as executable file name and ".config". Even this executable file uses this dll-file.
For example: ConSoleApplication.exe uses MyLibrary.dll. Then config file must be named ConSoleApplication.exe.config
If You need some other name for config file read this
Thank you all, I coped with the problem.
I can tell if someone will be interested.
Configuration Section Designer Codeplex
.NET Configuration Code Generator
Best regards, yauhen.

Categories

Resources