Solution wide app.config / web.config? - c#

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.

Related

How to add transformed web.$configuration.config files to project

I have a web service project where I have one main web.config file and then different environment specific files as well like web.Staging.config/web.QE.config etc. Now, I am following this: http://www.hanselman.com/blog/ManagingMultipleConfigurationFileEnvironmentsWithPreBuildEvents.aspx to add a prebuild event to my project to copy the configuration specific config file to the main web.config file but the problem is, it copies it without transforming and hence resulting into something like below:
<add key="somekey" value="Development" xdt:Transform="Replace" xdt:Locator="Match(key)"/>
My question is, is there a way to keep the transformed config files ready to be copied while building the project?
You can use SlowCheetah to do the transform for you.This work with multiple environment QA, UAT etc. This also has provided as nuget package
https://marketplace.visualstudio.com/items?itemName=VisualStudioProductTeam.SlowCheetah-XMLTransforms
Recent new feature in 2017 15.8.4 has feature for managing secret. Its worth to have a look
https://channel9.msdn.com/Shows/Visual-Studio-Toolbox/Managing-User-Secrets/?utm_source=vs_developer_news&utm_medium=referral

Centralize connection strings for multiple projects within the same solution

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

What is App.config in C#.NET? How to use it?

I have done a project in C#.NET where my database file is an Excel workbook. Since the location of the connection string is hard coded in my coding, there is no problem for installing it in my system, but for other systems there is.
Is there a way to prompt the user to set a path once after the setup of the application is completed?
The answers I got was "Use App.Config"... can anyone tell what is this App.config and how to use it in my context here?
At its simplest, the app.config is an XML file with many predefined configuration sections available and support for custom configuration sections. A "configuration section" is a snippet of XML with a schema meant to store some type of information.
Overview (MSDN)
Connection String Configuration (MSDN)
Settings can be configured using built-in configuration sections such as connectionStrings or appSettings. You can add your own custom configuration sections; this is an advanced topic, but very powerful for building strongly-typed configuration files.
Web applications typically have a web.config, while Windows GUI/service applications have an app.config file.
Application-level config files inherit settings from global configuration files like machine.config. Web also applications inherit settings from applicationHost.config.
Reading from the App.Config
Connection strings have a predefined schema that you can use. Note that this small snippet is actually a valid app.config (or web.config) file:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyKey"
connectionString="Data Source=localhost;Initial Catalog=ABC;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Once you have defined your app.config, you can read it in code using the ConfigurationManager class. Don't be intimidated by the verbose MSDN examples; it's actually quite simple.
string connectionString = ConfigurationManager.ConnectionStrings["MyKey"].ConnectionString;
Writing to the App.Config
Frequently changing the *.config files is usually not a good idea, but it sounds like you only want to perform one-time setup.
See: Change connection string & reload app.config at run time which describes how to update the connectionStrings section of the *.config file at runtime.
Note that ideally you would perform such configuration changes from a simple installer.
Location of the App.Config at Runtime
Q: Suppose I manually change some <value> in app.config, save it and then close it. Now when I go to my bin folder and launch the .exe file from here, why doesn't it reflect the applied changes?
A: When you compile an application, its app.config is copied to the bin directory1 with a name that matches your exe. For example, if your exe was named "test.exe", there should be a ("text.exe.config" in .net framework) or ("text.dll.config" in .net core) in your bin directory. You can change the configuration without a recompile, but you will need to edit the config file that was created at compile time, not the original app.config.
1: Note that web.config files are not moved, but instead stay in the same location at compile and deployment time. One exception to this is when a web.config is transformed.
.NET Core
New configuration options were introduced with .NET Core and continue with the unified .NET (version 5+). The way that *.config files works hasn't fundamentally changed, but developers are free to choose new, more flexible configuration paradigms.
As with .NET Framework configuration .NET Core can get quite complex, but implementation can be as simple as a few lines of configuration with a few lines of c# to read it.
Configuration in ASP.NET Core
Configuration in .NET Core
Simply, App.config is an XML based file format that holds the Application Level Configurations.
Example:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="key" value="test" />
</appSettings>
</configuration>
You can access the configurations by using ConfigurationManager as shown in the piece of code snippet below:
var value = System.Configuration.ConfigurationManager.AppSettings["key"];
// value is now "test"
Note: ConfigurationSettings is obsolete method to retrieve configuration information.
var value = System.Configuration.ConfigurationSettings.AppSettings["key"];
App.Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.
See this MSDN article on how to do that.
Just to add something I was missing from all the answers - even if it seems to be silly and obvious as soon as you know:
The file has to be named "App.config" or "app.config" and can be located in your project at the same level as e.g. Program.cs.
I do not know if other locations are possible, other names (like application.conf, as suggested in the ODP.net documentation) did not work for me.
PS. I started with Visual Studio Code and created a new project with "dotnet new". No configuration file is created in this case, I am sure there are other cases.
PPS. You may need to add a nuget package to be able to read the config file, in case of .NET CORE it would be "dotnet add package System.Configuration.ConfigurationManager --version 4.5.0"
You can access keys in the App.Config using:
ConfigurationSettings.AppSettings["KeyName"]
Take alook at this Thread
Just adding one more point
Using app.config some how you can control application access, you want apply particular change to entire application use app config file and you can access the settings like below
ConfigurationSettings.AppSettings["Key"]
Application settings enable you to store application information dynamically. Settings allow you to store information on the client computer that shouldn't be included in the application code (for example a connection string), user preferences, and other information you need at runtime.
To add an application configuration file to a C# project:
In Solution Explorer, right-click the project node, and then select Add > New Item.
The Add New Item dialog box appears.
Expand Installed > Visual C# Items.
In the middle pane, select the Application Configuration File template.
Select the Add button.
A file named App.config is added to your project.
take a look at this article

