Connection Strings - asp.net

Could you help me understand what this piece of code does in simple English? This is a beginner. Thank you in advance.
<connectionStrings>
<add name="BalloonShopConnection" connectionString="Server=(local)\Sql➥
Express; Database=BalloonShop; User=balloonshop; Password=ecommerce" ➥
providerName="System.Data.SqlClient" />
<remove name="LocalSqlServer"/>
<add name="LocalSqlServer" connectionString="Server=(local)\SqlExpress;➥
Database=BalloonShop; User=balloonshop; Password=ecommerce" providerName=➥
"System.Data.SqlClient" />
</connectionStrings>
This is from a tutorial. I covered everything up to first half of the book but this seems strange.

The web.config for your app is only part of the configuration settings your app gets. The total configuration is a combination of your web.config as well as the machine.config file, and settings defined in IIS. This line:
<remove name="LocalSqlServer"/>
implies that the there is a connection string named LocalSqlServer defined elsewhere that you may be getting from somewhere other than your web.config. So in your web.config they are explicitly removing that other LocalSqlServer connection string you would otherwise get, and replacing it with the one defined below that line. That change only affects your application. This is explained here: http://weblogs.asp.net/jgalloway/archive/2012/01/17/10-things-asp-net-developers-should-know-about-web-config-inheritance-and-overrides.aspx
If the remove tag wasn't there, and that connection string was also defined higher up the chain, your app would use the one defined higher up, and ignore the one defined in your web.config (which can be quite confusing!). That's why the remove tag is needed.
See also:
Avoid web.config inheritance in child web application using inheritInChildApplications

You add connection string which names BalloonShopConnection. Your sql server names (local)\SqlExpress; Your databese is BalloonShop user is balloonshop so you add second one which is very similar :)

Related

What does <clear /> signify when specifying a connectionstring?

This answer to another question states:
Do not forget to clear the connectionStrings first:
<connectionStrings>
<clear />
<add name="LocalSqlServer" connectionString="Data Source=(local);Initial Catalog=aspnetdb;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
... interesting. What does that do?
In .Net config files are inherited, so your applications config will inherit settings from your machines config.
The <clear/> tag will remove any inherited connection strings and thereby avoids confusion and potential problems.
In ASP.Net you may have several inherited connection strings, so this is very common there.
The element removes all sections and section groups from your application that were defined earlier in the current configuration file or at a higher level in the configuration file hierarchy.
http://msdn.microsoft.com/en-us/library/aa903345(v=vs.71).aspx
so for example, if this was a child config file and the parent config file had some settings... you may not want them being inherited so you specify the clear flag to clear it and then use your settings.

Can I specify a connection string in the web.debug.config only?

I have a group of apps that inherit their connection string from a web.config in the root directory of IIS. This means that I don't need to specify a connection string in the root directory of the app, but I do need to specify a connection string when debugging locally.
My question is, how can I set a connection string in web.debug.config that only is used when I'm debugging?
You could specify the connectionstring in the normal web.config and then in the web.release.config add a transform that simply removes the connection string all together.
That way it should exist in the debug one but not in the web.release.config.
Of course this assumes you are using those configs with transforms and not doing a simple copy/paste of the code when you deploy
MSDN has a good example of this
The following example shows how to select all the connection string
add elements in the development Web.config file. In the deployed
Web.config file, only the first connection string element is removed.
<configuration xmlns:xdt="...">
<connectionStrings>
<add xdt:Transform="Remove" />
</connectionStrings>
</configuration>
EDIT: I guess alternatively you could also create a transform in web.debug.config that adds it while in debugging, which might help to keep it out of the original web.config if you aren't appying transforms when deploying
Keep your Debug connection string in Web.Config and replace the release connection string in Web.Release.Config using the locator as show below
<connectionStrings>
<add name="DefaultConnection" connectionString="Release Connections tring" providerName="System.Data.SqlClient"
xdt:Transform="SetAttributes" xdt:Locator="XPath(configuration/connectionStrings)"/>
</connectionStrings>

One-click publish in vs 2012: how to remove _ConnectionStringsToInsert?

