How to retrieve key value from custom.config file in c# - c#

I am able to get Key values from app.config file by below way, Looking for to retrieve it from other.config file. I need to declare all key values in separate .config file.
How can we allocate ConfigurationManager class for other.config file ?
App.Config :
<appSettings>
<add key="Title" value="Configuration Example"/>
<add key="Language" value="CSharp"/>
</appSettings>
Key Retrieval by ConfigurationManager class:
var title = ConfigurationManager.AppSettings["Title"];
var lang = ConfigurationManager.AppSettings["Language"];
Unfortunately, I found all examples for default app.config or web.config file.
Is it possible to manage it with custom.config file ?

Could you not use configSource
web.config / app.config, Replace appSettings section with <appSettings configSource="ShareAppSettings.debug.config"/>
Then have a external file called "ShareAppSettings.debug.config" with all the settings in
<appSettings>
<add key="Version" value="3.0.0.0" />
<add key="Enabled" value="false" />
</appSettings>
Verify that the External file has the property set to Copy to Output Directory.
Load the setting via
var version = ConfigurationManager.AppSettings["Version"];

ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = configPath;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var val=config.AppSettings.Settings[key].Value;

Related

Modify appSettings in the custom config file which is referenced via 'file' attribute

In appSettings section of Web.config a file attribute is used referencing a custom config file. The goal is to have possibility to modify some app-settings in the custom config without causing the application to be restarted.
Web.config
<appSettings file="CustomAppSettings.config">
<add key="key1" value="val2" />
</appSettings>
CustomAppSettings.config
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="customKey1" value="custVal2"/>
</appSettings>
The following code does not work. It saves the value to Web.config but expected is to save it to the CustomAppSettings.config because so it will not restart the application (Source).
var configuration = WebConfigurationManager.OpenWebConfiguration("~/");
configuration.AppSettings.Settings[key].Value = value.ToString();
configuration.Save();
This does not work as well.
var configuration = WebConfigurationManager.OpenWebConfiguration("~/CustomAppSettings.config");
What am I doing wrong? Could someone point me to the right direction?
use configSource instead of file.
<appSettings configSource="CustomAppSettings.config" />
use ConfigurationSaveMode.Minimal on saving.
var configuration = WebConfigurationManager.OpenWebConfiguration("~/");
configuration.AppSettings.Settings[key].Value = value.ToString();
configuration.Save(ConfigurationSaveMode.Minimal);

MVC 4 dedicated configuration file

I have to add some constants to MVC 4 project.
Adding them to in web.config will work:
<appSettings>
<add key="MyConst1" value="123"/>
<add key="MyConst2" value="321"/>
<add key="MyConst3" value="234"/>
</appSettings>
Is there a way to create separate config file for this constants?
I guess you want to separate your appSettings from web.config, you can store them in a separate file and then specify that in your web.config under appSettings's configSource like:
<appSettings configSource="MySettings.config" />
and then you can have your settings in MySettings.config as:
<?xml version="1.0" encoding="UTF-8"?>
<appSettings>
<add key="MyConst1" value="123"/>
<add key="MyConst2" value="321"/>
<add key="MyConst3" value="234"/>
</appSettings>
You may see: Using configSource to split configuration files
If you put your code snippet in a file called appSettings.config, you can simply reference that file in your web config:
<appSettings configSource="appSettings.config" />

Read AppSettings from a secondary webconfig

I created a second web config and placed it in a folder:
~/Configuration/OtherConnections.config
My config file looks like:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="serverurl" value="http://serverUrl" />
<add key="UserName" value="myUser" />
<add key="Password" value="XXXXXXX" />
</appSettings>
</configuration>
When I attempt to read the value from one of the items like:
string connectionInfo = ConfigurationManager.AppSettings["UserName"];
I do not get a value back. Is this because the web config is in a folder, or is there something else going on in this web app?
I do not get a value back. Is this because the web config is in a folder ... ?
No, not the folder but the filename. You can use ~/Configuration/Web.config but then you have to explicity open it:
var config = WebConfigurationManager.OpenWebConfiguration("~/Configuration");
And then to read from it:
string url = config.AppSettings.Settings["serverurl"].Value;
Note that you cannot specify (and thus not change) the actual web.config file name. Just the folder.
you can have only one web.config file for each web folder
There are tow options anyway:
In the IIS Manager you need to configure the sub folder as a new application. It uses the web.config file from the running app.
Another option is using a single config file and adding a <location> section to segment the file to act differently for some folders or files. (which I would suggest more info here)
You can access multiple config files by using WebConfigurationmanager method. add namespace:
using System.Web.Configuration;
So, to access the appSettings of
../SomeProjectFolder/Environment/Web.config, you can do:
var config = WebConfigurationManager.OpenWebConfiguration("~/SomeProjectFolder/Environment/");
string username = config.AppSettings.Settings["username"].Value;
Hope this helps.

