Chapter 4

Introducing Active Server Pages


Up to now, this book has covered information leading to the door of the book's heart. Behind that door lies the information you need to create your first Active Server Page and your first Active Server Pages application. You've been introduced to the essence of Internet/intranet design. You've also seen the role that Windows NT plays in this new design environment and the particular advantages that the design of the Windows NT operating system brings to the Web development table. In Chapter 3, "Understanding Client/Server Programming on the Internet," we began our discussion of the basics of information architectures and gave you a feel for the historic roots of ASP development.

This chapter will introduce the players in the new game, the Active Server Pages development game. This chapter also serves as a wrap-up of the material covered thus far. The aim here is coherence-giving you a firm, conceptual foundation from which to build a solid understanding of the underlying technology of Active Server Pages.

Introducing the Active Platform

In November 1996, Microsoft formally introduced the Active Platform at the Site Builders Conference and the Professional Developers Conference. At those events, the audience saw a graphic, similar to the one in Figure 4.1, that outlined the major parts of Microsoft's vision of the future of Internet development. The two pillars of client-side and server-side scripting share a common tool set and are both based on consistent standards and protocols. It is a complete model, and is presented in detail in the rest of this chapter.

Figure 4.1

The Active Platform incorporates similar functions for the client and the server, exploiting their individual strengths.

The Vision

The Active Platform is Microsoft's vision of the next generation of distributed computing. It exploits the best of the centralized programming models as well as the best of decentralized programming. The Microsoft vision has profound implications for the Internet (not merely for industrial-strength client/server programming) and for the way that systems are developed and deployed. Microsoft's model creates applications that are logically centralized and physically decentralized. A logically centralized system can be administered from anywhere. Such a system is conceptually simple, and when properly tooled, is easy to manage. Physically decentralized systems can be more efficient, fault tolerant, powerful, and scaleable.

Two Profound Paradigm Shifts

There are two more key features to Microsoft's vision, and we return to them often in the pages to come. First, until the advent of the Active Server, programmers spent too much time worrying about infrastructure (e.g., programming Database Management System (DBMS) connections) and not enough time in their core competence (i.e., doing something useful with the recordsets fetched from the DBMS). By bringing the system services closer to the program and abstracting these services into server components, Active Server Pages promises productivity gains absolutely unrivaled in the history of computing.

The other feature of Microsoft's vision for Active Server Pages is in one of the company's key design goals for ActiveX Data Objects: universal access, not universal storage. This preference to know where everything is instead of collecting everything in one place is the natural extension of the overall mission of Active Server Pages-to keep things logically centralized and physically decentralized.

A Symmetric Programming Model

The most striking thing about Figure 4.1 is that both sides of the diagram are almost identical, evidently different only to the extent of system services. You may want to protest that "I thought you said this was client/server programming," but don't allow looks to deceive you. Under this apparent similarity are important differences. Let's start there.

Scripting

As you shall clearly see in Part II, "Programming Active Server Pages with VBScript," client-side scripting and server-side scripting have different missions in life. Client-side scripts most often add improved user interface and data validation (when HTML forms are used). Server-side scripts, especially in Active Server Pages, are practically unlimited; but they are primarily used to capture business rules and access to data (the second and third tiers in 3-tier client/server programming).

The important thing to stress here, however, is that server-side can, if properly implemented, create client-side scripts. One of the most important questions in Internet development is the one that makes you choose between programming to the broadest audience and programming for the richest on-line experience. To the extent that you choose the former, server-side scripting is important for two reasons:

For example, the thinnest client on the Internet is the one that cannot render graphics of any kind. The ALT parameter of the IMG tag in HTML originally was intended to help such clients interpret important parts of the screen that they otherwise couldn't see, by describing the area in words instead of an image. With an Active Server Page, your application can sense when such a browser (for that's what these kinds of programs are-as opposed to Web client programs that have more processing power) is making a request of your Web site. You can then present suchgraphics-challenged browsers with whole paragraphs, not merely short expressions, to give them as much information as possible, given their inherent limitations.

In today's Internet, a major difference between Web clients brands is whether they recognize ActiveX controls or not. Again, the Active Server Page doesn't care one way or the other. If it senses the ability to interpret ActiveX controls, it presents them; otherwise, it includes static images (or text, if necessary).

Of far greater importance than these mundane issues is the fact that Active Server Pages promote a new level of processing power into the Web server. It is critical to remember that the Web server was never designed to be an application server. It was designed to deliver HTML. This remains its primary mission, even on the Active Platform, but with Active Server Pages, this design constraint ceases to be a constraint at all.