Sharing an XML file between two projects?

I have looked around and simply cannot find a way to open a linked XML file. My folder structure is like this:
...\projects\ConfigService\
...\projects\Shared\
...\projects\WebTool\
Inside the Shared folder I have a single XML file that will be modified by the WebTool project and read by the ConfigService (many times after each one is built and running). To make things as simple as possible, I simply tried "add as link" at the XML in each project, but then how do I actually get a full path to the linked object so I can open it? I use a link because the file will be changed after my projects are built, but I will not rebuild.
All answers I have found either try to pack the linked file into the project's binary, or the instructions are for adding classes/code instead of just a flat resource.
Or is there a better way to do this?
The solution that worked out best for him was to use the Server.MapPath() method to find his Shared folder regardless of where in the file system his website was rooted. Since it will always be [virtual-directory]\Shared this works out perfectly and he doesn't need to worry about config settings.
I think you want to use an app.config file to resolve this. Here's how you would do it.
In the WebTool service, and in the Config service, add an app.config file with the following text:
<configuration>
<appSettings>
<add key="XmlFileLocation" value="c:\folder\projects\shared\myfile.xml" />
</appSettings>
</configuration>
Then, you can retrieve the file location in each program by using the following:
string filepath = ConfigurationManager.AppSettings["XmlFileLocation"];
You'll have to add a reference to System.Configuration in your projects though.
Good luck!
Two ways to go
One depends on how you are going to deploy. If they are all going to same folder, the Mr Oded's solution is a quick and simple.
If you are deploying to a more complex folder structure e.g
MyApps
Shared
ConfigService
WebTool
The create a folder structure that mirrors that and set the output directory in each project to the relevant one (instead of the default bin\debug bin\release). The you can grab it with a relative path from from each tool e.g. (..\MyXmlFile.xml).
That said, I like neither of the above.
What else in shared? If there's a dll, then may be it should have a method that returns the location of the file, or the content, and let it manage where that location is.
PS don't forget seeing as it is exposed on the file system (somewhere), you need to cope with some well meaning individual deleting or modifying it.

C# can we have multiple .config file for a project?

If we can have more than one .config files, we can share one config file with other projects and put private configuration into another. Visual Studio 2008 will be confused?
No, except for the <appSettings> node which has a special file= attribute which works in a "cummulative" manner, all configuration sections are single shot affairs - you have it, and you have one of it exactly - or you have nothing.
<appSettings file="common.appsettings.config">
<add key="private1" value="value1" />
</appSettings>
This will read in the contents of the common.appsettings.config file and anything that's not being overwritten by an explicit value in your own config here is being used from that external config file.
You cannot add additional "private" info to an existing configuration section, as far as I know.
Visual Studio 2010 has support for multiple .config files. It is one feature of new web application packaging and deployment system. We can create now separate web.config files for each configuration we have for application. But for 2008 there are no support for multi config files, you can workaround this by adding two config files and rename them in build time
Example:
private.config
public.config
on pre-msbuild event merge these two files
rename merged file, it should be web.config or app.config
Hope this helps...
s
You can have multiple web config for each directory although only one config section handler.
The configuration files are hierarchical from general to specific. Configuration files further down in the hierarchy override any settings from the previous ones. So if you have a solution that includes a master web.config file, any web.config files in your projects override it and are specific and visible only to those projects. If a project is comprised of several folders, you can add a web.config file to each of those as well, again with different settings that also override any of those set above. But I caution over-engineering this or you may have difficulty with a trickle-down of certain property values or loopholes in security if it is security that you are configuring at each level.
Each config section can be put in an external file, and referenced from the main app.config / web.config via the configSource attribute. However, you will have to write custom section handlers for each custom section / external config file that you want to write, which may get a little tedious. In addition, the appSettings section can be externalised and referenced via the same mechanism.

Categories

Resources