Is it possible to override both appSettings and connectionStrings in a Local.config file? - asp.net

We presently override appSettings from our web.config in a Local.config file for each developer. However we also need to override connection strings, so we access our local copy on our machine while the web.config might reference the production server. I know that you can override appSettings by specifying file="Local.config", but is this possible for the connectionStrings as well? We already make use of an external file for the connection strings but this file has all three connection strings (local developer, dev, and production).
What I'd like to do is have the connectionString defaulted to production, but overridden on a developer's machine and on the development server. However, this doesn't seem to be possible as unlike appSettings, you can't specify a value for connectionStrings when you tell it to use an external file.
Is this possible to achieve without having to add additional code?
I should note that I cannot use the Config Transformations at the moment as we are on ASP.NET 3.5.

In the main application configuration file, you use the configSource attribute to specify the fully qualified name and location of the external file. This example refers to an external configuration file named connections.config.
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<connectionStrings configSource="connections.config"/>
</configuration>
For detailed information, please visit this link on msdn (section: Using External Configuration Files)

Related

Private web.config for each developer

Consider a group of developers working on an ASP.net web application. Each developer would like to have a private version of the web.config.
By "private" I mean that a developer can freely change the file to suit their dev/test needs at any given moment, without it affecting other team members and without ending up in source control.
How can one go about achieving this with Visual Studio 2015?
My closest solution so far is to have a "private" Solution Configuration with a matching Web.config Transformation file ("web.private.config") that's excluded from source control.
But this is not a satisfactory solution because:
a. The transformation is not run automatically when debugging (with F5). The developers need to remember to run it manually.
b. The result of the transformation ends up in the main "web.config" file which is, naturally, included in source control.
We had a very similar problem but only needed personalized versions of the <appSettings> section in Web.config.
In this situation the inclusion of an external file through configSource turned out to be problematic, as this attribute completely replaces the <appSettings>-node. So there remains no way to keep global key/values AND personal key/values for all developers. The whole section is completely replaced by the included private file.
What we need is both global and private <appSettings>. The solution we found was the file attribute. It allows to merge Web.config settings with settings from an additional file.
We ended up with a construct like this one:
<!-- Web.config with global appSettings) -->
...
<appSettings file="Web.PERSONAL.config">
<add key="BaseUrl" value="https://projectname.dev.local" />
...
</appSettings>
...
­
<!-- Web.PERSONAL.config with personal appSettings -->
<?xml version="1.0" encoding="utf-8"?>
<appSettings >
<add key="EmailSmtpUser" value="my.name#my.domain.com" />
<add key="EmailSmtpPwd" value="***" />
</appSettings >
If you put identical keys in both files, the Web.PERSONAL.config version will overwrite the Web.config version.
The file Web.PERSONAL.config must be excluded from Git through .gitignore .
Keep in mind:
While configSource works for ALL nodes in Web.config, the file attribute is restricted to <appSettings>.
Have web.config include an external file (via configSource) and add that file to .gitignore
The correct answer is to host your local development site in a separate location from your Visual Studio solution. You can then use publish profiles to publish changes to that location and web.config transforms to maintain a separate local config for each developer. Each developer would use a different publish profile which transforms the web.config with their own transform and deploys the transformed web.config to the publish location. You can then attach a debugger to the published site using Visual Studio's Debug > Attach To Process option.
I think there is a lot of value in standardising dev environments so that one can just download the solution and run it.
Custom, long term/permanent, developer specific configs will sooner or later lead to a subtle bug that will be tricky to find.
My solution to your problem would be to find out the reason(s) why permanent individual configs are needed and have a look if these environment specific differences can be eliminated.

Can included sections in Web.config be encrypted

