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;"
Related
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
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;
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>
I'm doing a c# course at university, and now I'm beginning linQ to xml, linQ to Sql-Server, etc.
I work with the example projects in two PCs (university PC and office PC)
Is there an easy way to change connection string (from app.config) at runtime, or designtime (using a constant in main.cs) so I can use a connection string at university, and a connection string at the office easily?
Thanks a lot in advance,
You could try something like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Environment" value="Home"/>
</appSettings>
<connectionStrings>
<add name="Work" connectionString="..."/>
<add name="Home" connectionString="..."/>
</connectionStrings>
</configuration>
and, later:
string environment = ConfigurationManager.AppSettings["Environment"];
ConfigurationManager.ConnectionStrings[environment].ConnectionString;
Another way of doing it:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="HomeEnvironment"
connectionString="Data Source=**HOME-COMPUTER**\SQLEXPRESS;Initial Catalog=**HomeDatabase**;Integrated Security=True;"
providerName="System.Data.SqlClient" />
<add name="WorkEnvironment"
connectionString="DataSource=**WORK-COMPUTER**\SQLEXPRESS;Initial Catalog=**WorkDatabase**;Integrated Security=True;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
and use it like this:
var environment = Environment.MachineName == "HOME-COMPUTER" ? "HomeEnvironment" : "WorkEnvironment";
var connectionString = ConfigurationManager.ConnectionStrings[environment].ConnectionString;
var dbContext = new **Databasename**ContextDataContext(connectionString);
Bold strings should be customised as required
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);