Configuring ASP.NET Applications


ASP.NET configuration management allows you to configure settings, such as execution timeout, security, and maximum length of a request, for an ASP.NET application. You configure an ASP.NET application when you either create a new ASP.NET application or migrate from an ASP application to ASP.NET. Configuration files for ASP.NET applications are eXtensible Markup Language (XML) files that are easily readable or modifiable using any editor. You can change configuration settings for ASP.NET applications at runtime without restarting the Web applications and servers. The .NET runtime automatically reads settings from the configuration file. As a result, you need not compile the application after changing the settings in the configuration file. The two types of configuration files are:

  • Web.config: Specifies configuration settings at the folder level for the ASP.NET application.

  • Machine.config: Specifies how .NET applications run on the computer.

Some advantages of configuration management in ASP.NET are:

  • Allows you to describe new configuration parameters, such as log files and user access and write configuration section handlers to process these parameters.

  • Allows different Web.config files to configure the settings of different directories of an ASP.NET Web application. Configuration settings of each Web.config file are applied at the directory level that contains the Web.config file and all its child directories. Configuration files in child directories, including the files inherited from parent directories, supply the configuration information. Using the configuration settings of the child directory, you can modify or overwrite a configuration setting of a parent directory.

  • Identifies any change in configuration files and automatically sets the new configuration settings to the changed Web resources. The server need not restart to reflect the changes.

  • Protects configuration files from external access by configuring IIS, and avoids direct browser access to configuration files.

  • Allows the use of any text editor or XML parser to create and edit ASP.NET configuration files.

The Web.config File

The Web.config file contains standard XML document elements, tags, text, comments, and data to define settings for the Web application. It also consists of different sections, such as globalization, compilation, authentication, handler, and tracing and error settings. All the configuration information in the Web.config file is between the <configuration> and </configuration> tags. The <system.web> tag below the configuration tag contains the elements that specify application-specific configuration settings, such as compilation, authentication, and authorization mode. The custom settings that you configure are defined outside the <system.web> tag. The different elements of the Web.config files are:

  • configuration: Holds all the predefined elements that construct the ASP.NET application.

  • system.web: Contains different configuration elements, such as compilation, authentication, and authorization, which configure ASP.NET Web applications.

  • compilation: Specifies compilation options for all the pages in a directory of the ASP.NET application.

  • customErrors: Redirects control of the current page to the specified URL when an error occurs.

  • authentication: Allows the configuration of the authentication system for your application by configuring the mode of authentication for the directory or application.

  • trace: Specifies settings for the trace service.

  • sessionState: Configures options to manage the session state of the ASP.NET application.

  • globalization: Configures global settings for the applications, such as the encoding format of files in the application.

  • appSettings: Allows you to specify custom settings for the application.

Listing 3-1 shows a sample Web.config file.

Listing 3-1: A Sample Web.config File

start example
 <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <compilation defaultLanguage="vb" debug="true" /> <customErrors mode="RemoteOnly" /> <authentication mode="Windows" />  <authorization> <allow users="*" /><!-- Allow all users --> </authorization> <trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" /> <sessionState  mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false"  timeout="20"  /> <globalization requestEncoding="utf-8" responseEncoding="utf-8" /> </system.web> </configuration>  
end example

The above listing shows the different elements of a Web.config file.

The configuration Element

The configuration element is the root element of the Web.config file. It holds all the predefined elements, which are XML tags that construct the ASP.NET application. The <configuration> element is present in each Web.config file.

The system.web Element

The system.web element contains different configuration elements, such as compilation, authentication, and authorization, which configure ASP.NET Web applications. The following code shows the system.web element:

 <system.web> <authentication> <authorization> <browserCaps> </system.web> 

In the above code, the <system.web> element contains three child elements: authentication, authorization, and browserCaps.

The compilation Element

The compilation element defines the compilation settings of an ASP.NET Web application. The different attributes of the compilation element are:

  • explicit: Specifies the state of the .NET compile option.

  • debug: Identifies whether to compile or debug binaries.

  • tempdirectory: Specifies the directory to store temporary files when you perform the compilation.

  • defaultLanguage: Identifies the default programming language during compilation.

  • strict: Specifies the value of the VB.NET strict compile option. It enables or disables the implicit typecasting.

The following code shows the compilation element:

 <compilation debug="false"  defaultLanguage="C#"  explicit="true"  </compilation> 

The above code shows the debug attribute as false, defaultLanguage as C#, and explicit attribute as true.

The customErrors Element

The customErrors element allows you to configure the behavior of your application in response to different HTTP errors. For example, for the HTTP error 404, you can redirect an end user to a Web page that mentions that the page could not be found. The code to redirect the end user to the Web page is:

 <customErrors defaultRedirect="error.aspx" mode="on"> <error statuscode="404" redirect="pagenotfound.htm"/> </customErrors> 

The authentication Element

