Connection String Name - c#

So I have been thinking about how to make my life easier by automating the connection string name used to connect to my databases. I program on my laptop and on a PC at work. They utilize different databases. So I created the code below and it’s working. However, I don’t recall ever hearing about this method before and am wondering why? Is this a bad way to do this sort of thing. Understandably, I have to remove the code before releasing it but it sure seems like it’d make it easier to switch between computers since I don’t have to comment/uncomment lines in Web.config. Each connection string name is set to the computer name in Web.config.
static string connectionStringName = System.Environment.MachineName;
public ApplicationDbContext()
: base(connectionStringName, throwIfV1Schema: false)
{
}

A different approach to consider would be leveraging web.config transforms and create new environments (Dev-PC / Dev-Laptop) which contains has a different connection strings you need.
Then when you launch Visual Studio, you can simply select the build profile you need and when you launch the app the appropriate connection strings will be used. This will be helpful if you need to use file paths or other configurations that will differ between the two environments.

Your answer is to use a combination of web.config transforms, and your SetParameters.xml file. I know that they can seem daunting at first, but if you invest the time into learning, it pays off.
Using web.config transforms, or naming your connection strings based on machine names is a Bad Idea TM. These solutions will work, but they require you to rebuild your WebDeploy package every time you release to a new environment. You want a solution that lets you deploy any package to any environment.
Firstly you'll need to create two web.config transforms. One for Debug, and one for Release. Web.Debug.config will look something like this:
<connectionStrings>
<add name="MyDB" connectionString="Data Source=.\SQLExpress;Initial Catalog=MyDevDatabase;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
Whereas your Web.Release.config will contain a placeholder string. These placeholders will be updated when you deploy your package into IIS in your target environment. It should look like this:
<connectionStrings>
<add name="MyDB" connectionString="__targetenvironmentconnstring__"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
To get your target environment connection string in place when you do your deploy, you need to update your publish profiles under Properties in your web project. You'll create one publish profile (using the Package option) for each target environment; so QA.pubxml, UAT.pubxml, Production.pubxml, etc. Visual Studio will walk you through a wizard to create these files when you use the Publish dialog. Now open each file. You'll want to edit the end of the file to incorporate MSDeployParameterValue elements like I've done here
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup> <!-- A bunch of info --> </PropertyGroup>
<ItemGroup>
<MSDeployParameterValue Include="$(DeployParameterPrefix)MyDB-Web.config Connection String">
<ParameterValue><!-- Your target environment connection string goes here! --></ParameterValue>
</MSDeployParameterValue>
</Project>
Now right-click and Publish on your web project, selecting the publish profile you want. In the output directory you've specified, you'll see a SetParameters.xml file which contains your target connection string. This is what will go into your web.config file when you deploy, but crucially, you can also just import the package manually using IIS, and assign your own values at deploy time like this:
Finally you can just refer to your connection string using ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString and you've got the correct value, no matter what environment you're in!
To understand more, I highly recommend reading the following
https://www.asp.net/web-forms/overview/deployment/web-deployment-in-the-enterprise/configuring-parameters-for-web-package-deployment
https://www.asp.net/web-forms/overview/deployment/web-deployment-in-the-enterprise/deploying-web-packages
It takes a few goes to wrap your head around, but you'll never go back.

Related

Connection string changes not picked up by ConfigurationManager

