Centralize connection strings for multiple projects within the same solution - c#

I currently have three projects in my solution that all have their own App.config file with the same exact connection string.
Is there a way to consolidate the connections strings / app.config files so that I only need to make changes to one location?

You can share the connection strings among multiple projects in a solution as follows:
Create a ConnectionStrings.config file with your connection strings under a solution folder, this file should contain only the section connectionStrings
In your projects, add this config file As a Link (add existing item, add as link)
Select the added file and set its property Copy to Output Directory to Copy always or Copy if newer
In the App.config of your projects, point to the linked ConnectionStrings.config file using the configSource attribute:
<connectionStrings configSource="ConnectionStrings.config" />
ConnectionStrings.config
<connectionStrings>
<add name="myConnStr" connectionString="Data Source=(local); Initial Catalog=MyDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
...
<connectionStrings configSource="ConnectionStrings.config" />
...
</configuration>
Read more details....

There's a few ways you could do it:
Put common configuration settings in machine.config as shown here
Put common configuration settings in a central file and link to that in each projects's app.config as shown here
Store the configuration settings in the registry
For me, i always work with the last solution :)
Good luck!

First, take a look at this post. It describes how you can share the same app.config between multiple projects.
How to Share App.config?
Second, take a look at one other post, which describes how you let different app.config-files have a reference to one single shared xml-file which contains the connection strings.
Use XML includes or config references in app.config to include other config files' settings

Related

Read configuration from App.config instead of AppName.exe.config

I have developed a small windows service which performs few database operations. I have to give an option to the user to change server name on post-deploy. if user changes in app.config it doesn't affect the service, it is still reading connection strings from AppName.exe.config.
Here what I have tried.
<connectionStrings>
<add name="testString" connectionString="Data Source=ServerAddresss;Initial Catalog=DatabaseName;Integrated Security=True;" />
</connectionStrings>
C# code,
ConfigurationManager.ConnectionStrings["ProjectName.Properties.Settings.testString"].ConnectionString);
This returns a server connection string from AppName.exe.config file but I want to access it from App.config file.
can someone help me out in this?
App.config and AppName.exe.config aren't exactly separate - AppName.exe.config is the build output of app.config.
In other words, once the service is deployed, there shouldn't even be an app.config to change, and if there is, changing it won't do anything. AppName.exe.config is where your application gets "app.config" values.
If you need different configuration values for different environments, take a look at config transformations. They allow you to change or replace sections or individual values for different configurations such as debug, release, or other custom configurations.
This is useful because it means that all of the connection strings are part of the project and are in source control. You can do without this and just edit the config file in place on the server, but then there will be nothing in source control indicating where the connection string came from. And then if you redeploy the service the change will be overwritten unless someone remembers to make the same change every time. Having it in source control is much better.
For some reason that I do not understand, you can right-click a web.config and select "Add Config Transforms", but you can't do that with an app.config. Maybe there's a good reason.
You can install this extension which enables the same behavior for app.config. Then you can right-click on app.config and add a transformation for another configuration, like Release.
In that file (app.Release.config) add this:
<connectionStrings xdt:Transform="Replace">
<add name="testString" connectionString="...your Release connection string..." />
</connectionStrings>
When you build and deploy using the Release configuration it will replace the connectionStrings section with this one, leaving everything else just as it is. You can also right-click app.Release.config and select "Preview Config Transforms" to see the transformed file side-by-side with the original.
You should be able to just pull in an arbitrary file with a ConfigurationFileMap
System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(strConfigPath); //Path to your config file
System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
This question is a possible duplicate of: Using ConfigurationManager to load config from an arbitrary location
Also, you'll have to be sure that the service is restarted after updating the config file (either config file).

Reference connection strings in config from a separate project

I have a parent application which has a config file that contains connection strings.
I would like all child applications I develop to be able to reference this config file so I only have to update connection strings in one place.
Parent Application web.config
<connectionStrings configSource="ConnectionStrings.config"/>
Parent Application ConnectionStrings.Config
<?xml version="1.0"?>
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=***;Initial Catalog=***;Integrated Security=False; Password=***;User ID=***" providerName="System.Data.SqlClient" />
</connectionStrings>
This works fine for bringing in data in the parent application.
I've added the ConnectionStrings.config file to my child application as a linked file and then reference it in the web.config as follows:
Child Application web.config
<connectionStrings configSource="ConnectionStrings.config"/>
But when I run the child application I get the following error:
Unable to open configSource file 'ConnectionStrings.config'.
(C:\Child Application\web.config line 8)
Any ideas?
Thanks
Under the child project, open the file properties of the linked ConnectionStrings.config file and set Copy To Output Directory to Copy always. You have to do this in order for this file to be copied to the child project bin directory regardless of the setting for the parent project ConnectionString.config file.
You could also use project post build steps and copy configuration file into output directory.

How can I use several Application Configuration Files in one project?