I have an ASP.NET MVC5 website in development which I will shortly need to deploy to an IIS8 webserver. I'm trying to get the security model for the web.config file right, and in particular I want to:
Prevent secrets in the web.config file being exposed in my source control system
Protect the deployed web.config from prying eyes (I don't own the server).
From searching on SO and other sites I can see that there are specific tools/techniques to address each scenario:
'Included' sections in web.config that do not get saved to the SCCS.
Encrypted web.config files. Or encrypted sections of the file to be more precise.
I'm fine with both of those, but I can not for the life of me see how to combine the two techniques to solve both problems simultaneously. Is it possible to encrypt an external section? Is this even the right approach given that many of the answers are several years old now and address older versions of ASP.NET/MVC.
I can't be the first do want to do this so I'm sure I'm missing something obvious.
It has been suggested that this might already be answered here, however that question is about encrypting sections in the main web.config file, and I am asking about encrypting external sections. By that I mean sections that are 'included' using the configSource XML attribute.
It's probably bad form to answer ones own question, but I had a flash of inspiration and after a couple of hours of experimentation I have it working how I want.
The bit I had got all wrong was that I was trying to encrypt the external files. It does not work like that. Here's how it does work, at least, this is how it works for me on an IIS8.5 and ASP.NET v4.0.30319 server.
ConnectionStrings
Create the connectionStrings section in a separate file, e.g. Web.connectionStrings.config:
<?xml version="1.0"?>
<connectionStrings>
<add name="MyConnection" connectionString="{your connection string here}"
providerName="System.Data.SqlClient" />
</connectionStrings>
Ref this file from web.config:
<connectionStrings configSource="Web.connectionStrings.config" />
Make sure the external file is not under source code control so it does not get uploaded to your SCCS.
Deploy BOTH files, either as part of your deployment process or deploy the secure file manually if you're really paranoid.
Encrypt the connectionStrings section of the web.config normally, using the aspnet_regiis.exe command mentioned in the article mentioned by Afzaal. This process actually encrypts the contents of the Web.connectionStrings.config file and leaves the web.config file unchanged. You need to leave the external file in place but as it is now encrypted this is quite safe.
appSettings
Create your security-critical settings in a separate file, e.g. Web.appSettings.config.
<?xml version="1.0"?>
<appSettings>
<add key="wc1" value="web.app.config1" />
<add key="wc2" value="web.app.config2" />
</appSettings>
Ref this file from web.config:
<appSettings file="Web.App.config">
{other non-secure appSettings}
</appSettings>
Again, ensure the secure file is not under source control, and deploy both files to the production server.
Encrypt the appSettings section of the web.config file.
Unlike the connectionStrings section, this does not alter the external file at all. Instead, settings from both web.config and the external file are merged (external file takes precedence if duplicate keys are encountered) and are stored in an encrypted form in web.config.
At this point you can remove the Web.appSettings.config file as its contents are now incorporated into the main file.
Points to note:
If you introduce another Web.appSettings.config file at a later time, and restart the site, the contents of that file will override the encrypted settings in web.config. This may or may not be useful. When you remove the file and restart the site, the settings revert to the encrypted ones again.
If you decrypt the appSettings section, ALL the current settings are written back into the main web.config file, including those that originally came from the external file. You'll need to remember to remove them if you're just changing a setting and then re-encrypting the file again.

Web.Config files and locations

We have a whole bunch of websites with very similar web.config files.
Can you centralise the duplicate configs in 1 config file before the root directory of each website? Or is the only option machine.config?
We are looking to centralise an assembly reference in the GAC.
Structure:
Containing Directory
Website 1 Directory
Website 2 Directory
Website 3 Directory
Web.Config File for all above sites
I have not encountered a way to have inherited config files besides machine.config, app/web.config and user.config levels. But you can use configSource attribute on all config sections (ConfigurationSection based) to include a common file for example with service endpoints, client endpoints, bindings, connection strings and others. Even though VS intellisense marks it as unsupported it does work.
<configuration>
<system.serviceModel>
<services configSource="Services.config" />
<client configSource="Client.config" />
<bindings configSource="Bindings.config" />
<behaviors configSource="Behaviors.config" />
</system.serviceModel>
<pages configSource="pages.config"/>
</configuration>
Config source files must be in application's folder or any folder below. No going up or absolute paths. But there is a trick to overcome this limitation in VS2010. You need to add an existing file as a link and change its property named "Copy to Output Directory". This way your absolute path file will get copied to your application folder from where you can reference it in configSource.
In previous versions of VS it is also possible but in a less elegant way - copy file in post build event.
If you are looking mainly to centralize WCF settings there is another option: in-code configuration. Huge advantage of this is you get compilation-time check and refactoring support from VS. If this does not sound like much I can assure you that in a bigger WCF project, config file management is a nightmare especially when you need to change something. With this approach it is also very easy to centralize WCF settings by just creating a common assembly where all services, endpoints, bindings etc. are defined. Disadvantage is that you loose possibility to change WCF settings without recompilation. But if those settings do not change very often it is a tempting alternative.
You can use the web.config located in
%SystemRoot%\Microsoft.NET\Framework\<versionNumber>\CONFIG\Web.config
Or if in IIS you configure your Containing directory as a main web site and then put your website directories as applications, you can put the web.config in the main web site to have the structure you mention.

Conditional ConnectionString based on which folder the app is published to

I'm entering a parallel test and dev stage where I need to use one db for test and a different one for dev. How can I have the app choose which connection string to implement based on which physical folder it (the app) sits in?
I know there are SVN strategies to consider but this is small-scale enough to avoid 2 sperate code-bases. Would like to be able to publish the same VS project to either of my 2 directories without having to remind myself to change the connection string.
I'm running under IIS7 so perhaps it offers better control than conditionals in (and overrides) web.config. (or not)
thankx!
A word of advice:
I wouldn't base your connection string on your published folder. Down the road, the folder might change, and folks may not be aware that that determines which connection string you're using.
Instead, control it with a setting in your web.config file. Just add a setting that allows you to switch between production and dev databases. In fact, you could simply test for the presence of a debug mode setting. If that setting is there, you're targeting the development database; otherwise, you're targeting production.
The nice thing about that solution is that it doesn't depend on where you deploy the site, and you can document the setting in the Web.config file.
Hope this helps.
Edit for Clarity: By "a debug mode setting" I mean a setting that determines which database you're targeting, dev/production. Not whether your application is running in Debug mode, since the Framework already provides a function that does that. Also, you wouldn't necessarily remove the setting, since you'd want to keep it for documentation purposes. Rather, you'd comment it out.
You could e.g. create a <connectionStrings> container that contains a connection string for each folder your app could be in:
<connectionStrings>
<add name="Folder1" connectionString=".....(conn str. #1)...:" />
<add name="Folder2" connectionString=".....(conn str. #2)...:" />
....
<add name="Folder-n" connectionString=".....(conn str. #n)...:" />
</connectionStrings>
and then just pick the right one, depending on where your app starts up from.
Marc
Get a unique string for the application, perhaps something like:
string folder = Regex.Match(Server.MapPath("~"), #"\(.+?)\$").Groups[0].Value;
Then use the string to get a value from the web.config:
ConnectionStringSetting connectionString = ConfigurationManager.ConnectionStrings["ConnectionString." + folder] ?? ConfigurationManager.ConnectionStrings["ConnectionString"];
In the web.config you can add several connection strings with the folder names appended for each dev site, and a default connection string with just the name and no folder.
I usually put the connection strings into a separate config file and reference them from the main web.config using configSource:
In web.config:
<?xml version="1.0"?>
<configuration>
<!-- connection strings are located in an external config
file to facilitate deployment in various environments -->
<connectionStrings configSource="connections.config"></connectionStrings>
</configuration>
In connections.config:
<?xml version="1.0"?>
<connectionStrings>
<add name="ConnectionName" connectionString="[your connection string]"/>
</connectionStrings>
Once deployed, I usually exclude connections.config from future deployments (unless it should be changed, that is).

Changing web.config file based on an Environment Variable in ASP.NET

I need to change my connection string in the web.config file based on an environment variable (for different enviornments, like dev/staging/production, etc). I have seen other solutions that use build tasks to accomplish changing different configurations, but haven't been able to find something that will let me change my connection string based on an environment variable. Does anyone know of any way to do this?
We make use of the configSource attribute for the appSettings and connectionStrings elements in the web.config.
Basically, we have the same web.config file for all of our environments: dev, qa and production.
Then we utilize seperate "environment specific" files.. For example...
In web.config:
<?xml version="1.0"?>
<configuration>
<appSettings configSource="local.appsettings.config" />
<connectionStrings configSource="local.connectionstrings.config" />
</configuration>
Then we maintain the following files:
local.appsettings.config.development
local.appsettings.config.qa
local.appsettings.config.production
local.connectionstrings.config.development
local.connectionstrings.config.qa
local.connectionstrings.config.production
Since we pre-compile all of our asp.net applications before deployment, we've got a custom msBuild task utilized by our CI solution that copies the right configuration files (based on the target environment) to the proper .config file...
So, if we are deploying to dev, local.appsettings.config.development -> local.appsettings.config
If we are deploying to qa, local.appsettings.config.qa -> local.appsettings.config
This allows us to keep the core web.config the same across all of our environments.
How about having two connection strings and another variable, like "isTesting" in your web.config, then based on the value of isTesting pick which connection string to use?
you can also use config sections, and based upon server name switch between sections. this way you can have keys named the same.
link text
You can set a web.config for each environment in the configuration manager using prebuild events. I have tried this with excellent results.
http://www.hanselman.com/blog/ManagingMultipleConfigurationFileEnvironmentsWithPreBuildEvents.aspx
When you have debug and build you can have local/preproduction/production... etc

Resources