WEBSITE

Microsoft ASP.NET 4 : .NET Configuration

10/12/2010 3:26:32 PM
.NET configuration files are well-formed XML files whose vocabulary is understood by the .NET runtime. You can see a list of all the configuration files by looking in the configuration directory (which you explore just a little later).

The .NET runtime reads these configuration files into memory as necessary to set the various .NET run-time parameters, and these parameters are cumulative. For example, web.config is loaded when ASP.NET applications are started, but the first configuration file the server examines is machine.config.

1. Machine.Config

The default .NET configuration for your computer is declared in a file named machine.config. You can find machine.config in the directory C:\Windows\Microsoft.NET\Framework\vxxxxx\Config (where xxxxx is the .NET version; the current release at the time of this writing is 4 and the directory name of the beta version at the time of this writing is v4.0.21006). Machine.config sets the default .NET application behaviors for the entire computer.

Recent .NET versions have improved the machine.config arrangement. Versions 1.x of .NET lumped all of machine.config into a single file—even comments and configuration information for systems not in use on the specific computer (browser information, for example, even though the computer might not have been hosting ASP.NET). With version 2.0, machine.config was trimmed down substantially. The comments were moved to a separate file named machine.config.comments, and separate browser definition capability files were moved to separate configuration files. This is important to know because the machine.config comments are sometimes more useful as documentation for configuring .NET than the regular online documentation is. As you configure various ASP.NET applications, the machine.config comments should be the first place you look for information. Version 4.0 of the machine.config file is only a little bit larger than its 3.0 predecessor.

2. Configuration Section Handlers

At the top of machine.config you can see a number of configuration section handlers. Each handler understands a specific vocabulary for configuring .NET (and ultimately ASP.NET). Whereas machine.config controls the settings for the entire computer, ASP.NET applications rely on files named web.config to manage configuration. You see much more about web.config shortly. However, for now here is an example of what you might find in a web.config file for a specific application:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<authentication mode="Forms" />
<sessionState mode="SQLServer" cookieless="UseUri" timeout="25" />
</system.web>
</configuration>

This small segment tells the ASP.NET runtime to use Forms Authentication (one of the ASP.NET authentication options) to authenticate users of this site. The configuration information also tells ASP.NET to use SQL Server to manage session state, to allow session state information to expire after 25 minutes, and to track session information using a session ID embedded in the request Uniform Resource Identifier (URI). 

You can see from this example that configuring ASP.NET relies on the ability of the runtime to understand some keywords. In this case, the keywords authentication, mode, and Forms tell ASP.NET how to manage authentication. ASP.NET must correctly interpret sessionState, mode, SQLServer, cookieless, UseURI, and timeout to know how to manage an application's session state.

The .NET components that understand these vocabularies are listed near the top of machine.config.

<configuration>
<configSections>
<section name="appSettings"
type="{entire strong assembly name here...}"
restartOnExternalChanges="false" />
<section name="connectionStrings"
type="{entire strong assembly name here...}" />
...
<sectionGroup name="system.web"
type="{entire strong assembly name here...}">
<section name="authentication"
type="{entire strong assembly name here...}"
allowDefinition="MachineToApplication" />
<section name="sessionState"
type="{entire strong assembly name here...}"
allowDefinition="MachineToApplication" />

...
</sectionGroup>
</configSections>
</configuration>

The preceding code is necessarily abbreviated. Go ahead and take a look at machine.config and you'll see the section handlers in their full glory. (On most computers, machine.config is located at C:\Windows\Microsoft.NET\Framework\vxxxxx\Config.) When you look at the configuration handlers, you can see that the sessionState configuration settings are interpreted by an assembly with the strong name System.Web.Configuration.SessionStateSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a. A strong name fully specifies the name of an assembly, including a version (to ensure version compatibility) and a public token (to ensure the assembly has not been tampered with).

3. Web.Config

Machine.config lays out the default settings for your computer (and ultimately for your applications). The default settings are generally targeted toward the most common use cases you will encounter rather than some special configuration you might need to apply to a specific application. For example, sessionState is configured to be handled in process by default. That's fine when you're developing but almost certainly is not appropriate for a commercial-grade application that services many diverse clients.

Because all your .NET applications depend on machine.config to configure them, making changes to machine.config could potentially affect multiple applications. It's a bad idea to update machine.config directly.

To configure themselves, stand-alone .NET applications depend on configuration files named after the application. For example, an application named MyApp.EXE would have a configuration file named MyApp.EXE.config. Of course, ASP.NET applications do not follow that naming convention. Instead, the ASP.NET runtime expects configuration information to be declared in a file named web.config.

