Connection string changes not picked up by ConfigurationManager - c#

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.

Related

Attempt to attach an auto-named database when installing my app in another pc

I recently finished building this C# Winforms app that uses a localDB connection and when installing it on another PC, I get the error as shown in the title, even though I included the SQL Server Express localDB in the prerequisites folder.
I tried all kinds of solutions like changing the method of how to build the setup file (using Advanced Installer), but it seems that the problem is always related to the constant AttachDbFilename attribute of the connection string that's not changing according to where the database is newly installed.
Here's how the connection string is defined in the App.config file:
<connectionStrings>
<add name="client"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Surface\source\repos\VisaTurbo\VisaTurbo\Client.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Please I've been stuck with this problem for 3 days now and the due date to submit the application have already been reached.
Thanks in advance
You can by example check the database file exist in %userProfile%\DBName.mdf and create a new one with https://github.com/martincostello/sqllocaldb.
But this make the connectionstrings parameters obsolete :)
You can also generate a new one with SqlConnectionStringBuilder
But if the user move the database file this will reset the application each time.
That's why in general the database in on a server, not locally stored on the user's machine.

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.

Connection String Name

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.

using |DataDirectory| in connectionstring of multiproject solution

I have 2 projects in the solution - one class library with entities for database (using EF), one for Winforms.
Connection string is in app.config of the Winforms application, and it works correctly:
<add name="LibraryContext"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\MyLibrary.mdf;Integrated Security=True; "
providerName="System.Data.SqlClient"/>
But when I try to provide migrations, I get an error:
A file activation error occurred. The physical file name '\MyLibrary.mdf' may be incorrect. Diagnose and correct additional errors, and retry the operation.
When I provide full path in connection string, everything works fine. I assume the problem is in DataDirectory. The project with entities for database doesn't see it or maybe see it as own DataDirectory and not the one for startup project (Winforms).
Please, help me to provide correct relative path for database.
Try this hope this will works.
Go to Property of project check setting tab. If you contain more then one connection string then remove it. and add connection string which you have in app config.
Thanks.
Happy Coding :)

How to deploy multiple projects for an MVC website with different property settings files

I have an MVC website that also references another Class project in my solution called DAL
The MVC website has a settings.settings file that I am using for my Default database connection string, and this automatically gets updated in my Web.Config file.
However my Class project also uses a settings.settings file for a database connection (to create a connection if one is not already supplied to it by the MVC project) and I believe this is put into the App.Config file, but when it comes to deploying and running this MVC website?
What do I do for the DAL project?
I can see it has a DAL\bin\release\DAL.dll.config file in that location, does this need to go into the root of the website directory, using the same file path? or should I be doing something else?
Thanks
You should be able to override this setting in your web.config by using the full name. If your project is called DAL you should create a connection string in your web.config which looks something like.
<add name="DAL.Properties.Settings.MyDatabaseConnectionString"
connectionString="Data Source=(local);Initial Catalog=myDatabase;Integrated Security=true"
providerName="System.Data.SqlClient" />

Categories