ASP Component Guide

Source: Internet
Author: User
ASP Component Guide

Author: J. D. Meier
Microsoft Corporation

January 24, 2000

This article is applicable to the following situations:

  • Call components from Active Server Pages (ASP) Code
  • Design components that will be called from ASP code
  • You want to use the components in ASP code

Why use components?
Status Management
Segmentation Service
Thread Model
Server. Createobject and Createobject
PASS Parameters
Onstartpage/onendpage and objectcontext
Error Handling
Global Variables
Distribution Component


Component. Some people like them, while others are afraid. People who are afraid of components can often tell you a shocking experience. Let's face it: When we start using components in ASP, we don't know anything.YesHurt you. If you fall down, stand up, clean yourself, and come on. In this article, I will provide a general guide from practice to help you build a better Component-Based ASP solution.

Why use components?

Before I start to discuss the component guide, it is worth considering the value of adding components to ASP applications. Many developers who are not familiar with components always feel that everything is fresh. Components can bring the following benefits to ASP applications:

  • Encapsulate functions and hide Implementation Details
  • Reusability (including reuse by different client applications)
  • Intellectual Property Protection
  • Scalability (reflected in the ability to distribute applications across multiple computers)
  • Configuration and deployment flexibility
  • Performance (especially when early binding is an important factor)
  • Access the system, such as Win32 API call or any other underlying functions of the Programming Language
  • Strong typing functions (the "Visual BASIC script editor [VBScript]" has weak typing functions, and JScript is not very good)
  • Business logic is separated from the user interface, or web designers are separated from web developers.

Benefits are the same as payment. Creating component solutions can be more expensive to increase the complexity of the development process. Deployment and troubleshooting may become more difficult and become a real factor. However, do not let the current difficulties hinder long-term interests. How can we know whether the cost is worth it? Consider the following:

  • What is the current code library?
  • What is the level and experience of the development team?
  • What is your control scope for the master server?
  • What tools and languages have you chosen for a specific task?
  • What are the coordination problems?
  • Are there performance and scalability factors?
  • What is the project time framework?
  • WHO will continue to maintain and support this application? For example, can a development team intervene and take over?

After reviewing the above considerations, check your assumptions. The prototype can quickly draw the actual situation from the imagination.

Now we have a certain understanding of the possible benefits of components, so let's continue to discuss them. The following guide will help you maximize the benefits. These guides may be a guide to guide you through the establishment of more stable, scalable, and better-performing ASP Component applications.

Recommended Status Management

In general, try to use stateless components and stateless ASP pages whenever possible. The component should not need to be in the state from a method call to the next state. Store complex states in the database. For simple data, use cookies, querystring, or transfer data between pages to hide form fields.


Server resources are limited. Maintaining the status in the component means that the application consumes valuable resources in case of resource conflicts and concurrency issues. The stateless component helps you avoid these problems. The stateless component also provides more deployment options and enhances the ability to share resources on multiple clients.

Common traps

A common mistake for developers is to design or use components that require maintenance. Please note that this idea is often used in desktop development. Generally, developers with a background in desktop development will design dependency components.


Avoid using "ASP session" to improve server performance because it simplifies the code path and reduces server resource consumption. If you do not use "ASP session", disable the "session" status through "Internet Service Manager" (see "Internet Information Service [IIS]" documentation. You can also use the following tag to disable page-based sessions on ASP pages that do not require "sessions ":


Deployment flexibility is another important aspect, especially when running applications in the web area. If "ASP session" is dependent, the request of the given user is bound to the specified web server, because the "session" status is server-specific. Avoiding the status in the middle layer and Web server, and using the database, ASP requests can be processed by any valid Web server in the region. Therefore, you will reduce competition, provide better redundancy, and allow more distribution options.

For other methods for transferring data between pages without using ASP sessions, see the "knowledge base (Kb)" Article below:

  • Q175167 HOWTO: persisting values without sessions)
  • Q157906 HOWTO: maintain state authentication SS pages with VBScript)

In ActiveX Q & A, Don box also provides more insights on MTS status management.

Recommended Scope

Generally, use components within the scope of the page. A page range is used to create an object on the same page, use it, and release it-all of which are operated on the same page.

