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();
Related
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 am trying to learn to use VS2015 and I have seen a number of similar postings on the internet relating to this problem and none of them have gotten me any closer to a solution.
I am trying to write into a SQL Server database and have tested both my database and connection string and confirm they are both working well.
With that out of the way I went into web.config and created a definition for said connection string:
<connectionStrings>
<add name="Name"
connectionString="Data Source=<desktopname>\\SQLEXPRESS01;Integrated Security=SSPI;Initial Catalog=Database1"/>
</connectionStrings>
As far as I can tell this works fine...
However, when I declare the string as follows:
MyConnectionString = ConfigurationManager.ConnectionStrings["Name"].ConnectionString;
Somehow what this returns is not understandable by:
SqlConnection iData = new SqlConnection(myConnectionString);
As when I try and "open" the connection it fails... Despite the exact same connection string works when declared like this within the C# code:
SqlConnection iData = new SqlConnection("Data Source=<desktopname>\\SQLEXPRESS01;Integrated Security=SSPI;Initial Catalog=Database1");
Does anyone have any ideas?
The problem lies with how the information is handled from web.config to the string to the SqlConnection as far as I can tell.
Notably everything runs perfectly unless I use the string as the connection string...
Thanks in advance!
In C# the backslash needs to be doubled, because the compiler treats the backslash as an escape character. And then the \\ compiles to \ in the actual string used at runtime.
In XML that is not the case, it uses a different parser, so in Web.Config you should use a single \:
<add name="Name" connectionString="Data Source=<desktopname>\SQLEXPRESS01;Integrated Security=SSPI;Initial Catalog=Database1"/>
On top of that you may also need to add providerName="System.Data.SqlClient":
<add
name="Name"
connectionString="Data Source=<desktopname>\SQLEXPRESS01;Integrated Security=SSPI;Initial Catalog=Database1"
providerName="System.Data.SqlClient"
/>
Reference: https://msdn.microsoft.com/en-us/library/bf7sd233(v=vs.85).aspx
Try to add : providerName="System.Data.SqlClient" in your "< add name"
<add name ="Name" connectionString="Data Source=<desktopname>\\SQLEXPRESS01;Integrated Security=SSPI;Initial Catalog=Database1" providerName="System.Data.SqlClient"/>
I have created a LocalDB database in my project and its connection string is :
Data Source=(LocalDB)\v11.0;AttachDbFilename="E:\Projects\visual studio 2013\Projects\sqlce\mydb.mdf";Integrated Security=True;Connect Timeout=30
How should I pass it to SqlConnection()?
Note that it has an address within quotation marks. Have I done anything wrong?
I guess even if I program it correctly it won't work in another computer which doesn't have that .mdf file in that exact place. Isn't it so?
How can I have a program with a portable database so I can easily publish my pp?
Add the mdf file to your solution and and change the property "Copy to Output Directory" to Copy Always. Don't hardcode the mdf file path in connection string. Add the connection string in app.config or web.config file like below:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\myDB.mdf;Initial Catalog=MyDatabaseName;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Then you can access the connection string in your C# code as below:
string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString()
If you face any error regarding accessing the mdf file, the you can set the DataDirectory in your C# code using AppDomain.CurrentDomain.SetData() method.
<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>
you can access by
connString =rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
More about connection string
SqlConnection con = new SqlConnection(connstring);
or you can go in this way like
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
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
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;
}