This article looks at performing two tasks. The first is to create your own custom configuration class that will allow you to store application specific settings within web.config. The second is to encrypt sections within the configuration file.
Often you need to store application specific settings such as database connection strings and other settings that control your application. ASP.NET makes it very easy to store these settings in the web site configuration file (web.config).
There is already a dedicated configuration section "<connectionStrings>" for storing connection strings and you can store your own custom properties within the "<appSettings>" section e.g.:
<appSettings>
<add key="applicationName" value="My Application Name" />
</appSettings>
While this will suit most simple applications, there will be times when you have lots of application specific settings to store and you may need to group these into their own configuration elements. A common example of this is where different parts of an application may connect to different data sources or use different caching policies.
Creating your own configuration section is easy. First create the following class:
Imports System.Web.Configuration
Public Class MyConfigSection
Inherits ConfigurationSection
<ConfigurationProperty("applicationName", DefaultValue:="MyDefaultApplicationName")> _
Public Property ApplicationName() As String
Get
Return CStr(Me("applicationName"))
End Get
Set(ByVal value As String)
Me("applicationName") = value
End Set
End Property
<ConfigurationProperty("domainName")> _
Public Property DomainName() As String
Get
Return CStr(Me("domainName"))
End Get
Set(ByVal value As String)
Me("domainName") = value
End Set
End Property
<ConfigurationProperty("sqlConnectionString", DefaultValue:="localhost")> _
Public Property SqlConnectionString() As String
Get
Return CStr(Me("sqlConnectionString"))
End Get
Set(ByVal value As String)
Me("sqlConnectionString") = value
End Set
End Property
End Class
Then in web.config add the following before the closing </configSections> tag:
<section name="myConfigSection" type="MyConfigSection, __code" />
Next, after the closing <configSections> tag you can add your own custom configuration section:
<myConfigSection applicationName="My Application"
domainName="retroviz.com"
sqlConnectionString="Data Source=Server1; Initial Catalog=Northwind; User ID=user1; password=123456#" />
Next add a new class to your web site called helpers. This will allow us to retrieve an instance of the configuration section so we can easily access it's settings:
Imports System.Web.Configuration
Public NotInheritable Class Helpers
Public Shared ReadOnly Settings As MyConfigSection = _
CType(WebConfigurationManager.GetSection("myConfigSection"), MyConfigSection)
End Class
With that done we can easily retrieve our settings programatically. Add the following to the body of your default.aspx:
<asp:label runat="server" ID="lblAppName"><%=Helpers.Settings.ApplicationName%></asp:label><br />
<asp:label runat="server" ID="lblDomainName"><%=Helpers.Settings.DomainName%></asp:label><br />
<asp:label runat="server" ID="lblConnectionString">
<%=Helpers.Settings.SqlConnectionString%></asp:label>
Launch the page in your browser and your custom settings will then be displayed. You can then use the SqlConnectionString in the constructor when creating a new SqlConnection and may use the AppName to prefix all your page titles.
Protecting areas of web.config
ASP.NET 2.0 made if very easy for us to encrypt sections of web.config. This is very useful if you are storing sensitive information such as the username and passwords used in connection strings.
Do encrypt our custom section add the following code to the helpers class we created above:
''' <summary>
''' Encrypts/Decrypts the specified areas of web.config
''' </summary>
''' <param name="encrypt">Boolean value indicating whether to encrypt (True) or decrypt (False)</param>
''' <param name="sectionName">The section name within web.config to encrypt</param>
''' <remarks></remarks>
Public Shared Sub EncryptConfig(ByVal encrypt As Boolean, ByVal sectionName As String)
Dim path As String = "/ProtectingWebConfig"
Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(path)
Dim appSettings As ConfigurationSection = config.GetSection(sectionName)
If encrypt Then
appSettings.SectionInformation.ProtectSection _
("DataProtectionConfigurationProvider")
Else
appSettings.SectionInformation.UnprotectSection()
End If
config.Save()
End Sub
Now drop two buttons onto your default.aspx page as below:
<asp:Button runat="server" ID="btnEncrypt" Text="Encrypt"
onclick="btnEncrypt_Click" />
<asp:Button runat="server" ID="btnDecrypt" Text="Decrypt"
onclick="btnDecrypt_Click" />
and add the following event handlers:
Protected Sub btnEncrypt_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Helpers.EncryptConfig(True, "myConfigSection")
End Sub
Protected Sub btnDecrypt_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Helpers.EncryptConfig(False, "myConfigSection")
End Sub
Run your page and click the Encrypt button. Open web.config and you will see that our custom configuration section is now encrypted:
<myConfigSection configProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>
<CipherData>
<CipherValue>AQAAANCM.....</CipherValue>
</CipherData>
</EncryptedData>
</myConfigSection>
Click the Decrypt button and your configuration section will be decrypted.
You can now use these techniques in your own application to securely store sensitive information such as database connection strings.
A sample website can be downloaded at the top of the page.
Comments
Comment this article