Components marked as "dual" or "unit" can work properly within the page. Use the "unit" model component only within the scope of the page, such as the visual basic component. To store components in applications or sessions, we recommend that you use dual mode ". The components marked as "dual" can be stored within the range of "sessions" or "Applications", but the components must ensure thread security.


Use components within the page to recycle server resources. Releasing resources minimizes concurrency issues and allows shared resources on the client. In addition, the page range component avoids the thread issue that affects the objects in the "session" or "application" range. The thread issue is discussed in detail in the "thread model classification" below.

Common traps

One of the most common problems is to store Visual Basic or other "unit" Model objects within the scope of "Applications. If you try to storeServer. CreateobjectThe following error is displayed for the created "unit" model object:

Application Object error 'asp 0197: 66661'

The object cannot be used.

/Virdir/global. Asa, line 7

You cannot add objects with unit model behaviors to internal objects of an application.

However, if you use the <Object> label to store the "unit" model object within the "application" range, no running error will occur. On the contrary, the object will be created on the specified "single thread unit (STA)" thread, and all calls will be aggregated to that thread-and will be continuous. The reason is that the thread model of this component is not checked. Unfortunately, a problem occurs during the operation.

Another common problem is to store the "unit" model object in the "session" range, which binds the user session to the specified thread. This behavior seriously affects the server performance. Since all calls will be continuously aggregated to the thread that creates the object, it fundamentally affects the thread buffer pool.


For more information, see the following KB article:

  • Q243543 info: Do not store sta objects in session or application)
  • Q243548 info: Design Guidelines for VB components under ASP)

Splitting Service Recommendations

Separates expressions, services, and data services. Business components should implement business rules. Business components should not contain data access technologies. It is a task of the data layer component. Business components should not contain references to ASP objects.

ASP provides expression services. The object that references asp should be rendered as HTML. These objects can call the Business Objects registered to MTS/COM + in sequence.


Splitting an application into separate and distinct services has the following benefits:

  • Easier Component Reuse
  • Windows DNA model supported)
  • Better isolate Difficult Problems
  • More flexible deployment options (removing service coupling allows applications to be distributed across multiple computers)
Common traps

There is a common problem we call the Swiss Army Knife component. The Swiss army component combines all services (like a Swiss Army knife with 17 tools, such as screws and toothpicks ). Combining unrelated services into a component makes it difficult to use, understand, and maintain the component.

Another trap that is easy to fall into is to reference asp from business components. Coupling ASP with business logic (by usingRequestOrResponseObject, or construct HTML within it), not only restrict different clients to reuse your components, but also restrict horizontal scalability. The object that references the ASP built-in object should be in the same box as the web server. Ideally, business components can be distributed in different boxes due to horizontal scalability. The expression service can be provided directly in ASP scripts, HTML of components that reference ASP built-in objects can be created, and these components can be kept in the IIS circle.


A successful design model can be used as a model for solving public business problems. For example, a model that processes the "Create read update Delete (crud)" operation can help you divide an application into several different logical services, namely expressions, business rules, and data access.

See the following for more examples of design models. You can imitate them in your own applications:

  • Scalable Design Patterns)
  • Simplify MTS apps with a design pattern)
  • Fmstocks application: Start here)

Thread model suggestions

Select the component range or the component thread model. which method is preferred? Both methods require thread branches unless you decide to use "unit" or "double" model components within the page range. (If the Visual Basic programmer does not know which thread model the component is, it is always a "unit ".)

If you need to store objects in applications or sessions, you need to use components marked as "dual" and aggregate the "free thread grouping program (FTM )".

Do not use the "single thread" component and avoid using the "free thread" component from ASP.

Note:If you are not careful, Visual Basic can generate a "single thread" component. Make sure thatGeneralTabThread ModelSetUnit thread. You must also selectUnattended executionAndKeep in memory.


If you are using Visual Basic, it is a "Dummies" development environment. Visual Basic only applies to the "unit" model. If the Visual Basic "unit" model object is executed very well, I don't want to take too many restrictions on the page scope. Fitch and Mathers stock 2000 undermine any prethought on performance. In addition, many existing websites built by ASP, SQL, and Visual Basic all prove that the "unit" model component within the page is scalable and executed.

If FTM is clustered on components marked as "double", it can be called between threads without any grouping or thread switching. If a component marked as "double" does not aggregate FTM, ASP treats it as a "unit" thread object-just like a visual basic component. Remember, if you plan to use the "COM + Object pool", do not aggregate FTM. For more information about the "Object pool" rules, see the "Platform SDK" documentation.