The scripts that are contained in Active Server Pages, especially those driven by Active Server components (discussed in the next section), bring virtually all the power of traditional client/server programming to the Web server. Indeed, to the extent that Active Server components are utilized, Active Server Pages can do things that even the most sophisticated client/server programs can't. That's a pretty strong statement. Let's see if we can back it up in then next section.

Components

Components may be the single most important feature of Active Server Pages. Their importance to ASP is understandable when you step back and see how pervasively Microsoft has embraced components in virtually everything they create. Everything from the Internet Explorer to Windows NT 5.0 has been "componentized" by Microsoft engineers. Components give programmers many advantages, including lower development time and cost, added flexibility, easier maintenance, and most important, easy scaleability.

For the ASP development community, on the server-side, server components are either intrinsic to the Active Server or they are user-defined. On the client-side, ActiveX controls provide functionality similar to server components.

Because the word "component" is a generic term meaning any kind of part, you will see the expression "server component" in this book when it refers to those special features of Active Server Pages, viz., server components.

Active Server Components

Active Server Components basically do two things. First, they directly expose operating system services to your Active Server Pages. Second, they encapsulate business rules in a way that is extremely easy to program. Perhaps even more important in the long run, Active Server Components are easy to create. That is, by using programming tools and environments optimized to work with the Active Platform, writing sophisticated server components is no longer the province of the advanced programmer.

There is a truism in programming that the best programmers are users. Active Server components will prove that not only to be true but important, as well. In the summer of 1996, it was estimated that the number of lines of Visual Basic code finally exceeded the number of lines of code written in COBOL, the perennial champ. Perhaps the biggest reason Visual Basic is so prolific is that users, not professional programmers, wrote these "extra" lines of code. Active Server component development will bring the same ease of programming to the Internet that Visual Basic brought to creating Windows programs.

To get a feel for what server components are and what they do, take a look at a few of those that ship with the Active Server.

The Browser Capabilities component is the component that permits an Active Server Page to determine what kind of browser or Web client program is making a request. It makes this determination by looking to the User Agent HTTP header and looking up the identified browser in the browscap.ini file. All of the listed features of the browser are exposed as properties of the Browser Capabilities component.

The Browser Capabilities component is a clever piece of code, but it doesn't have anything to do with the operating system. One component that does get closer to the OS is the TextStream component. This component relies on the FileSystem object, which, as the name suggests, accesses low-level file I/O. With this component, opening or creating text files in the directory system is simple and direct. Navigating through the files' contents is equally straightforward.

See "The Browswer Capabilities Component" for more information about the Browser Capabilities component, in Chapter 13.

See "Textstream Objects" for more information about the TextStream component, in Chapter 13.

There is one Active Server Component that may keep you up nights, though. It's the Database Access component, and it exploits an operating system service of earthshaking importance: objects in the directory system. Actually, the earth won't shake until Windows NT 5.0 ships in 1997; at that time, ActiveX Data Objects (ADO) will be incorporated into the Windows NT Directory Services. That is, the directory system will be able to be managed like a database. Files become database objects with properties that will be exposed to ADO. You can already see what this will look like when you select the Properties menu option of a file on your Windows Desktop. By the way, these directory services aren't restricted to the Windows Explorer and the local file system; they reach out to every file system on the Internet!

We mentioned that a key design goal of the ADO team was to enable universal access to information-they do mean universal. To ADO, it won't matter if the data is a record in an ODBC database or a message stored in Exchange Server. It won't matter if the data is stored on your own hard drive or on one in the Smithsonian. ADO will find it and present it to your application (possession is no longer nine-tenths of the law). Again, this is the logical conclusion of the Web. The Web doesn't let you take possession of HTML; it just lets you see it. ADO doesn't let you possess the data, either; it just makes it available to your application.

When a connection is made to a data store with ADO, you can specify how long to wait for a connection to be made. If the connection isn't made in time, the attempt is abandoned, and the data provider returns a trappable error to ADO. This feature will not be supported by all data providers.

Now, imagine programming when most of the work done by your applications is done with the aid of other peoples' server components. Whether you're using a server component to access an interactive feature in your Web site or you access network functionality in Windows NT 5.0, you will be able to do far more programming of the real task at hand. No more time wasted doing things that every other programmer in the world is doing at the same time you are.

Even if the objects exposed by Active Server components don't qualify as "true" objects in the minds of the purists, the kind of object-centric programming that will become commonplace in Active Server Pages development will have an impact great enough that most of us will forget about polymorphism and inheritance..

ActiveX Controls

ActiveX controls are used like server components, only on the client side. That is, you instantiate an ActiveX control in a client-side script with the OBJECT tag, and then you manipulate this control through its exposed properties and methods. Most ActiveX controls enhance the user interface of your Web applications, but some can simply return a value directly to your application. For example, you can write an ActiveX control that makes a complex calculation from given inputs. The control would receive the inputs through its properties, and the resulting calculation would be returned to the calling application through a separate property.

