|
Using the <connectionStrings> Configuration Section of the Web.Config (ASP.NET) |
|
|
Written by: Evan Cummings
Using the <connectionStrings> Configuration Section of the Web.ConfigConfiguration files offer developers a great oppertunity to utilize a portable and standard format for storing pertinent information that an application may need. A great illustration is that of the connection string - the string of text defining all of the connection properties required to access a particular database. It is a best practice to isolate this string from your code and store it in a configuration file. Why do this? What if the database server changes? Or how about the user account and password? These are all within the realm of possibility in any environment - and changing a hard coded connection string means the application needs to be recompiled and redeployed. By moving this into an configuration file, we can simply modify it, save it, and have no worry about the internals of the application!
In the .NET framework these configuration files are represented as XML documents, and adding or modifying information within it simple entails changing or adding nodes to this file. The typical way this would be accomplished in the .NET 1.0/1.1 environment would involve adding a key containing the connection string value to the web.config:
<add key="connString" value="Server=myServer;Database=myDB;User ID=myID;Password=myPW;Trusted_Connection=False" />
This value could then be called from within the application:
GetRecords(ConfigurationSettings.AppSettings("connString").ToString)
This approach functions perfectly well in its own, however the .NET Framework 2.0 and onward has introduced a new method specfically designed for connection strings. A new node type has been included for application configuration files called <connectionStrings>. Our previous .NET 1.1 example converted to .NET 2.0 would result like so:
<connectionStrings>
<add name="connString" connectionString="Server=myServer;Database=myDB;User ID=myID;Password=myPW;Trusted_Connection=False" />
</connectionStrings>
Introduced also in .NET 2.0 is a new way to access configuration file information. ConfigurationSettings.AppSettings has been deprecated, and will produce warnings from Visual Studio. The new and preferred method involes using a ConfigurationManager which resides in a new namespace called System.Configuration:
GetRecords(System.Configuration.ConfigurationManager.ConnectionStrings("connString").ConnectionString)
The major benefit of this approach is that it provides us a strongly typed approach targetted directly for connection information. We can also singly target the <connectionStrings> node for any encryption that might be incorporated into the production application.
Although I typically deal with web applications with ASP.NET, this property is now available across all types of .NET development styles, such as Forms and Web Services, as well.
|
|
|
|
|
|