Benefits of using ConnectionStrings Element Instead of AppSettings
May 25th, 2007 by Sameer | Filed under .NET articles.In .NET 1.0 we used ConfigurationSettings instead of ConfigurationManager
With .NET 2.0 we can use ConfigurationManager.ConnectionStrings, and gain 3 benefits. Actually, if you just did a search and replace and changed ConfigurationSettings.AppSettings to ConfigurationManager.AppSettings you would not get the same special benefits that you would get by using the special ConnectionStrings element.
Here are three benefits you will get:
- We can encrypt our connection strings on the fly using reg_iis.exe (or by other methods)
- We can add SQL Cache Dependencies
- By putting connection strings in the right place, we can take advantage of any new features that come out that use the ConnectionStrings element
The incorrect way of storing connection strings:
Dim objConn As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
Here is the new node we can add to Web.Config
<connectionStrings >
<add name="DefaultConnection" connectionString="server=(yourserver);uid=whatever;pwd=your_plaintext_stored_password;database=DEV123"
providerName="System.Data.SqlClient" />
</connectionStrings>
To use the updated connectionstring element, see below (C# example)
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString
This is the preferred way to store and use your connectionstrings in .NET 2.0, allows you to do advanced stuff like encrypting your connection strings, using sqlParameterCache, etc.. If you want to encrypt your connection strings, the first step is putting them in the right place
ConfigurationManager is part of the Microsoft Application Blocks
Follow Up
-
How to encrypt connection strings using reg_iis.exe by Maurice Reeves (Google cache)
There are other benefits too that I did not document here.