On the other hand, Active Server components never have a user interface. They are designed to render services to your server application for the purpose of producing standard HTML output. In other words, Active Server Pages are never used directly by people. Active Server Pages produce the HTML that users see, and that HTML may include ActiveX controls. So sensing browser capabilities or manipulating text files or providing HTML source code with a randomly selected image or filling the controls on an HTML form with data from a database are all examples of the usefulness of server components.

One of the most important things about the relationship between those two "pillars" of Figure 4.1, the Active Desktop and the Active Server, is that server components can be made from existing ActiveX controls. In fact, Microsoft encourages this approach for three reasons. First, you don't need to reinvent the wheel. Second, it's too easy to incorporate ActiveX controls into server components to not exploit this advantage. Finally-and this is especially important in the context of Java-ActiveX controls can give you direct access to the Windows graphical user interface. Indeed, more and more of Windows will be available to the ASP developer through this medium. Get used to taking advantage of it now. Dividends await the astute.

You may be tempted to suggest that Microsoft also wants you to use ActiveX controls for self-serving reasons, but this allegation carries less weight now that the Open Group is responsible for the standard.

The Open Group, created in 1996 to act as the holding company for The Open Software Foundation (OSF) and X/Open Company Ltd., provides a worldwide forum for collaborative development and other open systems activities.

ON THE WEB

See this Web site for further details of the transfer. More information on the Open Group is at http://riwww.osf.org/.

System Services

Writing a book about emerging technology is never easy. Writing this one was particularly challenging, because even the operating system was making profound changes under our feet. When the first readers open the pages of this book, Microsoft probably will have shipped the next generation of its Windows NT operating system, Windows NT 5.0. At the same time, Microsoft is developing and shipping servers meant to be integral parts of Windows NT-most of which cost nothing to add on. These servers are awesome achievements in data processing. Things like the Microsoft Transaction Server (MTS), the Message Queuing Server (MQS), and the Index Server all are vital parts of the extended Active Platform. A detailed discussion of each of these assets would require a separate book for each one.

The point to grasp here is that, as powerful and revolutionary as the Active Platform is, it will not fully empower you as a user, programmer, or developer until you bolt it into related technologies like those just mentioned. For example, if you become proficient at developing Active Server components and start to develop sophisticated, n-tier client/server apps using DCOM (Distributed Component Object Model) to widely deploy your components and Active Server Pages, you do not want to administer this far-flung empire without the managerial genius of the Microsoft Transaction Server. If you expect difficulties and delays in the actual day-to-day use of your application, and if you don't want the entire system to come down while you wait to sort out the inevitable traffic jams on the Internet, then you do not want to leave town without the Message Queuing Server.

A View of the Active Server Programming Model

Having outlined the abstract features of the Active Platform, we turn your attention to the Active Server programming model. How do you actually implement Active Server Pages?

As you can see in Figure 4.2, the processing environment of Active Server Pages is much richer than your run-of-the-mill Web site. Actually, the full richness of this environment is impossible to depict in a simple graphic, and we hope that you come to appreciate this truth as you work your way through this book. You can see from the figure that there's a lot going on with Active Server Pages.

Figure 4.2

The programming environment of the Active Server is both rich and accessible to all programming skill levels.

Finally-A Foolproof Answer to the Cross-Platform Problem

The first thing you notice about Figure 4.2 is that four different client platforms are represented. Four is arbitrary. ASP serves all clients, versions, and platforms because ASP produces nothing but HTML. The constraint is not in ASP but in HTML. If you want ASP to produce HTML that's rich in ActiveX controls, ASP will comply without complaint, but any clients that are not ActiveX-enabled will not work the way you expect. With ASP you can produce HTML code consistent with the capabilities of the client, from the most basic feature set to the most advanced.

The real power to bridge this "feature gap" using ASP comes when a user interface is not what's unique about your application. Business and science will be the two disciplines that most severely test the practical feasibility of the Web because computation drives most of the need for their data processing.Because computation is encapsulated in components, and because ASP is a componentized development and deployment environment, it will shine brightly, attracting the best programming talent in the world. Instead of having to write large complex applications, these programmers can write compact computationally intense programs. That is a fundamental paradigm shift of the first order.

This brings up the next most noticeable features of Figure 4.2: the out-process server and DCOM. What are they? The answer is in the next section.

Distributed Component Computing

