Programatically adding sections to the configuration read from app.config - c#

I am working on a component/assembly that is to be distributed to other developers and included in their systems.
In order to minimize the work they have to do, all configuration is done in a seperate file (my.config).
My current problem is that a library I am using requires configuration to be added to the app.config file of the application. I have no way of modifying this, so that it reads my custom config file.
Is there any way to add a section/setting to the current config, so that it behaves as if it was read from the app.config?
I can add to the app.config, so it must work at runtime only.
Thanks, Jonas

I don't think you can update the configuration without changing the underlying file. It's a read-only thing.

Related

How to manage different settings for each customer?

We have 1 settings file with the customer settings for each costumer, but the problem is that we have to change lots of settings values when releasing a new version for each costumer, as we develop using the test settings. So, its a totally mess.
Whats the best solution for this?
Having one settings file and app.config for each costumer?
Saving the configurations into the database?(we would still have the connection string settings)
Each costumer cant see the settings from the others..
We use a Configuration Transformation for this and have multiple Build (Release) configs like
Release-Internal
Release-CustomerA
Release-CustomerB
You can have one "base" config file and just replace the values you need for the specific configuration.
Your file structure would look like this afterwards
app.config
app.Release-Internal.config
app.Release-CustomerA.config
app.Release-CustomerB.config
We usually use this for the connection strings and some specific view settings.
Visual Studio only has nativ support for ASP.NET projects (for whatever reason), but there are multiple Plugins to enable this for other .NET projects.
I can recommend Configuration Transform (I like this one better) or SlowCheetah.

Migrate away from settings file

I use a settings file in my project in addition to a configuration file, and I wish to move away from using the settings file in preference to the configuration file.
The settings file is the default .net application setting mechanism (ApplicationSettingsBase), and my configuration file is a custom class that I serialize and deserialize manually.
I have successfully in the past applied the NeedUpgrade/Upgrade() logic to keep settings from previous versions, but somehow it seems settings are lost non-the-less.
The difference with this project in regards to earlier projects, is that it is deployed using Click-Once.
To work around the problem, I wish to move away from the settings file all together and rather use my configuration file which is stored in a static folder (Environment.SpecialFolder.LocalApplicationData), but I do not know how I best would proceed in managing this migration/change.
Any advice is appreciated.

C# App.config vs Settings File

This may sound like a trivial question, however I have looked over the web briefly and what I found was that app.config is basically an older mechanism for storing Application key/pairs of data for the application.
What I want to know is there any reason we (as .NET developers) would opt to use app.config over a Settings file ?
-Can someone please provide some pros and cons on both so we can use them properly.
thanks again
App.config for desktop applications and Web.config for web applications are part of .NET configuration system. Primarily they are used to control .NET framework settings in respect to our application. These are such configuration settings as substitutions of versions of assemblies (section <assemblyBinding>), substitution of .NET framework version (<startup>) etc. (see msdn for the full app.config schema.) One section is dedicated for custom settings of application developers (<appSettings>). There is also a possibility to create custom sections. So, when we need to store settings we can either piggy-back on the app.config or create our own separate configuration files.
Here are pros and contras of using app.config:
Pro: There is already a standard API in .NET to read settings from appSettings section. If you only need just a couple of config settings, it is much easier to use this ready API than to develop and test your own class to read your config files. Also, app.config file is already included in VS project for you.
Pro: There is a standard hierarchy of machine.config/app.config. If you plan such settings that can be set machine-wide and overridden or left as-is for individual applications, you should use app.config.
Pro/Con: App.config is cached in run-time. If you anticipate updates of it while your application is running, you need to specifically request refresh of certain section of config file. For web.config the web app is automatically restarted when something is changed in the file. This is quite convenient.
Con: app.config is stored in the same directory as your .exe file. Normally it will be in a subfolder of C:\Program Files. This directory is extra protected in Windows 7 from writing. You need to be member of Administrators group to write there and if your UAC (User Access Control) level in Control Panel is not set to 0 (which normally is not), you will be asked by the OS to confirm writing to c:\Program Files. So, users without Administrator rights will not be able to change configuration in app.config. Same goes for changing your settings programmatically: your application will get exception when attempts to write app.config if it runs not under an admin user on Windows 7. Your own config files usually go to C:\ProgramData\ or c:\Users subfolder (on Windows 7). These locations are friendlier to writing by users or programs.
Con: If user edited your app.config file and accidentally corrupted it, the whole application will not start with some obscure error message. If your separate config file is corrupted, you will be able to provide more detailed error message.
In conclusion: app.config gives you easier (faster development) approach, mostly suitable for read-only settings. Custom settings file gives you more freedom (where to store file, validation/error handling, more flexibility with its schema) but requires more work during development.
You have it backwards, the settings file (or ini file as they were originally called) was the mechanism used to hold application settings (key/value pairs) prior to Windows 95. With the release of Windows 95 it was recommended that application settings be moved into the Windows Registry (which proved problematic since if you screwed up your registry your Windows may no longer be able to start).
The .config file came into play with .Net. The XML format allows more dynamic and complex settings configurations than simple key/value pairs.
The modern user/settings file is an XML extension of the .config file (settings that can override certain settings in the .config under specific conditions).

How to read values from App.config in .Net 4.0 using configurationManager?

I am creating a windows service in .Net 4.0 and testing some functions of said service with a windows forms client by referencing the service project.
The service project has an App.config file and that file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<clear />
<add name="myLocalMySQLDBUsername" connectionString="username"/>
</connectionStrings>
</configuration>
When a function belonging to the service calls:
ConfigurationManager.ConnectionStrings("myLocalMySQLDBUsername").ConnectionString
a null reference error is thrown because my connection string is not loaded. The only connectionStrings that are loaded are from the machine.config file located in c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Config\machine.config
If I create an application scope setting for the service, I can get that setting by using the My.Settings.setting -> so it's not like the App.config file is not being read.
My question is: why are my connectionStrings not being loaded from the App.config file?
Thank you for your help.
UPDATE:
Also, at this point, even a work around would be appreciated; the only reason for using app.config is to be able to encrypt the contents using the DpapiProtectedConfigurationProvider (the contents will have some username/password values for service and database connections).
I tried creating an AppSettings section manually in the app.config but those settings were also not read by the configurationManager (count = 0).
UPDATE 2:
Per a suggestion, I tried to manually open the app.config file like so:
Dim exePath As String = System.IO.Path.Combine(Environment.CurrentDirectory, "ServiceName.exe")
Dim myConfig As Configuration = ConfigurationManager.OpenExeConfiguration(exePath)
So here is the weird part, when I look inside, path is correct (points to my app.config) but the connectionStrings are still being loaded from the machine.config file (my connectionStrings are not loaded)!! ARGH
UPDATE 3:
Okay, so, I figured it out. When referencing a project(parent) from another project(child), the child's app.config is used even if the parent's classes are being used. Thus, I can get the connectionStrings to show up if I copy them over to the child's app.config. When trying to open it manually, my currentDirectory was of the child, not the parent (strange how it did not throw an exception - it wouldn't have been able to find the config file ... it just silently used the machine.config ... oh well).
Thanks all for the help!
The first thing you'll want to do is make sure that the service account has access to the file (if not running as SYSTEM). It sounds like it should be ok though since you mention My.Settings.Setting works.
The other thing to look out for is to make sure that the app.config has the name of the service executable in it - so if the service exe is MyService.exe the app.config must be named MyService.exe.config.
The last thing to make note of: libraries will read from the executable's app.config that loads the library, not the app.config that is with the library. So if you have a project for the service executable MyService and a project for the library MyServiceLibrary the code in the library will read the app.config from MyService not MyServiceLibrary.
I saw some people say this problem might be fixed by manually re-adding a reference to System.Configuration.dll
SIDE NOTE: If that really is you whole app.config file and not just a snippet then that is your problem... you're app.config file should be MUCH more complicated or .NET will not be able to load it.
WORK AROUND: Use the configuration manager to open this config file (there is an API for that.) You can't get it to load auto-magically just tell the config manager to open it.
I still think the problem is your config file is invalid -- could you please post the FULL file?
Make sure the config file is deployed to the same folder as the executable file, and that it's called your.assembly.exe.config.
I had a similar problem, but in my case it was because I had changed the project's namespace. This is also used as the application settings section element name in the config file, so the code was not finding the new section name. Fiddling with one of the custom setting's values in the project properties and rebuilding caused the new section to written into the app.config alongside the old ones which was what indicated the issue to me.

Overriding App.Config settings

We have an app.config file that lists specific endpoint addresses and also some additional service settings. We would like to change these settings using an external config file set by the environment that it is placed in. What we would like it to do is dynamically read the external config file for that environment without hard coding values.
I know there is a way to specify an external file in the section specific to that section. Is there a way to dynamically set this location?
I ended up just setting it to an external config file by modifying the setting with:
System.Configuration.AppSettingsSection appsettings = config.AppSettings;
appsettings.File = Environment.CurrentDirectory + "\\configs\\" + configFile;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appsettings");
That will allow you to dynamically set it to whatever config file you want it to be.
Your first question - yes, you can "override" any configuration section (such as <client>, <bindings> etc. not section group such as <system.serviceModel>) with an external file:
<client configSource="yourCustomClient.config" />
Visual Studio will highlight this with errors - but it works! - it's just a deficiency of Visual Studio's editor here.
Your second question: no, I don't believe there's any way to make this truly dynamic - the best I can think of is having some sort of an XML transformation of your config file at build and/or install time.
I do think this link will help you do dynamically load any App.Config file and use WCF services.
Yours,
Alois Kraus
My recommendation is to do any wcf configuration within the xap and passing in the environment information as a parameter. All WCF configuration calls can be done through code without the use of the settings in the web.config

Categories