So I'm using C# and I've got the following SQL connection string:
private static string _conn = Properties.Settings.Default.dBizConnectionString;
And I'd like to know if and how I can put it in the web config and app config? Thanks for the help!
Here's a blog post from Scott Forsyth explaining everything:
Using Connection Strings from web.config
The short answer is yes, like so:
<connectionStrings>
<add name="ConnectionStringName" providerName="System.Data.SqlClient" connectionString="Server=ServerName; Initial Catalog=InitialCatalog; User ID=User; Password=Password; MultipleActiveResultSets=True;" />
</connectionStrings>
There's a lot of information out there about connection strings. There are more options you can specify, they can be encrypted, etc. etc., but this will get you started.
Add it to the web config like this:
<connectionStrings>
<add name="myConnectionStringName" connectionString="Data Source=mySqlServerInstance;Initial Catalog=myCatalog;User ID=myUserId;Password=myPassword"/>
</connectionStrings>
Add code to retrieve it:
private static string GetConnectionString()
{
var config = WebConfigurationManager.OpenWebConfiguration("/myProject");
var connections = config.ConnectionStrings;
var settings = connections.ConnectionStrings["myConnectionStringname"];
string connectionString = settings.ConnectionString;
return connectionString;
}
Related
I'm working on a project that takes the connection to the database via the `Properties.Settings.Default;
so I have to set the connection string there, but it gets annoying because I already have a connection string set in the We.config file.
How to I set the Properties.Settings to use DefaultConnection connection string in the database?
var request = HttpContext.Current.Request;
var settings = Properties.Settings.Default; <--- use 'DefaultConnection' connectionString
using (var db = new Database(settings.DbType, settings.DbConnection))
{...}
my connection string
<connectionStrings>
<add name="DefaultConnection" connectionString="server=localhost;Database=DB;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>
THANK YOU!
I have two connections in the web.config basically they are calling the same database. I want to manage this in a better manner because change in one config also needs to change the second connection string as well.
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;persist security info=True;user id=test;password=test123;database=db-AUTH" providerName="System.Data.SqlClient" />
<add name="dbEntities" connectionString="metadata=res://*/InsuranceFinderModel.csdl|res://*/InsuranceFinderModel.ssdl|res://*/InsuranceFinderModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=db-AUTH;persist security info=True;user id=test;password=test123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
My question is, is there any way i can call the connection string into the other connection string.
For example. default connection connection string into db entities something like
<add name="dbEntities" connectionString="metadata=res://*/InsuranceFinderModel.csdl|res://*/InsuranceFinderModel.ssdl|res://*/InsuranceFinderModel.msl;provider=System.Data.SqlClient;provider connection string= DefaultConnection" providerName="System.Data.EntityClient" />
Any suggestions would be appreciated thanks.
You are not obliged to use connection string defined inside app.config(web.config) file for entity connection. You can change entity connection string at runtime. Read this article for that: http://www.c-sharpcorner.com/UploadFile/dacca2/pass-connection-string-in-run-time-to-entity-framework/ .
Also you can get another connnection string and separete every part of connection string( DataBase,DataSource and etc.) using StringConnectionBuilder class https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.initialcatalog.aspx.
The solution is: Get DefaultConnection string and change entity connection at runtime.
I have this in webconfig
<add name="dbConn" connectionString="Data Source=PC-PC;Integrated Security=True" />
Then I call them most of the time in my page via
string connstr = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
However some page requires two queries. What I have in mind is (or what I like to achieve)
string connstr = ConfigurationManager.ConnectionStrings["dbConn"+"MultipleActiveResultSets=True"].ConnectionString;
But ofcourse it will not work. Since what stated in here is like the code below.
footnote: I don't wanna use this in most of my page
string connectionString = "Data Source=MSSQL1;" +
"Initial Catalog=AdventureWorks;Integrated Security=SSPI;" +
"MultipleActiveResultSets=True";
because i have multiple pages, and of course to easily set-up the DB.
footnote2: reason why is that because i don't know maybe it's not robust and using 2 connection in a page that only requires 1 connection maybe is ugly.
EDIT: Sorry for bad english
You can have two connection for your scenario :
Without MultipleActiveResultSets=True,
<add name="dbConn1" connectionString="Data Source=PC-PC;Integrated Security=True" />
and with MultipleActiveResultSets=True,
<add name="dbConn2" connectionString="Data Source=MSSQL1;
Initial Catalog=AdventureWorks;Integrated Security=SSPI;
MultipleActiveResultSets=True;" />
You can load above connection string as per your requirement.
Load the connection string in SqlConnectionStringBuilder, manipulate the builder, then call ToString() to get the manipulated connection string:
string webConfigConnectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
var builder = new System.Data.SqlClient.SqlConnectionStringBuilder(webConfigConnectionString);
builder.MultipleActiveResultSets = true;
string modifiedConnectionString = builder.ToString();
I would like some explanations on how to create and set up a dynamic connection to SQL Server DB engine in a C # project
if you want connection string in config and read it than you need to do like this , put possible connectionstring in config
<connectionStrings>
<add name="CharityManagement"
connectionString="Data Source=.;Initial Catalog=CharityManagement;Integrated Security=True"/>
<add name="CharityManagement_two"
connectionString="Data Source=.;Initial Catalog=CharityManagement_two;Integrated Security=True"/>
</connectionStrings>
and than read it base on condition using configurationmanager class
//to read first connection string
var connectionString=ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;
//to read second connection string
var connectionString=ConfigurationManager.ConnectionStrings["CharityManagement_two"].ConnectionString;
This is what you're after
In the config file
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Then to read the connection string in your code you will do
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
Don't forget to use using System.Configuration;
Further reading here
I've noticed that when I create model-first database using EF it is ignoring web.config connection strings and doing it's own thing in the background. Then I found a way to set my own connection string in constructor like so.
public class MainDataContext : DbContext
{
public MainDataContext()
{
this.Database.Connection.ConnectionString = "MY CONNECTION STRING THAT IS ACTUALLY USED";
}
}
Question: How can I force/set it to use connection string from web.config?
I've been told that if you name your connection string just like your data context it will work but it doesen't for me. I know for sure that it does not work if I name it DefaultConnectionString.
<add name="MainDataContext" providerName="System.Data.SqlClient"
connectionString="Server=(LocalDB)\\v11.0;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|ProjectDB.mdf;" />
Error occurred when I try to do update-database -v -f from console.
You can try something like this:
public MainDataContext() :
base(typeof(MainDataContext).Name)
{
}
Are you sure your connection string declaration in the Web.config is correct? Like this:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyDatabase" connectionString="server=localhost;User Id=user;password=password;Persist Security Info=True;database=mydatabase" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>