The "single thread" and "Free thread" components run in the "System" security environment. Worse, the "single-threaded" component can cause deadlocks.

Common traps

Perhaps the most common trap is to use components that are not designed to run under ASP, such as "Single-threaded" components. Most developers fall into this situation because they move desktop applications to ASP or use third-party controls. If you cannot determine the thread model of the component, you can check the registry key of the component (but you cannot always rely on it ).


For more information about the thread model and its impact on ASP, see the following article:

  • Don box's Active Server Pages and COM apartments)
  • Agility in Server Components

In addition, the following KB article provides details about thread issues:

  • Q243543 single-threaded apartment objects in session or application)
  • Q243544 info: component threading model summary under Active Server Page)
  • Q150777 info: Descriptions and workings of OLE Threading Models)

Security recommendations

The component should not make any assumptions in the user environment it runs. Do not access user-specific information, such as HKEY_CURRENT_USER, or dedicated resources on the desktop, because these components are unavailable. Do not useSendkeysOr call components that depend on the user interface to perform operations that usually require desktop interaction, such as opening a dialog box.


Components will run on different security desktops. First, this indicates that the application cannot open a dialog box and cannot interact with other GUI utilities (for exampleSendkeys). By default, inetinfo.exe cannot interact with the desktop. Different user environments also restrict components from accessing certain resources-mainly the HKEY_CURRENT_USER part of the Registry.

Common traps

A common mistake is to reference the table item under HKEY_CURRENT_USER. For exampleGetsettingAndSavesettingFunctions cannot be used in ASP, because they reference table items under the HKEY_CURRENT_USER Configuration unit. The following KB will discuss this issue:

  • Q248348 PRB: savesetting and getsetting not available in Visual Basic 6.0 webclass (Iis Application)

When a component is called from an ASP Client instead of a desktop client, printer, mapi information, and network sharing are usually "invalid ".

For more information, see the following KB article:

  • Q184291 PRB: COM objects fail to print when called from ASP)
  • Q217144 info: difficulties using net APIs in ISAPI and asp com objects)
  • Q207671 HOWTO: Accessing Network files from IIS applications)

Security considerations:

  • Which IIS authentication method is enabled?
  • Is your web application in-process or out-of-process?
  • If a component is registered with MTS or COM +, is it on the "server" or in the library software package?
  • Are you calling local DLL, remote DLL, local EXE, and remote EXE?

Security details are beyond the scope of this article. However, due to the complexity of this topic, the following article will be of great help to understand the problem from the ASP Component perspective:

  • Securing a Web-based Microsoft Transaction Server Application)
  • Q172925 info: security issues with objects in ASP and ISAPI extensions)
  • Q217202 PRB: CGI applications and iis oop applications may fail)

The following describes how IIS handles security:

  • Authentication and security for Internet developers)

Suggestions for server. Createobject and Createobject

UseServer. Createobject. If you are using the MTS/COM + Library package, useServer. CreateobjectTo avoid thread blocking.


CreateobjectIt is equivalent to calling through the script engine.Cocreateinstance. If you useCreateobjectInsteadServer. Createobject, The following will happen:

  • ASP cannot recognize this object.
  • Onstartpage/OnendpageThe page method is not called.
  • ASP does not know the thread model of the object.

Server. CreateobjectEquivalentGetobjectcontext. createinstance. This indicates that ASP knows the object clearly and Its thread model. In addition, if ASP pages are transactionalServer. CreateobjectMake the component and ASP page in the same transaction. (Please note that a transactional page may mean the coupling between unavoidable business rules and the presentation layer .)

Common traps

If the object is behind the firewall, you may need to callCreateobject. For more information, see q193230 PRB: Server. Createobject fails when object is behind firewall.


Although under IIS 4.0CreateobjectRatioServer. CreateobjectFast, but the performance in IIS 5.0 is the same. Similarly, if you are using the MTS/COM + Library package/application,Server. CreateobjectPrevents thread blocking.

Recommended Parameters

StatementOutThe parameter isVariant. In visual basic terminology, this indicatesBy ReferenceThe parameter should beVariant.By ValueThe passed parameters (InParameter) is not limitedVariant, But must beVariantCompatible.


