How to have a common ConfigSource file for ConfigSections and connectionStrings? - c#

My project has 2 different config sections(one technical & one functional) and some connection Strings.
I would like to have in a same configSource file, the technical config section & the connection strings & in an other one the functional section. I know how to do this in 3 separate files but not in 2. It would be logical to have technical configuration like server hostnames & connection string in the same file.
My configuration files should look like this:
App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="MyService.Functional" type="Logger.ConfigHandler, Logger"/>
<section name="MyService.Technical" type="Logger.ConfigHandler, Logger"/>
</configSections>
<MyService.Functional configSource="Config\MyService.Functional.Config"/>
<MyService.Technical configSource="Config\MyService.Technical.Config"/>
<connectionStrings configSource="Config\MyService.Technical.Config">
</connectionStrings>
</configuration>
MyService.Technical.Config
<MyService.Technical.Config>
<MyResourceServer value="tcp://MyServer:9000"/>
</MyService.Technical.Config>
<connectionStrings>
<add name="MyEntities" [...] />
</connectionStrings>
However if I mix the section MyService.Technical & the connectionStrings in the same file, the ConfigurationManager can't load any section anymore.
Do you have any tip to do this ? Is it absolutely mandatory to have 3 separate files for this case ?

From my experience, it seems to load the contents of the file as the inner XML of the referring element, which would mean you need to have different files for each section being externally referenced.

Related

Config file in C# with a simple syntax?

I'm building a C# (WPF) application and I would like to use a simple configuration to define the file paths.
The purpose is for the user to be able to read and/or modify the configuration file easily and without having to learn any complicated syntax (or boilerplate), and to do it using a simple text editor.
I've been reading about the App.config file and from what I understand it is really complicated to modify by hand.
In the past in Windows and in Linux (even today) there were very simple Key=Value files that are exactly what I'm used to - however I see that C# doesn't have any builtin support for INI file reading/parsing.
Can an App.config file be modified easily by a user that isn't familiar with the syntax? If not is there any easy alternative?
For ease of editing, and to remove the complexity of the file as a whole, you can split the appSettings section out to a separate file, referenced from app.config...
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!- stuff in here -->
</configSections>
<appSettings configSource="myCustomisableSettings.config" />
</Configuration>
The separate file should look like this.
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="FirstPathKey" value="FirstPath" />
<add key="SecondPathKey" value="SecondPath" />
</appSettings>
For this situation, either using the app.config or web.config there is an appsetting's section that can contain key/value pairs for storing information such as file paths etc that are easily modifiable and readable:
<configuration>
<appSettings>
<add key="myFilePath" value="pathToFile" />
</appSettings>
....
</configuration>
you can add as many sections within the appSettings as you need
The App.config file is easily modified. The below is a standard App.config with a custom value.
<!-- Start Ignore here -->
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<!-- End ignore here, the below is what you want -->
<appSettings>
<add key="myCustomPath" value="C:\Path\To\Something"/> <!-- The user can edit this value -->
</appSettings>
</configuration>
As you can see all the user has to do is change the value under the appSettings node. It's that simple.
Then to access the value (in your code) all you have to do is call the ConfigurationManager:
var path = ConfigurationManager.AppSettings["myCustomPath"];

Include ConnectionStrings from class library's config file [duplicate]

This question already has answers here:
How to access a custom config from my class library application?
(3 answers)
Closed 8 years ago.
This questions has been asked quite a few times here, but I cannot seem to apply any of the answers to my case. So here we go again.
I have two projects, ProjectA and ProjectB. ProjectA is a class library and uses Entity Framework, which (by default) writes its model settings to the App.config file. ProjectB on the other hand, is an executable with its own Web.config file and references ProjectA in order to satisfy its data access needs. Of course, the problem is that at run-time, ProjectB's web.config is read since it's the "executing assembly", which means I need to include all the connection strings from ProjectA's app.config in ProjectB's web.config.
I really don't like the idea of manually copying these connection strings. I'm wondering if there's a way to tell ProjectB's web.config to replace its connectionStrings section with the one in app.config of ProjectA. So in theory, I'd start with something like this:
ProjectA (App.config):
<configuration>
<connectionStrings>
<add name="MyModelContext" connectionString="blahblah" />
</connectionStrings>
</configuration>
ProjectB (Web.config):
<configuration>
<connectionStrings>
</connectionStrings>
<configuration>
After building the project/at runtime:
ProjectB (Web.config):
<configuration>
<connectionStrings>
<add name="MyModelContext" connectionString="blahblah" />
</connectionStrings>
<configuration>
Is this feature supported?
You can replace just about any app.config/web.config section with an external file by using the configSource attribute.
In your web.config, where connectionStrings.config is your app.config connectionStrings section from ProjectA:
<connectionStrings configSource="connectionStrings.config" />
The configSource is a path relative to the web.config file, so you can point it at any file within your application, e.g. config\connectionStrings.config.

How to stop .Net looking for .config files for my executable