As you may know, the entire vocabulary of OLE was supplanted recently with a new moniker, Component Object Model (COM). With the advent of Windows NT 4.0, COM evolved into the Distributed Component Object Model (DCOM). This specification was designed to permit developers to store their Active Server components (or access someone else's) anywhere on any network. For the purposes of Figure 4.2, you need to understand that part of your ASP application can be out there on the Internet; it doesn't have to be on your own Web server.

See "Distributed Computing" for more information about DCOM, in Chapter 5.

See "What is a COM Server" to understand the difference between in-process and out-process servers, in Chapter 5.

Currently, only out-process servers can be deployed with DCOM (the implication in the Microsoft literature is that one day, in-process DLL servers will run in another server's address space on a remote machine).

A Quick Overview of Server Types

If you look in your Windows directory you will see two predominant file types: .exe and .dll. The .exe file can be activated directly by the user; the .dll (which stands for Dynamic Link Library) file, on the other hand, can only be used by another program. This means that the .exe file runs in its own address space and the .dll file runs in the address space of another .exe file. For example, the ASP.DLL (the Active Server Pages program) file runs in the address space of INETINFO.EXE (the Internet Information Server program).

Any program that runs in its own address space is called an out-process server, and any program running inside an out-process server is called an in-process server.

At this point, you might be wondering, so what? Isn't the Internet just one big computer system where you can call any file on any server and have the results delivered to the client that addressed you with the request? What does DCOM give you that's unique?"

Fair enough, but let me warn you at the outset that the answer you read here will make much more sense once you've read Chapter 14, "Constructing Your Own Server Components." The simplest way to answer the question is to say that DCOM permits the ASP developer to create instances of objects from components that are not on the same machine, and to do it in the context of a single program, a single HTTP transaction.

To better understand this, again think about what would have to happen in a large, complex ASP application if you wanted to use the Internet instead of DCOM. To use the Internet to access other servers and their resources, you need a separate HTTP transaction. You can't nest HTTP transactions, because they're all self-contained units. When you call a server with a URL, you initiate an HTTP transaction with a request, and your client waits for the HTTP response. If your ASP application already has been called and is in the process of delivering the requested resource, it can't stop what it's doing, initiate another HTTP request, and then incorporate the response into the response that it then will make itself. Do you see the quandary?

With DCOM, none of this is a problem. You use the out-process Active Server component that you are accessing with DCOM exactly as if it were on your own computer. You instantiate it just like in-process DLL servers, and you manipulate it with its exposed methods and properties exactly as you do its lightweight cousin, the in-process server. Think of DCOM as an "Internet inside the Internet." Absolutely brilliant.

The Bridge from Desktop Apps to Client/Server Apps(and Beyond)

Active Server Pages have everything a programmer (or power user) needs to turn her old desktop applications into full-blown, three-tier client/server applications, almost overnight. Truly.

In the "Active Server Components" section, you saw that there's a lot of Visual Basic code out there. Porting the business rules contained in that code to VBScript is a slam dunk. Using Visual Basic 5.0 Control Creation Edition to turn those programs into real DLLs is now simple, accessing data through ActiveX Data Objects is an integral part of Active Server Pages, and using DCOM to distribute them around the world, if necessary, finishes the transformation.

And there's more in store. Porting legacy applications is one thing, but writing new code from scratch (still using the tried and true friend, Visual Basic) you now can create asynchronous servers-servers that take your requests, return a success code to the client, and then do time-consuming processing, updating the client program's user interface later, when everything's done.

For example, say that you are a financial advisor and you have a client who makes a request of one of these asynchronous servers. Your client wants to know his current position in the market but doesn't want to sell his stock unless his portfolio is in real need of rebalancing. He then launches Internet Explorer and calls a portfolio server, hosted by you, the financial advisor. Your server knows what assets your client holds, as well as where the last asset allocation model is stored. It retrieves the model and reruns it.

Your asynchronous server then makes a request of the virtual operations center (which collects the transaction and pricing data for all your clients, as well as those of several other financial advisors across the country) and updates your client's portfolio with the most current data.

Hiding in the preceding story is a subtle but important advantage of ASP apps. They can hide the details about how you interact with the structure of a database system, yet they give your client all the access he needs to that data. The watchword here is control. No one has to know anything about your system, only what methods and properties are exposed by its mediating objects.

While the transaction data is being collected, your asynchronous server makes another request of yet another asynchronous server that handles mutual fund analysis. It asks for the top ten mutual funds whose asset classes match those required by the asset allocation model that it passes along for reference. While it waits for the list of funds, your asynchronous server gets updated with the results of the latest transactions, and it sees that the market has been good to your client. Your portfolio server then re-balances your client's portfolio, lopsided in stocks, and makes another request of the mutual fund server for any new asset class it has selected as a result of optimizing the portfolio.

Your asynchronous server then places all this data and its recommendations for sells and buys in an e-mail message and sends the message to you, with an Urgent flag attached. You see the urgent message appear on your screen while reading your personal edition of one of the main investment e-zines (also driven by an Active Server Pages application). You review the results of processing, and, in the interest of prudence, make the necessary changes that the over-aggressive portfolio server suggested.

When the dust settles, your client gets an e-mail message notifying him that all processing has been completed and is ready for his review and approval. He sends an HTTP request to another Active Server Page, which displays the new information, and your client approves it for implementation.

Every piece of the previous programming scenario can be written today by a sufficiently skilled ASP developer. By the time you're done with this book, perhaps that developer will be you.

Seeing Where ASP and HTTP Fit Together

There really are three entities involved in an HTTP transaction: the Web client, the Web server, and the human being.

The Web client and Web server communicate using HTTP headers. These are collections of data that the client and server exchange with one another to ensure that, regardless of the contents of the body of the HTTP transaction, the entire transaction remains coherent and complete.

The data displayed to the human being is transmitted from the Web server to the Web client, and the Web client transfers the text and the interpreted HTML source code to the screen or printer, so the human can read it.

Active Server Pages permit the developer to affect all facets of the HTTP transaction. The ASP objects known as Request and Response interact with the HTTP body and headers, respectively. This feature gives the ASP developer almost unlimited flexibility in management of interaction on the Web.

For example, using these two objects lets the developer authenticate secure HTTP transactions and control the contents of the STATUS header, blocking access to requested content when such access would violate established security policy. Even complex authentication schemes can be implemented using new headers defined just for your ASP application.

The Active Server is implemented as an ISAPI filter running under IIS. Whenever a Web client makes an HTTP request of a Web server, the Active Server ISAPI filter gets a chance to intercept the request. If the request is for an .asp file, the Active Server takes over from IIS, parses the entire file from top to bottom, processes the server script(s), and returns an HTML output file to IIS. IIS then returns this data stream to the requesting Web client.

Be careful when you enter a URL for your .asp files. If you don't use the protocol prefix, HTTP://, the browser interprets the request as a call to display a file. This command bypasses IIS, so the filter never gets its chance. As a result, under Windows NT, the contents of the file is displayed instead of the results of the .asp source code. Under Windows 95, if a file has been associated with the .asp extension-for example, an excellent ASP editor, such as HomeSite-then that program launches and opens your .asp file outside the Web client window.

Remember, because an .asp file needs to execute IIS, use HTTP in the URL.

Exploiting the Power of Windows NT Technology

The Active Server is running in the same address space as IIS, and IIS is running as a service under Windows NT, so both IIS and the Active Server inherit all the security features of the Windows NT operating system. Security comes through four access mechanisms: IP address, user account, virtual directory, and the NT File System (NTFS). User account access is granted by using one of two authentication methods: basic authentication and NT Challenge/Response authentication. Virtual directories enable IIS to control access to specific directories (and all subdirectories) that were identified by a single name, an alias. Access Control Lists (ACLs), A product of the NTFS, permit you to specify access permission for individual users or groups.

Use the Microsoft Internet Service Manager to specify IP address restrictions (from the Advanced tab) and to configure virtual directories (from the Directories tab). Specify ACLs in the Windows NT Explorer through the Security tab on Properties dialog of the directory or file to which you want to restrict access.

Because the Active Server is linked to IIS through the ISAPI filter mechanism, and because IIS runs as a service under NT, all your .asp files have direct access to these programming assets. This means that your ASP applications are highly scaleable: Their performance doesn't degrade as demands on them increase.

Because everything is running as a service under NT there may be other services available to your ASP programs. Of these services you are most likely to use the other two perennial Internet severs, FTP and Gopher. Other important servers are the Microsoft Index Server, a Personalization Server, and a Proxy server. Microsoft Exchange Server now has a Web interface as well, and the directory services provided by NT also are ready to be pressed into action.

Where's ActiveX in Active Server Pages?

You've seen that HTTP is what gets an Active Server Page running, but what makes it tick? In a word, ActiveX. But what kind of ActiveX?

If you did any advanced HTML programming before coming to Active Server Pages, you already may be familiar with ActiveX controls. ActiveX controls are slimmed-down OLE Automation servers. That is, Microsoft reduced the number of object interfaces required by OLE objects so that they would work more efficiently in the bandwidth-challenged world of today's Internet. ActiveX controls, therefore, work wherever OLE Automation servers worked in the past.

ActiveX controls usually have a user interface and some way to interact with it at runtime. Other ActiveX controls have no user interface, such as computation engines or text-formatting functions.

The Active Server can be extended using Active Server Components. You will learn all about Active Server Components in Chapter 14, "Constructing Your Own Server Components"; for now, you need to understand that Active Server Pages are object-centric programs. Most of the work done in an .asp file is done by some kind of object.

We use the term object-centric to distinguish the informal kind of object commonly encountered in computer programming from the formal objects encountered in full-blown object-oriented programming languages like C++, Java, Smalltalk, and Delphi. Most of the features of real objects are found in object-centric languages, but some of the most problematic-such as inheritance-are missing.

The most important feature of all objects is that they are self-contained programs that encapsulate data and source code. In ASP development, objects expose collections, methods, and properties by which work is requested and results are accessed.

The Active Server is a collection of objects, but it also can interface with any other programs written to the ActiveX specification. In the same way that ActiveX controls are OLE Automation servers on a diet, so Active Server components now are ActiveX controls with a reduced set of interfaces. Specifically, the only interfaces that an Active Server Component needs to support are IUnknown, IClassFactory, and IDispatch. The other feature recommended, though not required, for a program to be an Active Server component is a type library.

The ActiveX scripting engine with which the Active Server Engine interfaces is the same one with which the Web client interfaces. So, if you develop a scripting engine of your own, all you need to do is incorporate the ActiveX scripting interface into your own scripting engine, and your work will work on both the client and the server.

Because Active Server components are running on a controlled server and not on a user's desktop, they have full access to the server's file system and network resources. This makes them a natural alternative to client-side scripting technologies such as Java and the twin client-side scripting engines, VBScript and JavaScript.

An Active Server component can be instantiated in the global.asa file and stored as a Session property. This component can be accessed simultaneously by all sessions (assuming that it uses one of the multithreading models supported by the Active Server). Here, then, are the reasons why in-process Active Server components are so superior to the traditional CGI implementation of Web interactivity:

Seeing Where ASP and HTML Fit Together

You've seen how Web clients access IIS (IIS is running as a service of Windows NT) and how IIS communicates with the Active Server (which is running in the address space of IIS). Now take a look at the last step in this process.

Basic HTML Output

Although an .asp file contains text, HTML source code, and scripts, the only thing it produces is HTML. The Active Server is merely an HTML factory-it writes HTML code for you. This code actually might be written by you along with scripting logic that determines what, if anything, will be returned to the client. Or it might be an .asp file that generates HTML entirely on its own from source code stored in a database record.

When you call an ASP program that contains only .asp source code, which generates no HTML, your Web client complains because there is no data in the response body. Sometimes the program won't even run.

If the program does run, the error message that invariably appears includes an evident non sequitur: "The operation completed successfully." This means that the Active Server ran to completion, but the client wasn't happy with the result.

If you need to create what is basically an ASP utility (a function that does not deserve to be made into a full-fledged Active Server Component), find a way to return some HTML, even if it's merely a <BR>. Even better is a redirect to another .asp file.

Many editors permit you to create a template .html or .asp file. If you have, at a minimum, the standard HEAD and BODY tags in your template, you will never run into the error noted above.

Data-Driven HTML

Most HTML on the Internet always has been and still is static. Forms provide a basic level of interactivity, and ActiveX controls can give static HTML pages a dynamic appearance and enhance interactivity, but that depends on the client software supporting the ActiveX specification. Using Active Server Pages immediately does two things for you: It enables the highest form of interactivity on the Web-namely, secure commercial transactions-and it encourages the greatest amount of dynamic content. Whether that content changes because the Ad Rotator randomly selected another banner ad or because the structure of the HTML page was generated to suit the ActiveX control-enabled client program, it all was done automatically by your ASP application.

Part III, "Working with ActiveX Server Objects and Components," and Part IV, "Database Management with Active Server Pages," are dedicated to showing you exactly how to move up to this level of Internet development.

Special Cases

With sufficient experience, you may find that there's nothing beyond your reach with ASP extending your grasp. This new power won't come without exacting a cost, however. To really improve your reach with Active Server Pages you will have to meet the following two challenges, at least.

To whet your appetite, we close this section with a brief introduction of the programming problems posed by the particular challenges of these two special cases.

Dynamic Client-Side Scripts

The first challenge presents itself when the server is called to create a dynamic client-side script. The most frequent occurrence of this almost certainly will be in filling out on-line forms. For example, say you have an HTML FORM with SELECT tags and TEXT fields in it. Further suppose that the specific variables displayed in these controls are stored in your database. The OnLoad event of your scripted page would normally populate the SELECT tag. With ASP, the server-side script would first fetch the SELECT options from the database, and it would then be able to write the client-side script that would run when the OnLoad event fired. The result is a dynamic SELECT tag.

See "Modifying Client Scripts from the Server" for more information about modifying client-side scripts with server scripts, in Chapter 6.

HTML Layout Controls

Once you get past the more common dynamic HTML challenge, you will likely be confronted by the second challenge: using the ActiveX Layout Control in your .asp file. The trick is to give the file created in the ActiveX Control Pad an .asp extension, instead of the standard ALX value. There are other requirements that

have to do with protecting the .asp delimiters embedded in the .alx/.asp file, but details dictate a prerequisite knowledge of .asp syntax that you won't learn until Chapter 11, "Building a Foundation of Interactivity with Request and Response Objects."

The ActiveX Control Pad and the .alx file

Standard HTML is a structural language, not a page layout language like PostScript. HTML is only interested in specifying the components of a document, not for their relative positions on the page. Microsoft introduced what they called a 2-D control called the Microsoft HTML Layout Control. This control permits the HTML author to specify precise locations for controls. With this control you can also specify the layering of objects and their transparency. The results can look pretty spectacular.

These specifications, and any scripts that manipulate the controls contained within the Microsoft HTML Layout Control, are stored in a separate file that uses the .alx extension.

Creating an instance of the Microsoft HTML Layout Control is facilitated by the Microsoft ActiveX Control Pad program. This small application was designed to help identify and configure ActiveX controls and to create the ALX file.

ON THE WEB

The program is free and can be downloaded from the Microsoft Web site at:

http://www.microsoft.com/

Complete documentation for the Microsoft HTML Layout Control is at:

http://www.microsoft.com/workshop/author/layout/layout.htm

At any rate, being able to use the sophistication of ALX files and .asp files-and in the same file- perhaps is the most impressive example of how ubiquitous .asp source code will be in your Web applications. Are you beginning to see how the advent of the Active Server Page is going to empower Web developers like nothing else in the history of the Internet?

Understanding the Structure of Active Server Pages

There is no structure, per se, in an .asp file that isn't already there in the structure of the HTML, Visual Basic, or JavaScript code. In this respect, .asp files are not really programs. Indeed, a single .asp file can implement any combination of supported scripting engines, using languages as diverse as Perl and Rexx to Visual Basic and JavaScript. ASP is an "ecumenical" programming environment.

HTML, All by Itself

It is acceptable, though not necessarily recommended, to rename you HTML files with the .asp extension and turn them all into Active Server Pages. That's all that's required to make an ASP application. If you only want to control more of the HTTP headers in your HTML files, then you may see minimal .asp source code in those renamed HTML files. But if you want to turbo-charge those sluggish old HTML files, or if you want to stop maintaining two versions of your Web site (one for the interactive-impaired), then read on.

HTML Mixed with .asp Source Code

Once you choose to add .asp source code to your HTML files, you have to make several more choices. If you are silent, the Active Server Engine makes a few of these choices on your behalf. The choices fall into two categories: to use scripting or not and, if so, what kind(s) of scripting.

For the purposes of this discussion, .asp source code consists of either native ASP commands or scripting commands. Native commands are those that access Active Server Engine objects and components. Scripting commands rely on a particular syntax, as well. This means that you have to tell the Active Server Engine which language to use to interpret the commands. If you are silent, the engine will use VBScript by default.

This choice is not trivial when you are using Active Server Pages to write client-side scripts. As soon as you opt for this feature in your Web site, you're back to square one: are you writing to a captive audience such as an intranet, where all the client programs are the same brand and version? Even if all the browsers are the same brand and version, do they all support VBScript, or will you have to rely on the more ubiquitous JavaScript?

As noted in the introduction to this section, you don't have to choose one scripting engine. Choose the ones that suit your needs. If you have a nifty Perl program that you'd like to use, use it. If most of your server-side scripting will be done in VBScript because that's the language in which you are most fluent, use it. And if you need a generic, client-side scripting engine, use JavaScript, while you're at it.

Once you have made the preliminary choices, you must begin to contend with the challenge of separating the HTML source code from its ASP counterpart.

You have two basic choices here: Use code delimiters <%...%> or use the HTML <SCRIPT>...</SCRIPT> delimiters. When you are mixing scripting engines, you must use the <SCRIPT>...</SCRIPT> tags, because you have to identify the scripting engine to the Active Server. You identify the language with the LANGUAGE parameter (the comment delimiter is different for each scripting engine as well, and comments are an integral part of the <SCRIPT>...</SCRIPT> tag).

Comments are necessary in client-side scripts because browsers that cannot interpret scripts need to ignore everything within the <SCRIPT>...</SCRIPT> tag. However, if you use a comment in the server-side version of a script, nothing will happen. In other words, do not use comment lines when defining server-side scripts.

.asp Source Code

As mentioned, you can write an .asp file with only .asp source code, but if you intend to have a client program call the file and there isn't a stitch of HTML in the output, your client is going to balk.

An important advantage of using scripting delimiters is that the .asp source code never is visible to the reader of the HTML that is sent by the Active Server Page. This is because the source code is processed entirely at the server. This invisible source code trick holds whether you use the <%...%> or the <SCRIPT>...</SCRIPT> options. However, to the extent you have client-side scripts in the HTML output, you are directly exposing your programming expertise to anyone who looks at the HTML source code.

Scripting Functions and Subroutines

For server-side scripting functions and subroutines to work, they must be delimited by the <SCRIPT>...</SCRIPT> tags, and the RUNAT parameter must be set to Server so that the client scripting engine doesn't get its hands on it. You cannot use the <%...%> delimiters to define a function because you cannot give names to .asp code blocks. Even if you could, there's no inherent way to get a code block to return a value, the required function of a function.

To use .asp files to generate client-side scripts, you need to mix the <SCRIPT>...</SCRIPT> tags with the .asp source code delimiters, <%...%>. That is, client-side scripts consist of <SCRIPT>...</SCRIPT> blocks. When those scripts need content generated by the server (namely, filling form controls with database contents, as mentioned earlier), you must tell the Active Server Engine which code is to be executed at the server and which is to be streamed to the client and executed there.

Sound complicated? It's not, really. Most of the secret is in the fact noted a couple of paragraphs ago: The Active Server Engine won't run a script unless the RUNAT parameter equals Server. Obviously, then, all other occurrences of scripts will run at the client, and the <SCRIPT>...</SCRIPT> commands are just plain old HTML, dutifully sent back to the client in the response body of the HTTP transaction.

There is no hard and fast rule for where to put your functions and subroutines. A common practice is to put them in the <HEAD> section of your HTML file. Short functions sometimes can be installed directly with the HTML command. You will have ample practice with all of these design alternatives when you get to Part II, "Programming Active Server Pages with VBScript."

Server-Side Includes

Server-Side Includes are powerful tools for programmer productivity. In a sense, they are the most basic kind of reusable code. Their primary purpose is to insert text file contents into .asp files. Server-Side Includes can contain other Server-Side Includes, so you can stuff an incredible amount of text into an .asp file with a single command.

See Using Server-Side Includes" for more information about Server-Side Includes and examples of how they are used, in Chapter 9.

Because Server-Side Includes are included in your .asp files before any of the files' ASP commands are executed, Server-Side Includes can't do anything fancy, such as looking up database records. They can, however, call other Server-Side Includes.

Server-Side Includes insert text in exactly the same place in your file as they are located. In other words, they replace themselves at runtime. This distinction can be important when the resulting text has a particular role to play and that role has a particular place in the file to play it. At other times, this is not so important. One of the most common uses for the Server-Side Include is when you need to refer to constants in your .asp source code. For example, the adovbs.inc file contains all the VBScript constants used by ActiveX Data Objects.

A final point about Server-Side Includes is that they really don't add any marginal overhead. In a UNIX shop, however, .html files are usually not opened before they are sent on to the client program. But to process a Server-Side Include the server must open the .html file and the Server-Side Include file. It must then insert the text in the Server-Side Include into the .html file at the proper location Finally, it must close the .html file and send it on to the Web client.

Under the Active Server, the .asp file has to be opened anyway, so the extra effort of inserting the text is negligible. Anyway, this entire file I/O is processing in the address space of Windows NT, so even in the worst case, the overhead of processing .asp files in this way is nothing compared to the power you get in the bargain.

From Here...

In this chapter, you were introduced to the results of what can only be described as the most spectacular course correction ever attempted by an American corporation. In less than a year, Microsoft redeployed all of its resources to incorporate and exploit the revolution in data processing that is the Internet. If the definition of an asset is "anything that enables you to do something you couldn't do before," then the Internet is one of the most amazing assets ever to appear on this planet-look at what its mere presence did for Microsoft. But if the Internet is a consummate example of an asset, then the technologies that Microsoft has built and delivered can only be described as a mutual fund of technology. This mutual fund goes by the name of the Active Platform.

Perhaps the most remarkable Internet development asset in this mutual fund is the Active Server Page. Designed to be used by anyone who can deliver content to the Internet (and that's practically anyone who can type), it is typified by a single file that can be packed with an incredible amount of processing power. You can mix a virtually unlimited number of scripting languages into a single .asp file, each language used for the kind of work for which it's optimized. In that single file, you have immediate access to all the processing power of the Active Server Engine's internal objects and components. And if they don't do what you need, you can build your own Active Server Component. Once registered, your component is accessed and behaves exactly like those components that ship with the server. You can build those components in any language that conforms to the COM specification, from C++ to Java to Visual Basic 5.0. And you can store those components anywhere on the planet and use them as if they were on your desktop. With Active Server Pages, there are no separate files to compile (or even store). Everything can be contained in a single file extension, if you want.

Nothing even comes close to the breadth and depth of processing horsepower that you have at your fingertips when you have mastered the Active Server Framework.

From here, you will progress through the following chapters on the road to mastering the Active Server Page:


© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.