In this post we will examine step by step how to create simple connection string for connecting with SQL Server and what are the best practices to create and manage connection string for connecting with SQL Server in ADO.Net.
Syntax of connection stringConnection string consists of key\value pairs where each key\value pair is separated by other key\value pair through semicolon. Each key\value pair in connection string provides part of the information that is required to connect to a databse. We will examine the most basic key\value pairs one by one.
Data source or network address = server address\instance nameWe specify the address of the machine where SQL Server instance is running followed by '\' and then name of the SQL Server instance. Before moving on i will like to tell you What is SQLServer instance?
When we install the SQL Server on our machine it is usually given a default name of SQLExpress, so most probabbly name of the SQL Server instance will be SQLExpress but it is not necessary you can give any name to it while you are installing it. If Sql Server is running on your local machine then your connection string can be written as
Data Source = (local)\SQLExpress or DataSource = .\SQLExpress
Where '.' means local machine.
Database or Initial Catalog = database_nameUse the keyword Database or Initial Catalog to specify the name of the database to which you want to connect.
So uptill now if Sql server is running on your local machine with default instance name SQLExpress and the name of the database that you want to connect is 'MyFirstDB' then your connection string will look like
"Data Source =.\SQLExpress;Initial Catalog = MyFirstDB"
Inegrated Security or Trusted Connection = True\False or Yes\no or SSPISetting the value of key
Integrated Security to True or SSPI or setting the value of key
Trusted Connection to Yes or true (both keys integrated security and trustesd connection have same meaning and any of them can be used to get the same result) means we are using windows authentication for accessing the database.
Userid = "***" ; Password ="**"If we want to use SQL Server authentication to access the database instead of windows authenticaion then we need to use the keys
User Id and
Password to specify the login credentials for logging in to sql server
Summing up the above disscussion if suppose SQL Server is running on local machine and instance name of SQL Server is SQLExpress. Name of the database to which we want to connect is MyFirstDB and we are using Windows authentication to connect to SQL Server. Then resulting connection string will look like
"Data Source = .\SQLExpress;Initial Catalog = MyFirstDB;Integrated Security = SSPI"
Using Windows Authentication with SQL ServerUsing windows authentication for connecting with SQL Server means you are using application's process identity or thread identity for accessing the SQL Server.When using windows authentication you do not specify user id and password in connection string. Because identity of the client application's process requesting the connection is used to connect with SQL Server.Identity of the client application's process will most probabally be the identity of the logged on user who is running the application.
Using SQL Server authenticationWhen using SQL Server authentication you specify user Id and Password in connction string to connect to SQL Server.
Comparison between Windows Authetication and SQL Server AutheticationYou should use windows authentication if possible rather than SQL Server authentication because when using windows authentication you do not need to specify User id and password in connection string as compared to SQL Server authentication. Specifying credential information in connection string can compromise the security of application and requires additional overhead to protect the information. Requiring you to encrypt the connection string and using secure mechanism when transferring credentials over network between data server and application server
Saving connection string in configuration file
You can save connection string in configuration file which is your web.config file in case of ASP.NET applications and app.config file in case of windows application. Application can retrieve the connection string from configuration file at run time.
You can save more than one connection strings in configuration file . Connection strings are stored in the 'connectionStrings' section of configuration file. You use the 'add' element under the 'connectionStrings' sections to add any new connection string.you give name to the connection string so that it can be refer later on with that name, specify the data provider and the connection string iteslf. Below is an example of connection string specified in configuration file
<>
< name="Name" providername="System.Data.ProviderName" connectionstring="Valid Connection String;">
< /connectionStrings >
Hard coding connection string in your application also put it at security risk because it can be retrieved by hijackers from code using MSDIL.exe tool otherwise if you save it in configuration file and encrypt it then it will be more difficult for hijackers to gain access to information in connection string even if they gain access to the file containing connection string.(See: How to encrypt connection string in configuration file?)
Saving connection String in external configuration fileChanging connection string in configuration file will restart your application and you will loose any state information for example in case of ASP.net application running in inprocess session mode. The workaround is that you can save your connection string in external configuration file and then refer that external configuration file in your main configuration file.Changing external configuration file does not restart your application.
To store connection string in external configuration file create a new file with only connectionStrings section in it.Do not specify any other section.
<>
< name="Name" providername="System.Data.ProviderName" connectionstring="Valid Connection String;">
< /connectionStrings >
In the main configuration file you use the configSource attribute to specify the path of the external configuration file
<>
< configsource="external_connection.config">
< /configuration >
Encrypting connection string in web configuration file
You can encrypt or decrypt sections of web configuration file using Aspnet_regiis.exe tool. You will find the aspnet_regiis.exe tool in %windows%\Microsoft.NET\Framework\versionNumber folder. To encrypt the configuration file you run the Aspnet_regiis.exe tool with
–pe switch followed by the name of the section in configuration file you want to encrypt. ASP.NET application will automatically decrypt the encrypted section at run time.
Use the following command to encrypt the connection string in web configuration file of 'MyApplication' web application using RsqProtectedConfigurationProvider.
Aspnet_regiis.exe –pe “connectionStrings” –app “MyApplication” –prov “RsaProtectedConfigurationProvider”.
Switch
–app specifies the name of the application whose web configuration file we want to encrypt.
Switch
–prov specifies the name of the protected configuration provider that will perform the encryption or decryption of web configuration file.
They are two built in protected configuration provider shipped with .net RSAProtectedConfigurationProvider and DPAPIProtectedConfigurationProvider.
Retrieving connection string from configuration fileYou can retrive the connection string information from configuration file using
ConfigurationManager class in case of windows application and you can use
WebConfigurationManager class to retrieve connection string information from web.config file.
You can get the ConnectionStringSettings object that represent a single connection string entry in connectionStrings section. Properties of connectionStringSettings correponds to the attributes of the connection string entries in connectionStrings section. By using the 'ConnectionString' property of ConnectionStringSettings object you can get the connection string.
public string getConnectionString()
{
string connectionString = null;
ConnectionStringSettings settings =
WebConfigurationManager.ConnectionStrings[connectionStringName];
if (settings != null)
connectionString = settings.ConnectionString;
return connectionString;
}
ConclusionAbove we have disscussed how to construct connection string, save it in external configuration file, retrieve connection string from configuration file and how to encrypt connection string using Aspnet_regiis.exe. In next post we will try to look in detail about windows authentication and SQL Server authentication.