Multiple SQL Server connection strings in app.config file - c#

I'm interested in displaying in a Windows Forms app a list of N radio buttons for the user to choose a target database server. I would like to add the SQL Server connection strings in the app.config file, so they are read by the app at runtime and rendered in the windows form as radio buttons.
At first I thought of using a delimiter to separate the connections
<appSettings>
<add key="ConnectionString" value="connection1|user id=user;password=123;server=10.0.0.1;database=myDatabase;connection timeout=30|connection2|user id=user;password=123;server=10.0.0.2;database=myDatabase;connection timeout=30"/>
</appSettings>
And then split the key value pairs.
Is it possible to do this in a different way?

To find all defined connection strings from your app.config, use the ConfigurationManager (from System.Configuration).
It has an enumeration: ConfigurationManager.ConnectionStrings which contains all entries in your <connectionStrings>.
You can loop over it with this code:
foreach(ConnectionStringSettings css in ConfigurationManager.ConnectionStrings)
{
string name = css.Name;
string connString = css.ConnectionString;
string provider = css.ProviderName;
}
The Name is just the symbolic name you give your connection string - it can be anything, really.
The ConnectionString is the connection string itself.
The ProviderName is the name of the provider for the connection, e.g. System.Data.SqlClient for SQL Server (and others for other database system). If you omit the providerName= attribute from your connection string in config, it defaults to SQL Server (System.Data.SqlClient).
Marc

Use the connectionStrings section to define your connection strings.
<connectionStrings>
<add name="connection1" connectionString="user id=user;password=123;server=10.0.0.1;database=myDatabase;connection timeout=30"/>
<add name="connection2" connectionString="user id=user;password=123;server=10.0.0.2;database=myDatabase;connection timeout=30"/>
</connectionStrings>

Yes, it is possible to do this in another way. Check the connectionStrings section that you can make in the app.config file.
<configuration>
<connectionStrings>
<add name="" connectionString=""/>
<add name="" connectionString=""/>
</connectionStrings>
</configuration>

We can declare multiple connection string under Web.Config or App.Config
<connectionStrings>
<add name="SourceDB" connectionString="..." />
<add name="DestinationDB" connectionString="..." />
</connectionStrings>
In DAL or .cs file you can access connection strings like this string SounceConnection = ConfigurationManager.ConnectionStrings["SourceDB"].ConnectionString;
string DestinationConnection = ConfigurationManager.ConnectionStrings["DestinationDB"].ConnectionString;

You can use the AppSettings class, get a list of all keys that start with ConnectionString and display them.
Your config file will look like this:
<appSettings>
<add key="ConnectionString_Name1" value="..."/>
<add key="ConnectionString_Name2" value="..."/>
<add key="ConnectionString_Name3" value="..."/>
</appSettings>
You can get the name, by splitting the key name (using "_" in this example).
BTW: You should also use the ConnectionStrings section, you are only interrested in connection strings.

This is how to use LINQ to get list of connection strings:
List<string> connectionStrings = ConfigurationManager.ConnectionStrings
.Cast<ConnectionStringSettings>()
.Select(v => v.ConnectionString)
.ToList();
Or you can build a dictionary of it:
Dictionary<string/*name*/, string/*connectionString*/> keyValue = ConfigurationManager.ConnectionStrings
.Cast<ConnectionStringSettings>()
.ToDictionary(v => v.Name, v => v.ConnectionString);

Related

Changing connection string dynamically on runtime in WinForms

I am making Winform dekstop application. I am giving an option in my application that user can select database or set database path. when user select database or database path then connection string should be changed at runtime in APP.config.
You probably shouldn't try and change the connection string in the config at runtime. You could have a set of possible connection strings in the <connectionStrings> section of the config file, allow the user to choose what database they want to use and read the appropriate connection from the file.
Even if there is no special needing for connection strings being stored in the standard way in the configuration file,it could be convenient to have a bounch of named <connectionStrings> in the standard configuration file and you can enumerate it like this:
foreach (ConnectionStringSettings c in System.Configuration.ConfigurationManager.ConnectionStrings)
{
//present the name in some combo etc etc.
}
then the user can select the connection string based on a friendly name.
The configuration file for your app will look like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
.....
<connectionStrings>
<add name="connection1" connectionString="Data Source=your connection string 1" />
<add name="connection2" connectionString="Data Source=your connection string 2" />
<add name="connection3" connectionString="Data Source=your connection string 3" />
</connectionStrings>
....
Is the path of database file effects connection string??? One database is in my "C:\ProgramFiles\SQLEXPRESS\data\abc.mdf" and same database with same name is in "F:\mydb\abc.mdf" both database have same connection string or not????

How to set connectionstring at web.config file programmatically or dynamically?

I'm trying to create an ASP.NET website. There I'm using a database. To connect with the database I'm using the connectionstring which I've stored in the web.config file like
<connectionStrings>
<add name="DBConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=G:\CarRentalServices\App_Data\CarRentalServiceDB.mdf;Integrated Security=True"/>
</connectionStrings>
and at code behind
private string _connectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
So you can see the database is stored at G:\path\to\db\CarRentalServiceDB.mdf.
But now if my friend want to take the project from me and try to run the project from his machine then he has to change the connectionString at web.config. Say the website is now at D:\path\to\db\foo\CarRentalServiceDB.mdf in my friend's machine, then the connectionString needs to change. Isn't it tedious?
Is there any way to change the connectionString dynamically with any batch file or code so that it will change with respect to the current directory it is residing now?
You shoud use the |DataDirectory| token: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx
<connectionStrings>
<add name="DBConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\App_Data\CarRentalServiceDB.mdf;Integrated Security=True"/>
You would add multiple connections strings in your web.config file and call the one you need like
Web.config File
<connectionStrings>
<add name="DBConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=G:\CarRentalServices\App_Data\CarRentalServiceDB.mdf;Integrated Security=True"/>
<add name="DBConnectionStringTwo"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\path\to\db\foo\CarRentalServiceDB.mdf;Integrated Security=True"/>
</connectionStrings>
Code for connection strings
//Connection String 1
private string _connectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
//Connection String 2
private string _connectionString2 = ConfigurationManager.ConnectionStrings["DBConnectionStringTwo"].ConnectionString;

