Using ConnectionStrings in App.config, is it possible to have multiple groups/sections of connectionstrings? Some way to delineate between one set of connections and another. Either something like;
<configuration>
<connectionStrings>
<clear />
<add name="ConA" connectionString="Data Source=..."
<add name="ConB" connectionString="Data Source=..."
</connectionStrings>
<otherConnectionStrings>
<clear />
<add name="ConC" connectionString="Data Source=..."
<add name="ConD" connectionString="Data Source=..."
</otherConnectionStrings>
</configuration>
OR
<configuration>
<connectionStrings>
<clear />
<add name="ConA" Group="1" connectionString="Data Source=..."
<add name="ConB" Group="1" connectionString="Data Source=..."
<add name="ConC" Group="2" connectionString="Data Source=..."
<add name="ConD" Group="2" connectionString="Data Source=..."
</connectionStrings>
</configuration>
I know there are <configSections> which you can use to split up the config file, but I want to use ConnectionStringSettingsCollection settings = ConfigurationManager.ConnectionStrings; to access the connectionStrings if possible.
NEED
I have two dropdown boxes. One is populated with a list of possible connectionStrings. Selecting an option will populate the second dropdown with a sublist of the remaining connectionStrings based on the option selected in dropdown 1. How would you cleanly populate both? Perhaps I'll just need to create connectionStringName lists in code for each group of connections I could potentially need and have all my connections in a the single section in my config?
Thanks for the comments. It seems having separate connectionStrings sections isn't possible. In order to hold onto that functionality for all my connections I conceded to having them all together but prefixing their names based on the grouping (as per #Igor's suggestion), then in code using Linq to select only the connections I needed.
Note: In order to use Linq on ConnectionStringSettingsCollection you need to .Cast<ConnectionStringSettings>() as per; https://stackoverflow.com/a/26419656/1365650
Related
I got mixed with app.config file.
I had config that failed to get connectionStrings:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<connectionStrings>
<add name="MovieDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="ProgrammingInCSharpConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=ProgrammingInCSharp;" />
</connectionStrings>
</configSections>
</configuration>
Problem was solved after placing <connectionStrings> outside of <connectionStrings> :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections />
<connectionStrings>
<add name="MovieDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="ProgrammingInCSharpConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=ProgrammingInCSharp;" />
</connectionStrings>
</configuration>
But I found many samples with pattern below
<configSections>
<connectionStrings>
...
</connectionStrings>
</configSections>
It might work in some cases?
What is logic of configuration file in general and what kind of information might be located in each section?
No. It is not possible to have a valid app.config file and yet having a connectionStrings in your configSections node.
According to MSDN, this is the list of allowed elements:
section
sectionGroup
add
clear
connectionStrings isn't in the list and I don't expect an application to find the connection strings in that place.
The configSections node contains configuration section per namespace declarations, but is not usually used for connection strings, unless they are namespace - specific.
But I found many samples with pattern below
The patterns you found could never work since <connectionStrings> is not allowed to be nested directly under <configSections>.
This could be achieved, by stating a connection string variable under the <section> itself, and if the server code targets them via a specific namespace.
An example:
<configuration>
<configSections>
<section name="section1" type="System.MyNameSpace" />
</configSections>
<section1 connString="...conn.." />
</configuration>
In the example above the namespace System.MyNameSpace will now have a variable (field) called connString, so it can target it in code behind.
For conclusion, if your connection strings are not per namespace, the <connectionStrings> element should be nested directly under the <configuration> node and no where else.
I store several different connection strings in my web.config for development and testing. All but one is commented out so I can change info as needed.
When I publish, I would like to replace everything (including comments) in the connectionStrings node with this:
<add name="myDb" connectionString="Data Source={SERVER};Initial Catalog=ManEx;User Id={USER};Password={PASSWORD};" providerName="System.Data.SqlClient" />
<!--<add name="myDb" connectionString="Data Source={SERVER};Initial Catalog=ManEx;Integrated Security=True" providerName="System.Data.SqlClient" />-->
I know how to change the active string with this:
<add name="myDb"
connectionString="Data Source={SERVER};Initial Catalog=ManEx;User Id={USER};Password={PASSWORD};"
providerName="System.Data.SqlClient"
xdt:Transform="Add"
xdt:Locator="Match(name)"/>
But I don't know how to clear out the comments I don't want and add the comment I do want.
Any ideas?
Instead of transforming the string, or using "Remove" and "Insert" clean the section try using "Replace".
For example:
<connectionStrings xdt:Transform="Replace">
<add name="myDb"
connectionString="Data Source={SERVER};Initial Catalog=ManEx;User Id={USER};Password={PASSWORD};"
providerName="System.Data.SqlClient" />
</connectionStrings>
You can configure this section exactly how you want it, even if that means you add new comments.
What I did based on this answer was the following:
Removed the existing connectStrings section in Web.config which contains commented out connection strings used during debug time;
Re-added the connectionStrings section with the correct connection string to be used when the app is deployed.
So in your Web.config transform file you have something like this:
<!-- Removes the existing connectionStrings section which contains internal connection strings used for debugging -->
<connectionStrings xdt:Transform="Remove">
</connectionStrings>
<!-- Re-adding the existing connectionStrings section -->
<connectionStrings xdt:Transform="Insert">
<add name="MyConnectionStringName" connectionString="Data Source=CLUSTERSQL;Initial Catalog=MyDatabase;Integrated Security=True;multipleactiveresultsets=True" providerName="System.Data.SqlClient" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
In Visual Studio 2013, you can have several Web.config files.
Also, when you create a new project, VS creates 2 for you : Web.Debug.config and Web.Release.config. That way, you can have a different Web.Config for your debug project and for your release project
If you need to Add/Insert/Setattributes inside a replaced connectionstring (for example if you use deployments) you can nest the transformations to remove the comments and replace the attributes:
<connectionStrings xdt:Transform="Replace">
<add name="connectionDatabase"
connectionString="#{ConnectionString}"
xdt:Transform="SetAttributes"
xdt:Locator="Match(name)" />
</connectionStrings>
Let's say I have got simple WPF application using Entity Framework Code First to create database, connect to it and display some data. From start I do not want to worry about connection strings so after adding entityframework reference via Nuget I'll get auto generated app.config looking like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
I'll run test and observe connection string:
var strings = ConfigurationManager.ConnectionStrings;
with result:
[0] = {data source=.\SQLEXPRESS;Integrated Security=SSPI;attachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true}
As I Like to define my own connection string, I will add this into my app.config:
<connectionStrings>
<add name="MyContext" connectionString="data ource=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\myDb.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
And so when I run the test again and observe the connection srings I can see that there are two now:
[0] = {data source=.\SQLEXPRESS;Integrated Security=SSPI;attachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true}
[1] = {data source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\myDb.mdf;Integrated Security=True}
Why is it that I can see two connection string? If the first one is default, should it not be forgoten once I've created one?
Thanks
First connection string which you see comes from machine.config from your PC. It has following section:
<connectionStrings>
<add name="LocalSqlServer"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient"/>
</connectionStrings>
Which defines default connection string for ASP.NET database. If you really don't need it for your application, you can either edit machine.config file (not recommended) or clear connection strings before adding yours:
<connectionStrings>
<clear />
<add name="MyContext"
connectionString="data source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\myDb.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Also keep in mind - this connection string is not used by Entity Framework. By default it uses SQLEXPRESS server and database with name equal to full name of your DbContext class. You can check it by accessing context.Database.Connection.ConnectionString.
The configuration manager just grabs all of the connection strings defined in the app/web.config.
It can't make the generalized assumption that once you add a connection string you wouldn't want a default one around anymore. That second connection string might point to an entirely different database.
I wonder if anybody know a solution to achieve this.
Basically, I need to build a website like -
1) www.domain1.com/subApp1 goes to one database and one appsettings.
2) www.domain1.com/subApp2 goes to one database and one appsettings.
In Webform application - I point the main domain (www.domain1.com) to a folder (landing) with a web.config which contains
<location path="subApp1">
<connectionStrings>
<clear/>
<add name="SchemaConnection" connectionString="data source=dev;initial catalog=Schema;user id=sa;password=password" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="brandName" value="subApp1"/>
<add key="ImageLocation" value="~/uploaded/subApp1/"/>
</appSettings>
</location>
<location path="subApp2">
<connectionStrings>
<clear/>
<add name="SchemaConnection" connectionString="data source=dev;initial catalog=Schema2;user id=sa;password=password" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="brandName" value="subApp2"/>
<add key="ImageLocation" value="~/uploaded/subApp2/"/>
</appSettings>
</location>
That works fine. But in MVC, It ain't working. I hope there is a way to do in MVC to achieve this. Please advice if anyone know.
I am working on a Windows application.
I have a form with labels like
HOST:
UserName:
Password:
How I can declare the connection string in the app.config file so that it takes the initial catalog, userID and password as variables that I can use in further to check the user whether which database the user wants to get connected with the entered userID and password.
I am using SQL Server 2008 and Visual C# 2008 Express Edition.
As I'm reading your question, you want to have a generic connection string that you want to inject username/password variables into. To do that you would need to have a key with this format:
<add name="myDBKey" connectionString="Data Source=myDB;Initial Catalog={0};Persist Security Info=True;User ID={1};Password={2}" providerName="System.Data.SqlClient"/>
Then in your code, you would need to have these variables declared and assigned, and then use String.Format to complete it.
string dbCatalog = "myCatalog";
string dbUser = "myUser";
string dbPW = "myPW";
string myDBConnectionString = String.Format(
ConfigurationManager.ConnectionStrings["myDBKey"].ConnectionString,
dbCatalog, dbUser, dbPW);
This will inject your variables into the string.
There is a <connectionString> section to the app.config file.
<connectionStrings>
<add name="MyDatabase" connectionString="Data Source=sqlserver,1433;Network Library=DBMSSOCN;Initial Catalog=MyDatabase;User ID=xxx;Password=xxxx;" />
</connectionStrings>
For your Host, User ID and Password, you can define these in the <appSettings> section.
Try this
<connectionStrings>
<add name="ConString" connectionString="Server=Servernae;Database=DBName;User Id=username;password=yourpassword"/>
</connectionStrings>
For more information try Connection Strings
Start by declaring the variables by going to your project's property tab, then going to the Settings tab (on the left), declaring your variables by mentioning the name, default value, and scope (which will be Application).
In your code, to fetch the values:
using System.Configuration;
//....
ConfigurationSettings.AppSettings["ConnectionString"].ToString();
// or
ConfigurationSettings.AppSettings.ConnectionString;
Please note that you can't change the value in code for an Application setting.
EDIT:
Alternately, there is also the connectionStrings node which can be set (but it must be done in the app.config file itself. See MSDN for documentation.
Example of XML:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="ConnStr1" connectionString="LocalSqlServer: data source=127.0.0.1 Integrated Security=SSPI;Initial Catalog=aspnetdb"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
In C#, you will get a System.Coonfiguration.ConnectionStrings, which is a collection of ConnectionStringSettings.
Example of usage in C# code: http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings.aspx
You can do some thing like this,
<appSettings>
<add key="SettingName" value="SettingValue" />
</appSettings>
or go to "Variables within app.config/web.config".
My library Expansive is designed with this as a primary use-case.
Moderate Example (using AppSettings as default source for token expansion)
In app.config:
<configuration>
<appSettings>
<add key="Domain" value="mycompany.com"/>
<add key="ServerName" value="db01.{Domain}"/>
</appSettings>
<connectionStrings>
<add name="Default" connectionString="server={ServerName};uid=uid;pwd=pwd;Initial Catalog=master;" provider="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Use the .Expand() extension method on the string to be expanded:
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
connectionString.Expand() // returns "server=db01.mycompany.com;uid=uid;pwd=pwd;Initial Catalog=master;"
or
Use the Dynamic ConfigurationManager wrapper "Config" as follows (Explicit call to Expand() not necessary):
var serverName = Config.AppSettings.ServerName;
// returns "db01.mycompany.com"
var connectionString = Config.ConnectionStrings.Default;
// returns "server=db01.mycompany.com;uid=uid;pwd=pwd;Initial Catalog=master;"
Advanced Example 1 (using AppSettings as default source for token expansion)
In app.config:
<configuration>
<appSettings>
<add key="Environment" value="dev"/>
<add key="Domain" value="mycompany.com"/>
<add key="UserId" value="uid"/>
<add key="Password" value="pwd"/>
<add key="ServerName" value="db01-{Environment}.{Domain}"/>
<add key="ReportPath" value="\\{ServerName}\SomeFileShare"/>
</appSettings>
<connectionStrings>
<add name="Default" connectionString="server={ServerName};uid={UserId};pwd={Password};Initial Catalog=master;" provider="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Use the .Expand() extension method on the string to be expanded:
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
connectionString.Expand() // returns "server=db01-dev.mycompany.com;uid=uid;pwd=pwd;Initial Catalog=master;"