ASP from A to Z
Nancy Winnick Cluts
Developer Technology Engineer
October 22, 1998
What ASP Is
How ASP Works
ASP from A to Z
There's lots of helpful information about Active Server Pages (ASP) available on this site and other sites. If you have plenty of time to search for the information, you can find answers to most of your questions. But if you want to find out what tools you can use to debug ASP or how to handle errors, you need to do some digging. This article provides an easy way to find information that pertains to ASP, including a short definition of what ASP is, how ASP works, and an alphabetical list of terms and tips that relate to ASP. In the A-to-Z list, you will see a brief description as well as pertinent links to more detailed information (when that information is available). This article is meant to be a "living" document. That means that I plan on updating it with new tips and removing tips that no longer apply. If you are an ASP developer and have a "juicy" tip, send it to me. If I publish it here, you'll get credit and the everlasting gratitude of throngs of other ASP developers.
What ASP Is
Active Server Pages is a programming environment that provides the ability to combine HTML, scripting, and components to create powerful Internet applications that run on your server. If you are already creating Web sites that combine HTML, scripting, and some reusable components, you can use ASP to glue these items together. You can create an HTML interface for your application by adding script commands to your HTML pages and you can encapsulate your business logic into reusable components. These components can be called from script or other components.
How ASP Works
When you incorporate ASP into your Web site, here's what happens:
- The user brings up a Web site (like MSDN Library) where the default page has the extension .asp.
- The browser requests the ASP file from the Web server.
- The server-side script begins to run with ASP.
- ASP processes the requested file sequentially (top-down), executes any script commands contained in the file, and produces an HTML Web page.
- The Web page is sent to the browser.
Because your script runs on the server, the Web server does all of the processing and standard HTML pages can be generated and sent to the browser. This means that your Web pages are limited only by what your Web server supports. Another benefit of having your script reside on the server is that the user cannot "view source" on the original script and code. Instead, the user sees only the generated HTML as well as non-HTML content, such as XML, on the pages that are being viewed.
ASP from A to Z
This section contains a list of terms and tips to help you understand ASP. They are listed in alphabetical order. Scroll down to the topic that interests you or click the letter in the alphabet below to jump down to the section containing the topic. I cribbed, er, I mean, compiled these tips and definitions from a number of sources, including technical articles (listed in the bibliography below), Knowledge Base articles, and a beta version of the Microsoft® Internet Information Server (IIS) 5.0 documentation (I'm so lucky!).
A B C D E F G I J L M O P Q R S T V W X
Active Data Objects (ADO) provides a programming model for an OLE-DB data source. It is the database model that ASP uses; however, ASP can use other database access mechanisms. ADO supports the following installable objects, which are often used in ASP files: Command, Connection, Recordset, Field, and Error. Refer to the ADO Web site at http://www.microsoft.com/data/ado/ for more information than you can shake a stick at.
ASP is not just for prototyping. When using ASP as a solution, design your solution as an application instead of designing stand-alone ASP pages. As far as objects are concerned, it's best to take a look at what you need to accomplish and decide what you need, then whether you can buy the objects or will need to create the objects yourself. Take into consideration caching, scalability, reusability, security, and consistency.
Identify your bottlenecks (that is, the database, network card, or network connection) using the tools available: WCAT, NetMon, and performance counters. To improve server performance, take a look at all parts of the system for potential bottlenecks, including hardware configuration and software settings. This way, if you are ever asked to scale the project larger, you will know where the work needs to be done.
In IIS 4.0, use the Response.IsClientConnected property to determine if the browser is still connected. If the browser is not connected, you can conserve CPU cycles by ceasing the processing of the ASP page. Refer to the Knowledge Base article Use IsClientConnected to Check if Browser is Connected.
Turn buffering ON. By default it is OFF in IIS 4.0; in IIS 5.0, buffering is ON by default. You should buffer your ASP files so that you can abort sending a Web page. This might happen if the script being processed runs into a problem or if a user does not have appropriate security credentials. If this happens, and if you are using IIS 5.0, you can transfer the user to another page using Server.Transfer, or clear the buffer (using the Clear method of the Response object) to send different content to the user.
If you are creating page-level components, you can use server scriptlets, Visual Basic®, Visual J++™, and Visual C++®. If you are writing components that will be in application or session state, we recommend that you write them in C++ or Java so you can create them as both-threaded. Visual Basic is apartment-threaded. See the section below on threading for more details.
If your application sends pages to the client via a proxy server, the proxy server may cache pages to return them more quickly to the client. This reduces the load on the network and the Web server. To prevent a browser from caching ASP pages, set Response.Expires to some negative number. This will force the cached pages to expire immediately. If you set Response.Expires to 0, and if your browser clock is behind by a few minutes, the page won't expire immediately. If your Web site contains objects that do not expire often, such as images, set the expiration to some time in the future. This will greatly increase the speed at which a page is refreshed or downloaded. Proxy caching via pragma:nocache is already done for you by IIS, so you don't have to set this in your headers. More information about caching can be found in Got Any Cache?
Distribute the work on your Web site by providing script on both the client and the server. See Client-Side and Server-Side Objects.
COM Object Debugging
If you create a COM object and use it through ASP with Server.CreateObject, you cannot go back into your development environment and recompile the COM DLL without restarting the IIS Admin and W3SVC (Web server) service. Otherwise, the COM DLL will be locked. To restart these services, do the following:
- At a command prompt, type net stop iisadmin /y. Please note that this will shut down IIS' parent service, IIS Admin. This will also shut down FTP and other services that are children of IIS Admin. If you type only net stop w3svc, inetinfo.exe will not be unloaded.
- At a command prompt, type net start w3svc. This will restart IIS Admin and the W3SVC service (Web server).
- You may recompile at any point after Step 1. Once you refer to an object that loads your DLL, you must repeat Step 1 before building the component successfully.
Use components to encapsulate the business logic in your ASP applications. You can create your own components or buy them "off the shelf." Once you have a component, you can reuse it wherever you need it. Develop your components using C++ or Java. Because Visual Basic is not marked as both-threaded, you cannot use Visual Basic components within application scope. If you design your own components, be sure to design components that are stateless (that is, the methods you define take parameters, rather than having a script set properties then call the method without the parameters).
Stateless components are far more flexible and reusable. In addition, if you have areas in your script where you have more than 100 lines of contiguous script, consider turning that script into a server scriptlet. More information about creating components can be found in the Active Server Components section of the Server area of the MSDN Library. A comprehensive list of third-party components available for ASP can be found in the ASP Component Catalog.
Pool your connections for optimal performance. By pooling your connections, your resources are allocated more efficiently. For support of multiple logons, provide one connection for read-only access and one connection for read/write access. In general, avoid putting ADO connections in session state. ODBC (version 3.0 and later) automatically does connection pooling for you, and OLE-DB provides session pooling.
Design for scalability. Stress your ASP applications at 100% CPU to determine how to best allocate your resources. Use WCAT or a third-party tool such as Mercury's LoadRunner to tune your performance.
Data Access Components
Read Improving the Performance of Data Access Components in IIS 4.0 for a detailed explanation of the techniques that you can use to improve performance.
Use ADO for adding database access to your Web pages via components. ADO can be used to create small components that connect to any OLE-DB compliant data source, whether it's relational or non-relational. This includes spreadsheets, databases, or e-mail directories.
There are many tools available for debugging, including the Microsoft Script Debugger. The Script Debugger lets you run your server-side scripts one line at a time, monitor the value of variables, properties, or array elements during execution, and trace procedures.
Once you have finished debugging your Web site, don't forget to turn off debugging on your live servers. This will increase performance.
The Dictionary object enables you to look up and store arbitrary key-data pairs rapidly. The Dictionary object gives you access to items in the array by key, so it is faster to find things that aren't stored contiguously in memory. Instead, you use a key rather than having to know where in the array the object is stored.
Disconnecting a Recordset means you can view the Recordset's data after severing the connection to the data store that generated the Recordset. You can create a disconnected ADO Recordset in-process with a Recordset whose CursorLocation property is adUseClient and whose ActiveConnection property is set to NULL/Nothing. You can then put the Recordset into ASP application state and use the Recordset Clone method to share and access the Recordset in your ASP files. You can then pass this Recordset to a remote client using either RDS or DCOM (or both together). Read the Knowledge Base articles HOWTO: Getting ADO Disconnected Recordsets in VBA/C++/Java and INFO: Disconnected Recordsets with ADO or RDS for detailed information.
You can use the ASPError object to obtain information about an IIS 5.0 error condition that has occurred in an ASP file. The ASPError object is returned by the Server.GetLastError method. If the error condition generates an exception and you are using VBScript, use OnErr. In JScript™, use the try…catch method. Detailed information about error handling can be found in the article Microsoft JScript Version 5.0 Adds Exception Handling, by Michael Edwards.
Flow control is the ability to set the flow of your ASP application. Flow is controlled through Response methods and two new Server methods (for IIS 5.0). Using Response.Redirect causes posted data to be lost. The Response.End method causes ASP to stop when an error is found. You do not need to call this method after calling Response.Redirect. The Server.Transfer method is the same as Response.Redirect, except that the work is done on the server and posted data is not lost. The Server.Execute method will flow into a nested ASP call and return execution to where you were before the error occurred.
The FileSystem object blocks on files. If you are running a high-volume Web site, don't use the FileSystem object because the performance of accessing a single file will degrade. If you are using multiple files that are not being accessed at the same time, use of the FileSystem object will not result in a performance hit.
The Global.asa file is an optional file in which you can specify event procedures and declare objects that have session or application scope. It is not a content file displayed to the users; it stores event information and objects used globally by the application. This file must be named Global.asa and must be stored in the root directory of the application. An application can have only one Global.asa file. Instead of using the ASP FileSystem object to read files on a page, load the file(s) into an Application level array in Global.asa.
Use ASP for the glue and components for the business logic. If you have 100 or more lines of consecutive script, turn it into a component using server scriptlets (bearing in mind that server scriptlets have the same limitations as Visual Basic components).
The InetLoad tool can be used to tune your Web site. This tool generates customizable loads on various Internet services, over a broad range of Internet protocols, including HTTP, SMTP, POP3, and LDAP. You can use this tool to simulate traffic on your Web site. InetLoad is available at http://www.thaiware.com/software/internet/IN00470.htm. See also WCATW and Mercury LoadRunner for tuning tools.
If you are providing a Web site that will be viewed in countries other than the United States, you can use the CODEPAGE tag within the <% %> delimiters to specify the proper code page. Alternatively, you can use the Session.CodePage property. Read all about it at http://www.microsoft.com/workshop/server/nextgen/nextgen .asp. In addition to CODEPAGE, you can also use the Local Language Identifier (LCID) to determine the language that the user has set as her preference. Detailed information about LCID can be found in the IMultiLanguage Reference.
You can separate IIS, ASP, and components into different processes for better performance. The drawback to putting these in different processes is the cross-process communication performance hit. You can put IIS, ASP, and your components in one process. This is the fastest method, but if your component goes down, it can bring down ASP and IIS. You can put IIS in one process and ASP with your components in another so that IIS will not crash if your component or ASP crashes. You can put IIS and ASP in one process and your component in another process. This is slower than the previous option due to all of the cross-process communication; however, it does insulate IIS and ASP from a buggy component. The slowest but "safest" option is to put IIS, ASP, and your components all in separate processes. If one crashes, nothing else will, but the performance will be very, very slow. It's a better idea to test your components really well.
|IIS, ASP, and components in one process||1||4|
|IIS in one process, ASP and components in another process||2||3|
|IIS and ASP in one process, components in another process||3||2|
|IIS in one process, ASP in one process, components in one process||4||1|
Legend: 1 = Least, 4 = Most
Use Java (or C++) to write components. Java is a powerful language that you can use to create components that are both-threaded.
You can turn on URI_Query extended logging to log ASP failures. This is not turned on by default. Turning it on is tricky, so here are the steps:
- Select a Web or FTP site and open its property sheets.
- Enable logging if it is disabled and select the W3C Extended log file format.
- Click Properties.
- On the Extended Properties property sheet, select the fields you want to log (in this instance, URI_Query). By default, Time, Client IP Address, Method, URI Stem, and HTTP Status are enabled.
- Click Apply.
You can also log to the Windows NT® Server Event Log; however, logging to the Windows NT Server Event Log is not a good idea if you've got lots of errors or are in debugging mode because you can fill up the log quickly. Using the Windows NT Performance Monitor, you can log a variety of error conditions, including how many ASP requests have failed and how many errors occurred during the script run-time.
Use Collaboration Data Objects (CDO) to send mail for Windows NT Server. CDO is a lightweight version of CDO for Exchange. It works on SMTP or Exchange. If you are using another e-mail protocol, use a third-party component. A comprehensive list is at http://www.microsoft.com/workshop/server/components/catalog.asp.
If you need to refer to objects that may not be used, instantiate them by using the <OBJECT> tag rather than using Server.CreateObject. Using Server.CreateObject causes the object to be created immediately. If you don't use that object later, you end up wasting resources.
Turn on the Option Explicit option in your .asp file. Visual Basic enables you to use variables without explicitly declaring them. Turning on this option helps to identify undefined variables—you will get an error message for undefined variables. Turning on Option Explicit makes undeclared variables illegal. Undeclared local variables are as slow as global variables. Turning on this option will help you find these slugs so that you can get them out of your code.
Order of Execution
ASP does not guarantee the order of execution of script written in different script blocks. It is strongly recommended that only procedures (functions and subs) be used in script blocks. This way, you can control the execution order by calling those procedures from the primary script (that found inside <% and %>) or by calling one procedure from another procedure.
Make sure to monitor the performance of your ASP application. You can use the System Monitor to determine the number of connections and file transfers for a week-long period on your Web site. You can also check the Event Viewer to view the Windows NT Event log. (See the logging topic just above.) Some events that can be helpful include:
- Request.WaitTime (how long the request has been waiting)
- Request.Queued (how many requests are queued up)
- Request.Executing (what's being done concurrently)
- Request.PerSecond (throughput)
- Sessions.Current (to see if there aren't any or how many are going on)
- Request.Disconnected (if the browser has disconnected, stop processing the ASP to reduce the waste of CPU cycles)
- Templates.Cached (if you are caching too many, you may run out of memory)
If you want to have efficient scripts, consult the programming conventions available in the IIS Resource Kit. These conventions are published online at http://www.microsoft.com/workshop/server/asp/aspconv.asp .
You can use Message Queuing Services to bundle an update or set of updates into a transactional message that is delivered to a remote server. Message Queuing Services ensures that updates will be delivered to the remote server, even if the network is currently unavailable. Your application receives a commit message and can continue with the transaction.
Remote Data Service (RDS)
To tune RDS, increase ADCThreads from its default of six to twelve. The Registry entry for this parameter is located at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters\ADCThreads. The maximum number you can specify is 50. Note that the server must be rebooted for this change to take effect.
By default, sites start automatically when your server restarts. To start, stop, or pause a site in the Internet Information Services snap-in, select the site you want to start, stop, or pause. Then click the Start, Stop, or Pause button on the toolbar. If a site stops unexpectedly, the Internet Information Services snap-in may not correctly indicate the state of the server. Before restarting, click Stop, and then click Start to restart the site. Use the Cluster Administrator user interface for starting and stopping clustered sites.
Break your include files into multiple small files rather than having one large file, and include only those files required by your server-side script. If the file that your ASP script includes contains a large number of functions and variables that are not used by the including script, you can waste resources and adversely affect performance and scalability.
ASP comes with scripting engines for Microsoft Visual Basic® Scripting Edition (VBScript) and Microsoft JScript. COM Scripting engines for PERL, REXX, and Python are also available through third-party developers. Cache as many script engines as you have threads running.
ASP supports the VBScript, JScript, Perl, and REXX scripting languages.
You can create server-side script using ASP that extracts a user's client certificate and saves the information. You can then use Secured Sockets Layer (SSL) to catalog and manage the certificates of users accessing your server. Read more about implementing a secure site with ASP at http://www.microsoft.com/isn/whitepapers/security.asp.
A new feature for IIS 5.0 enables ASP to detect when executing requests are blocked by external resources, and to automatically provide more threads to simultaneously execute additional requests and continue normal processing. If the CPU becomes overburdened, ASP cuts down on the number of threads to reduce thread-switching on simultaneous non-blocking requests.
You can optimize your server performance by techniques like changing Registry settings for both your system and for IIS. Read this detailed explanation of the settings used on the Microsoft Web site and how the Web team tunes the site: http://www.microsoft.com/backstage/whitepaper.htm.
In IIS 5.0, ASP supports server scriptlets. Now you can turn your business logic script procedures into reusable COM components that you can use in your Web applications, as well as in other COM-compliant programs.
Be sure to get the latest service pack for IIS and ASP. You can find information about service packs on the IIS site at http://www.microsoft.com/ntserver/web/default.asp.
Use the AspSessionMax metabase property to set the maximum number of concurrent sessions that IIS will run. Using this property will limit the memory overhead incurred by maintaining sessions. You can also manage the lifetime of session objects within IIS using the AspSessionTimeout property.
Session identifiers can be lost for a variety of reasons including bad code, an insufficient Session.Timeout value, and lack of cookie acceptance. If you are running into this problem, refer to this very helpful article on ASPAlliance at http://www.aspalliance.com/juan/.
Session requests are serialized unless they are in sessionless ASP pages. Sessionless ASP pages can often improve the responsiveness of your server by eliminating potentially time-consuming session activity.
By default, the creation of temporary stored procedures is set to ON for SQL Server 2.65 and 3.5 drivers. If you have connection pooling enabled, your temporary stored procedures can be inadvertently deleted. We recommend that you disable the creation of stored procedures when running with connection pooling. A detailed explanation of this phenomenon can be found in the article Improving the Performance of Data Access Components with IIS 4.0, http://www.microsoft.com/workshop/server/components/daciisperf.asp, in the Connection Pooling and SQL Server Temporary Stored Procedure section.
Templates can be either static, like a style sheet or a Word document template, or can include logic. You can use ASP to provide templates that contain logic that you use for many different files.
Test your ASP. Use the tools available with IIS and Visual InterDev 6.0 to test your script and components.
Use objects that are marked as "both" for the threading model in your ASP file, if you plan to store those objects in session or application state. Objects marked "both" or "apartment" will give you the best performance for objects that are within the scope of the page. ASP does not guarantee that your session will run on a particular thread. If you use an apartment-threaded component, that component will always run on the same thread. Components that are both-threaded can run on any thread. In simple terms: Let's say that you are at a supermarket. You notice that checkout line number three has only one person in line while the other checkout lines are long. You choose checkout line number three. If you come back to the store later, you might see that checkout line number three now has a very long line, so you'd prefer to go to another checkout that has a shorter line. If you are apartment-threaded, you can't go to another line; you must go back to the thread that created you. Read http://www.microsoft.com/workshop/server/components/agility.asp for more information about threading and ASP components.
A transaction is a group of operations that you can have perform as a whole. Transactions are used with databases to ensure that all related data is updated as a whole. If an error occurs, the original state of the database is restored.
Drumbeat, FrontPage 2000, and NetObjects Fusion are tools that you can use to get started using ASP quickly and easily.
You can cache type libraries on the server using the AspEnableTypelibCache metabase property. This property applies to all ASP applications that are running in the same process.
If you are running a smart browser, it's capable of doing some validation for you. Take advantage of this whenever you can. Then, perform validation through your scripting. When all else fails, you can go ahead and access your database on the back end. But remember that whenever you access the database that lives on the server, you are going to take a performance hit. This can be very expensive if you have several values in a form that you are validating. If you know that you will need to run some script on the client side, go ahead and move the code to the client side for faster performance. When you are running on the client, you have the processor(s) for your use; the server has to use its processing power for all of the requests it receives.
Use Microsoft Visual InterDev® to quickly create leading-edge Web sites. Visual InterDev includes a set of integrated database tools that greatly simplify connecting your Web site to OLE-DB data sources and open database connectivity-compliant (ODBC) databases. For more information, visit the Microsoft Visual InterDev Web site at http://msdn.microsoft.com/vinterdev/. For development information, refer to http://msdn.microsoft.com/vinterdev/technical/articles.asp.
If you are running into problems debugging local ASP in Visual InterDev, the problem might be with the way you have your permissions set. Open DCCOMCNFG and go to the Catalog Class and Machine Debug Manager application identifiers. Go to the Security tab and make sure that your machine Administrators group is listed in the Custom Access and Launch Permissions dialogs. In addition, be sure to add yourself to the Administrators group.
The WCAT tool runs simulated workloads on client/server configurations. Using WCAT, you can test how IIS and your network configuration respond to a variety of different client requests. The results of these tests can be used to determine the optimal server and network configuration. WCAT is designed to evaluate how Internet servers running Windows NT Server and IIS respond to various workload simulations.
A Web farm is a Web site that is served by more than one computer. As a result, user requests will not always be routed to the same server. Software is used to distribute the work. This is known as load balancing. When loads are balanced, it can be difficult to maintain session information. If you are going to use ASP session management on a Web farm that is load-balanced, you need to be sure that all requests made within a user session are directed to the same server. You can do this by writing a Session_OnStart procedure that uses a Response object to redirect the browser to the Web server where the user's session is running.
Extensible Markup Language (XML) enables you to describe complex data structures to be used in your Web applications (for C-types, think of a struct). You can use the Microsoft XML Parser (part of Internet Explorer 4.0) to create ASP applications using XML.
More information about ASP can be found in the following articles:
- IIS documentation: http://www.microsoft.com/workshop/ntserver/web/default.asp
- ASP overview: http://wdvl.internet.com/Software/Tools/ASP.html
- ASP technology overview: http://www.microsoft.com/workshop/server/asp/aspfeat.asp
- Geek Speak Decoded #3: Client-Side and Server-Side Objects: http://www.microsoft.com/workshop/essentials /geekspeak/clientvserver.asp
- Tom Moran's ASP Q&A: http://www.microsoft.com/workshop/server/feature/morqa.asp