Microsoft Visual Studio 2010 introduces a new feature: separate configurations for debug and release versions of your application. Earlier versions of Visual Studio provided only a single web.config file, and the debug and release versions of the application shared the same settings. In Visual Studio 2010, when you generate a Web application, Visual Studio provides three configuration files: web.config, web.debug.config, and web.release.config. Settings shared by the debug and release versions go in web.config. Settings specific to the debug or release version (such as the Trace setting) go in the respective web.config files.

To override the default settings, you simply need to include a file named web.config in the application's virtual directory. For example, the following code sets up the Web application to which it applies. The configuration file turns on Forms Authentication and tracing, for example.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<authentication mode="Forms" />
<trace enable=true/>
</system.web>
</configuration>

The configuration settings your application actually sees have been inherited from a (potentially) long line of other web.config files. The machine.config file sets up the default .NET configuration settings. The top-level web.config file (in the .NET configuration directory) sets up the initial ASP.NET configuration. Then, you can use subsequent child web.config files in the request path to tweak folder-specific settings for a single application.

This way of managing configuration information works well. Many of the usual defaults apply in most situations, and you sometimes need to tweak only a few items. When you do, you just drop a web.config in your virtual directory and/or subdirectory.

However, managing settings by littering your hard disk with web.config files can get a bit unwieldy if many separate configurations are necessary. The ASP.NET configuration schema includes a location element for specifying different settings for different directories—but all the settings can all go in a master configuration file for your application.

For example, the following configuration section removes the ability of the AppSubDir directory to process standard ASP.NET Web Services. The remove instruction causes ASP.NET to have amnesia about all files with the extension .asmx.

<configuration>
<location path="AppSubDir">
<system.web>
<httpHandlers>
<remove verb="*" path="*.asmx" />
</httpHandlers>
</system.web>
</location>
</configuration>

You could also apply other specific settings to the subdirectory, such as for security purposes. You might not find it surprising that ASP.NET configuration files include terms to manage authorization and authentication. This is a perfect use for the location element. The following configuration code allows all users into the main (virtual) directory but requires that users who want to access the PagesRequiringAuth subdirectory be authenticated:

<configuration>
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
<location path="PagesRequiringAuth">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
</configuration>

4. Managing Configuration in ASP.NET 1.x

In ASP.NET 1.x, you configured settings manually by typing changes into a target web.config file. For example, if you wanted your application to use SQLServer as a session state database, you had to insert the correct verbiage into the application's web.config file, keystroke by keystroke. Unfortunately, there was no configuration compiler to help ensure that the syntax was correct. If you typed something wrong, you usually wouldn't know about it until you ran the application, at which point ASP.NET would display a cryptic error message.

5. Managing Configuration in Later Versions of ASP.NET

ASP.NET 2.0 introduced some major improvements to the process of managing ASP.NET applications, and these improvements carry through to the current version of ASP.NET. Although you can still type configuration information into the web.config file manually, ASP.NET 2.0 and later versions provide some new configuration utilities, including the Web Site Administration Tool (WSAT) available in Visual Studio and the ASP.NET configuration facilities available through IIS 7.x.

In this exercise, you change settings in an application's configuration and see how they are reflected in web.config.