After creating new Visual C# Console Application (.NET Framework 4.5), such project contains default App.config file.
After adding a reference for System.Configuration to project and use it in some source file using System.Configuration; I can use static class ConfigurationManager to operate with App.config file. But before, I want to add some settings to the file, so it's somehow like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DeployWeb" value="true" />
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Now, I can write something like this, to get the value of the setting:
Boolean deployWeb = false;
Boolean.TryParse(ConfigurationManager.AppSettings["DeployWeb"], out deployWeb);
However I didn't set which configuration file to read,but it's okay, because there is the default one. But I can add more configuration files by right click on the project -> Add -> New Item... -> Application Configuration File, so that I have, for example, 5 configuration files, like on the picture:
And ConfigurationManager will still read the default one, but I want to manually control, which config file to use. I want to know, if is there an appropriate way to set to the ConfigurationManager config file name to use etc. and if it's not a bad practice. I know how to use different configurations in debug/release mode, but in my case I have an application, that can be runned in different modes for different purposes in release, for example.
Question: Is it possible to have several configuration files in a project and to have ability to switch which one I want to use. Isn't it a bad practice, shall I use some another approach for my purpose ? Using build events is not suitable in my case (I think).
PS. I am sorry for stretching my question, however my itis quite simple and could be just asked in two sentences, but as the rules says, question should contains details.
UPDATE:
From already existing answer "Option: You can use the ConfigurationManager Class to load an alternate config file by code." From reading msdn I didn't get which of the methods should I use. Should I open Exe configuration ?
It can be done using mapped config file ,
ExeConfigurationFileMap configFileMap =
new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = "App4.config"; // full path to the config file
// Get the mapped configuration file
Configuration config =
ConfigurationManager.OpenMappedExeConfiguration(
configFileMap, ConfigurationUserLevel.None);
//now on use config object
AppSettingsSection section = (AppSettingsSection)config.GetSection("appSettings");

How can I access the connection string in my Web.Config file through a Windows Application

I have my Entity Connection String set in my Web.Config file. In the same solution, I have a Windows Application, and I want to access the Connection String of my Entity. How can I access the connection string that exist in my Web.Config file? Or I have to create a specific one in my Windows Application ?
If you're unfamiliar with adding a config file to a windows app, you must select an "Application Configuration File" from add new items, it will create a file named App.Config which will at compile time become YourProgramsName.exe.config but internally it works mostly just like a web.config with an appsettings section and connectionstrings sections and all the other normal sections.
The best way to share this data between Web and Win config files would be:
Create a separate file that looks like:
<connectionStrings>
<add name="Name"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
and reference it from both config files with:
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<connectionStrings configSource="connections.config"/>
</configuration>
Then just add the connections.config (add existing item by link) to each project.
More reading: http://msdn.microsoft.com/en-us/library/ms254494.aspx
Put the connection string your windows application's App.config.
use this code:
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

Solution wide app.config / web.config?

I have a solution with one asp.net-mvc-2 project, one web service, one class library and three normal desktop apps. Currently I need to copy all app.config settings from one project to the other. That is a nightmare if I want to change something.
I know there is a solution to store all these information in the global .config files, but I am looking for a solution to store the values dedicated to my solution not to my machine. Is that possible?
You can add a single .config file to one of your projects, and then choose Add -> Existing Item... -> Add As Link to add a reference to that file to your other projects. They will all build with the file as if it was their own copy, but there will really only be one copy, and you will only have to make changes in a single place.
I have found a really simple solution here:
1. Create a file CommonSettings.config In your Common, Class library project.
2. Put your common setting in this file:
<appSettings>
<add key="someCommonSetting" value="some value"></add>
<!-- more setting here -->
</appSettings>
Note: <appSetting> has to be the root element in your CommonSettings.config (don't put it under <configuration>)
3. Make sure CommonSettings.config file is copied to output directory:
4. In all other project's App.Config/Web.config files, add the above common settings
That's it... You common settings will be included in every other config file.
<appSettings file="CommonSettings.config">
<add key="Value1" value="123" />
</appSettings>
Note:
For this approach to work, the shared config file should be copied to
the project’s output directory so it is adjacent to the regular
App/Web.config file. Add the existing shared .config file to the
project as a Linked file and set it to ‘Copy if newer’. You should see
something similar to this in your .csproj file:
<None Include="..\CommonConnectionStrings.config">
<Link>CommonConnectionStrings.config</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
You can do the same for ConnectionString, copy all your connection strings in CommonConnectionStrings.config, and in other App.Config/Web.Config, reference it like this:
<connectionStrings configSource="CommonConnectionStrings.config" />
Note: If you are using this solution for connectionStrings, you cannot have a project specific connection string, all of the connection strings will be copied from the common config.
Assuming you could have a path where both your website and webservice could access it, then you could potentially use the appsettings " file " attribute to have the settings stored in one common place.
Refer http://www.codeproject.com/KB/dotnet/appsettings_fileattribute.aspx
Hope this helps!
I would comment on the answer #Sahuagin gave, but I don't have enough reputation. This does work with App.config files, but you have to add a text file, then call it App.config. After that just declare the XML (as seen below)
<configuration>
<!-- add you values or whatever here-->
</configuration>
Then do as #Sahuagin said and add it as a link to your solution. It works a treat.

Categories

Resources