update app.config file programmatically with ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

update app.config file programmatically with
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
this is my xml
<configuration>
<configSections>
<section name="nhibernateSettings" type="ProjectBase.Data.OpenSessionInViewSection, ProjectBase.Data" />
</configSections>
<appSettings>
<add key="NHibernateConfigPath" value="D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\NHibernate.config" />
<!--<add key="NHibernateConfigPath" value="C:\_ZAGON\ViaMura\CurrencyApp\at\NHibernate.config" />-->
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<connectionStrings>
<add name="connectionString" connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Viamura_at;Data Source=.\SQL2008" providerName="System.Data.SqlClient" />
<!--<add name="connectionString" connectionString="server=193.37.152.24\SQL2008;User Id=DBUser;password=Lualah8991;database=Viamura_at" providerName="System.Data.SqlClient" />-->
</connectionStrings>
<nhibernateSettings>
<!-- List every session factory that will be needed; transaction management and closing sessions
will be managed with the open-session-in-view module -->
<sessionFactories>
<clearFactories />
<sessionFactory name="WebCrawlerFactory" factoryConfigPath="D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\NHibernate.config" isTransactional="true" />
<!--<sessionFactory name="WebCrawlerFactory" factoryConfigPath="C:\_ZAGON\ViaMura\CurrencyApp\at\NHibernate.config" isTransactional="true" />-->
</sessionFactories>
</nhibernateSettings>
how can I programmatically edit WebCrawlerFactory? I am using
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
You can use the following code:
private void UpdateConfig(string key, string value, string fileName)
{
var configFile = ConfigurationManager.OpenExeConfiguration(fileName);
configFile.AppSettings.Settings[key].Value = value;
configFile.Save();
}
Where: fileName is the full path + application name (c:\project\application.exe)
In your case, change the AppSetting by Sections:
configFile.Sections["nhibernateSettings"]
The ProjectBase.Data.OpenSessionInViewSection indicates that there is already a custom config section defined that will allow access to the config settings. It may, however be protected or internal to NHibernate.
See if you can reference that class to access the settings.
You could also create a custom configuration section yourself, however it would cause NHibernate to be improperly configured since it would not be able to load the config section properly.
see How to: Create Custom Configuration Sections Using ConfigurationSection

Best practice to include log4Net external config file in ASP.NET

I have seen at least two ways to include an external log4net config file in an ASP.NET web application:
Having the following attribute in your AssemblyInfo.cs file:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log.config", Watch = true)]
Calling the XmlConfigurator in the Global.asax.cs:
protected void Application_Start()
{
XmlConfigurator.Configure(new FileInfo("Log.config"));
}
What would be the best practice to do it?
At startup, call:
XmlConfigurator.Configure();
In your Web.config, specify log4net.Config in appSettings:
<add key="log4net.Config" value="Log.config" />
This special setting allows you to change the log configuration without having to recompile. Especially helpful for moving between multiple environments.
Example
Consider the following project file structure:
\config\log4net\debug.config
\config\log4net\staging.config
\config\log4net\release.config
\config\appSettings\debug.config
\config\appSettings\staging.config
\config\appSettings\release.config
Application and logging configurations are distinguished for each environment. References to the logging configurations are maintained in the application settings.
\config\appSettings\debug.config:
<appSettings>
<add key="log4net.Config" value="config\log4net\debug.config" />
...
</appSettings>
\config\appSettings\staging.config:
<appSettings>
<add key="log4net.Config" value="config\log4net\staging.config" />
...
</appSettings>
\config\appSettings\release.config:
<appSettings>
<add key="log4net.Config" value="config\log4net\release.config" />
...
</appSettings>
Changing environments is a simple matter of updating the appSettings file in Web.config.
<appSettings file="config\appSettings\staging.config">
...
</appSettings>
I was dissatisfied with the "magic" configuration approach, because I wanted to specify my configuration in a path with an environment variable (%PUBLIC%\MyApp\MySettings.config).
So instead, I have this in my app.config:
<add key="MyLog4NetConfigFile" value="%PUBLIC%\MyApp\MySettings.config"/>
And do this to set my log4net configuration:
var configFile = ConfigurationManager.AppSettings.Get("MyLog4NetConfigFile");
if( !string.IsNullOrEmpty(configFile))
{
configFile = Environment.ExpandEnvironmentVariables(configFile);
XmlConfigurator.Configure(new FileInfo(configFile));
}

Categories