The authentication element allows you to configure the authentication system for your application. You use the mode attribute of this element to configure the mode of authentication for the directory or application. The different types of modes are:

  • Windows: NT File System permissions on the files and directory decide the use of Windows authentication and access to the resources in this directory. Windows authentication contains all types of IIS authentication, such as Integrated Windows Authentication, Digest, Basic, and Digital Certificates.

  • Passport: Indicates Microsoft Passport as the default authentication system. The code to redirect an end user to the InvalidLogin.aspx file if the Web server fails Passport authentication is:

     <authentication mode="Passport"> <passport redirecturl="InvalidLogin.aspx"/> </authentication> 

    The above code performs passport authentication by specifying the mode as passport. You redirect the end user by specifying redirecturl in the passport element as InvalidLogin.aspx.

  • Forms: Specifies end-user authentication using cookies. End users need to log on to the computer using a Web form before the computer sends the cookies to the end users. Listing 3-2 shows Forms authentication:

Listing 3-2: Forms Authentication

start example
 <authentication mode="Forms"> <forms name="verification" loginUrl="/verification/login.aspx"/> <credentials passwordFormat="Clear"> <user name="administrator" password="administrator"/> </credentials>  </forms> </authentication>  
end example

In the above listing, the authentication element contains the forms and credentials child elements. You specify the authentication mode as forms, the URL of the form as loginurl, and the user name and password login credentials as administrator.

  • None: Specifies that ASP.NET will not provide any authentication services.

The trace Element

You use the trace element to debug the Web application and trace the progress of the execution of code. By default, the trace element is set to true. Trace elements contain objects called listeners that listen, collect, and route different messages. You can also add a listener to the trace element. Listing 3-3 shows how to add a listener to the trace element:

Listing 3-3: Trace Element Settings

start example
 <trace enabled="true" requestLimit="15" pageOutput="false"> <listeners> <add name="TraceListener" type="System.Diagnostics.TextWriterTraceListener, System" initializeData="TraceListener.log"/> </listeners> </trace> 
end example

In the above listing, you add a new trace listener, which is a class that inherits from the abstract base class TraceListener found in the Systm.Diagnostics namespace.

The sessionState Element

The sessionState element of the Web.config file manages session state configuration. You maintain session state by sending session cookies that expire when the browser is closed. In default mode, session state is maintained locally. You can also maintain session state remotely using ASP.NET State Service, which is a Windows service. As a result, you can maintain session state across multiple computers and servers. You can also maintain session state using SQL Server. The following code shows sessionState settings, where you disable cookies and use the caching feature of ASP.NET.

SessionState Element Settings

 <sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;user id=sa;password=" cookieless="true" timeout="20"/> 

In the above code, you disable the use of cookies to store session-related information by setting the cookieless property to true.

The globalization Element

The globalization element allows you to configure the global settings of your application. For example, you can configure the text-encoding format of the text exchanged among the end users of the Web site. The default value is utf-8, which is 1-byte ASCII encoding. The following code configures the globalization element:

Globalization Element Settings

 <globalization  requestEncoding="utf-8"  responseEncoding="utf-8"/>  

In the above code, you set the text-encoding format to utf-8 in the globalization element of the application.

The appSettings Element

You can add various settings to an application, such as a site description, using the appSettings element. The appSettings element is a subelement of the configuration element. You specify the appSettings element by indicating name and value pairs. The following code shows a sample section <appSettings>of a Web.config file:

The appSettings Element

 <appSettings> <add key="sitedescription" value="This is a news site"/> <add key="siteobjective " value="Share the information"/> </appSettings>       

In the above code, <appSettings> stores the site description and the site objective.

The Machine.config File

The Machine.config file manages the settings of the server. This file is located in the %runtime install path%\config directory. Machine.config contains pointers to classes in .NET Framework, called HTTPHandlers, which manage the Web server's processing of different files before the Web server provides them to the end user. The HTTPHandlers element of the machine.config file contains pointers to different HTTPHandlers that are used before the Web server provides the file to the end user.

Specifying ASP.NET Configuration Settings

Consider an ASP.NET application called WebConfig_Test that allows the end user to specify login credentials, validates the login credentials, and splashes a welcome message to the end user if the login information is correct.

Listing 3-4 shows the Login.aspx file that defines the Login page:

Listing 3-4: The Login.aspx File

start example
 <%@ Page language="c#" Codebehind="Login.aspx.cs" AutoEventWireup="false" Inherits="WebConfig_Test.WebForm1" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <title>WebForm1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body MS_POSITIONING="GridLayout"> <form  method="post" runat="server"> <asp:Label  style="Z-INDEX: 101; LEFT: 125px; POSITION: absolute; TOP: 58px" runat="server" Width="81px" Height="27px">UserName</asp:Label> <asp:Label  style="Z-INDEX: 102; LEFT: 123px; POSITION: absolute; TOP: 104px" runat="server" Width="97px" Height="20px">Password</asp:Label> <asp:TextBox  style="Z-INDEX: 103; LEFT: 249px; POSITION: absolute; TOP: 51px" runat="server" Width="191px" Height="29px"></asp:TextBox> <asp:TextBox  TextMode="Password" style="Z-INDEX: 104; LEFT: 248px; POSITION: absolute; TOP: 101px" runat="server" Width="190px" Height="29px"></asp:TextBox> <asp:Button  style="Z-INDEX: 105; LEFT: 231px; POSITION: absolute; TOP: 166px" runat="server" Width="92px" Height="36px" Text="Submit"></asp:Button> </form> </body> </HTML> 
end example

In the above listing, HTML code defines all the elements on the Login page.

Listing 3-5 shows how to create the code behind class for the login page:

Listing 3-5: The Login.aspx.cs File

start example
 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace WebConfig_Test {    public class WebForm1 : System.Web.UI.Page    {       protected System.Web.UI.WebControls.Label Label1;       protected System.Web.UI.WebControls.Label Label2;       protected System.Web.UI.WebControls.TextBox txtUser;       protected System.Web.UI.WebControls.Button cmdSubmit;       protected System.Web.UI.WebControls.TextBox txtPassword;       private void Page_Load(object sender, System.EventArgs e)       {       }       private void cmdSubmit_Click(object sender, System.EventArgs e)       {          Session["user"]=txtUser.Text;          Response.Redirect("Welcome.aspx");       }    } } 
end example

The above listing defines the different Web controls to input login information, such as UserName and Password. The WebConfig_Test namespace includes a WebForm1 class. The WebForm1 class declares several Web controls, such as text boxes, labels, and buttons. The Page_Load() method is invoked when the end user clicks Submit on the Login page. This method redirects the end user to the Welcome page. The cmdSubmit_Click() method sets the session variable and the name of the end user to the value of the session variable.

Listing 3-6 shows the welcome.aspx file that defines the Welcome page:

Listing 3-6: The welcome.aspx File

start example
 <%@ Page language="c#" Codebehind="Welcome.aspx.cs" AutoEventWireup="false" Inherits="WebConfig_Test.Welcome" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <title>Welcome</title> <meta content="Microsoft Visual Studio 7.0" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="JavaScript" name="vs_defaultClientScript"> <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema"> </HEAD> <body MS_POSITIONING="GridLayout"> <form  method="post" runat="server"> </form> </body> </HTML> 
end example

In the above listing, HTML code defines all the elements of the Welcome page.

Listing 3-7 shows how to create the code behind class for the Welcome page:

Listing 3-7: The Welcome.aspx.cs File

start example
 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace WebConfig_Test {    public class Welcome : System.Web.UI.Page    {       private void Page_Load(object sender, System.EventArgs e)       {          Response.Write("Welcome " + Session["user"] + "!!!!!" );       }    } } 
end example

The above listing defines the Page_Load() method, which is invoked when the end user clicks Submit on the Login page. This method uses the Session variable Session("User") to retrieve the user name of the end user and displays a welcome message to the end user.

Listing 3-8 shows the Web.config file for the WebConfig_Test application:

Listing 3-8: The Web.config File

start example
 <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <!--  DYNAMIC DEBUG COMPILATION This section sets the debug value to false. --> <compilation  defaultLanguage="c#" debug="false" /> <!--  CUSTOM ERROR MESSAGES This section provides the user friendly messages by having the mode value as ‘On’. --> <customErrors  mode="On" />  <!--  AUTHENTICATION  This section sets the authentication mode as Windows to use the default Windows security features.  --> <authentication mode="Windows" />  <!--  APPLICATION-LEVEL TRACE LOGGING This section sets the enabled property of the trace element as true to enable trace log output for every page within this application. You can view the application trace log by browsing the "trace.axd" page from your Web application root. --> <trace enabled="true" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" /> <!--  SESSION STATE SETTINGS This section disables the use of cookies to store the session related information by setting the cookieless property as true. This application uses the caching feature of ASP.NET for session state management. --> <sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;user id=sa;password=" cookieless="true" timeout="20"/> <!--  GLOBALIZATION This section sets the globalization settings of the application. --> <globalization  requestEncoding="utf-8"  responseEncoding="utf-8"  /> </system.web> </configuration> 
end example

The above listing configures the following elements of the Web.config file for the WebConfig_Test application:

  • <compilation>: Sets the value of the debug attribute to false. When you start the WebConfig_Test application, the application starts without debugging.

  • <customErrors>: Sets the value of the mode attribute to On. This provides user-friendly messages to the client if any errors occur while running the application.

  • <authentication>: Sets the authentication mode to Windows to use the default Windows security features.

  • <sessionState>: Disables the use of cookies to store session-related information by setting the cookieless property to true.

  • <globalization>: Sets the value of the requestEncoding attribute to utf-8.




Migrating Unmanaged Applications to. NET
Migrating Unmanaged Applications to. NET
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 31

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