Where to store Connection String in Web.Config? - asp.net

We can store Connection String in Web.config file in two ways One is
<connectionStrings>
<clear/>
<add name="LocalSqlServer"
connectionString="Data Source=(local);Initial Catalog=aspnetdb;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Other One is
<appSettings>
<add key="ConnectionString"
value="server=localhost;database=Northwind;uid=sa;password=secret;" />
</appSettings>
Now I want to know
What is difference between these two approach?
Which one is better way?
What are their limitations?
UPDATE:Can you explain that <connectionString> has any significant advantage over <appSetting>?

The connectionStrings section is dedicated to connection strings and was only introduced in .NET 2.0.
appSettings is more general and is to be used for other application settings.
You should use the connectionStrings section, as it can also be encrypted separately from any other settings.

The first approach can be accessed directly by some data controls like SQLDataSource.

Using the connectionStrings element would be the most appropriate way to handle connection strings. The appSettings element is how connection strings used to be handled before .NET 2.0. You can use either approach but it is probably easier to work with multiple connection strings if you use the connectionString element. With multiple connection strings stored in appSettings you would have to parse each name (or value) to work out if it is a connection string before you could use it. This leads to maintenance issues. It's easier to just check if all of the connectionString items are present.

If you add your connection strings to the appSettings section, you need to manually retrieve them using the ConfigurationManager.AppSettings.Get(key) method.
By adding your connection strings instead to the connectionStrings element, .NET can automatically find these by name when you create your connection object.

connection-string section is declare the connection for system.I mean that you application know that you string is connectionString. If you will use appSettings for application it is just any string value.

Besides the benefits mentioned in the other answers, connectionStrings elements have a providerName attribute that appSettings elements do not. This is particularly useful if your data source is not SQL Server.

Related

Connectionstring in windowsservice

My web application's webconfig file contain following connectionstring.
<connectionStrings>
<add name="TestConnectionString" connectionString="Data Source=ServerIp;Initial Catalog=databasename;Persist Security Info=True;User ID=userid;Password=password"
providerName="System.Data.SqlClient" />
May I know what meaning of Persist Security Info?.What is purpose of it in this case?
In my windows service, class file contain following connectionstring.
connectionString="Server=ServerIp;Database=databasename;MultipleActiveResultSets=True;Integrated Security=false;User Id=userid;Password=password"
I want to add appconfig file for connection and replace above one.Does I need to mention provider name?Here is sample one which I am going to write in app.config file.
<connectionStrings>
<add name="SampleConnectionstring" connectionString="Server=ServerIp;Database=databasename;MultipleActiveResultSets=True;Integrated Security=false;User Id=userid;Password=password" providerName="System.Data.SqlClient" />
</connectionStrings>
what is meaning of MultipleActiveResultSets?Why it is used here?
From MSDN: Multiple Active Result Sets (MARS) is a feature that works with SQL Server to allow the execution of multiple batches on a single connection. When MARS is enabled for use with SQL Server, each command object used adds a session to the connection.
With regards to Persist Security Info: When set to false or no (strongly recommended), security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state. Resetting the connection string resets all connection string values including the password. Recognized values are true, false, yes, and no.
More information can be found here: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx
Also, here's a great resource for connection strings: http://www.connectionstrings.com/

Proper format for SQL Server Connection String on 1and1.com

I have spent several hours trying to search this on the web in addition to calling and emailing support at 1and1.com web hosting with no success.
I have ASP.NET pages which connect to MS SQL Server database using the entity framework. On my local machine, all works fine (naturally). However, when I modify the connection string in my web.config to point to my SQL Server database on 1and1.com, I get the following error:
"Unable to load the specified metadata resource."
Here's my current connection string (as defined in my web.config file):
<add name="TimeDataLicenseEntities"
providerName="System.Data.EntityClient"
connectionString="metadata=res://*/
Model1.csdl|res://*/
Model1.ssdl|res://*/
Model1.msl;
provider=System.Data.SqlClient;
provider connection string="
data source=dbXXXX.db.1and1.com,1433;
Integrated Security=false;
initial catalog=database_name;
user id=dboXXXX;
password=valid_password;multipleactiveresultsets=True"" />
(Please note that where there are 'XXXX' the values are different in the actual config file as well as for 'database_name' and 'valid_password')
I'm using the Entity Framework in the code so I'd prefer solutions that correct the content of my web.config file.
Here is what ended up working for me:
<add name="TimeDataLicenseEntities"
providerName="System.Data.EntityClient"
connectionString="metadata=
res://<assemblyname>/Model1.csdl|
res://<assemblyname>/Model1.ssdl|
res://<assemblyname/Model1.msl;
provider=System.Data.SqlClient;
provider connection string="
data source=dbXXXX.db.1and1.com,1433;
Integrated Security=false;
initial catalog=database_name;
user id=dboXXXX;
password=valid_password;
multipleactiveresultsets=True"" />
By including the assemblyname for my code in the sections above (the brackets ('<' and '>') should not be included), I was able to finally get it to work.
Thanks all for your assistance.
Here is what actually works on 1and1 server from ASP.NET Code first design. So, simply replace your serverName, DatabaseName, UserID, and Password.
<add name="DefaultConnection"
connectionString="Data Source=dbXXX.db.1and1.com,1433;Initial Catalog=dbYYYYY;Integrated Security=False;user id=dboZZZZZ;password=YOURDBPASSWORD;MultipleActiveResultSets=True;Application Name=EntityFramework"
providerName="System.Data.SqlClient" />
Hope this can help anyone looking to use 1and1 asp.net server since their customer service is pretty useless.

