How to change connection string in app.config - c#

I have a program that generates reports by using DataTables created by TableAdapters. Now my client has a new database, and he wants to be able to switch between the new one and the old one. I found that I can do it by changing the connection string in the app.config, but I don't know how to do it during run time. Can you suggest me a way?
Thanks

I don't know how to do it during run time
Don't. You can have multiple connection strings in the app.config and access each when needed.
Configuration:
<connectionStrings>
<add name="conn1" providerName="System.Data.SqlClient"
connectionString="..." />
<add name="conn2" providerName="System.Data.SqlClient"
connectionString="..." />
</connectionStrings>
In code:
var conn1 = ConfigurationManager.ConnectionStrings["conn1"];
var conn2 = ConfigurationManager.ConnectionStrings["conn2"];

You can define more than one connection strings like this:
<add name="Conn" connectionString="Data Source=PC\SQLEXPRESS;Initial Catalog=NHIB;Integrated Security=True" providerName="System.Data.SqlClient"/>-->
<add name="Conn1" connectionString="Data Source=WINSERVER;Initial Catalog=NHIB1;Integrated Security=True;" providerName="System.Data.SqlClient"/>
And after that you can use conn or conn1 based on your requirement..like:
SqlConnection con;
con = new SqlConnection(ConfigurationManager.AppSettings.Get("Conn")); Or
con = new SqlConnection(ConfigurationManager.AppSettings.Get("Conn1"));
You can switch between them as below:
string connectionString = HttpContext.Current.Request.IsLocal ?
ConfigurationManager.ConnectionStrings["Conn"].ConnectionString :
ConfigurationManager.ConnectionStrings["Conn1"].ConnectionString;
yourDataContext = new YourApplicationDataContext(connectionString);

Related

Can't connect to local database when using connection string

i'm unable to connect to SQL server when i use connection string:
this code works well:
SqlConnection db_connection = new SqlConnection("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
db_connection.Open();
but if put this on Web.config:
<connectionStrings>
<add name="conn" connectionString="Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" />
</connectionStrings>
Then on my page:
SqlConnection db_connection = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
db_connection.Open(); // fail - error 50
So it will only work if i don't use the configuration manager...
The issue was that the slashes between the server and the instance name were escaped for the code to interpret the string, but in the [app|web].config file, it understands there are going to be interesting characters in there, and handles them accordingly, and do not need the escaping that the code does.
Removing the double slash between the (localdb) and MSSQLLocalDB fixed the issue for me. Try the following in your connectionStrings config:
<connectionStrings>
<add name="conn" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" />
</connectionStrings>
Hello try to use this and
1. in reference add System.Configuration
2. write in cs Using System.Configuration
3. var connectionString = ConfigurationManager.ConnectionStrings["conn"].ToString();
put this into config file

c# connection string and concatenation app.config

I have the following connection string through which i connect to an Access database(.mdb) located in a sub-folder inside the root-folder of my application :
OleDbConnection con = new OledbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + System.AppDomain.CurrentDomain.BaseDirectory() + "Data\rctts.mdb;Jet OLEDB:Database Password=mypassword;")
My question is, how do i put the connection string in the app.config file? Generally, i use :
<connectionStrings>
<add name="Test" connectionString="Data Source=.;Initial Catalog=OmidPayamak;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
The issue i am facing is that in my connection string, i am doing some concatenations and also using System.AppDomain.CurrentDomain.BaseDirectory() to set the Data Source...
How do i do the same concatenation in app.config ? Is it possible to do so ?
You could try the following:
connectionString="Data Source=|DataDirectory|\rctts.mdb;Initial Catalog=OmidPayamak;Integrated Security=True"
and then try to set the value of DataDirectory as below:
var currentDomain = AppDomain.CurrentDomain;
var basePath = currentDomain.BaseDirectory;
currentDomain.SetData("DataDirectory", basePath+"\Data");
at the corresponding startup file of your application.
Although configuration APIs offer no facilities to manipulate connection strings for you, you could place connection string "template" into configuration, and do the rest of manipulation in your code using string.Format:
Config:
<connectionStrings>
<add name="Test" connectionString="Data Source={0}Data\rctts.mdb;Initial Catalog=OmidPayamak;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
C# code:
string conStr = string.Format(
ConfigurationManager.ConnectionStrings["Test"].ConnectionString
, System.AppDomain.CurrentDomain.BaseDirectory()
);

How to write connection string in web.config file and read from it?