Configuring your application

  1. Begin by creating a new Visual Studio ASP.NET Web Application project named ConfigORama.

  2. After Visual Studio generates the application, click Project, ASP.NET Configuration to open the ASP.NET Web Site Administration Tool, which is shown in the following graphic:



    The Other Administration Tabs

    Notice that the Web Site Administration Tool includes four tabs: Home, Security, Application, and Provider. The Security tab manages authentication and authorization settings. That is, you can use the Security tab to add users and assign roles to them. You explore that process in detail in the next chapter.

    The Application tab is for maintaining various settings related to your application. You can control basic configuration settings here, including maintaining key/value pairs specific to your application, Simple Mail Transfer Protocol (SMTP) settings for defining how the site manages e-mail, and turning debugging and tracing on and off. You can also use the Application tab to take an application offline to perform maintenance.

    Finally, you can use the Provider tab to manage various data providers. In ASP.NET 2.0, Microsoft introduced the concept of a provider designed to make data access for a given ASP.NET subsystem easier and more standardized. For example, users might have personalized settings, and the Membership provider retrieves them for your code to display to the user or otherwise manage. The Roles provider provides the roles your user might be assigned when using your Web application. You can configure the various providers individually using the Provider tab. Although you will most likely use the built-in ASP.NET providers that access a database for data archival and retrieval, you could use custom providers that you create, third-party providers, or mix and match the two types. Provider configuration in the Provider tab includes which provider to use (if you have more than one available) and database connection string settings if a database is to be used.


    With the Web Site Administration Tool, you can manage parts of web.config without having to type settings manually. The tool is accessible from Visual Studio. Visual Studio 2010 creates a web.config file by default. But if for some reason one is not created, the Web Site Administration Tool can create a web.config file for you. When you manage authentication and roles, the tool also creates a database suitable for consumption by SQL Server Express in the App_Data folder of your Web site for storing application data. (You see more about that later in the discussion of ASP.NET features such as personalization and authorization.)

  3. Click the Application tab and add a couple of application settings by clicking the Create Application Settings link. Add a setting named Copyright and one named CompanyName, as shown in the following graphics. In this exercise, it doesn't matter what you type as the corresponding value. First, go to the Application tab.



    Then, click the Create Application Settings link to add some settings:



    When you return to the Application tab, it shows how many application settings there are in the config file:



  4. Open the application's web.config file. You should see entries for Copyright and CompanyName.

    Web.config should look like this now (some entries inserted by Visual Studio have been omitted):

    <?xml version="1.0" ?>
    <configuration >

    <appSettings>
    <add key="Copyright" value="Copyright © 2009 " />
    <add key="Company" value="ThisIsACompanyName" />

    </appSettings>

    <connectionStrings/>
    </configuration>

  5. Now write some code to access the application settings you just added, which are available through a class named ConfigurationManager. Add a drop-down list to the Default.aspx form to hold the application settings keys (with an ID of DropDownListApplicationSettings) and a label to display the values (with the ID LabelSetting). Add a button with the ID ButtonLookupSetting so that users can look up the value associated with the application settings key. In the Page_Load handler, interrogate the ConfigurationManager for all the application settings:

    using System.Configuration

    public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {



    if (!this.IsPostBack)
    {
    foreach (String strKey
    in ConfigurationManager.AppSettings.AllKeys)
    {
    this.
    DropDownListApplicationSettings.
    Items.Add(strKey);
    }
    }

    }
    protected void ButtonLookupSetting_Click(object sender, EventArgs e)
    {

    string strSetting;
    strSetting =
    ConfigurationManager.AppSettings[this.
    DropDownListApplicationSettings.
    SelectedItem.Text];
    this.LabelSetting.Text = strSetting;

    }
    }


  6. Compile the program and run the site. When you start the page, it loads the drop-down list so that it contains all the keys from the ConfigurationManager.AppSettings collection. When you select application settings by clicking a key in the drop-down list, the code you inserted in the previous step looks up the value of the application setting and displays it in the label:



In ASP.NET, you can also manage application settings using the Configuration tab for your site when it is hosted in IIS.

Other  
 
Most View
Is Blue The Color? (Part 2)
Fujifilm X-E1 - A Retro Camera That Inspires (Part 1)
The Sony Xperia SP - The Impressive Mid-Range Android Smartphone
Windows 7 : Managing Print Jobs (part 3) - Creating XPS Documents
EVGA GeForce GTX 650 1GB - Severely Cut Down From GTX 660 Ti
30 Something CD Players Group Test (Part 4) - Quad Elite CDS
Chillblast Fusion Blaze - Perfectly Overclocked System
Slim, Light And Mighty Ultrabooks Supertest (Part 3) : Lenovo IdeaPad U300s, HP Envy 14 Spectre, Lenovo U300s
Blackberry Q10 - An Ultimate Messaging Machine For Socializing, Sharing And Working (Part 2)
Western Digital Sentinel DX4000 NAS Review (Part 4)
Top 10
Sharepoint 2013 : Farm Management - Disable a Timer Job,Start a Timer Job, Set the Schedule for a Timer Job
Sharepoint 2013 : Farm Management - Display Available Timer Jobs on the Farm, Get a Specific Timer Job, Enable a Timer Job
Sharepoint 2013 : Farm Management - Review Workflow Configuration Settings,Modify Workflow Configuration Settings
Sharepoint 2013 : Farm Management - Review SharePoint Designer Settings, Configure SharePoint Designer Settings
Sharepoint 2013 : Farm Management - Remove a Managed Path, Merge Log Files, End the Current Log File
SQL Server 2012 : Policy Based Management - Evaluating Policies
SQL Server 2012 : Defining Policies (part 3) - Creating Policies
SQL Server 2012 : Defining Policies (part 2) - Conditions
SQL Server 2012 : Defining Policies (part 1) - Management Facets
Microsoft Exchange Server 2010 : Configuring Anti-Spam and Message Filtering Options (part 4) - Preventing Internal Servers from Being Filtered