Configuration Files


There has always been a need to configure applications for the specific machines on which they run. This need arises because of a number of factors, including differing security requirements, differing levels of functionality provided in different environments, and differing capabilities provided by the machines on which the applications execute.

Text-Based Configuration Files

UNIX and Windows 3.x have traditionally solved the issue of configuration using text files. Often these files follow a specific format and are stored in system directories, such as \Windows\System or /etc . When applications start up, they read these files to configure themselves . For example, the process syslogd , which logs system messages into files, uses the syslog.conf file to see which message should be redirected to which files. Lines in the syslog.conf file have a specific layout.

Another example on UNIX systems involves a process called inetd that listens for incoming network connections on multiple ports. When a connection is requested , inetd will start the appropriate server, if one is available and not already running, and pass the connection to that server. To accommodate different configurations, inetd reads its configuration information from a text file, usually called inetd.conf . An interesting point about inetd is that dynamic configuration is achieved by editing the configuration file and then sending a signal to the process. On receipt of the signal , the process will reread the configuration file and thus be updated with the new settings. The configuration file often has the following format: [1]

[1] Nemeth, E., Snyder, G., Seebass, S., and Hein, T. (1995). UNIX System Administration Handbook , 2nd ed., Prentice-Hall.

 ftp     stream  tcp  nowait  root  /etc/ftpd     ftp  telnet  stream  tcp  nowait  root  /etc/telnetd  telnetd bootp   dgram   tcp  wait    root  /etc/bootp    bootp -f 

The use of text-based configuration files offers a number of advantages. Such files are generally easy to read and can be easily edited by numerous programs. Of course, binary configuration files have some additional drawbacks as well. When using the Registry to store configuration information, for example, the programmer needs to understand a complex hierarchical structure. Also, the developer must use tools such as regedit to open and access Registry entries. Finally, because all programs share the Registry, if the Registry becomes corrupted then many programs may exhibit faulty behavior.

Unfortunately, although text files are easy to read and modify, they do not readily describe their structure ”that is, what each column means. Normally, comments are inserted in the file to describe the structure. A more self-describing structure would be beneficial.

CLR Configuration Files

CLR configuration files are XML files that allow an application (or many applications, or even .NET itself) to use a different configuration without recompiling. Thus your application's configuration may change according to the configuration of the machine on which the application is deployed. As these files are written in XML, the elements provide a more self-describing quality than traditional text-based files such as those used in UNIX.

Configuration files were mentioned in Chapter 5 during the discussion of how to bind to a different version of an assembly than that used when building an application. Ideally, configuration files should do a lot more than version binding for single applications ”and, in fact, they do.

.NET supports several different configuration files: one that applies at the machine level, one that applies at the application level, ones that relate directly to security, and so forth. Individual applications can use the System.Configuration class library to use and extend these configuration files for their own purposes.

Configuration File Format

As XML files, configuration files consist of tagged XML elements, each containing zero or more attributes. Chapter 5 included the following example:

 <configuration>     <runtime>       <assemblyBinding         xmlns="urn:schemas-microsoft-com:asm.v1">          <dependentAssembly>             <assemblyIdentity name="AboutBox"               publicKeyToken="a0df1539bc79861c"/>             <bindingRedirect oldVersion="1.0.0.0"               newVersion="2.0.0.0"/>          </dependentAssembly>       </assemblyBinding>    </runtime> </configuration> 

Here the top-level configuration element consists of a single subelement runtime , which consists of a single subelement assemblyBinding , which consists of a single subelement dependentAssembly , which is where the action finally starts! DependentAssembly has two subelements ( assemblyIdentity and bindingRedirect ), with each subelement having two properties.

Configuration File Schema

The root element of configuration files is always the configuration element. The valid subelements of the configuration element, which are detailed in the .NET documentation, include elements such as runtime , startup , network , and so forth.