Reading a connection string from a class library

I am currently struggling to read a connection string from the App.config inside my WinForms application from my Class Library (and Unit Testing).
I added a 'test' entry to the App.config;
<connectionStrings>
<add name="MyConnString" connectionString="Test;" />
</connectionStrings>
My TestMethod looks like this;
[TestMethod]
public void TestConnection1()
{
string connString = "";
if (ConfigurationManager.ConnectionStrings["MyConnString"] != null)
{
connString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
}
string expected = "Test;";
string actual = connString;
Assert.AreEqual(expected, actual);
}
This, obviously, fails. Actual's value is empty.
What am I doing wrong?
you need to add connection string key into Test project's config as well.
Regarding your comment to DJ Kraze: "#DJ KRAZE, If I put 0 as index, it returns me a connectionstring for SQLExpress "aspnetdb.mdf". If I put 1 as index, I get an exception (IndexOutOfRangeException), so obviously my string is not found."
The problem is you forgot the configuration element. For example:
Referenced from MSDN: Storing and Retrieving Connection Strings
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<connectionStrings>
<clear />
<add name="Name"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
</configuration>
The machine.config file also contains a <connectionStrings> section, which contains connection strings used by Visual Studio. When retrieving connection strings by provider name from the app.config file in a Windows application, the connection strings in machine.config get loaded first, and then the entries from app.config. Adding clear immediately after the connectionStrings element removes all inherited references from the data structure in memory, so that only the connection strings defined in the local app.config file are considered.

C# Sql Connection String Across Pages

If I have several pages what would be the correct procedure in creating a connection string variable and sharing it among all of my pages. I would prefer not to type the connection string 100 times for each page and would just rather call it. Can I create it in my namespace or whats the best approach?
Put the connection string in the web.config file. See the following on MSDN: How to: Read Connection Strings from the Web.config File
Example of connection string in config:
<connectionStrings>
<add name="Movies2"
connectionString="Data Source=(local);Initial Catalog=Movies;User ID=wt3movies;Password=lalalalala;Integrated Security=SSPI"
providerName="System.Data.SqlClient" />
</connectionStrings>
Using the string:
string connStr = ConfigurationManager.ConnectionStrings["Movies2"].ConnectionString;
It's typically in your configuration file (web.config)
can't you use the <connectionStrings/> configuration ?
http://msdn.microsoft.com/en-us/library/ms178411.aspx
Well i would have included Setting file and placed it over there.It may be not the best bet but works for me.
There are many options. It depends on what data access methodology you are using. I would suggest creating a class to handle loading the connection string from the web.config file and exposing it as a public property.
There are a variety of ways to approach this which would delve in to architecture/SOC/IoC/Repository/ etc, but to answer your question in its simplest possible sense, you could create a Database class that had a single method that fetched your connection string from configuration.
internal class DataAccess
{
static string GetDatabaseConnection()
{
return ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString;
// where AppDb is defined in your web.config/app.config.
}
}
Your pages could just use:
string connection = DataAccess.GetDatabaseConnection();
connection strings are usually stored in configuration files such as the web config. Here is a simple example
add something like this to the config
<connectionStrings>
<add
name="NorthwindConnectionString"
connectionString="Data Source=serverName;Initial
Catalog=Northwind;Persist Security Info=True;User
ID=userName;Password=password"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
and then retrive it as
System.Configuration.Configuration rootWebConfig =
S
ystem.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
System.Configuration.ConnectionStringSettings connString;
if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString =
rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
if (connString != null)
Console.WriteLine("Northwind connection string = \"{0}\"",
connString.ConnectionString);
else
Console.WriteLine("No Northwind connection string");
}
full article is here http://msdn.microsoft.com/en-us/library/ms178411.aspx
You should keep it in you config file. For winforms that will be app.config, and for webforms it's web.config. Here is the section you need to have (for winforms).
<connectionStrings>
<add name="MyNameSpace.Properties.Settings.ConnectionString1"
connectionString="Data Source=MYSQLSERVER;Initial Catalog=DATABASENAME;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Then you can access the connection string like this (depending on your .NET version - this is for 2.0)
string connectionString = ((string)(configurationAppSettings.GetValue(ConnectionString1"", typeof(string))));
Have the connection string (CS) in (App/Web).Config file and have the CS returned from a static method GetConncectionString().It means, this particular static method would be used in all the pages where CS is required.
You can also make a file called connectionStrings.config,or a name you choose, with this content:
<connectionStrings>
<add name="MyConnection" connectionString="server=MyServer; database=MyDataBase; user id=myUser; pwd=MyPwd;"/>
</connectionStrings>
And then, in your Web.Config
Insert this tag under node
<connectionStrings configSource="connectionStrings.config"/>

How to declare a variable in the app.config file?

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;"

Categories

Resources