Click here to Skip to main content
15,885,366 members
Articles / Programming Languages / C#
Article

Enhancements done for storing connection strings in Visual Studio 2005

Rate me:
Please Sign up or sign in to vote.
2.91/5 (18 votes)
29 Jun 20053 min read 58.5K   38   5
Enhancements done for storing connection strings in Visual Studio 2005.

Introduction

This article contains some enhancements done for storing connection strings in Visual Studio 2005 and the usage of ConnectionStringBuilder. We are always curious about storing connection strings whenever we work on ADO.NET. "Where should I store my connection strings?" - might be a FAQ at least for a beginner.

Storing connection strings in .NET 1.x

In the .NET Framework 1.x, configuration files (such as the web.config file) support a section named <appSettings>, which is used to store name/value pairs. All these values populate the AppSettings collection and can be easily retrieved programmatically, as shown here:

C#
string connString = ConfigurationSettings.AppSettings["MyNWind"];

This is a common scenario of storing the connection string in our day to day application. The advantage is that you can keep the connection string out of the compiled code. This way of storing the connection string also makes the information global to the application which can be easily called from any module. So, we are sure that there no issues related to the connection strings. You can store any data in the <appSettings> section that can be rendered with a flat name/value pair.

Enhancements done in Whidbey

In Whidbey, Microsoft has introduced a <connectionStrings> section that is created to contain the connection strings (such as SQL connection strings). The section is named <connectionStrings>. Its structure is shown here:

XML
<connectionStrings>
    <add name="EmployeeDB"
      connectionString="SERVER=…;DATABASE=…;UID=…;PWD=…;" />
    <add name="OrdersDB"
      connectionString="~\DATA\CustDB.mdb" />
</connectionStrings>

You can manipulate the contents of the section by using <add>, <remove> and <clear> nodes. You use an <add> node to add a new connection string, <remove> to remove a previously defined connection and <clear> to reset all connections and create a new collection. By placing a web.config file in each of the application’s directories, you can customize the collection of connection strings that are visible to the pages in the directory. Each stored connection is identified with a name. This name references the actual connection parameters throughout the application. The <connectionStrings> section is a global and centralized repository of connection information. Retrieving connection strings programmatically All the connection strings defined in the web.config file are loaded into the new configuration - Settings.ConnectionStrings collection. If you are programmatically setting the connection string of an ADO.NET object, this feature makes your code flexible and easy to maintain. For example, consider the following web.config file:

XML
<configuration>
    <connectionStrings>
        <add name="MyNWind"
            connectionString="SERVER=…;DATABASE=northwind;UID=…;PWD=…" />
    </connectionStrings>
</configuration>

It registers a connection that points to the Northwind database on a given server and with certain credentials. To physically open that connection, the following code is required:

C#
string cnStr;
cnStr = 
  ConfigurationSettings.ConnectionStrings["MyNWind"].ConnectionString;
SqlConnection cnObj = new SqlConnection(cnStr);

Apart from this, we can also encrypt the connection strings. Encryption is optional, and you can enable it for any configuration section by referencing the name of the section in the web.config file. You can use the newest version of a popular system tool - aspnet_regiis.exe - or write your own tool using ASP.NET 2.0 configuration API.

aspnet_regiis.exe –pe connectionStrings –app /myapp

Creating connection strings in .NET Framework 1.x

In the .NET Framework 1.x, if we want to programmatically write the connectionstring, we do something like this:

C#
//serverName,uid,pwd are provided from the user
public void GetData(string serverName, string uid, string pwd)
{
    String connectionString = String.Empty;
    connectionString += ("Data Source = " + serverName +";");
    connectionString += ("User ID = " + uid +";");
    connectionString += ("Password = " + pwd +";");
    SqlConnection c = new SqlConnection (connectionString);
    c.Open();
    //Do something with the connection
}

This has no compile time checking problem and can even raise various run time issues.

Enhacements in ADO.NET 2.0

ADO.NET 2.0 introduces the use of ConnectionStringBuilder for building connection strings that are less prone to errors and the best part is that it does compile time checking.

C#
public void AccessData(string serverName, string uid, string pwd)
{
    String connectionString = String.Empty;
    //Get serverName from the user
    SqlConnectionStringBuilder conStrbuilder = 
                                        new SqlConnectionStringBuilder();
    conStrbuilder.DataSource = serverName;
    conStrbuilder.UserID = uid;
    conStrbuilder.Password = pwd;
    SqlConnection c = new SqlConnection (conStrbuilder.ConnectionString);
    c.Open();
    //Do something with the connection
}

Happy coding with Visual Studio 2005!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
Nishith Pathak is an avid reader,Prolific writer, Speaker for Microsoft India,Published Author of APress and a Microsoft Purist.He is MVP, MCPD, MCTS MCSD.Net,MCAD.Net(EA),MCSD. His proficiency lies in exploring Microsoft technology and to share them with other peers. He is a contributing author and an avid technical reviewer for multiple electronic and print publications. He has recently co-authored a book on WCF called Pro WCF: Microsoft Practical SOA Implementation for APress Inc, USA. Over the years, he has also been involved in providing consultancy and training services to corporations. He has been awarded with Microsoft Most Valuable Professional (MVP).Working since beta version of .Net makes his competecy in .Net. He can be contacted at NisPathak@Hotmail.com or at his blog http://DotNetPathak.Blogspot.com. Currently he is focused on key areas of the Microsoft platform, specifically Distributed Computing, service orientation and exploring VISTA and help companies architecting solutions based on Service Oriented Architecture.

Comments and Discussions

 
Generalbest practice Pin
Shaikh Babu19-Dec-06 0:43
Shaikh Babu19-Dec-06 0:43 
GeneralHmm... Pin
M@dHatter30-Jun-05 11:04
M@dHatter30-Jun-05 11:04 
GeneralRe: Hmm... Pin
_Stilgar_24-Jul-05 4:09
_Stilgar_24-Jul-05 4:09 
You wish dude. What's up with you anyway, Adam?
Contact me asap.

Stilgar (aka Bronso).
Questionhow about Pin
Ellery_Familia30-Jun-05 4:19
Ellery_Familia30-Jun-05 4:19 
AnswerRe: how about Pin
Nishith Pathak30-Jun-05 18:33
Nishith Pathak30-Jun-05 18:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.