Leveraging ASP in IIS 5
From Mynoteswiki.com
J.D. Meier
February 28, 2000
Contents |
Summary
The following article originally appeared in the MSDN Online Voices "Servin' It Up" column.
Introduction
Internet Information Services (IIS) 5.0 sports improvements for administration and application development. Building on the foundation of its predecessor, IIS 5.0 takes performance, reliability, and scalability to the next level (in fact, many customers are reporting 50-100 percent improvements in performance when running their sites on Windows® 2000). In addition to an engine overhaul for IIS, updates to core technologies improve the overall Active Server Pages (ASP) experience. In this article, I'll help you get the most out of ASP in IIS 5.0 by sharing my experiences working with it over the past several months.
New Features You Can Use from ASP
In Windows 2000, the ASP built-in objects add methods that provide developers with enhanced program control, including improved server-side processing and error handling. Windows 2000 also includes version 5 of the script engine (VBScript.dll and JScript.dll), which provide more extensibility for your ASP pages. From a data perspective, Windows 2000 includes MDAC version 2.5, which adds XML integration. Below are some of the highlights of this new platform, and how you can leverage them.
Use theServer.Transfer Method to Forward Requests to ASP Pages
When you need to redirect requests to another page in IIS 4.0, you are limited to Response.Redirect. This has the side effect of requiring a roundtrip to the client, isolating the transactions of both pages, and forcing you to cancel all output from the first page. You also lose the contents of the Request collection.
IIS 5.0 introduces the Server.Transfer method, which overcomes all of these limitations. Because it does not require a client roundtrip, it is significantly faster (a customer reported seeing up to 30 percent improvement in performance in his application by replacing Response.Redirect with Server.Transfer). Note that Server.Transfer is limited to the current machine; you cannot transfer requests to another machine.
The following sample illustrates Server.Transfer: ST1.asp
<% Response.Write("Hello from page 1.
")
Response.Write("SessionId on page 1: " & Session.SessionId & "
")
Session("MyVar") = "Hello World"
Server.Transfer("/MyOtherApp/ST2.asp")
%>
ST2.asp
<% Response.Write("Hello from page 2.
")
Response.Write("SessionId on page 2: " & Session.SessionId & "
")
Response.Write("myvar: " & Session("myvar"))
%>
Output from ST1.asp would be:
Hello from page 1. SessionId on page 1: 705396680 Hello from page 2. SessionId on page 2: 705396680
MyVar: Hello World
Notice that because this technique used Server.Transfer, the SessionId is the same on both pages, and you are able to access the original applications user specific session and application variables.
Use Server.Execute as an Alternative to Server-side Includes
The Server object now includes an Execute method, which will process another ASP page as part of the current ASP page. This provides a new way to encapsulate your code and maintain more modular ASP pages -- and now gives you truly conditional #includes. The following sample illustrates using Server.Execute: SE1.asp
<% bExecute = True
If bExecute Then
Response.Write("Calling the routine ...
")
Server.Execute("SE2.asp")
End if
%>
SE2.asp
<% Response.Write("Routine has run.")
%>
Output from SE1.asp would be:
Calling the routine ... Routine has run.
Note that when using either Server.Transfer or Server.Execute, the current transaction flows to the second page, as specified by the @Transaction setting.
Clear your Contents Collection with Remove and RemoveAll
IIS 4.0 introduced the Contents collection for the Application and Session objects. The Session.Contents collection contains all data stored in Session that weren't created with the <OBJECT> tag. Similarly, the Application.Contents collection contains items added to Application scope. In IIS 5.0, Contents.Remove and Contents.RemoveAll methods were added to the Contents collection. Remove allows you to delete a specific item, while RemoveAll will remove all of the items from the Contents collection in one fell swoop.
Use ASP's New Centralized Error-Handling Capabilities
We've all struggled with error handling in ASP. Now, there is an option to avoid handling all errors in line. You can handle the errors on a different page from where the errors occurred. This error-handling page can use the new AspError object to retrieve the error properties to display and/or log meaningful error information, allowing you to create a more centralized error-handling page that can be used by your entire ASP application.
By default, this page is the 500-100 ASP page that is returned when ASP encounters an error that isn't handled. You can either customize this page or build your own. The default page used by a Web site is the 500-100.asp file, found in the %WinDir%\Help\iisHelp\common, but you can use the Internet Service Manager (ISM) to specify a custom ASP file. This file will be called whenever there is a script-parsing or run-time error. You can access the error information from this page by using the AspError object and its properties.
In your error-handling page, you use Server.GetLastError to retrieve the instance of the AspError object (you'll notice that the default 500-100.asp page does this for you). This object will tell you if the problem was at parse or run time and the position, number, and description of the error. You can use this information to display meaningful error information, create comprehensive logs, and notify administrators.
As a general rule, you will want to use inline error handling when your error logic is tightly coupled with your application logic. You will want to use the centralized error-handling mechanism for more generic scenarios.
For more information on the AspError object and Server.GetLastError, see the IIS documentation.
IIS 5's Browser Capabilities Component Improves over Earlier Design Limitations In IIS 3.0 and IIS 4.0, the Browser Capabilities component uses a static list to lookup capabilities. This approach has some limitations:
- Configurable aspects of a client's capabilities are not included.
- There is no way to determine which capabilities are actually enabled when a request is made.
In IIS 5.0, the Browser Capabilities component can be modified when a client returns a cookie describing its capabilities. See the IIS 5.0 documentation for more information and sample code for using the Browser Capabilities component. You Can Add Server-side Includes Through the <SCRIPT> Tag's SRC Attribute
In IIS 5, you can run server-side includes by pointing to an include file in the SRC attribute of a <SCRIPT> tag and specifying RUNAT=SERVER. For example:
<SCRIPT SRC="MyInclude.asp" RUNAT=SERVER>
While this is another option for executing includes, it's a matter of preference.
Use the New Script Engine Features from Your ASP Page Version 5.0 of the Script Engine is included with Windows 2000 and adds some great features to Visual Basic® Scripting Edition (VBScript) and JScript®. From VBScript, you can now use a Regular Expression parser to assist you in complex validations and pattern matching. VBScript also adds the ability to create Classes (but I prefer components for that job; to each his own). You'll appreciate VBScript's addition of the With statement, which optimizes performance when accessing an object repeatedly. This sample illustrates the use of VBScript's With statement:
<% Response.write("Using With:
")
With Response
.Write("Hello
")
.write("Goodbye")
End with
%>
In JScript, we now have effective error handling built in. With version 5.0 of JScript, you can now use try-catch blocks:
try
tryBlock
catch(exception)
catchBlock
For more information on the new Script Engine features see the Windows Script Technologies Web site.
Use MDAC 2.5's XML Integration
Microsoft Data Access Components (MDAC) 2.5 ships with Windows 2000. This version provides the new Record and Stream objects, has better support for URL-based resources, and has an enriched XML functionality. You can now obtain an XML representation of a recordset by using the Recordset.Save method with a stream or with the Response object. This is possible because both the Request and Response objects support streaming in IIS 5.0.
The following code demonstrates using Recordset.Save:
<% Const adPersistXML = 1 Const adUseClient = 3
Set c = Server.Createobject("ADODB.CONNECTION")
c.CursorLocation = adUseClient
c.Open "pubs", "sa"
set r = Server.CreateObject("ADODB.RECORDSET")
set r = c.Execute("Select * From Authors")
r.ActiveConnection = Nothing
c.Close
Set c = Nothing
Response.ContentType = "text/xml"
r.Save Response, adPersistXML
r.Close
Set r = Nothing
%>
See the Knowledge Base article "HOWTO: Get XML Representation Of an ADO Recordset in VB" for more information.
New Behavior in ASP
You'll notice some things in ASP behave differently in Windows 2000. Knowing these differences will help you both to leverage these changes and to understand issues that may arise from them. Below are some of the new behaviors you should be aware of.
ASP Buffering Is on by Default
ASP buffering is on by default in IIS 5.0. This means ASP script will finish processing on the server before sending a response to the client unless Response.Flush is called. Buffering improves performance, because it reduces network roundtrips and response times. While buffering is on by default after a clean install of Windows 2000, you may need to set it if you upgrade from NT 4.0 and IIS 4.0. Note that because buffering is on by default, it may be helpful either to turn buffering off for a specific page or to call Response.Flush to force output so that you can trace activity while you are debugging your ASP page.
IIsClientConnected Can Be Used Prior to Sending Content to the Browser
In IIS 4.0, you needed to first send content from an ASP page to the browser before Response.IsClientConnected would be accurate. With IIS 5.0, you can now call Response.IsClientConnected before sending content from the ASP page to the browser. This method is mainly useful in the middle of a long-running ASP page, because you can exit out if you determine the client is no longer connected.
Objects Marked Both that Do not Support the Free-threaded Marshaler Will Fail if They Are Stored in Application Scope
Both-modeled components must aggregate the FTM (Free-Threaded Marshaler) to be stored in Application state. In IIS 4.0, you get away with this (if you can call it getting away), but the object actually gets treated as an STA (Single-threaded Apartment) object and kills the performance of the application. If, when using IIS 5.0, you do not aggregate the FTM and you store your Both-modeled object, ASP will return the following error message:
Application object, ASP 0197 (0x80004005)
Cannot add object with apartment model behavior to the application intrinsic object. /dev/VC/ATL/BothNoFTM/Test.asp, line 12
For a discussion on how to aggregate the FTM, see "Agility in Server Components."
COM Objects Are Released Earlier
In IIS 5.0, a COM object is released prior to the completion of the page. In IIS 4.0, COM objects are not released until ASP finishes processing the page. This means that in IIS 4.0, setting an object = Nothing would release the object reference as far as the Script Engine is concerned, but ASP would not release the object until the page went out of scope. Because IIS 5.0 releases objects earlier, setting an object = Nothing now actually releases the object from ASP prior to page completion, making it even more beneficial to follow good coding practices and clean up your objects as soon as you no longer need them.
In IIS 5.0, an object will be released prior to the completion of the page if both of the following conditions apply:
- The object does not use the OnEndPage method.
- The reference count for the object is zero.
Cloaking Changes the Identity of Local COM Servers
Local COM servers launched under IIS 4.0 use the process token by default. For this reason, local COM servers launched from in-process Web applications run as SYSTEM, while COM servers launched from out-of-process Web applications run as IWAM_<machine>.
In IIS 5.0, because of cloaking, local COM servers will run as the identity of the thread token. This means that local COM servers launched from both in-process and out-of-process Web applications will run as IUSR_<machine>, if Anonymous access is allowed; otherwise, the credentials used during authentication will determine the COM server's identity. See the KB article INFO: Security Issues with Objects in ASP and ISAPI Extensions for more information regarding security credentials used when launching local COM servers.
Include File Security Is Now Based on the Security Credentials of the Physical Path This is good, because ASP now enforces the security credentials of the physical path when processing includes as it should. In IIS 4.0, include files in virtual roots do not use the security credentials of the physical paths. In IIS 5.0, however, the security credentials of the physical path are enforced when ASP processes includes. Be aware of this change. Simply knowing this detail can save you potentially a lot of troubleshooting and can help you properly set your permissions.
Improved Performance for HTML Files Saved as .ASP
Prior to IIS 5.0, saving HTML pages with a .asp extension would have performance costs regardless of whether the HTML pages contained script. For this reason, HTML pages without any ASP code would not be saved with a .asp extension. Now, in IIS 5.0, .asp files that do not contain ASP code are processed nearly as fast as if they were saved with .htm or .html extensions. This is really an administrative benefit that allows you to save all of your HTML pages with an .asp extension, preventing the need to redirect should you later add ASP code to your pages.
New ASP Settings
ASP adds new some entirely new settings as well as changes the defaults for some existing parameters. While most cases will perform optimally with the default settings (which is why they are the default), knowing the new settings and how they affect your application can be beneficial when you need to tweak behavior for your scenario.
AspQueueConnectionTestTime Prevents Unnecessary Processing of Pending Requests
AspQueueConnectionTestTime is a new setting for IIS 5.0. In IIS 4.0, requests taken from the ASP queue are always processed, regardless of whether the client is waiting around for the response. This changes in IIS 5.0, however. If the request has been queued for longer than the number of seconds specified by this setting (3 seconds by default), ASP will check to determine whether the client is still connected before executing the pending request. If the client is no longer connected, the pending request will not be processed, and will be removed from the queue.
AspThreadGateEnabled Allows ASP to Self-tune Under Load
AspThreadGateEnabled is a new setting for IIS 5.0. When it's enabled, IIS performs thread gating. Thread gating dynamically regulates the number of threads that can execute concurrently when ASP detects external resources are blocking during request execution. This setting is off by default, because autopilot is not always the best choice. Leave this setting off until you've thoroughly tested for your particular application with a stress test tool, such as WAS (Web Application Stress). For more information on getting started with WAS, see "I Can't Stress It Enough -- Load Test Your ASP Application.".
ASP's Default Thread Pool Is Now Set to 25 Threads per Processor and per Process ASP now has more threads at its disposal. In IIS 4.0, the default value is 10 and is configurable through ProcessorThreadMax in the registry. In IIS 5.0, ProcessorThreadMax has been moved to the Metabase and is renamed to AspProcessorThreadMax, with a new default of 25. See "Tuning Internet Information Server Performance" for details and the implications of tuning ASP threads.
In general, it's not a good idea to play with this number. While there are exceptions, the new default should handle most scenarios. Before you adjust this number, you can probably eliminate some other bottleneck in your application.
AspScriptEngineCacheMax Defaults to 125
In IIS 5.0, the new default for this maximum number of script engines to cache in memory is 125. In IIS 4.0, the default is 30. The AspScriptEngineCacheMax setting allows each ASP thread to cache a script engine, which results in processing ASP pages more efficiently. This higher default in IIS 5.0 helps contribute to the overall performance gains. While there may be some gain increasing this number if you have thousands of unique pages, the higher default in IIS 5.0 will suit most Web applications.
AspScriptFileCacheSize Is Set to a Default Limit of 250 Files In IIS 4.0, the AspScriptFileCacheSize default is –1. In effect, -1 means there is no limit; therefore, the cache could consume a lot of RAM. The new default in IIS 5.0 helps keeps the cache size in check. As with AspScriptEngineCacheMax, you may see some performance gains associated with a higher cache size if you have thousands of unique pages, but most applications will perform well with the default. See the KB article "ASP Caching May Cause 'Server Too Busy' Errors and Blank Pages" for more information.
AspRequestQueueMax Defaults to 3,000
In IIS 4.0, the limit for requests in the queue is 500. In IIS 5.0, the new limit is increased to 3,000. This means that now 3,000 requests are waiting in the queue before "Server Too Busy" is returned.
Administration
Set Unecessary Services to Start Up Manually or Disable Them
After you've installed Windows 2000, shut off any services that you know you don't need, which will maximize your resources available to IIS. To view your services through the Services console: 1. Click Start and point to Programs. 2. Click Administrative Tools. 3. Click Services.
For example, if you're not using FTP Publishing Service, set it to a manual start. If you're not sure that you don't need something, then you're probably better off leaving it alone until you know for sure.
Specify Your Machine as an Application Server
You can specify whether your machine should be an application server. If your server will be used primarily as a Web server, it can be set to run either as an application server or as a file server. File server is the default, but it is recommended that you set your server to run as an application server to improve performance. To specify your server as an application server:
1. Click Start, point to Settings, point to Network and Dial-up Connections, and click Local Area Connection. 2. From the Local Area Connection dialog box, open Properties. 3. Select File and Printer Sharing for Microsoft Networks, and click Properties. 4. On the Server Optimization tab, select Maximize data throughput for network applications. 5. Reboot the server.
Note that this option can still be set after installation.
Use Process Throttling to Limit CPU Time for Applications in High Isolation
Throttling is new to IIS 5.0. By using Process Throttling, you can limit the percentage of time the CPU spends processing ASP applications running in High Isolation mode (Throttling is not possible for applications running under Medium Isolation). For more information on Process Throttling, see the KB article "How to Change Process Throttling Options for IIS 5.0."
Create a New Console for Easier Administration
You'll notice the ISM has a few changes. For example, the it no longer contains the Microsoft Transaction Server (MTS) node, as it did in IIS 40. In Windows 2000, COM+ replaces MTS. As such, COM+ applications are administered through the Component Services console found in the Administrative Tools group. You may find it convenient to create a new console that contains both the ISM and Component Services. Also, it can be a good idea to add additional snap-ins for frequently used tools, such as Event Viewer.
Pool Your Web applications with Medium Isolation Another change you will notice in the ISM is that the Application protection setting replaces IIS 4.0's Run in a separate memory space option. In IIS 5.0, you have the following choices for isolation levels (see Figure 1):
- Low (IIS Process). The application will run in the same process space as Inetinfo.exe. While you may gain some performance, you jeopardize stability and manageability of your main Web service.
- Medium (Pooled). New in IIS 5.0, this option introduces the concept of a pooled process for application protection and is the default setting. Effectively, pooling means that every Web application set to Medium will share the same instance of Dllhost.exe. Typically, Medium isolation performance in IIS 5.0 is better than in-process applications running under IIS 4.0.
- High (Isolated). This choice allows you to run applications outside of both IIS and pooled processes. High isolation, again, is typically faster than IIS 4.0 in-process applications.
Stick with Medium isolation in most scenarios. Medium isolation offers a nice tradeoff between performance and reliability, and is great for trusted Web applications. By trusted, I mean you've had the Web application in production and have worked out most of the kinks. While Low isolation may buy you some performance, you could probably tweak another part of your application rather than invade inetinfo's space. High isolation is where you should run Web applications that are not yet trusted.
Figure 1. Application protection
Sync Your IWAM_<machine> Identity with COM+ It's important to note that the IWAM_<machine> identity needs to be in sync in the Metabase, the SAM (Security Account Manager), and COM+. Account information stored in the IIS Metabase is synchronized with the local SAM, but COM+ applications will not automatically be updated.
If you run into problems starting out-of-process applications, the IWAM_<machine> account may be out of sync. Requests to out-of-process applications may generate the following events in the system event log:
Event ID: 10004 Source: DCOM DCOM got error "Logon failure: unknown user name or bad password. "
and was unable to logon .\IWAM_MYSERVER in order to run the server:
{1FD7A201-0823-479C-9A4B-2C6128585168}
Event ID: 36 Source: W3SVC
The server failed to load application '/LM/W3SVC/1/Root/op'.
The error was 'The server process could not be started because
the configured identity is incorrect. Check the username and password.'
IIS 5.0 provides a utility script named synchiwam.vbs to update the launching identity of all IIS COM+ application packages that run out of process. The synciwam.vbs script can be found in the \Inetpub\AdminScripts directory and can be run using cscript or wscript (see the synchiwam.vbs file for more information).
Note using the synciwam.vbs will reset all out of process applications (Medium and High isolation) to IWAM_<machine>.
Use Terminal Services to Remotely Administer Your Server
Absolutely. Terminal Services can be an excellent option for remotely administering your server. By running a lightweight client for Terminal Services, you can remotely administer your Windows 2000 server from a console window.
For information on Terminal Services, see the following articles:
- Windows 2000 Management Services
- Using Terminal Services for Remote Administration of the Windows 2000 Server Family
Restart IIS with IISReset.exe
By default, IIS 5.0 uses a new utility, IISReset, to restart your IIS services automatically if they fail. The downside is you may not notice problems with the server so easily. Be sure to monitor the Event Log regularly.
If you have to restart your Web service, IISReset makes it easier by allowing you to stop and restart IIS services and out-of-process Web applications with one command. You can get a list of options for IISReset by running the following from a command prompt:
C:>iisreset /?
Get to Know the New Windows 2000 Security Options In the ISM, you'll notice a couple of changes to the Authentication Methods dialog box (see Figure 2). What was formerly called Windows NT Challenge/Response, or NTLM, is now Integrated Windows Authentication. Integrated Windows Authentication supports both the Kerberos version 5 and its own challenge/response protocol. With Kerberos, the browser exchanges a hash of the user's credentials with the Web server to prove identity. NTLM also exchanges a hash. So what's so special about Kerberos? Delegation. Delegation allows IIS to use a client's credentials to connect to remote machines.
For Kerberos to work, the client and server machines must both be running Windows 2000, and both machines must be in Windows 2000 domains that have a trust relationship. A note here is that Kerberos supports cloaking. Cloaking determines the identity used during impersonation on the server.
Another change in the Authentication Methods dialog box is the addition of Digest Authentication. Digest Authentication provides the same service as Basic authentication -- except it transmits hashes of the user's credentials, whereas Basic transmits plain text passwords over the wire. To use Digest Authentication, the Web server needs access to passwords in plain text, and it is supported only with a Windows 2000 domain controller.
Figure 2. Authentication methods
For more information on Kerberos and Windows 2000 security changes, see the following articles:
- Q217098: "Basic Overview of Kerberos User Authentication Protocol in Windows 2000"
- "Exploring Kerberos, the Protocol for Distributed Security in Windows 2000"
- "Overview of Windows 2000 Security"