Script client usageVariant. The specified data type can be used for the COM server. When you set the specified data typeBy ValueWhen passed to the COM server, the COM server can receive it without any problem. ExceptVariantOtherBy ReferenceParameters cannot be "sent back" to ASP scripts.

Common traps

One of the most common errors is "Type mismatch ". This is usually becauseBy ReferenceThe variable passed to the COM object is notVariant. The common solution isBy ValuePass the parameter or change the parameterVariant.


If you want to distribute components on multiple computers or run them outside the process, you may seeBy ValueSignificant performance obtained by passing parameters.By ReferenceTransfer will cause more grouping overhead between processes or computers because data must be sent in and out. If notBy ReferenceWhen passing parameters,By ValueThe correctness and validity of the passed parameters are also a problem. Note: by default, Visual BasicBy ReferencePass parameters.

The following KB article discusses how to pass parameters from ASP to COM objects:

  • Q197956 PRB: Passing parameters by reference to a vb com Object)
  • Q197957 PRB: Passing parameters by reference to a vc com Object)

Event suggestions

Avoid calling components that wait for other components to return events.

The component method should return the execution of ASP as soon as possible. Please consider using "MSMQ" or "COM + queuing components" to provide asynchronous calls-or when the work to be done is running for a long time and does not need to be run online.

Assign work items asynchronously instead of waiting for ASP to end a long-running process. Then you will return a response from ASP to the client. Once the project is completed, you can notify the client by email or other means (see the following content ).


ASP is not designed for event processing. To optimize the server performance, return the response to the HTTP request as soon as possible.

Common traps

The status mark on the server is not a "server-friendly" method that provides browser notifications.


Generally, the developer pays attention to the event to notify the browser about the work handled on the server. Although a sophisticated browser notification system can be developed, such as opening another port on the server through sockets, many developers implement their needs through the following technologies:

  • Use email notification
  • Add the meta-Refresh tag to the page to poll the server.
  • Connection sent to the browser, and the client is asked to manually check the status of pending requests.

The following KB article discusses these issues:

  • Q243547 PRB: ASP does not provide SS configurations to Client browsers)
  • Q243546 PRB: ASP does not support events)

Onstartpage/onendpage and objectcontext suggestions

In IIS 4.0 and later versionsObjectcontextAccess ASP built-in objects (such as responses, requests, servers, and so on ). Avoid using it whenever possibleScriptingcontextObject,OnstartpageAndOnendpage.


Onstartpage,OnendpageAndScriptingcontextObjects are used for legacy support.

Common traps

If an ASP object is inserted, the ATL wizard usesOnstartpageAndOnendpage.


Obtained using "dual" or "unit" Model ComponentsObjectcontextYou do not need to register with MTS/COM +. The local ActiveX EXE cannot be used.Objectcontext, So you need to useOnstartpage/Onendpage. To use the "free thread" and "single thread" component environments, you must register these components with MTS/COM +. Otherwise, useOnstartpage.

Error handling suggestions

The error processor will look forward to unexpected situations. Capture errors in each part of the application and record them as completely as possible. Good logs are of great significance for tracking, isolation, and troubleshooting. These logs can be text files or NT Event Logs written. In most cases, an error occurs while adding information. This is an effective way to notify callers that an error has occurred. When an error occurs, the caller can freely interact with the specific method to solve the problem.

It is critical to provide as much useful information as possible when an error is recorded. Consider the following:

  • Current user environment (call Win32 API-GetUserName)
  • Current thread ID (call Win32 API-GetcurrentthreadidOr in Visual BasicApp. threadid)
  • Current Time (using Win32GettickcountIn milliseconds)
  • Parameters passed to the Method
  • Error source, including method name

Based on our experience, good error handling and recording are the most effective way to isolate and diagnose runtime problems.

Common traps

Do you still remember the ASP 0115 error? I hope you don't have to fight it. If you are still worried about it, we recommend that you refer to troubleshooting with the IIS exception monitor ).

ASP 0115 errors do not always occur under the control of developers-but most of the time, error handling may have avoided many such situations, it may also help solve them when they happen.

In short, the biggest problem is skipping error handling or not containing useful diagnostic information.

In COM, exceptions are rarely transmitted across the boundaries of components. Capture exceptions-but return hresults to send failure messages to the caller.


The following article provides examples of how to handle valid errors:

  • Fitch & Mather stocks: Web Application Design)