ASP.NET EFCodeFirst not using correct connection string

I am trying to publish a website using ASP.NET MVC3 EF and CODEFIRST with a SQL Server 2008 backend. On my local machine I was using a sql express db for development, but now that I am pushing live, I want to use my hosted production database. The problem is that when I try to run the application, it is still using my local db connection string. I have completely removed the old connection string from my web.config file and am using the <clear /> tag before creating the new connection string. I have also cleaned the solution and rebuilt, but somehow it is still connecting to the old db. What am I missing?
This is the new connection string:
<connectionStrings>
<clear />
<add name="CellularAutomataDBContext"
connectionString=" Server=XXX;
Database=CellularAutomata; User ID=XXX; Password=XXX; Trusted_Connection=False"
providerName="System.Data.SqlClient" />
</connectionStrings>
UPDATE
When I debug and look at the DBCONTEXT object, this is what is showing up for its connection:
Data Source=.\\SQLEXPRESS;Initial Catalog=CellularAutomata.Models.D1K2N3CARuleDBContext;Integrated Security=True;MultipleActiveResultSets=True"
I am unsure why this is happening because I cannot find it being set to this anywhere. Also, under configuration it says LazyLoadingEnabled = true, I assume this may be part of the problem, maybe it is not loading the new connection string. Where do I change these parameters?
UPDATE 2
EFCodeFirst is using a default connection string, I can't figure out how to get it to accept the connection string that I specify in the web.config file.
So, When using EF CodeFirst, there is a default connection string that it uses. If you want to be able to use a custom connection string, there are a few parameters guidelines that you must follow.
name ="this must match the name of your database context class"
connectionString="Server=yourserverurl; Database=yourdatabasename; User ID=youruserid;
Password=yourpassword; Initial Catalog=the name of the database to use;
Trusted_Connection=False"
providerName="System.Data.SqlClient"
So far this is working for me.
The connectionString you show is not an EF connection string. The EF won't use it. So you're changing the wrong thing.
An EF connectionString will include providerName="System.Data.EntityClient"
It will look for the same name as your context and depending on what else you
are using other names as well. I usually use the following for controlling
specific features with either the same or specific connection strings
(I keep app services in a different db for example so EFCF can drop tables as needed):
<connectionStrings>
<add name="MyAppContext" .../>
<add name="ApplicationServices" .../>
<add name="DefaultConnection" .../>
</connectionStrings>

including a connection string generates error in asp.net site

I have set up a small SQL Server database for users to login and also create accounts. There is a problem with the connection string though. Whenever I use the connection string below in the web.config file I get a server error page and cannot view the website. However when I take out this connection string I am able to view the website albeit the database doesn't work. Any ideas would be greatly appreciated.
<configuration>
<appSettings/>
<connectionStrings>
<addname="ConnectionString" connectionString="Server=.\SQLEXPRESS;Database=medicale_Members;User ID=user_admin;Password=medicalmembers;"/>
<connectionStrings/>
<system.web>
Unsure if it's a typo in your question, but you need to ensure your connection string element looks like:
<add name
rather than
<addname
Ensure you close your element with
</connectionStrings>
Change it to:
</connectionStrings>
Also as another person mentioned. Change the add to:
<add name ... />

add connection string at runtime

Is it possible to insert a connection string into a web.config file at runtime, if it isn't there? Would this work?
The connection string is for a ASP.NET user login and create account database.
How do you mean "insert?" If you mean can you manually edit web.config: yes, you can. You'd add an entry for connectionStrings (if there wasn't one) an then a child node for your specific connectionString.
If you mean can you do it in code: theoretically yes. However, it is normally bad practice, and a pain the rear.
Yes it is very possible:
<connectionStrings>
<add name="yourNameHere" connectionString="connectiongStringHere" providerName="nameHere"/>
</connectionStrings>
inside ConfigSections
Put a default connectionstring in your web.config and replace the username/password and database name at runtime as desired.

Resources