3.2 Configuration Data
When Web applications are deployed, there are often constant data values that need to be modified so that the application runs properly on the deployment server. Examples of such values include database connection strings and preferences or settings that influence the appearance or behavior of the application. ASP.NET configuration files provide a specific element for storing generic
Listing 3-3 Specifying Application-Specific Configuration Data
<!-- File: web.config -->
<configuration>
<appSettings>
<add key="DSN"
value="server=localhost;uid=sa;pwd=;database=pubs"
/>
<add key="bgColor" value="white" />
</appSettings>
</configuration>
In this example, we have
Listing 3-4 Retrieving appSettings Configuration Data
<!-- File: samplepage.aspx -->
<%@ Page Language='VB' %>
<%@ Import Namespace='System.Configuration' %>
<script runat=server>
Protected Sub Page_Load(src As Object, e As EventArgs)
Dim dsn As String
dsn = ConfigurationSettings.AppSettings("DSN")
' use dsn to connect to a database...
' (or just display here)
_dsn.Text = dsn
Dim bgColor As String
bgColor = ConfigurationSettings.AppSettings("bgColor")
' use retrieved background color...
_body.Attributes("bgColor") = bgColor
End Sub
</script>
<!-- remainder of page not shown -->
Note in Listing 3-4 that the namespace System.Configuration was imported, because that is where the ConfigurationSettings class resides. This class provides a static indexer called AppSettings that is used to retrieve the values indexed by their key in the appSettings element of a configuration file. The keys used to index the appSettings element are not case sensitive, so be aware that bgColor and BgColor , for example, will map to the same element.
One frequently asked question is, What
|