C# articles and tutorials on SharpDeveloper.NET

Sharpen your .NET skills with our C# articles, tutorials, demos, and source code by Sameer Alibhai
posts - 63, comments - 53, trackbacks - 1

Benefits of using ConnectionStrings Element Instead of AppSettings

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:

  1. We can encrypt our connection strings on the fly using reg_iis.exe (or by other methods)
  2. We can add SQL Cache Dependencies
  3. 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

There are other benefits too that I did not document here.

Print | posted on Friday, May 25, 2007 9:38 AM | Filed Under [ .NET articles ]

Feedback

No comments posted yet.

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 8 and 7 and type the answer here:

Powered by: