Configuring ASP.NET Applications


You can control any type of .NET applications, including ASP.NET applications, by changing various settings in the configuration files. There are three types of configuration files in the .NET, all of which are XML files:

  • The machine configuration file

  • The application configuration file

  • The security configuration file

In addition to these files, an ASP.NET can also have a global.asax file that is similar to the global.asa file in classic ASP. The following sections discuss the machine configuration file, the application file, and the global.asax file. The security configuration file is related to the security aspect of an ASP.NET application and is discussed in the "Working with the Machine and Application Configuration Files" section.

Working with the Machine and Application Configuration Files

A computer has one machine configuration file that includes settings that apply to all .NET applications in that computer. This file is located in %runtime install path%\Config\Machine.config.

The application configuration file is named differently for different types of .NET applications. For ASP.NET applications, the application configuration file is web.config. Usually, there is one web.config file, which is located in the application directory. However, a subdirectory of the application directory can have its own web.config file, and any subdirectory or the application directory's subdirectory can also have its own web.config file.e

When there is more than one application configuration file in an ASP.NET application, the web.config file in a directory located higher in the hierarchy is the parent of any web.config file in any directory below it. A child web.config file inherits all settings in the parent configuration file and overwrites the settings that are similar. The web.config file in the application directory itself is the child of the machine configuration file.

For example, if the root directory of an ASP.NET application is C:\Inetpub\wwwroot\myApp and there is a web.config file in that directory, this web.config file is the main application configuration file of that ASP.NET application and is the child of the machine configuration file. If there is a directory called shopping under C:\Inetpub\wwwroot\myApp and there is a web.config file in the C:\Inetpub\wwwroot\myApp\shopping directory, this web.config file is the child of the web.config file in the C:\Inetpub\wwwroot\myApp directory.

The root element of a configuration file is always <configuration>. There are two main areas in a configuration file:

Configuration section declaration area Contains all configuration section declarations in the <configSections> container tags. The <configSections> tags can contain <section> tags and <sectionGroup> tags.

You use a <section> tag for each class that must access information in the configuration file. This tag contains two attributes:

  • type: The name of the class that reads the information.

  • name: The name of the tag containing the information that will be read by the section handler.

Because a child configuration file inherits all settings from its parent, you can declare settings in the machine configuration file and write the settings themselves in the application configuration file.

You use a <sectionGroup> tag as a container tag to group related sections. Therefore, a <sectionGroup> tag contains zero or more <section> tags. Using a <sectionGroup> tag is also a good way to avoid naming conflicts between the section you declare and sections declared by someone else.

Configuration section settings area Contains the settings of each section declared in the configuration section's declaration area.

The skeleton of a configuration file is as follows:

 <?xml version="1.0" encoding="utf-8" ?> <configuration>   <!-- the configuration section declaration area -->   <configSections>     <!-- declarations of <section> and <sectionGroup>          tags go here -->   </configSections>   <!-- end of the configuration section declaration area -->   <!-- settings go here --> </configuration> 

The following is an example of a configuration file. The configuration section's declaration area has a <section> tag and a <sectionGroup> tag. The <section> tag's name is customSection and the <sectionGroup> tag's name is customGroup:

 <?xml version="1.0" encoding="utf-8" ?> <configuration>   <!-- the configuration section declaration area -->   <configSections>     <section name="customSection"       type="System.Configuration.SingleTagSectionHandler" />     <sectionGroup name="customGroup">       <section name="groupCustomSection"         type="System.Configuration.NameValueSectionHandler,System" />     </sectionGroup>     <!-- declarations of <section> and <sectionGroup>          tags go here -->   </configSections>   <!-- end of the configuration section declaration area -->   <!-- settings go here -->   <customSection setting1="value1" setting2="value2"/>   <customGroup>     <groupCustomSection setting1="value1" setting2="value2"/>   </customGroup> </configuration> 

The default machine configuration file comes with a predefined configuration section named appSettings. You use this setting to define custom settings for your ASP.NET application. The syntax for this setting is as follows:

 <appSettings>   <add key="key" value="value"/> </appSettings> 

For example, Listing 6-16 offers an application configuration file that defines two keys in the <appSettings> element: author and company.

Listing 6-16: Defining Two Keys in the <appSettings> Element

start example
 <?xml version="1.0" encoding="utf-8" ?> <configuration>   <appSettings>     <add key="author" value="Budi Kurniawan"/>     <add key="company" value="BrainySoftware"/>   </appSettings> </configuration> 
end example

You can access the custom application settings you define in the configuration file. For example, the code in Listing 6-17 prints the author and company values defined in the application configuration file given in Listing 6-16.

Listing 6-17: Accessing the Custom Application Settings

start example
 <html> <head> <title>Accessing the configuration settings</title> <script language="VB" runat="server"> Sub Page_Load(sender As Object, e As EventArgs)   message.Text = "Author: " & _     ConfigurationSettings.AppSettings("author") & _     "<br>Company: " & _     ConfigurationSettings.AppSettings("company") End Sub </script> </head> <body> <form runat="server">   <asp:Label  runat="server"/> </form> </body> </html> 
end example

Of special interest for ASP.NET application developers and system administrators is the <system.web> section. This section contains subsections that have specific meanings to the ASP.NET application. Table 6-3 describes all subsections contained in the <system.web> section.

Table 6-3: Configuration Sections in the <system.web> Section

CONFIGURATION SECTION

DESCRIPTION

<authentication>

The setting for ASP.NET authentication

<authorization>

The setting for ASP.NET authorization

<browserCaps>

The setting for the browser capabilities component

<compilation>

The setting for ASP.NET compilation options

<customErrors>

The setting that controls the custom error messages for the application

<globalization>

The globalization setting

<httpHandlers>

The setting that maps HTTP requests' Uniform Resource Locators (URLs) to IHttpHandler classes

<httpModules>

The setting used for adding, removing, or clearing HTTP modules within an application

<httpRuntime>

The setting responsible for the ASP.NET HTTP runtime configuration

<identity>

The setting for the application identity

<machineKey>

The setting that determines the key used in the encryption and decryption of forms authentication cookie data

<pages>

Contains page-specific configuration settings

<processModel>

The setting that controls the process model of ASP.NET on the Internet Information Services (IIS)

<securityPolicy>

The setting that defines valid mappings of named security levels to policy files

<sessionState>

The setting that manages the session management scheme for that application

<trace>

The setting used for the ASP.NET trace service

<trust>

Configures the code access security permission used to run a particular application

<webServices>

The setting that controls the ASP.NET Web services

The following sections describe the often-used subsections from Table 6-3.

<authentication>

You use the <authentication> setting to configure ASP.NET authentication:

 <authentication mode="Windows|Forms|Passport|None">   <forms name="name" loginUrl="url"     protection="All|None|Encryption|Validation"     timeout="30" path="/">     <credentials passwordFormat="Clear|SHA1|MD5>       <user name="username" password="password" />     </credentials>   </form>   <passport redirectUrl="internal"/> </authentication> 

(You can find more information about this setting in the "Securing ASP.NET Applications" section.)

<authorization>

You use the <authorization> setting to configure ASP.NET authorization:

 <authorization>   <allow users="comma-separated list of users"     roles="comma-separated list of roles"     verbs="comma-separated list of verbs" />   <deny users="comma-separated list of users"     roles="comma-separated list of roles"     verbs="comma-separated list of verbs" /> </authorization> 

(You can find more information about this setting in the "Securing ASP.NET Applications" section.)

<browserCaps>

The <browserCaps> setting configures the browser capabilities component. For example, the application configuration file in Listing 6-18 contains a <browserCaps> element.

Listing 6-18: Using the <browserCaps> Setting

start example
 <?xml version="1.0" encoding="utf-8" ?> <configuration>   <system.web>     <browserCaps>       <result type="System.Web.HttpBrowserCapabilities" />       <use var="HTTP_USER_AGENT" />       browser=Unknown       version=0.0       majorversion=0       minorversion=0       frames=false       tables=false       cookies=false       backgroundsounds=false       vbscript=false       javascript=false       javaapplets=false       activexcontrols=false       win16=false       win32=false       beta=false       ak=false       sk=false       aol=false       crawler=false       cdf=false       gold=false       authenticodeupdate=false       tagwriter=System.Web.UI.Html32TextWriter       ecmascriptversion=0.0       msdomversion=0.0       w3cdomversion=0.0       platform=Unknown       clrVersion=0.0       css1=false       css2=false       xml=false     </browserCaps>   </system.web> </configuration> 
end example

<customErrors>

You use the <customErrors> setting to control the custom error messages for your ASP.NET application:

 <customErrors   defaultRedirect="url"   mode="On|Off|RemoteOnly">   <error statusCode="statusCode"     redirect="url"/> </customErrors> 

For example, the application configuration file in Listing 6-19 causes the user to be redirected to the http://www.brainysoftware.com/ErrorPage.html if there is an uncaught exception in any ASP.NET page in the application.

Listing 6-19: Using the <customErrors> Setting

start example
 <?xml version="1.0" encoding="utf-8" ?> <configuration>   <system.web>     <customErrors defaultRedirect="http://www.brainysoftware.com/ErrorPage.html"       mode="On">     </customErrors>   </system.web> </configuration> 
end example

<globalization>

You use the <globalization> setting to configure globalization options of your ASP.NET application:

 <globalization   requestEncoding="a valid encoding string"   responseEncoding="a valid encoding string"   fileEncoding="a valid encoding string"   culture="a valid culture string"   uiCulture="a valid culture string"/> 

The default value for the requestEncoding and responseEncoding attributes is "iso-8859-1".

<httpRuntime>

The <httpRuntime> setting configures ASP.NET runtime options:

 <httpRuntime useFullyQualifiedRedirectUrl="true|false"   maxRequestLength="size in kilobytes"   executionTimeout="number of seconds"/> 

The useFullyQualifiedRedirectUrl attribute specifies whether client-side redirects must be fully qualified URLs. Setting this attribute to false sends relative redirection URLs to the clients.

The maxRequestLength attribute specifies the maximum size of the HTTP request in kilobytes (KB). You can use this setting to restrict the maximum number of bytes of uploaded files or to prevent denial of service attacks.

The executionTimeout attribute specifies the number of seconds an ASP.NET page can be executed before it is terminated by ASP.NET.

Listing 6-20 presents a typical application configuration file that uses the <httpRuntime> setting.

Listing 6-20: Using the <httpRuntime> Setting

start example
 <?xml version="1.0" encoding="utf-8" ?> <configuration>   <system.web>     <httpRuntime       maxRequestLength="1024"       executionTimeout="120"     />   </system.web> </configuration> 
end example

<identity>

You use the <identity> setting to determine the identity of your ASP.NET application:

 <identity   impersonate="true|false"   userName="username"   password="password"/> 

(You can find more information about this setting in the "Applying Settings to Certain Resources" section.)

<pages>

The <pages> setting enables you to control specific options related to the ASP.NET pages in the application. For instance, you can determine whether page output buffering is enabled, whether state management is on, and so on. The syntax for this setting is as follows:

 <pages   buffer="true|false"   enableSessionState="true|false|ReadOnly"   enableViewState="true|false"   enableViewStateMac="true|false"   autoEventWireup="true|false"   pageBaseType="typename, assembly"   userControlBaseType="typename"/> 

The following describes the attributes:

  • buffer: Indicates whether response buffering is enabled.

  • enabledSessionState: Indicates whether the pages in the application participate in the ASP.NET session management. Assigning ReadOnly to this setting causes the application to be able to read but not modify session state variables.

  • enableViewState: Indicates whether state management is enabled.

  • enableViewStateMac: Indicates whether ASP.NET should run a machine authentication check (MAC) on the page's view state when the page is posted back from the client.

  • autoEventWireup: Indicates whether page events are enabled automatically.

  • pageBaseType: Forces the page class to inherit the specified code-behind class.

  • userControlBaseType: Forces user controls to inherit the specified code-behind class.

For example, the application configuration file in Listing 6-21 causes the application's response to be buffered, makes the application's pages not participate in the session management, and disables the state management.

Listing 6-21: Using the <pages> Setting

start example
 <?xml version="1.0" encoding="utf-8" ?> <configuration>   <system.web>     <pages       buffer="true"       enableSessionState="false"       enableViewState="false"     />   </system.web> </configuration> 
end example

<processModel>

The <processModel> setting controls the ASP.NET process model options on IIS:

 <processModel   enabled="true|false"   timeout="minutes"   idleTimeout="minutes"   shutdownTimeout="hours:minutes:seconds"   requestLimit="num"   requestQueueLimit="num"   memoryLimit="percent"   cpuMask="num"   webGarden="true|false"   userName="username"   password="password" /> 

The following describes each attribute:

  • enabled: Indicates whether the process model is enabled.

  • timeout: The number of minutes ASP.NET will wait before starting a new worker process to take over processing from the current one. The default is infinite.

  • idleTimeout: The number of minutes of continuous inactivity that causes ASP.NET to shut down the worker process. The default is infinite.

  • shutdownTimeout: The number of minutes given to the worker process to shut itself down. When the time expires, ASP.NET shuts down the worker process. The time is expressed in hr:min:sec format, so 0:00:05 is 5 seconds. The default is 5 seconds.

  • requestLimit: The maximum number of requests that must be reached before ASP.NET automatically starts a new worker process to take over from the current one. The default is infinite.

  • requestQueueLimit: The maximum number of requests allowed in the queue. ASP.NET will begin returning the "503—Server Too Busy" error to the new requests once this number is exceeded. The default is 5000.

  • memoryLimit: The maximum size in percentage of the total system memory that the worker process can use before ASP.NET starts a new process and reassigns existing requests. The default is 40 percent.

  • cpuMask: Specifies which processors on a multiprocessor server are eligible to run ASP.NET process. The cpuMask value specifies a bit pattern that indicates the CPUs eligible to run ASP.NET threads.

  • webGarden: Determines the CPU affinity when used in conjunction with the cpuMask attribute.

  • userName: When present, represents the user name of the account running the worker process.

  • password: When present, causes the worker process to run with the configured Windows identity.

<sessionState>

The <sessionState> setting controls ASP.NET session management for the application.

<trace>

The <trace> setting determines whether the application trace functionality is enabled:

 <trace   enabled="true|false"   requestLimit="number"   pageOutput="true|false"   traceMode="SortByTime|SortByCategory"   localOnly="true|false"/> 

The following describes each attribute:

  • enabled: Indicates whether tracing is enabled. The default is false.

  • requestLimit: The number of trace requests to store on the server. The default is 10.

  • pageOutput: Indicates whether trace output is rendered at the end of each page. The default is false.

  • traceMode: Specifies whether the trace information is displayed in the order it is processed or alphabetically by user-defined category. The default is SortByTime.

  • localOnly: Indicates whether the trace viewer (trace.axd) is available only on the host Web server. The default is true.

As an example, the application configuration file in Listing 6-22 presents an ASP.NET configuration that uses a <trace> setting.

Listing 6-22: Using the <trace> Setting

start example
 <?xml version="1.0" encoding="utf-8" ?> <configuration>   <system.web>     <trace       enabled="true"       requestLimit="20"       pageOutput="true"       traceMode="SortByCategory"       localOnly="false"     />   </system.web> </configuration> 
end example

Applying Settings to Certain Resources

The settings in an application configuration file located in a directory apply to all ASP.NET pages in that directory and pages in the subdirectories of that directory. Therefore, it is not possible to have two or more configuration files in a directory to apply specific settings to some pages and other settings to other pages in the same directory. To achieve this, you can use the <location> element on top of the <system.web> setting to define options that only apply to specific resources.

In addition to specifying a resource in the current directory, the <location> setting can also define settings for all resources in a subdirectory under the current directory. To use the <location> setting, you specify the resource name or the subdirectory name in the path attribute of this element.

For example, the configuration file in Listing 6-23 defines settings for the following resources:

  • All resources in the current directory

  • The Special.aspx file in the current directory

  • All resources in the subdir1 subdirectory

  • All resources in the subdir2 subdirectory

Listing 6-23: Using the <location> Setting

start example
 <?xml version="1.0" encoding="utf-8" ?> <configuration>   <system.web>     <!-- configuration that applies to the current          directory and all subdirectories under it -->   </system.web>   <location path="Special.aspx">     <system.web>       <!-- configuration that applies only            to the Special.aspx file in the current directory -->     </system.web>   </location>   <location path="subdir1">     <system.web>       <!-- configuration that applies only to all pages            under the subdir1 subdirectory -->     </system.web>   </location>   <location path="subdir2">     <system.web>       <!-- configuration that applies only to all pages            under the subdir2 subdirectory -->     </system.web>   </location> </configuration> 
end example

Note

You can add an allowOverride="false" attribute to a <location> setting to disallow the setting defined for a subdirectory to be overridden in the application configuration file in that subdirectory.

Working with the Global.asax File

You can also configure the ASP.NET application using the global.asax file. This file must reside in the root directory of your application and will be compiled into a class that extends the System.Web.HttpApplication class. Any change to the global.asax file will automatically take effect at the next HTTP request for any resource in the application. There can only be one global.asax file per application.

Note

The global.asax file is the replacement for the global.asa file in classic ASP. Fortunately, ASP.NET supports backward compatibility for the ASP global.asa file. Therefore, you can copy your old global.asa file into a global.asax file when migrating to ASP.NET.

Compared to the global.asa file in an ASP application, the global.asax file can be much more complex. Four elements can appear in a global.asax file:

  • Application directives

  • Code declaration blocks

  • Server-side object tags

  • Server-side include directives

Application Directives

Application directives for an ASP.NET application appear on the top of the global.asax file and specify settings for the page compiler. These directives are similar to the directives for an ASP.NET page, and there are three directives you can use in a global.asax file: @ Application, @ Import, and @ Assembly.

The @ Application Directive

The @ Application directive gives instructions to the ASP.NET compiler. The syntax for the @ Application directive is as follows:

 <%@ Application [attribute="value"]+ %> 

where the plus (+) sign indicates that there is one or more repetition of the content in the bracket.

The attribute for the @ Application directive is either Inherits or Description. The Inherits attribute specifies the name of the class to extend, and the Description attribute is assigned the description of the application. For instance, the following is an @ Application directive that instructs the compiler that the application class must extend the MyParentApp class:

 <%@ Application Inherits="MyParentApp"   Description="E-commerce app"%> 
Note

The class you specify for the Inherits attribute must inherit the System.Web.HttpApplication class.

The @ Import Directive

The @ Import directive imports a namespace into an application so that you can use the types in that namespace in your global.asax file. The @ Import directive has the following syntax:

 <%@ Import Namespace="namespace" %> 

For instance, the following imports the System.Data namespace into your global.asax file:

 <%@ Import Namespace="System.Data" %> 
Note

If you want to import more than one namespace, you use one @ Import directive for each namespace.

The @ Assembly Directive

You use the @ Assembly directive to link an assembly to the application at parse-time. The syntax for the @ Assembly directive is as follows:

 <%@ Assembly Name="assembly" %> 

For example, the following @ Assembly directive links the BuyDirect.dll assembly:

 <%@ Assembly Name="BuyDirect.dll" %> 

Code Declaration Blocks

A code declaration block in the global.asax file contains application member variables, methods, and event handlers. Its syntax is as follows:

 <script runat="server" language="language" src="externalfile">   ' the code goes here </script> 

The language attribute is an optional attribute that specifies the language used in the current code declaration block and can be any .NET-compliant language. The src attribute is also optional and is assigned the name of the file that contains the code that is loaded and used in the current code declaration block.

For example, the following code declaration block contains the Application_OnStart event handler and a method called WriteToFile:

 <script runat="server">   Sub Application_OnStart()     ' write code here   End Sub   Sub WriteToFile()     ' write code here   End Sub </script> 

Server-Side Object Tags

A server-side object tag declares and creates new application and session variables. Its syntax is one of the following:

 <object emphasis">id" runat="server"   scope="application|session|pipeline" emphasis">class name"/> <object emphasis">id" runat="server"   scope="application|session|pipeline" progemphasis">COM ProgID"/> <object emphasis">id" runat="server"   scope="application|session|pipeline" classemphasis">COM ClassID"/> 

The attributes are as follows:

  • id: A unique identifier for an object.

  • scope: The scope at which the object is declared. "Pipeline" (the default) means that the object is available only to the HttpPipeline instance defined by the containing ASP.NET application file. "Application" causes the object to be stored in the HttpApplicationState object. "Session" causes the object to be stored in the user's session object.

  • class: Identifies the type of the object that will be instantiated.

  • progid: The COM component to be instantiated.

  • classid: The COM component to be instantiated.

Note

The class attribute must not be assigned an interface or an abstract class.

As an example, Listing 6-24 is a global.asax file that instantiates a Hashtable object and assigns it to an identifier called myHashtable. Some entries are added to the Hashtable object in the Application_OnStart event handler. Listing 6-25 is an ASP.NET page showing that the object is available in any page in that application.

Listing 6-24: The global.asax File Containing a Server-Side Object Tag

start example
 <object  runat="server"   scope="application" /> <script runat="server">   Sub Application_OnStart()     myHashtable.Add("name1", "value1")     myHashtable.Add("name2", "value2") End Sub </script> 
end example

Listing 6-25: Using the Static Object in an ASP.NET Page

start example
 <html> <head> <title>Using Server-side Object Tag</title> <script language="VB" runat="server"> Sub Page_Load(sender As Object, e As EventArgs)   Dim sb As New StringBuilder(1024)   Dim entry As DictionaryEntry   For Each entry in myHashtable     sb.Append(entry.Value).Append("<br>")   Next   message.Text = sb.ToString() End Sub </script> </head> <body> <form runat="server">   <asp:Label  runat="server"/> </form> </body> </html> 
end example

Server-Side Include Directives

You can use a server-side include directive to include the content of a file. Its syntax is either one of these two:

 <!-- #include File="filename" --> <!-- #include Virtual="filename" --> 

The included file is processed before any dynamic content is executed.

Event Handlers

There are four events that can be present in a global.asa file: Application_OnStart, Application_OnEnd, Session_OnStart, and Session_OnEnd. These events are still available in the global.asax file. However, because a global.asax file is compiled into a class derived from the System.Web.HttpApplication class, all events in that class are also available.

You can view the complete list of events in the .NET Framework Software Development Kit (SDK) reference. Some useful events are BeginRequest, EndRequest, Error, PreSendRequestContent, PostRequestHandlerExecute, and so on. All of these events are self-explanatory.

As an example, the global.asax file in Listing 6-26 uses some events to write to a file when that event fires.

Listing 6-26: Utilizing the Event Handlers in a global.asax File

start example
 <%@ Import Namespace="System.IO" %> <script runat="server" language="VB">   Sub Application_OnStart()     WriteToFile("Application_OnStart") End Sub Sub Application_OnEnd()   WriteToFile("Application_OnEnd") End Sub Sub Session_OnStart()   WriteToFile("Session_OnStart") End Sub Sub Session_OnEnd()   WriteToFile("Session_OnEnd") End Sub Sub Application_BeginRequest(source As Object, e As EventArgs)   WriteToFile("Application_BeginRequest") End Sub Sub WriteToFile(s As String)   Dim sw AS StreamWriter = File.AppendText("C:\log.txt")   sw.WriteLine(s)   sw.Close()   End Sub </script> 
end example

Deploying ASP.NET Applications

Compared to classic ASP, application deployment in ASP.NET is extremely easy. There is no more DLL problem when deploying an ASP application. There is no more using regsvr32.exe program to register your COM component, and there are no more headaches with the versioning of your DLL files.

In fact, this section is short because ASP.NET application deployment is straightforward. Basically, you need to perform the following steps in the deployment stage:

  1. Create a directory and all needed subdirectories for your application.

  2. Use the Internet Information Services Manager to create an ASP.NET application, just as you would create an ASP application.

  3. Copy all ASP.NET pages into the application directory and subdirectories.

  4. Copy any .dll files containing user controls or other custom controls to the bin directory under the application directory.

  5. Make sure the debugging mode is false—in other words, that the debug attribute of the compilation element under <system.web> is assigned the value false:

     <system.web>   <compilation debug="false"/> </system.web> 

    By default, the machine configuration file disables debugging. However, if you enabled debugging in the application configuration file when developing the project, it is now time to turn it off. Enabling debugging will incur a memory/performance penalty.

  6. Deploy assemblies into the Global Assembly Cache, if necessary.

The assemblies containing components you deploy into the bin directory of your application directory can only be used from that particular application. ASP.NET, however, allows you to deploy global components that can be used by all applications in that machine. To do this, you have to deploy the global component into the Global Assembly Cache. However, assemblies that are to be shared by multiple applications must be signed with strong names using standard public key cryptography.

Deploying assemblies into the Global Assembly Cache therefore involves the following steps:

  1. Creating a public and private cryptographic key pair using the Strong Name tool (sn.exe)

  2. Compiling the code file using the /keyfile option.

  3. Installing the assembly using the Global Assembly Cache tool (gacutil.exe)

As an example of creating an assembly that is deployed into the Global Assembly Cache, consider a class named MyFirstClass in the MyNamespace namespace, as shown in Listing 6-27. This class is written to the MyFirstClass.vb file.

Listing 6-27: The MyFirstClass Class (MyFirstClass.vb)

start example
 NamespaceMyNamespace   Public Class MyFirstClass     Public Const MyConstant As String = "secret"   End Class End Namespace 
end example

Compiling this class and deploying it into the Global Assembly Cache requires the following steps:

  1. Open a command prompt window.

  2. Create a public key for it by typing:

     sn -k MyKeyPair.snk 

    A file called MyKeyPair.snk will be created. For easier deployment, copy this file to the directory where MyFirstClass.vb is located.

  3. Change directory to where MyFirstClass.vb is located.

  4. Compile the MyFirstClass.vb file using the key pair by typing the following:

     vbc /t:library /out:MyAssembly.dll /keyfile:MyKeyPair.snk  MyFirstClass.vb 
  5. Install the assembly into the global cache using the gacutil program. Type the following:

     gacutil -i MyAssembly.dll 
  6. Test the assembly by creating an ASP.NET file in Listing 6-28.

  7. To uninstall MyAssembly.dll, type gacutil -u MyAssembly.

Listing 6-28: Testing the Assembly in the Global Assembly Cache

start example
 <%@ Import Namespace="MyNamespace" %> <html> <head> <title>Deploying assembly into global cache</title> <script language="VB" runat="server"> Sub Page_Load(sender As Object, e As EventArgs)   Response.Write(MyFirstClass.MyConstant) End Sub </script> </head> </html> 
end example

Running the ASP.NET page in Listing 6-28 should display the word secret on the browser.




Real World. NET Applications
Real-World .NET Applications
ISBN: 1590590821
EAN: 2147483647
Year: 2005
Pages: 82

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