I have a program called parser.exe and it uses a config file called parser.config (a txt format; I read it with streamreader). For some reasons C# complains and doesn't like this.
Unhandled Exception:
System.Configuration.ConfigurationErrorsException: Configuration
system failed to initialize --->
System.Configuration.ConfigurationErrors
BUT if I created a file called parser.exe.config. with just followng content application runs fine:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>
Why this is happening and how to suppress this problem without having parser.exe.config and changing the config name from parser.config to parser.exe.config?
it uses a config file called parser.config (a txt format; I read it with streamreader)
There's no need for this. .NET already has a perfectly good framework for application configuration files. Just add an app.config file to your project and Visual Studio will automatically create a parser.exe.config file when you build.
You can then use the ConfigurationSettings.AppSettings dictionary to read individual configuration items - or use more complex structured for more complex configurations.
To use an external configuration file for a config section, just use the configSource attribute in app.config:
<configuration>
<appSettings configSource="parser.config" />
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
parser.config:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="Test" value="This is a test"/>
</appSettings>
why this is happening?
That's the way the framework was designed - it will look for a {executable name}.config file by default - you can add external config files as explained above but there's no way that I know of to have the framework look for a different file name by default.
You could load a new file into a separate configuration object:
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = #"parser.config";
var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
But then you have to use that config instance to access config settings:
Console.WriteLine(config.AppSettings.Settings["test"].Value);
instead of
Console.WriteLine(ConfigurationManager.AppSettings["test"]);
But that seems like a long way to go to avoid the default config file name.
You can tell .NET to look for your settings in another file, like this:
<configuration>
<appSettings file="parser.config"></appSettings>
</configuration>

Custom configuration file for different solution projects

I have more than one solution projects for an application with using one app.config for each solution.
Can i do a separate configuration file (other than app.config) for common setting like db name (connection string) ?
Because currently i put these setting in each and every app.config file.
Please try following.
Create one config called "common.config" like below which will be common to all solutions and let's say it's located # "E:/myconfig". Please keep all common setting in this config.
<appSettings>
<add key="connstring" value="conn string value" />
</appSettings>
Now link this common config in you specific solution config lets say web.config using file attribute
<configuration>
<appSettings file="E:\myconfig\Common.config">
<add key="key1" value="value" />
</appSettings>
</configuration>
Hope this will work for you.

How to have different parts of config file in c#

what I am trying to do is for my App.config file i have a bunch of settings, and what i want to do split up my config file into different files. For example; my app.config file file has setting pertaining to emails, so i want to take those settings out and store it in an email.config file and then in my app.config file use the configSource attribute to add thos settings from the email.config file and add it to the app settings node. Is this possible?
If so please advice on how to acheive the above result.
Many thanks.
so for example i have another config file called app1.config and has the following xml:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings >
<add key="l" value="test"/>
</appSettings>
</configuration>
and then from my main app.config file have a reference to the app1.config file and then from code be able to do this to get the value of the app setting key:
var x = ConfigurationManager.AppSettings["l"];
EDIT to reflect changed question and additional comments:
For custom settings defined in the <appSettings> part of the config file there is a file attribute that can contain the path to a file that overrides the appSettings parameters:
http://www.codeproject.com/Articles/8818/Using-the-File-attribute-of-the-appSettings-elemen
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="settings.config">
</appSettings>
</configuration>`
You can indeed also use the configSource attribute, as specified in the MSDN documentation:
http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource.aspx
The ConfigSource property represents the value of the configSource attribute that is specified for a ConfigurationSection object that is associated with the SectionInformation object.
A ConfigurationSection implementation can optionally specify a separate file in which the configuration settings for that section are defined. This can be useful in multiple ways:
Using include files can result in a more logical and modular structure for configuration files.
File-access security and permissions can be used to restrict access to sections of configuration settings.
Settings in an include file that are not used during application initialization can be modified and reloaded without requiring an application restart.
The following example shows how this attribute is used in a configuration file to specify that the pages section is defined in an external include file:
<pages configSource="pages.config"/>
Or, if you want to store info from the same section in separate files, you can always revert to using the ConfigurationManager.Open...Configuration functions and read the settings programatically:
http://msdn.microsoft.com/en-us/library/ms134262.aspx
You can use the built in configuration section for smtp settings in a file of its own:
<system.net>
<mailSettings>
<smtp deliveryMethod="network">
<network
host="localhost"
port="25"
defaultCredentials="true"
/>
</smtp>
</mailSettings>
</system.net>
This can be referenced in your app.config using configSource.
You can limit this to the smtp section alone, if you want:
<system.net>
<mailSettings>
<smtp configSource="smtp.config" />
</mailSettings>
</system.net>
You could do this using the configSource attribute:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings configSource="cs.config" />
</configuration>
ConfigSource maps an entire section to an external file. Once you've added it, you can't use the section in the root config file anymore. neither can you have more than one mapping per section.
You could create a custom config section, as suggested above, with the sections you want to map & then map each section in turn.
web.config:
<myConfig>
<mysection1 file="section1.config"/>
<mysection2 file="section2.config"/>
</myConfig>
section1.config:
<mysection1>
<add key="key1" value="val1"/>
</mysection1>

Categories

Resources