I'm trying to write Connection string to Web.config like this:
<connectionStrings>
<add name="Dbconnection" connectionString="Server=localhost;
Database=OnlineShopping ; Integrated Security=True"/>
</connectionStrings >
and read from it like this:
string strcon =
ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlConnection DbConnection = new SqlConnection(strcon);
when run the program I get an error because of the null reference. but when I use this code:
SqlConnection DbConnection = new SqlConnection();
DbConnection.ConnectionString =
"Server=localhost; Database=OnlineShopping ; Integrated Security=True";
I don't get any error and the program works correctly!
What is the problem?
Add reference to add System.Configuration:-
System.Configuration.ConfigurationManager.
ConnectionStrings["connectionStringName"].ConnectionString;
Also you can change the WebConfig file to include the provider name:-
<connectionStrings>
<add name="Dbconnection"
connectionString="Server=localhost; Database=OnlineShopping;
Integrated Security=True"; providerName="System.Data.SqlClient" />
</connectionStrings>
Web.config:
<connectionStrings>
<add name="ConnStringDb" connectionString="Data Source=localhost;
Initial Catalog=DatabaseName; Integrated Security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
c# code:
using System.Configuration;
using System.Data
SqlConnection _connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnStringDb"].ToString());
try
{
if(_connection.State==ConnectionState.Closed)
_connection.Open();
}
catch { }
Try this
After open web.config file in application and add sample db connection in connectionStrings section like this
<connectionStrings>
<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient"/>
</connectionStrings >
Are you sure that your configuration file (web.config) is at the right place and the connection string is really in the (generated) file? If you publish your file, the content of web.release.config might be copied.
The configuration and the access to the Connection string looks all right to me. I would always add a providername
<connectionStrings>
<add name="Dbconnection"
connectionString="Server=localhost; Database=OnlineShopping;
Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
try this
var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();
Try to use WebConfigurationManager instead of ConfigurationManager
After opening the web.config file in application, add sample db connection in connectionStrings section like this:
<connectionStrings>
<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient" />
</connectionStrings>
Declaring connectionStrings in web.config file:
<add name="dbconnection" connectionString="Data Source=Soumalya;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System.Data.SqlClient" />
There is no need of username and password to access the database server.
Now, write the code to get the connection string from web.config file in our codebehind file. Add the following namespace in codebehind file.
using System.Configuration;
This namespace is used to get configuration section details from web.config file.
using System;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
//Get connection string from web.config file
string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
//create new sqlconnection and connection to database by using connection string from web.config file
SqlConnection con = new SqlConnection(strcon);
con.Open();
}
}

Something wrong with app.config (SQL Server Express)

In my app.config:
<add name ="connSpionshopString" connectionString="Data
Source=.\SQLEXPRESS;;AttachDbFileName=|DataDictionary|Spionshop.mdf;
Integrated Security=True;User Instance=True"/>
And in my form.cs:
SqlConnection conn2 = new SqlConnection();
conn2.ConnectionString = ConfigurationManager
.ConnectionStrings["connSpionshopString"]
.ConnectionString;
This always gets an error: "Invalid v alue for key 'attachdbfilename'."
I don't know what's wrong with this.. :(
You should be able to fix it by modifying it just a tad:
<add name ="connSpionshopString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|Spionshop.mdf;Integrated Security=True;User Instance=True"/>
You had DataDictionary instead of DataDirectory
The invalid value for key 'attachdbfilename' error can be thrown if the database server/host name is considered incorrect by the SqlConnection class. When using SQL Server Express you may only use an instance of the local host (., (local), or NETBIOS or DNS name of local machine).
that means either use like this
<add name ="connSpionshopString" connectionString="Data
Source=.;AttachDbFileName=|DataDictionary|Spionshop.mdf;Integrated Security=True;User
Instance=True"/>
or
<add name ="connSpionshopString" connectionString="Data
Source=machinename;AttachDbFileName=|DataDictionary|Spionshop.mdf;Integrated Security=True;User
Instance=True"/>
or
<add name ="connSpionshopString" connectionString="Data
Source=(local);AttachDbFileName=|DataDictionary|Spionshop.mdf;Integrated Security=True;User
Instance=True"/>
I suppose expecting the server name of the sql database to be a local address and not /sqlexpress in DataSource variable
I believe you have a typo:
connectionString="Data Source=.\SQLEXPRESS; **HERE!! ;**
AttachDbFileName=|DataDictionary|Spionshop.mdf;
Integrated Security=True;User Instance=True"
You put 2 semicolons instead of one.

How to use the ConfigurationManager.AppSettings

I've never used the "appSettings" before. How do you configure this in C# to use with a SqlConnection, this is what I use for the "ConnectionStrings"
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
And this is what I have for the "appSettings"
SqlConnection con = new SqlConnection();
con = ConfigurationManager.AppSettings("ConnectionString");
but it is not working.
Your web.config file should have this structure:
<configuration>
<connectionStrings>
<add name="MyConnectionString" connectionString="..." />
</connectionStrings>
</configuration>
Then, to create a SQL connection using the connection string named MyConnectionString:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
If you'd prefer to keep your connection strings in the AppSettings section of your configuration file, it would look like this:
<configuration>
<appSettings>
<add key="MyConnectionString" value="..." />
</appSettings>
</configuration>
And then your SqlConnection constructor would look like this:
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyConnectionString"]);
ConfigurationManager.AppSettings is actually a property, so you need to use square brackets.
Overall, here's what you need to do:
SqlConnection con= new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
The problem is that you tried to set con to a string, which is not correct.
You have to either pass it to the constructor or set con.ConnectionString property.
you should use []
var x = ConfigurationManager.AppSettings["APIKey"];
\if what you have posted is exactly what you are using then your problem is a bit obvious. Now assuming in your web.config you have you connection string defined like this
<add name="SiteSqlServer" connectionString="Data Source=(local);Initial Catalog=some_db;User ID=sa;Password=uvx8Pytec" providerName="System.Data.SqlClient" />
In your code you should use the value in the name attribute to refer to the connection string you want (you could actually define several connection strings to different databases), so you would have
con.ConnectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;

Categories

Resources