c# connection string and concatenation app.config - c#

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()
);

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

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;

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();
}
}

c# Loading connectionString from file on runtime

I have an application (Console) already in place which is reading connection string from the bin directory.
We are planning to pass a directory path from command line which would point to the configurations.This way we would be able to switch between pointing to different DBs by just changing the command line parameter for "ConfigurationDirectory"
This requires us to dynamically load the connectionstring, the format of my connection string is as below :
<connectionStrings>
<add name="DB1" connectionString="Data Source=DB;Initial Catalog=someCatalog;Persist Security Info=True;User ID=****;Password=****; Asynchronous Processing=true" providerName="System.Data.SqlClient" />
<add name="DB2" connectionString="Data Source=DBName;Initial Catalog=someCatalog2;Persist Security Info=True;User ID=****;Password=****; Asynchronous Processing=true" providerName="System.Data.SqlClient" />
</connectionStrings>
We do not have a configuration tag.
To load up the connection string dynamically I am trying this :
var connectionStringconfigfile = "C:Somepath\connectionstring.config"
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = connectionStringconfigfile;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
I am unable to use the connectionstring file I have currently because it complains that there is no configuration tag.
The problem is that my code already uses the following to initialize connection string :
ConfigurationManager.ConnectionStrings["DB1"].ConnectionString
With this new approach the above line does not seem to work and always gives me null, is there a way so that I do not have to change my existing code?
If you wrap your external config file in a <configuration> block, like this:
<configuration><br>
<connectionStrings><br>
<add name="DB1" connectionString="Data Source=DB;Initial Catalog=someCatalog;Persist Security Info=True;User ID=****;Password=****; Asynchronous Processing=true" providerName="System.Data.SqlClient" /><br>
<add name="DB2" connectionString="Data Source=DBName;Initial Catalog=someCatalog2;Persist Security Info=True;User ID=****;Password=****; Asynchronous Processing=true" providerName="System.Data.SqlClient" /><br>
</connectionStrings><br>
</configuration>
Your code should work.

How to change connection string in app.config

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

Categories

Resources