This section offers a brief description of the top-level elements supported by .NET, but makes no attempt to demonstrate or document all of the supported elements. In version 1 of .NET, the following elements are supported under the top-level configuration element:

  • startup

    Configuration options that affect how the process is created. Currently, the only option available is requiredRuntime , which allows an application to specify the version of the .NET runtime environment that should be used.

  • runtime

    Configuration options that change the runtime behavior of the .NET system, most notably the assembly loading and garbage collection subsystems. Assembly policies can dictate version binding policies, the directories to be searched (including debugging support), the code base (download location) for referenced assemblies, and more. The concurrency of garbage collection can also be changed to control the threading semantics of object destructors.

  • system.runtime.remoting

    Configuration options that allow you to fine-tune how .NET manages remote objects. A huge array of options allows you to specify timeouts and lease times for remote sessions, and to dictate how objects implement and use SOAP services. These options also include debugging techniques for remote objects.

  • system.net

    Configuration options that dictate how network resources are used and authenticated. You can specify how many connections an application can open on a specific server and how authentication with that server is achieved. Proxy server settings are also specified in the defaultProxy element.

  • cryptographySettings

    Advanced options that allow you to customize the encryption providers used by the system.

  • system.diagnostics

    Configuration options that can prove useful when debugging .NET applications. You can configure how .NET reacts to an application assertion or redirect application debugging messages to various locations to enhance debugging. Some options control exactly which debug settings and verbosity levels are used by the application.

  • system.web

    Configuration options for ASP.NET.

Note that not all configuration options are supported in all configuration files. Certain options make sense only in the context of a single application or for the entire machine, whereas others could be used in either machine or application files depending on the specific site requirements.

Machine Configuration Files

One machine configuration file per computer applies to an entire computer: machine.config . It is found in the {Windows Directory}\ Microsoft.NET\Framework{Framework Version Installation Directory}\Config directory.

Application Configuration Files

An application configuration file is found in the same directory as the application executable; it carries the name of the executable file with " .config " appended to it. In Chapter 5, for example, the application UseAboutBox.exe had an application configuration file named UseAboutBox.exe.config .

Security Configuration Files

.NET permits configuration of security settings via configuration files. Because security settings are so vitally important and complex to set up, it is strongly recommended that you use the .NET Framework Configuration Tool to maintain these files. .NET defines Enterprise Policy, Machine Policy, and User Policy configuration files. The Enterprise and Machine Policy files are named enterprisesec.config and security.config , respectively, and are found in the {Windows Directory}\Microsoft.NET\Framework{Framework Version Installation_Directory}\Config directory. The User Policy file is also named security.config but is found in the user profile directory tree (the exact location depends on the particular operating system).

ASP Configuration Files

ASP.NET supports configuration files named web.config and provides its own hierarchical namespace (based on the file system) for these files. Thus, an ASP.NET Web site may have a large number of web.config files, each tailoring the settings for that specific part of the site. See the ASP.NET documentation for more information.

Custom Configuration Sections

Applications can store their own configuration data in the machine or application configuration files. The configuration file schema allows custom configuration sections to be defined, then permits the section itself with the configuration data to appear. The definition of a section includes the name of the .NET class that is responsible for parsing the data contained within the section, and the configuration data include anything allowed by the definition.

To see how this definition works, let's look at an example from the default machine.configuration file. Listing 6.1 shows the entries.

Listing 6.1 Default machine.configuration file
 <?xml version="1.0" encoding="UTF-8"?> <configuration>  <configSections>   <sectionGroup name="system.web">     <section name="httpHandlers"       type="System...HttpHandlersSectionHandler..."       />   </sectionGroup>  </configSections>  <system.web>   <httpHandlers>     <add verb="*" path="trace.axd" type="..." />   </httpHandlers>  </system.web> </configuration> 

The first sectionGroup element defines a namespace called system.web . This group supports a section named httpHandlers ; this section is parsed and extracted by the .NET type System.Web . Configuration.HttpHandlersSectionHandler .

After the </configSections> element, the code creates the previously defined system.web group and defines the httpHandlers section. The subentries here depend on what is allowed by the System.Web.Configuration.HttpHandlersSectionHandler implementation.

The .NET class library provides a few general-purpose configuration handlers designed for reuse by applications, including the System.Configuration.SingleTagSectionHandler and System.Configuration.NameValueSectionHandler classes. Both allow you to define fairly arbitrary string data.

Let's demonstrate custom configuration data very simply by using application configuration files. The example application is named ReadCustomData.exe , so the application configuration file is called ReadCustomData.exe.config . Simply create this file with the contents shown in Listing 6.2.

Listing 6.2 Application configuration file: ReadCustomData.exe.config
 <configuration>  <configSections>   <section name="customSection"     type="System.Configuration.SingleTagSectionHandler"   />   </configSections> <customSection setting1="some value"                 setting2="value two"                 setting3="third value" /> </configuration> 

