Retrieving Configuration
You can access configuration settings from within an ASP.NET application by using either the
ConfigurationManager class, or the GetConfig or GetAppConfig method of the current HttpContext.
The object returned by ConfigurationManager.GetSection
depends on the section type mapped to the configuration section.
The following code demonstrates how you can access the configuration data exposed for a <customConfig>
section. In this example, it is assumed that the configuration section handler returns an object of type
CustomConfigSettings with the property Enabled.
Dim settings as CustomConfigSettings = CType(ConfigurationManager.GetSection("customConfig"), CustomConfigSettings)
If settings.Enabled
' Do something here.
End If
VB
Note: the runtime API will return a read-only instance of the configuration section.
Using Application Settings
Configuration files are perfectly suited for storing custom application settings, such as database
file paths, or remote XML Web service URLs. The default configuration sections (defined
in the machine.config file) include an <appSettings> section that may be used to store these settings as name/value
pairs. The following example shows an <appSettings> configuration section that defines
web service URLs for an application
<configuration>
<appSettings>
<add key="currencyService" value="http://www.microsoft.com/services/currencyService.asmx" />
<add key="creditCardValidationService" value="http://www.microsoft.com/services/cc.asmx" />
</appSettings>
</configuration>
The ConfigurationManager object exposes a special AppSettings property that you can use to retrieve
these settings:
Dim service As String = ConfigurationManager.AppSettings("currencyService")
VB
The following sample illustrates this technique.
VB Using Application Settings
Using Connection Strings
Like general application settings, ASP.NET provides a configuration section specifically for storing
database connection strings, used by ADO.NET.
The following example shows a <connectionString> configuration section for an application
that uses the Northwind sample database.
<configuration>
<connectionStrings>
<add name="northwind"
connectionString="server=(local)\SQLExpress;database=Northwind;Integrated Security=SSPI"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
The ConfigurationManager object exposes a special ConnectionStrings property that you can use to retrieve
these settings.
Dim connection As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("northwind").Name)
VB
If the providerName property of each connection string is set, you can use it to create and connect to
the database generically using ADO.NET provider factories, rather than using
code specific to the type of ADO.NET provider.
The following sample illustrates this technique.
VB Using Connection Strings
|