I usually put my connection string to a separate file, adding something like this in web.config:
<connectionStrings configSource="WebConnection.config" />
I've just installed VS 2012 and it automatically picked up my existing publish settings.
However, when I do a webpublish it now adds two connections strings by itself, so my web.config on the deployment target now looks like that:
<connectionStrings configSource="WebConnection.config">
<add name="EF.Model.DbContext" connectionString="EF.Model.DbContext_ConnectionString" providerName="System.Data.SqlClient" />
<add name="Migrations.Db.MigrationDb" connectionString="Migrations.Db.MigrationDb_ConnectionString" providerName="System.Data.SqlClient" />
</connectionStrings>
certainly, that produces an error (node contents must be empty when using configSource).
I noticed, that in newly generated .pubxml files (where publish settings are now stored) there are following lines:
<ItemGroup>
<_ConnectionStringsToInsert Include="EF.Model.DbContext" />
<_ConnectionStringsToInsert Include="Migrations.Db.MigrationDb" />
</ItemGroup>
How can I remove them? :) If I delete them from file, Web-publish dialog adds them anytime I edit the publish settings.
I suddenly resolved that by going to project properties, "Package/Publish Web" and checking the mark "Include all databases configured in P/P SQL tab" (and I don't have any DB configured there :)).
After doing this and deleting the mentioned lines from .pubxml everything went fine.
Seems like a hack, but it was a way to go for me :)
#Sayed, thanks for confirming it's a bug, hope it'll be resolved!
I came up with a (possibly) less hacky solution for bypassing the bug in publish that forces discovered Entity Framework code first db contexts to have a connection string. This is still an issue that I'm having in VS 2013.
In your web.config, add a dummy version of the connection string:
<add name="DbContextName" connectionString="This is a dummy connection string to bi-pass publish bug." providerName="System.Data.SqlClient" />
Now, setup a transform for the configuration you want to create a publish package for. Read more about it here.
In your web.config.{configuration} file, use the following transform to remove the connection string:
<connectionStrings>
<add name="DbContextName" xdt:Transform="Remove" xdt:Locator="Match(name)"/>
</connectionStrings>
This transform runs AFTER the publish transform in your pubxml runs, so it clears out the unwanted connection string.
On the Settings tab of the publish profile, clear the Use this connection string at runtime check box and the Apply Code First migrations check box. Make sure that migrations is enabled, or the Use this connection string box won't stay cleared, and even then you may have to clear it again each time you open the profile.

What is the difference between connectionstrings and appsettings?

In one of the applications I have been referring to, the Connection String is stored in AppSettings! Till now I have been storing the connection in the <connectionstring/> element. But what is the correct way?
So my question is, what are the differences between <connectionstrings> and <appsettings> in the web.config and are there any specific reasons why I should or should not be storing connection strings in appsettings? Are there any rules / guidelines provided to follow? Or is this completely the choice of the developer?
There is a fundamental difference between connectionString and appSettings:
They look for different things. In .NET 2.0 and above:
A connectionString object is an XML node that has specific attributes to set; and semantically it refers to a database connection string.
For instance, a connectionString looks like the following:
<connectionStrings>
<clear/>
<add name="LocalSqlServer"
connectionString="Data Source=(local);Initial Catalog=aspnetdb;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
You'll notice it has a few different attributes:
name
connectionString : This has a specific string inside of it, it needs an Initial Catalog, a security mechanism (in this case Integrated Security
providerName
Whereas appSettings is just a user-defined Key-value pair that allows you to... well... set application settings. It can be anything:
<appSettings>
<add key="Mom" value="Your"/>
<add key="UseCache" value="True"/>
<add key="MapsKey" value="1234567890-AA"/>
<add key="SMTPServer" value="smtp.peterkellner.net"/>
</appSettings>
In many cases, it would just be odd to put the connectionString in a key-value pair like appSettings (semantically and programmatically). As well as it would make it more difficult to encrypt the connectionString when you need to.
There is more information about this from this blog post.
As far as I know it doesn't make a huge amount of difference, other than it being in the "correct" place - the main advantage of putting connection strings in their own section (you do encrypt your connection strings.. right?) is so you can encrypt that section without encrypting all of the settings you might want to change.
Connection strings are generally kept in the <connectionstring/> element...and is a good guideline since it's named properly.
Sometimes you might use a third party control or usercontrol that looks for the connection string in a key in the <appsettings> element. That should be the only exception to the guideline.
Additionally, in IIS7, connect strings can be maintained through the respective IIS7 Administration.
You can use appSettings section to share custom application configuration settings across projects in .NET.
How to share custom application configuration settings across projects in .NET
Regarding deployment, there's one significant difference between them. When you import web packages to IIS:
Connection strings will automatically be included in the wizard dialog for further parameterization.
App settings will not be there by default. If you really want to do that, please follow the steps in "Custom Parameterization - Application settings in the web.config file" section of Configuring Parameters for Web Package Deployment
That means, when it comes to deployment, you'd better put environment parameters(database, cache, AWS key/secret, etc.) in connection strings. It will provide differentiation between dev/staging/prod environment explicitly.

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).

Resources