I'm having a issue with ConfigurationManager not picking up a change to a connection string.
I'm sure there's a simple explanation, however I've been staring at it for the last two hours and given myself contextual blindness.
Inside a WCF project I've updated the database name of a named connection string in the web.config:
<connectionStrings>
<add name="appDb"
connectionString="Data Source=HOST;Database=DB_NEW;User=X;Password=X;"
providerName="System.Data.SqlClient" />
</connectionStrings>
There's a separate repository project that orchestrates the database connection, abstracting it from the WCF project. In that project it uses the connection string value from the web.config file, accessed using the following expression:
ConfigurationManager.ConnectionStrings["appDb"].ConnectionString
(The WCF project manages dependency injection using Unity and is responsible for creating an instance of the session factory in the referenced project for NHibernate's ISessionFactory.)
However, at runtime it's still picking up the connection string prior to me changing it.
Things I've tried:
Full clean/rebuild of the entire solution
iisreset
Checked IIS physical path is the correct directory (I have multiple branches of the same project)
Checked the connection string isn't being defined anywhere else in the solution
Restarted Visual Studio (2015)
No transforms being applied to the web.config
The connection string value must be being cached somewhere, but where I do not know.
Update
Could this be NHibernate caching the connection string? Apologies I have very little knowledge with NHibernate (I'm usually EF).
var config = new NHibernate.Cfg.Configuration()
.SetProperty(Environment.ConnectionString,
ConfigurationManager
.ConnectionStrings["AppDb"].ConnectionString)
Update
IIS seems to recognise the new config in IIS Manager, so this confirms that it's being read from the file correctly.

Proper way to manage test/prod connection strings in .NET web.config file [duplicate]

This question already has answers here:
Using different Web.config in development and production environment
(10 answers)
Closed 5 years ago.
I have the source code of an application that I maintain. In my web.config file, I have connection strings for both my test and production databases as follows:
<add name="conn" connectionString="Data Source=TestDBServer; (etc...)">
<add name="conn" connectionString="Data Source=ProdDBServer; (etc...)">
Whenever I am in test, I just comment out the production connection string and vice-versa. For example, when I finish testing, I comment out the test connection string and uncomment the production connection string and then deploy.
I am very early on in my career as a developer, but it seems to me that there must be a better or more standard way to handle this. What should I do?
Edit
Guilherme Lofrano Corneto linked an identical question that completely answers my own question. I have since marked mine as a duplicate. Here is the link:
Change connection string from development to production when publishing
Visual Studio can automatically transform your web.config based on your currently active build configuration. So you should have a build configuration "Test", "Dev", "Prod" etc. (whatever you need for your workflow).
Then you can right-click on your web.config and click "Add transform". This creates a new config like web.Prod.config where you can overwrite your config values. When building with a specific build configuration, visual studio will automatically overwrite the default web.config with your corresponding transformation.
If you need to apply such transformations to other files than the web.config you might want to check extensions like "SlowCheetah - XML Transforms"
You can follow the following steps to transform web config file during deployment.
Here is a short summary:
1- Set your development connection string in the web.config file. Should look similar to this:
<connectionStrings>
<add name="ConnStringDb1" connectionString="Data Source=TestDBServer; (etc...)" />
</connectionStrings>
2- Expand your web.config file and open web.release.config
3- Use the Replace function to replace the connection string with the one for you want for deployment. You can use xdt:Locator="Match(name)" attribute to match it with the name of the connection string (ConnStringDb1) in this example:
<connectionStrings>
<add name="ConnStringDb1" xdt:Transform="Replace" xdt:Locator="Match(name)"
connectionString="Data Source=ProdDBServer; (etc...)" />
</connectionStrings>
More information on transformation syntax in web.config.
My team usually keeps the "dev" setup as the one in TFS as the default. It helps if all team members install the same SqlServer "instance" so if does not differ from dev to dev.
Example :
"localhost\SqlServ2014Stand
or something like that.
For deployments to QA, Staging, UAT, Production (whatever you call them)......we write wix installer(s) (one per product) and we handle the xml-transforms in the wix project. This is what will change the connection string (or anything else) for the different environments.
You may want to look at a CI server like CruiseControl.NET or Jenkins or TFS or something. This is what will build your code in a consistent way. This takes a little time to setup. If time if the main factor, I would try Jenkins.

Using Entity Framework app.config how to switch between environments Dev, Stage and Production

I have a windows application accessing Dev database using DataModel.edmx and it works fine. To access stage environment database I have added another StageDataModel.edmx. So there are two connection strings in app.config:
and
How do I switch between databases in app.config based on environment?
Thanks in advance!
Normally it should be the other way around - create one EF edmx model and two (or more) configuration files for every environment.
At my work, we have three environments:
Release = Production
Stage = before GO live (copy of production, final tests)
Debug = new development, dev team tests
For the three environments, we have three databases, that are (almost) similiar to each other. We create our model from the DEV database. Every project that communicates with the database has always three connection strings with different credentials.
In order to achieve this, you need to:
1) create different build platforms using the Visual Studio configuration manager (in my example, there are three build configurations - Dev/Stage/Release):
2) extract the connection string configuration from the app.settings file. Instead of specifying the connection in the app.settings file, use the configSource parameter like this (the app.config looks like this):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings configSource="App.ConnectionStrings.Config" />
</configuration>
3) now create different files for every build configuration, named after each build configuration (the wording must be exact!) and containing different servers or databases
App.ConnectionStrings.Debug.config
App.ConnectionStrings.Stage.config
App.ConnectionStrings.Release.config
Foer example the Debug can look like this:
<?xml version="1.0" encoding="utf-8" ?>
<connectionStrings>
<add name="Named.ConnectionString"
connectionString="metadata=res://*/Abstraction.DbDataContext.csdl|res://*/Abstraction.DbDataContext.ssdl|res://*/Abstraction.DbDataContext.msl;provider=System.Data.SqlClient;provider connection string="data source=sql.server.address;initial catalog=People;integrated security=False;user id=DbUser;password=DbPassword;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
4) now open your project settings in Visual Studio, go to Build Events and in the Post-Build event command line tell Visual Studio to take on every build the file named after the currently selected build platform and copy it with the specified (in the app.config) name to the output directory:
copy $(ProjectDir)\App.ConnectionStrings.$(ConfigurationName).config $(TargetDir)App.ConnectionStrings.config
Now when you build and start your application, the configuration depends on the build configuration, so you can even debug your application connected to the LIVE environment (when the currently chosen build configuration is Release).
More info on how to use external configuration files and connection strings, can be found in this MSDN article.
A good Entity Framework quick start.
I think you are asking how to use different app.config files for debug/release.
Just name them app.Release.config or app.Debug.config and have the debug or release settings in either one.
If its more complicated than that, you can install a tool such as SlowCheetah to modify XML files, you just need to set up different build configurations.