Recommended global variables

Avoid using global variables in components. In visual basic terminology, this indicates that there is no public or global variable in the standard. Bas module.


The global variable is not a real global variable. Each thread has its own copy. If several methods are executed in the same thread, they will see the same variables; otherwise they will access different copies of these variables. This means that you may assign a value to a global variable (in thread a), but another user (executed in thread B) cannot see the new value.

The reason is that visual basic uses "local thread storage (TLS)" to reference global variables. This means that each thread has its own copy of the Public variable, and because it has multiple copies, the global data is not really "Global ". That is to say, users that run in the same thread will access the same variable, whether or not they expect it.

Common traps

If the public variable is used in the standard. Bas module, the data may have been damaged when different threads provide services to different users who want to use the same data.


The following articles by Matt Curland in Visual Basic programmer's journal (English) June 1999 are required:

  • Black belt programming-create worker threads in DLLs
  • Component builder-create efficient multithreaded apps

In addition, the following article by Daniel appleman gives a good overview of the working principle of multithreading in Visual Basic: a thread to Visual Basic (English)

Distribution Component suggestions

The distribution of components involves performance, scalability, and security issues. Different Distributions of the same component may produce higher-performance, more scalable, and more manageable configurations.

The following guidelines help improve performance and scalability when components are distributed on multiple computers:

  • Run the component that references the ASP built-in object in the same box of IIS.
  • Run the database component on the application server.
  • It is important to run business components on a computer. If you remove the coupling between business components and any ASP, you can choose based on your application design, computer availability, and testing.

Of course there are exceptions. But these are the good start of the Guide.


Cross-computer distribution components allow applications to meet scalability requirements. Secondly, the guidelines mentioned above help achieve the performance and scalability goals of the application.

Objects Reference ASP built-in objects, which can communicate a lot with your web server and are there because they are part of the presentation layer.

The database or data-sensitive logic may be stored in the database. Place Data Access Components on application servers rather than databases, avoiding expensive calls between components. On the contrary, the data access component uses SQL Server communication (such as TCP/IP) to communicate more effectively with the database.

Common traps

You should try to avoid the following problems:

  • When the horizontal scalability is more appropriate, continue to pursue the vertical scalability from your computer.
  • Ignore the firewall considerations (to help yourself. If the product environment between computers has a firewall, add a firewall to the test solution .)
  • Place components that reference ASP built-in objects on a computer that is separated from the IIS server (it is costly to reconcile and group ASP built-in objects .)
  • Bind components later (this generates additional calls to getidsofnames, which may be expensive in distributed applications. Try to use early binding .)
  • By ReferencePassing parameters (this generates more grouping overhead. PASS Parameters by value as much as possible .)

It may be tricky to successfully call the remote MTS component from IIS. A simple and effective solution that improves performance and simplifies security issues is to call the MTS/COM + software package/application in the middle. Early binding can reduce network segments and improve performance. If you use the "server" software package/application, you can set the running ID of the software package/application. This technology will be discussed in KB article 159311 instantiating Remote components in Microsoft Transaction Server and Internet Information Server.


If services have been decoupled, especially ASP, outside the business components, the distribution will be quite flexible. You can think more about the box and distribute components as needed to solve the scalability and performance problems that follow. How do I know? Test. How to test? See the following basic guide:

  • To test the reliability of the web site, analyze the computer and check for errors.
  • To test the performance, check the number of ASP requests that can be processed per second.
  • To test scalability, set the threshold for the number of ASP requests to be processed per second. Test applications with important tools-add users until performance is unacceptable.
  • It is important to enhance the test of the application because the operating conditions need to be exposed and other issues that will not occur during the single browser test.

For more information about application enhancement testing, see I can't stress it enough -- load test your ASP application ).


As you can see, there are some things that require constant attention throughout the development. Here, the many factors involved in the Application Guide have been fully clarified as they help completely avoid serious mistakes. Follow the guidelines described in this article throughout the development cycle to not only avoid some additional work, but also submit a scalable, reliable, and high-performance ASP Component-based solution.


J. D. MeierBorn on the East Coast of the United States. Following hsf-e Greeley's advice, he became a "Developer support" engineer focusing on server-side components including MTs and ASP technology and Windows DNA applications.

Archive servin' it up Column

December 27 ASP Guide
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.