The SingleTagSectionHandler section allows you to place arbitrary keys and values into a single tag. At runtime, the application uses the System.Configuration.ConfigurationSettings class to fetch the data, which in turn causes .NET to call the SingleTabSectionHandler class to deserialize the data. Reading the documentation reveals that SingleTagSectionHandler returns the data via an IDictionary , so you can cast the object accordingly .

Listing 6.3 shows the code to fetch the data in ReadCustomData.cs .

Listing 6.3 Fetching data, version 1: ReadCustomData.cs
 using System; using System.Collections; using System.Configuration; namespace Samples {   class Demo   {     public static void Main()     {       IDictionary sampleTable = (IDictionary)          ConfigurationSettings.GetConfig("customSection");       Console.WriteLine(          "First is: {0}, second is: {1}, third is: {2}",           sampleTable["setting1"],           sampleTable["setting2"],           sampleTable["setting3"]);     }   } } 

You can build and run this example as follows :

 First is: some value, second is: value two, third is: third value 

In addition to SingleTagSectionHandler , another useful option parser class is available: System.Configuration.NameValueSectionHandler . Using this handler, your configuration options can support discrete elements per configuration value. For example, ReadCustomData2.exe.config (see Listing 6.4) shows an alternative representation for the example data.

Listing 6.4 Representing data: ReadCustomData.exe.config
 <configuration>  <configSections>   <section name="customNamedSection"     type="System.Configuration.NameValueSectionHandler" />  </configSections>  <customNamedSection>    <add key="setting1" value="some value" />    <add key="setting2" value="value two" />    <add key="setting3" value="third value" />  </customNamedSection> </configuration> 

The code to read these data is very similar to the version given in Listing 6.3. NameValueSectionHandler sections are returned at runtime as a System.Collections.Specialized.NameValueCollection , as shown in ReadCustomData2.cs (see Listing 6.5).

Listing 6.5 Fetching data, version 2: ReadCustomData.cs
 using System; using System.Collections.Specialized; using System.Configuration; namespace Samples {   class Demo   {     public static void Main()     {       NameValueCollection sampleTable =         (NameValueCollection)         ConfigurationSettings.GetConfig(         "customNamedSection");       Console.WriteLine(         "First is: {0}, second is: {1}, third is: {2}",          sampleTable["setting1"],          sampleTable["setting2"],          sampleTable["setting3"]);     }   } } 

Note that the custom section does not include any information about the application that needs the data. If you store the custom configuration data in your application configuration file, no problem arises ”by definition, all settings in this file remain local to your application. However, if you store the data in the machine configuration file, then the settings are shared among all applications. Thus, in the preceding example, any application could fetch the settings simply by referring to customNamedSection . If another .NET application expects to find configuration data under this key, a conflict would result.

Which Configuration Files to Use?

In many cases, you may have a choice as to which configuration file to use for a particular setting. In both the version binding and custom configuration examples described here and in Chapter 5, you could place the information in either an application configuration file or the machine configuration file.

In many cases, it is clear that the configuration setting you want to change is local to a single application; the custom data example in the preceding section demonstrates this scenario. In many cases, however, you may want to modify a setting that is either global to all applications or used by a component that is itself shared among many applications, so that its configuration data are also shared among applications.

Unfortunately, no easy answer to this dilemma exists. .NET provides only a very global machine configuration file or a very local application configuration file. To help you determine the best course of action, this section briefly discusses some of the advantages and disadvantages of each scheme.

If you store your settings in the application configuration file, deployment of your application remains simple: An xcopy of your application is all that is required. Because the application configuration file appears in the same directory as your application, it, too, is copied to the new computer.

Another key advantage of application configuration files is that they tend to be far smaller than machine configuration files, thereby allowing you to readily see all relevant settings required by your application. If the same settings were stored in the machine configuration file, they might get lost in the noise.

The only advantage that machine configuration files offers over application configuration files is sometimes also the killer advantage: They apply to multiple applications. In some cases, options cannot practically be stored in application configuration files because they apply to too many applications for this approach to be feasible . In this case, the machine configuration file is the only reasonable alternative.



Programming in the .NET Environment
Programming in the .NET Environment
ISBN: 0201770180
EAN: 2147483647
Year: 2002
Pages: 146

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net