web.config issue in ASP.Net

I am using VSTS 2010 + ASP.Net + C# 4.0 to learn someone else's code for a WCF application. I find besides Web.Config, there are also Web.Debug.config and Web.Release.config. I searched the content of Web.Config, but cannot find any reference to Web.Debug.config and Web.Release.config. However in VSTS 2010 IDE solution explorer, I find there is an arrow pointed from Web.Config to Web.Debug.config and Web.Release.config -- so seems there is reference relationship. It makes me confused.
In all 3 config files, there are identical items with different values, for example, in web.config, there is connection string DBConnectinString defined in this way,
<connectionStrings>
<add name="DBConnectinString" connectionString="data Source=10.10.10.123;uid=foo;pwd=foo;database=FOO" providerName="System.Data.SqlClient"/>
</connectionStrings>
And in Web.Debug.config, there is connection string DBConnectinString defined in almost the same way with different values,
<connectionStrings>
<add name="DBConnectinString" connectionString="data Source=10.10.10.124;uid=foo;pwd=foo;database=FOO" providerName="System.Data.SqlClient"/>
</connectionStrings>
My quesiton is,
what is the relationship between Web.Config and Web.Debug.config/Web.Release.config?
Why define the same item with different values in Web.Config and Web.Debug.config/Web.Release.config?
You have different config files for different settings. Consider Debug as your local environment settings, like connectionstrings to the testserver, debug variables on, etc. The Release settings would contain settings like the connectionstring for the production server.
In the top bar, next to the run debug should be a drop down, containing all available settings. You can also add some.
This settings are useful for oneclick-deployment like the new WebDeploy with VS2010
Edit:
This link How to use web.config transforms to replace appSettings and connectionStrings? should show you a basic walkthrough about web.config transforms
This is new feature in Visual studio 2010. It allows you to have diffrent config files for you build configuration schemes. So that, when you build in debug mode it will include the Web.Debug.Config file, the same when you build for release.
This allows you for example to maintain diffrent configs for your database - one for your dev environment and for your live environment.
Hope that helps!

connection string in web config

I have a web application which i make on my local host and publish it on different servers.
in the web config of this application i have connectionstrings property like:
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=XYZ-PC\SQLEXPRESS;Initial Catalog=SumooHServerDB;Integrated Security=True" providerName="System.Data.SqlClient"/>
Now connectionstring data source has the name of my server and when ever i publish it and run this application on different server i have to change XYZ-PC\SQLEXPRESS to the name of the server..
Is there a way i dont have to do this as it does not feel right..
any suggestions..
thanks
Try replacing XYX-PC with localhost provided the instance name is the same.
If database stands on the same server as IIS, you can use Data Source=localhost\sqlexpress
I like to use configSource to pull the connection string out into a separate file, as explained here*: http://stevenharman.net/blog/archive/2007/06/07/tip-put-connection-strings-in-their-own-configuration-file.aspx
That way, you can configure each server's connectionStrings.config once, but continue updating their web.config files with a single version that works for all of them.
* Except, I usually name it connectionStrings.config, so it's more obvious for maintenance by others.
The following article could be a solution to your question :
Handling Multiple Environment Configurations with .NET 2.0
Basically, the idea is to use the fact that in your config file you can indicate that some sections have to be read from an external file. Than during the build of your project you copy the right external file according to your environment. I think the link will explain this better.
Take a look at Web Deployment projects.
In addition to letting you merge everything into a single assembly, it give you the option of doing section-based web.config replacements. We use this on our build server to alter the standard web.config for running in the test environment. As a bonus, you're not limited to just changing connection strings. Anything in the web.config is fair game.
Use this connection string:
name="MyConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SumooHServerDB;Integrated Security=True" providerName="System.Data.SqlClient"
It will work.

Categories