Platinum Edition Using Visual Basic 5

Previous chapterNext chapterContents


- 37 -
Creating Active Server Pages

When should a site be static? When can dynamic content help? And when is dynamic content essential? Learn the general reasons for each approach and how to decide what is best for your Web projects.
Server-Side Scripting provides the power to create dynamic content available to any browser. Bring the business advantages of client/server technology to the Internet.
Receive an overview on how to get Active Server Pages running.
An introduction into Server-Side Scripting. Transfer your knowledge of Visual Basic to Web development.
A discussion of the common problems and the solution or work-around required to correct them.

Static Web pages are a thing of the past and dynamic content is here to stay. As the Internet becomes increasingly congested with information, sites must be up-to-date to be successful. People won't keep coming back to a Web site if the "Headlines of the day" start becoming the headlines of the month. Only by modifying and adding information on a daily basis can a site stay successful and keep attracting visitors. The time and expense involved to do this can be overwhelming and is not feasible for many individuals and companies.

The solution is not to hire more Web page editors, it is to design and build sites that keep themselves current. This doesn't mean artificial intelligence, just the application of client/server knowledge to the Internet. Web sites that automatically update themselves are not new, but how you create one is changing all the time. One of the newest, and most popular, technologies is Active Server Pages (ASP). By using ASP, you can create Web sites that do almost anything and do it quickly.

Static versus Dynamic Content

Whether you know it or not, you probably have already seen examples of both static and dynamic Web sites. Static content, or a static Web site, is made up of pages whose content does not change on its own. Any Web page can be changed by its owner through an editor, but that doesn't make it dynamic. Consider the example of billboards. Like Web pages, billboards can be either dynamic or static. Most billboards advertise such things as the distance to the advertiser's next fast food restaurant or gas station. These billboards have static content; it doesn't change unless someone manually changes it.

On the other hand, some billboards display such things as the current time and temperature. This is dynamic content; it changes as the information displayed changes. Obviously, some types of billboards are more suited for static content than dynamic content. The distance to the fast food restaurant isn't likely to change, so a dynamic electronic sign wouldn't be very useful. The reverse is also true--a painted sign displaying the time and temperature would always be wrong. It is usually clear from the content whether a dynamic or static billboard is called for.


Dynamic HTML
In this chapter, you spend a lot of time reading about Dynamic Web pages. It is important not to get this confused with Dynamic HTML, which is another important technology from Microsoft that is being released as part of its latest Internet browser (Internet Explorer 4.0).

Whereas Dynamic Web pages are called dynamic because their content may change every time you visit the site (reload the page), Dynamic HTML is a technology that enables Web pages to change appearance on the client side (without reloading). For example, text that changes as you move your mouse over different sections, or displaying database records that you can browse through without the page having to reload. Look for more information on this hot new technology in upcoming Que books, particularly Special Edition Using Visual Studio.


The same rules that apply to billboards apply to Web pages. The nature of the content determines whether the site should be dynamic or static. Dynamic content is relatively new to the Web and, until recently, it was difficult to achieve. Difficulty often translates into expense and, consequently, simplistic Web sites are popping up all the time.

If a plain wooden sign were put up to display the time and temperature and a painter were hired to repaint the sign every few minutes to update it, people would think the advertiser was crazy. But many of the sites on the Web today are tantamount to a painted time and temperature billboard. Sites are created as static pages, displaying information (such as news headlines, tips of the day, and so on) that changes on a regular basis, but the person (the "painter") hired to update the page works only once a week or month. Fortunately, this is changing.

When to Build Dynamic Sites

Two key questions determine the need for dynamic content:

For example, a site that displays stock price information must be dynamic. The information changes every second and those changes need to be fed electronically to the Web server. Conversely, a site that displays the names of the 50 states of the U.S. probably doesn't need to be dynamic. While the states' names are available in electronic form, they don't change and therefore such a site doesn't require dynamic features. It is important to justify the extra time or money required to build a dynamic site. As an example, take a look at the following case scenario for a proposed Web site project and compare the choice of a static site versus a dynamic site.

Suppose a company that offers courses on a variety of computer-related topics decides it wants to create a Web site. The function of this Web site is to serve as an Online Course Catalog. Visitors to the site can browse a list of available courses, view schedule information to determine course schedules, and register for courses if interested--all through the Internet.

The reason for creating this site is clear to the training company: the paper catalog it currently produces is too expensive and becomes outdated too quickly. In many industries, such as technical education, things change so rapidly that information becomes outdated in the time it takes to develop and print a brochure or catalog. Even if the catalog is correct when it is first sent out, there is no way to deal with changes that occur the very next day. If a course is cancelled, it isn't removed from the catalog, and if a course is added, it won't suddenly appear in the catalog.

The cost of the catalog includes much more than the time and money required to create it. Keeping the catalog current means reprinting it frequently, which can quickly begin to cost a great deal more than the original printing. A Web-based catalog doesn't require reprints; changes occur instantly. The Web version of this course catalog would provide online registration capabilities that would enable the school to cut personnel costs of staffing employees to answer phone calls from students who want to register. If the site were expanded to allow direct payment with a credit card through a secure connection, the entire process could be completely automated, reducing the personnel costs even further.

So, what the company needs is a Web site that

Given these specifications, a decision must be made regarding which type of site to build--dynamic or static.

A static Web site could be developed quickly. It would be relatively easy to convert the pages of the print catalog into corresponding Web pages. A listing of the courses available could be created in any HTML editor, as could a schedule of dates and places the courses are offered. Some small, pre-built CGI component (such as the WebBot features built into Microsoft FrontPage) could be used to save registration information to a file, but in general, the entire site could be built as standard, static Web pages.

Assume that a static site can be created quicker than a dynamic version of the same site. The dynamic pages would get the course list and schedule from a database, but otherwise, the site would look identical to its static counterpart. (Of course, programmers know better, but they usually aren't the ones making these decisions.) To some people, the choice is obvious: if the static site costs less to develop and the two versions look the same, why would any company choose a dynamic solution?

The advantages of a dynamic site are not immediately obvious--until a change needs to be made. For example, suppose a course currently labeled as NT 3.51 Administration needs to be called NT 4.0 Administration. Making this change in the static site involves the Web designer (or someone else with Web page skills) coming in and changing the listings page, the schedule page, and perhaps a few other pages where the course names are being used in such things as drop-down lists. This change could take an hour or more, plus the time for the Web designer to arrive. Even if the Web builder is available the next day, that is one entire day with incorrect information being shown to potential clients of the company.

In contrast, to make this change in the dynamic site, the training administrator (or another company employee) opens a standard database-editing program (custom made through MS Access or similar program) and changes the few characters that need editing. Instantly, the information displayed on every part of the Web site is correct. With that one change, the company has started to recoup the increased cost of building a dynamic Web site. Likewise, if such changes are required often (as is typical), the cost benefit of the dynamic site grows quickly. The entire investment eventually will be recouped and the Web site will begin to save the company money almost immediately.

How to Build Dynamic Sites

Determining that you need a dynamic site isn't the end of the process; now you have to build it, and this isn't necessarily easy. To create a dynamic site, you need to pick a technology to use. The technology most commonly used for this purpose is CGI (Common Gateway Interface). This generic term describes programs that interface with Web servers and respond to requests by sending back Web pages, using a combination of parameters and back-end data to determine its content. These applications can do almost anything you want with a Web site, and can be written in several languages, including C and Perl--so why would you use anything else?

CGI is difficult; it involves the creation of low-level programs in languages that lack most of the features of new development tools (like Visual Basic). Many of the functions required to generate the Web page, such as database access, are not provided to the programmer; you would have to build those functions your self. Most CGI applications do not support ODBC (Open Data Base Connectivity), DAO (Data Access Objects), or many other features programmers have become used to.

See "Improving Data Access with Data Access Objects (DAO)," Chapter 31

See "Introducing ODBC," Chapter 32

A major problem, and one that is of major importance to Visual Basic programmers, is that most CGI applications do not support the Component Object Model (COM), making it virtually impossible to reuse business logic contained in Visual Basic applications. Chapter 23, "Using Microsoft's Object Technologies," covers this topic in more detail. In today's environment, with more and more systems being designed with a 3-tier architecture, the business rules are contained within (middle-tier) objects accessed by many client applications. If the Web interface to that same business data cannot use those same objects, then a duplication of code and a deviation from the rest of the system is required.

In addition to those problems, CGI applications are inefficient. Each concurrent request against a CGI application creates another process on the server, resulting in poor performance and higher memory usage. In general, CGI is out of date; the concept is good, but it is not up to the task. The need for dynamic Web sites still exists and it is steadily increasing--so what should be used to create them?

Active Server Pages

Programmers want all the functionality of existing CGI applications, combined with the ease of use and support for language standards such as Visual Basic. Programmers want Active Server Pages (ASP). ASP is the perfect replacement for CGI, and it is still a handy TLA (three-letter acronym). It is built on the same standards programmers have become used to, allowing the use of COM objects directly. You can connect to the same middle- or back-end objects as your client VB applications do, and do it almost exactly the same way. It uses VBScript (or any other ActiveX Scripting Language, such as JavaScript), thus allowing programmers to transfer their knowledge of Visual Basic directly into this new environment.

How ASP Works

Well, now that you know that ASP is wonderful, let's discuss why. To understand what ASP is, it is important to discuss first what happens when a Web page is viewed.

The first step in the viewing process is the browser request. When the user types an URL (uniform resource locator) into their Web browser, or clicks an existing hyperlink that points to that URL, the browser initiates a request. For the purposes of this example, let's assume the user typed in the following URL: http://www.microsoft.com/ie/default.htm. The browser first looks at the address to determine which server to send the request to (in this example, this would be www.microsoft.com) and what to ask for (the document /ie/default.htm). This request is sent to the server by using HTTP (Hypertext Transfer Protocol), a common language that both the browser and the server understand.

The second step starts when the server gets involved. When the server receives the request, it begins to process it. In the case of a simple Web page, this processing isn't very involved; the content of the appropriate file on the server is read from the server's hard disk and sent back to the browser, unchanged.

The final part of the cycle occurs when the requesting browser receives the Web server's response. In this case, the response consists of the text contained in the requested file. The browser uses the HTML tags contained in the response to determine how to display the page to the user.


NOTE: The server's response, before being parsed by the browser, is available for any page you are viewing through the View Source menu option.

In the case of Active Server Pages, the server side of the request-response process becomes a little different. Once again, the browser is directed to an URL, and it creates a request (as above, but the URL would end in a .asp instead of .htm). The Web server is contacted and the request is sent. Up until this point, nothing occurs any differently then for a regular HTML page; the difference occurs when the server becomes involved.

When the server receives a request for a page, it looks at the extension to determine how to handle it. If the extension is .htm or .html, it treats the page like a standard HTML document, but if the extension is .asp, further processing is required. A special program on the server reads in the scripting code contained in the Active Server Page, and then executes it. The results of that code execution are then sent back to the browser. This response is standard HTML, no different than the results sent back from a regular page.


NOTE: ASP is actually implemented as an ISAPI (Internet Server API) extension to IIS 3.0. ISAPI enables programmers to create programs that run along with the Web server that is performing content-filtering and some page-generation services. You can build your own ISAPI extensions by using Visual C++ if you need to integrate yourself closely with the Web server itself.

Browser Independence

Although there are common elements between ASP and other Internet technologies such as client-side scripting (VBScript) and ActiveX controls, there is also one important difference--ASP occurs completely on the server. What does this mean? If you write an ActiveX control and put it on your Web page, it is up to the browser to download, install, and use that control. If you view that page with a browser that doesn't support ActiveX controls, such as Mosaic, it wouldn't work. Similarly, if you include VBScript in your page, attached to a button click for instance, it won't work on a browser that doesn't support VBScript. These are examples of client-side technologies, and they are browser dependent.

ASP does not involve the browser. All of the code is executed on the server; the browser just receives standard HTML from the server and displays it. The fact that the HTML was generated is hidden from the client-side of the process. This makes ASP browser independent, an important feature that makes ASP perfect for the Internet, where you have no control over what type of browser people are using. Of course, it is still possible to use client-side scripting and ActiveX controls in the pages generated by ASP, if browser independence is not required.

Support for Standards

A big selling point of Active Server Pages is that they support the same existing standards that Visual Basic does. Because the server components that interpret and execute the Active Server Page code are designed using COM, it isn't surprising that the scripting languages used to write the actual pages also support COM. Intrinsic objects in ASP allow the script to create COM objects and use their properties and methods directly. This gives ASP its greatest power--the capability to use existing objects, which could be written in Visual Basic, directly in the Web application.

Active Server Pages use the ActiveX Scripting Engine to provide the interpreting and execution functionality of their pages. The obvious benefit of this is that it supports the use of any scripting language written to that standard. This currently includes two languages from Microsoft, VBScript (discussed in Chapter 35, "Internet Programming with VBScript") and JavaScript, as well as several languages from other third-party vendors, including an implementation of Perl. The side effects of choosing to implement ASP in this way are that any additional languages, or language features, that are added to the Scripting Engine will immediately be available to developers of ASP applications.

The two main features of ASP--support for COM and support for VBScript--have the general effect of enabling programmers to use their existing knowledge in this new environment. VBScript uses the same syntax and supports many of the same functions as full-blown Visual Basic, smoothing the ASP learning curve considerably. COM support provides for more direct code transfer through the reuse of objects that were written in VB, or for use in VB. The mortgage approval object currently in use by your client/server Visual Basic system now also can be used by your ASP version of the same interface. If a change in the workings of the object is made, both the traditional system and the new Web application will be automatically affected. Redundant code is avoided, and the existing investment that you or your company have made in a system doesn't have to be lost.

Visual Basic is one of the most popular programming environments in the world. By maintaining such a high level of compatibility between it and ASP, Microsoft has made this technology a success from the moment it was released.

Programming Active Server Pages

We know that the server looks at the contents of an ASP file on the server and generates an HTML file to send back to the browser, but how does it determine what to send back? The ASP file on the server contains scripting code, which code is executed by the server, resulting in HTML. The scripting code itself is what you, as the Web site developer, create. This code may be written in various ways and by using different languages but, regardless of these details, it is still programming. If you know how to program a non-Web application, then you already understand the fundamentals of programming in ASP. To get started, the general structure and flow of ASP pages will be covered next through the use of some simple examples.

The Basics

As previously discussed, the code required to program ASP can be written in any supported scripting language that is available for client-side scripting. At the moment, the two most commonly used languages for this purpose are VBScript and JavaScript. This section will discuss VBScript only. JavaScript is a dialect of Java. VBScript is a language that is related to Visual Basic. There are differences between the two, but general coding syntax and methods are the same. Because of the similarity between ASP and VB, which you already have at least some familiarity with, the best way to learn is to get right into it, so take a look at the example file in Listing 37.1.


NOTE: All the commands and functions of VBScript and JavaScript are available in ASP, but the object model is different. Many of the objects you have seen in client-side scripting, such as Document, Frame, and Window, have no place in server-side scripting, and thus are not available. Don't worry, though. ASP has its own powerful set of objects that will be addressed in the next chapter, "Working with Active Server Page Objects."

Listing 37.1 sample.asp--Programming a Simple Loop in ASP

Response.Write "<HTML>"
Response.Write "<HEAD><TITLE>Example Page</TITLE></HEAD>"
Response.Write "<BODY>"
<%
For j = 1 to 10
        Response.Write  "<P>Line: " & j & "</P>"
Next j
Response.Write "</BODY>"
Response.Write "</HTML>"
%>

The first thing that will help you understand this code is the Response.Write statement. It is a type of print function that outputs information to the browser. Anything sent out by one of these statements is sent directly--unmodified--as part of the server's response. The For loop is the other piece of code in this example, but it doesn't look any different than the Visual Basic equivalent, and it behaves exactly the same. The code in Listing 37.1 produces the HTML code shown in Listing 37.2, which is then sent back to the browser that requested the page.

Listing 37.2 Output from sample.asp

<HTML>
<HEAD><TITLE>Example Page</TITLE></HEAD>
<BODY>
<P>Line: 1</P>
<P>Line: 2</P>
<P>Line: 3</P>
<P>Line: 4</P>
<P>Line: 5</P>
<P>Line: 6</P>
<P>Line: 7</P>
<P>Line: 8</P>
<P>Line: 9</P>
<P>Line: 10</P>
</BODY>
</HTML>

The Response.Write statement is just one way to send output back to the browser. Plain HTML may also be written directly into the .asp file. Scripting code can be placed around the HTML to insert variables into the HTML statements. The <% and %> symbols around the scripting code in Listing 37.1 are delimiters used to mark where scripting code begins and ends. If the sample.asp file is redone using this other method, it looks like Listing 37.3.

Listing 37.3 EWSAMP.ASP--Another Method of Creating the Same Output as sample.asp

<HTML>
<HEAD><TITLE>Example Page</TITLE></HEAD>
<BODY>
<%
For j = 1 to 10
%>
<P>Line:<%=j%></P>
<%
Next j
%>
</BODY>
</HTML>

The preceding code will produce the exact same output as the previous method (see Figure 37.1), but it is much easier to use and understand. The line <P>Line:<%=j%></P> is an example of using ASP to insert a variable into HTML. When that line is processed by the server, it will just replace <%=j%> with the current value of j. This combination of using standard HTML, scripting code, and variable substitution is how most Active Server Pages are written, and it's how the examples will be done from here forward.


NOTE: If you haven't worked in VBScript before, you may wonder why the variable j wasn't declared before it was used. Unlike Visual Basic, all variables are considered to be of type Variant and, therefore, there is little advantage to declaring them. Variable declaration is only required for arrays, as in Dim month_array(12), but these arrays are still composed only of variants.

FIG. 37.1
A simple list of numbers, created from an Active Server Page script.

It is helpful to try out these examples as you progress (you can modify them and see what happens) to get a better understanding of what the end result will look like.

Generating HTML from Active Server Pages

When designing Active Server Pages, you really are creating programs that will create Web pages completely from scratch; no portions of the page are being generated for you. If you miss important parts of the page or create them improperly, the results of your page will not be what you expect. It is important that you understand what you are trying to create. If you were writing a VB program to generate MS Word documents, you certainly would want to find and study a reference on that file format. The same applies to HTML. Que's Special Edition Using HTML 4, Third Edition, provides a full reference and discussion of the HTML language.

Everything in HTML is based on tags, matching delimiters in the form <TAG>TEXT</TAG>, that indicate the formatting or meaning of text contained between them. The key tags you need to know when learning ASP are those at the top of every HTML page.

The first tag that you should see in the output from any ASP you create is <HTML>. This marks the page as HTML and delimits the beginning and ending of the page's content. No other HTML tags or any other content that you want the Web browser to see should come before <HTML> or after its corresponding end tag, </HTML>. Following immediately after the HTML tag is <HEAD> (for header), nested inside of which should be the tag <TITLE>. Text placed between the <TITLE></TITLE> tags specifies the page's name for display in the title bar of the browser window.

In almost all HTML pages (except frame sets, which are not be covered in this discussion), after the closing tags of both </TITLE> and </HEAD> comes the <BODY> tag. This tag is a little more complicated and has a few options, including the capability to set the background image and color for the page. In its most basic form, it is just <BODY>, but it can also contain any combination of the following parameters: BGCOLOR, TEXT, LINK, VLINK, ALINK, or BACKGROUND. The most commonly used tags inside <BODY> are BGCOLOR (to set the background color) and BACKGROUND (to set a background image). The following are a few examples to illustrate the use of this tag.

For a page that has a black background and no background image, you would use:

<BODY BGCOLOR="#000000">

For a page with a background image of "swirls.jpg" and a specified background color of white, you would use:

<BODY BACKGROUND="swirls.jpg" BGCOLOR="#FFFFFF">


CAUTION: It may seem pointless to specify a background color when you have already set an image, but the color you set will be used as a background if the image is unavailable or images have been turned off in the browser. This can be very important if you choose a particular text color because it will display well on the specified background image. If you don't specify a background color, the text may be unreadable against the browser's default background.

This <BODY> tag, like most others, requires a closing tag, but it doesn't appear until after the content of the page is finished. The last couple lines in a Web page are usually

</BODY>
</HTML>

to mark the end of the body of the page, and then the end of the page itself.

Once past the header portion of the page, there is a very large number of tags and options available, but only a few others are required to build and test some simple Active Server Pages.

The Paragraph Tag

<P></P>

These tags mark the beginning and ending of a paragraph.

The Break Tag

<BR> (this tag has no matching end tag)

This tag is the equivalent of a soft return and can be used within a body of text to define the line-break point without forcing any space between the two lines. You can use <BR> between the <P></P> tags.

The Heading Tags

<H#></H#> (where # is a number from 1 to 6)

These tags denote that the text contained within the tags is a heading. The lower the number is from 1 to 6, the more important the heading contained within the tags. Browsers usually display lower heading numbers as progressively larger, bold font. For example, if you were to have the following lines in your Web page:

<H1>My Web Page</H1>
<H2>by Jane Doe</H2>

the first line, your main heading, would be displayed larger and with a heavier boldface than the second, your subtitle.

Hyperlinks

<A HREF = URL></A>

This is a very useful tag that is used to mark a piece of text as a hyperlink to an URL. This URL might represent another Web page, a file, or even someone's e-mail address. A link pointing to the Microsoft Site might look like this:

<A HREF="http://www.microsoft.com/">Click here to go
to the Microsoft Web Site </A>

The text Click here... will appear as a link in the Web browser, which means that it will be underlined, colored differently, or otherwise distinguished. When this text is clicked in the browser, it causes the browser to initiate a request for the page this link points to.

Other Tags It is likely that the tags just discussed will not be enough to build a proper Web site, but there are many more available. To find out more about these other tags, look at an HTML reference, look at the source for other people's pages, or use a Web page editor, such as Microsoft FrontPage. The advantage of using an editor is that it enables you to quickly create the look of your pages, using all of the tags needed, through an interface that provides the capability to tweak details of the page's appearance. Once you have the prototype page completed, replace portions of the HTML (created by the editor) with your scripting variables, or copy some of that HTML into your .asp files. The FrontPage Editor is, of course, available as part of the FrontPage 97 product, but it is also included in Microsoft Visual InterDev.

Microsoft Visual InterDev

Visual InterDev is Microsoft's development tool for building Active Server Pages, and it has many features that can help you build ASP applications. As part of Visual Studio 97, it uses the common development environment found in Visual C++ and Visual J++, and it is similar to the environment of Visual Basic (see Figure 37.2). This environment provides all of the editing bells and whistles you are used to, including code highlighting, direct access to comprehensive help information (that reference material alone makes the product worthwhile, in my opinion), and other time-saving features specific to the creation of dynamic Web sites.

FIG. 37.2
Visual Interdev gives you an integrated development environment in which to create and modify ASP files, while providing instant access to a large library of reference material.

Visual InterDev has the capability to connect to a Web site, whether created with InterDev or not, and display it using a link view (showing all of the pages, by the hyperlinks joining them) or an explorer tree view (basically showing the files and directories that exist on the Web server). This is similar to the functionality of the FrontPage Explorer, but page editing can take place right next to the tree view (in a dockable, resizable window), making coding a quicker process. For straight HTML editing or for creating HTML sections to include in your .asp files, the FrontPage 97 Editor is included. Several wizards and Design Time Controls (DTC) are also included, enabling you to generate quickly large amounts of ASP script customized to your purpose.

The shared development environment (Dev Studio) means that Visual InterDev is fully scriptable (using VBA) and can support the addition of new tools (through Add-Ins, such as Visual Basic). Built-in support for Visual Source Safe enables multiple programmers to work on the site together without fear of overwriting pages.

In conclusion, Visual Interdev is a great alternative to creating ASP files directly in Notepad or other text editors, especially if you are used to working in Dev Studio because of Visual C++ or J++. Visual Interdev is very affordable if purchased as part of the entire Visual Studio 97 package (including Visual Basic 5, Visual Fox Pro 5, Visual C++ 5, Visual J++ 1.1, Visual Source Safe 5, and other development tools). It isn't required (you can build any size ASP application without it), but for a large project, it quickly justifies its cost.

The ASP examples in this book can be created, edited, and run without Visual InterDev as well, so don't worry if you don't have it available at the moment.

Running Active Server Pages

As you work through the remainder of this chapter and the next two chapters dealing with ASP, you will want to try it out for yourself. Due to the nature of ASP as a server-side component, setting up a machine to test the pages can be somewhat involved.

Software Requirements

To run the examples shown in this book, or any other programs you find or create, you will need:

You need a Web server due to the way in which ASP works; if you look at an asp file directly (without a server) using an URL such as file://c:\sample.asp, it simply asks if you want to save the file to disk. When the same file is requested through the server (http://www.online-can.com/sample.asp), it intercepts requests for .asp files and processes them, returning the results to the browser, not the page. If the request doesn't go through the server, no processing will take place.

At the moment, there are two Web servers available that support Active Server Pages. For Windows NT (version 4.0), there is Internet Information Server 3.0 (IIS), a true production-level Web server, which is recommended for development and deployment of your application. Not everyone will have access to a computer running NT Server, so the Personal Web Server (PWS) for Windows 95 is also available. This Web server, which is not really suited to running a production site, enables you to do much of your development and experimenting without having to purchase the hardware and software required for Windows NT.

Internet Information Server is tightly integrated with Windows NT; to properly use it as your Web server, you need to understand its functionality as much as possible. This book can't teach you everything about Windows NT and IIS, but the key areas that impact ASP are discussed in the section "Troubleshooting ASP Files."

ASP is included with IIS 3.0, but you will need to install it separately if you are using PWS for Windows 95. Fortunately, ASP is available as part of several different products from Microsoft, including Visual InterDev, and it shouldn't be too difficult to find.

Any database access that takes place occurs on the server, so it is there that ODBC is required (software allowing use of the Open Database Connectivity standard to connect to databases). ODBC is the method used by most Active Server Pages (including all of the database- orientated examples in this chapter) to access databases. 32-bit ODBC must be installed on the server, and a System DSN must be set up for the desired data source. To determine if ODBC is installed, check for an ODBC 32 icon in the Control Panel of your server (as shown in Figure 37.3). If present, this control panel provides access to create and configure ODBC entries. For more information on ODBC and setting up DSNs, see Chapter 32, "Using Remote Data Objects (RDO)." Although not installed by default in Windows NT, ODBC is included with many other products, including Microsoft Visual Basic 5.0, Microsoft SQL Server, Microsoft Access, and Microsoft Visual InterDev, and is also available free of charge from Microsoft (www.microsoft.com).

See "Setting Up an ODBC Data Source," Chapter 32

FIG. 37.3
Looking for the ODBC 32 icon.


CAUTION: Database connections from Active Server Pages require the 32-bit version of ODBC.

You need a Web browser to test the pages. The type or brand of browser required is dependent on what you choose to do in your pages. If you are producing standard HTML only, then you should be able to use any browser, but if you are also working with ActiveX controls or VBScript on the client side, you will need Internet Explorer (free from Microsoft at http://www.microsoft.com/ie). If you want your pages to be browser independent, you should use multiple browsers to test your pages to ensure that you get the desired results on each browser.

Troubleshooting ASP Files

After everything is set up, you should be able to run .asp files without any trouble. If you do run into problems, the following sections provide descriptions of some common errors that occur while using ASP, possible causes of these errors, and suggestions for solving these problems.

Browser Doesn't Open the Page If the browser doesn't show your page, but instead puts up a dialog box asking if you want to open the .asp page or save it to a disk (see Figure 37.4), the URL you are attempting to go to is not a format you can view from your browser. The same message appears when you click a link or type in an URL that points at an .exe file.

FIG. 37.4
The Browser dialog box that is shown when a Web browser doesn't understand how to display your page.

This problem occurs because the ASP files are not directly supported by your browser, although the results of them are. This error means that the .asp file is not being executed for one of the following reasons:

Browser Requests Username and Password If your browser displays a dialog box that asks you to provide a username and password (see Figure 37.5), or the result of the page states that access is denied, then you don't have sufficient access rights on the Web server to execute the ASP file. The anonymous Web user, commonly named "IUSR_<Server Name>", must have at least "Read & Execute (RX)" rights to the file. See the section "Security Settings in Windows NT, IIS, and ASP," later in this chapter.

FIG. 37.5
The Browser dialog box requests authentication information to access an Active Server Page on the server.

An Error Message Appears on Your Page An error message is displayed directly on the page; see Figure 37.6 for an example. This usually means there is an error in your script(as opposed to a system setting, file access, or other form of problem). This type of error is equivalent to a compile-time or run-time error in Visual Basic. There is an error in your scripting code, and the text displayed should contain the error number and description.

This is the best error to get: All it means is that something is wrong with your code--and the error message is the best place to determine what that something is. Debugging code is simply part of the process, and this message, in fact, suggests that ASP is working correctly. The extremely straightforward, simple error messages that are returned make it easy to fix the problem (refer to Figure 37.6). (Where are those <SARCASM></SARCASM> tags when you need them?)

FIG. 37.6
These are the results of an Active Server Page that contains an error in its scripting code.

Page Takes Too Long to Load This problem presents itself as a page that seems to be loading but never stops; part of the page may display, but the entire page never completely loads. A dialog box may appear on the browser stating that a script is taking a long time to execute, and it usually gives the user the option to cancel (see Figure 37.7). ASP sends back results from the .asp file as it generates them; there is no real limit to how long that processing will take, so the first few lines of the page can arrive well before the rest of the page. The browser will continue to indicate that it is loading until the .asp file stops executing on the server. There is a server setting (see SCRIPT.TIMEOUT in the next chapter) that will stop the execution of the .asp script if it takes too long, but this is usually set high enough that you will notice that the page isn't loading completely long before an actual timeout occurs.

FIG. 37.7
An error message displays when an ASP script has taken too long to execute.

There really is only one possible cause--the .asp file's script is taking a long time to finish execution--but there are many reasons why that can happen:

Security Settings in Windows NT, IIS, and ASP

This section is a continuation of the "Troubleshooting" section, as many errors in ASP are really caused by incorrect security settings on the Web server. In general, these types of problems are found only on Web servers running under Windows NT. Therefore, this section begins with a general discussion of security in ASP and NT. If you already are an advanced NT user, you may find this discussion unnecessary, but for anyone else, it should provide a quick overview of a very complex topic.

File Systems Windows NT supports the use of several different file systems, two of which, FAT and NTFS, are most often used and thus will be the focus of this section. The FAT (File Allocation Table) file system is the standard used in most DOS systems and in Windows 95. NTFS (NT File System) is designed and used exclusively by Windows NT. The primary difference, and of most relevance to a discussion of Active Server Pages, is that FAT does not provide grant or denial of access to users and groups on a file or directory basis--NTFS does. Although you can run NT and Internet Information Server on a FAT volume, it is recommended that you use NTFS. The ability to control access down to the file and directory level is very important in running a secure Web server. Each user or group that is set up in NT (using the User Manager program, as shown in Figure 37.8) can be given a set of security rights to distinct files or directories. This is a huge difference from FAT, where the entire file system is open for access to any user.

FIG. 37.8
Here is the Windows NT User Manager, where you can add, edit, or remove users and groups.

File and Directory Access Rights T Security, using NTFS as previously described, provides the administrator with the capability to control exactly which users (or groups of users) can access each particular file and directory on the server (see Figure 37.9). For each file, a user (or group) can be assigned any of the access types shown in Table 37.1.

FIG. 37.9
Through a series of dialogs, the exact security rights can be set for a file or directory.

Table 37.1 File Permissions (Windows NT)

Setting Meaning
Read The user can only read the file. Sufficient for static HTML pages.
Execute The file can be run. Necessary for script files, Dlls, or other programs.
Change The user can read and modify the file. Usually not required for Web pages.
Full Control The user can read, write, or delete the file. Should not be given to any user unless necessary.

For a directory, the permissions are a little different. There are two additional settings: List, which means that the user has the right to see the list of files contained within a directory, and Add, which gives the user the right to create new files in a directory. When changing the permissions for a directory, you have the option of setting all subdirectories of the current directory to have the same permissions, or to have the settings changed for all files under the directory.

When someone attempts to connect to an NT Server, authentication is required from him/her through the use of a userid/password combination, enabling the server to determine exactly who he/she is. After the server knows the individual's userid, it can determine that individual's security rights to files on the server. Each file-system access involves a check of the user's permissions for that portion of the file system. In the case of a Web server, there are unique problems. If the pages are designed for public browsing, then visitors to the page will not have to log in, so the server needs to have a default user setup to handle the special case of anonymous Web users.

Anonymous Access to Your Web Site The userid that is used for anonymous users is set up in the WWW service properties dialog box, which is accessible from the Internet Service Manager of IIS. Your screen may look different, depending on the services you have installed. For each service listed, you can stop, start, pause, or edit its properties from this screen. Right-clicking the WWW Service gives you a menu of these options (see Figure 37.10). Choose Service Properties to bring up the Service Properties dialog box (see Figure 37.11).

FIG. 37.10
The Service Manager program, installed with Internet Information Server, gives you access to many of your Web server's most important settings.

FIG 37.11
Here is the WWW Service Properties properties sheet, Service Tab.

This properties dialog box includes four tabs:

The Service Tab The settings on the first tab deal primarily with security settings, but the tab also contains the TCP/IP port for the service. You shouldn't change this field (the default is 80) unless you know what you are doing. Web browsers look for servers on the default port and won't be able to connect to your site if you aren't using that port. The remainder of the settings on this tab deal with security issues, enabling the administrator to control which authentication methods are allowed. The Web server can be set up to use any combination of the three types listed, as long as at least one method is selected. A description of each of the three types of authentication and of their positive and negative features is discussed next. Windows NT Authentication allows the server to use pass-through authentication with the Microsoft Networking client software on the browser end of the connection. Two main advantages of this method are:

There are also disadvantages, a key one being that (at the moment) only Microsoft's browsers support this authentication method. Another problem with Windows NT Authentication is that it doesn't function through all types of firewalls. This authentication method is best used for secure intranet sites, where the browser can be a controlled choice, and a firewall isn't an issue. It isn't very well-suited for a public site.

Basic Authentication is the general method of requesting identification for Web page access. The browser is told that a user ID and password are required for access to the page it has requested, and it takes care of putting up a dialog box asking for that information (see Figure 37.5, in the troubleshooting section). Whatever the user enters is unencoded and is included in the HTTP request for the page. This method has the advantage of being supported by most browsers (including Netscape and Microsoft), but is relatively unsecured. The HTTP request (containing the authentication information) can be intercepted during transmission and decoded to obtain the user's ID and password. Chapter 39, "Using the Web, Databases, and Visual Basic," discusses a possible solution to the security problems of Basic Authentication.

The remaining option is Anonymous Access, which is not really a method of authentication but instead a choice to allow access without authentication. If it is checked, then HTTP requests are treated as being from the user specified as the Anonymous User.


NOTE: During installation of IIS, an anonymous user account is created for you. It is named IUSR_<Machine Name>, where machine name is the name of the server. You do not have to use this account and may instead specify one of your own choosing.

The specified user ID is then used to determine access rights to files on the server. If a file is requested that requires more access than the anonymous user has, then further authentication is requested, using one of the other methods that are checked off. If no other method is checked, then anonymous access only is allowed, meaning that any request will fail if it requires more rights than the anonymous user has.


CAUTION: No check is performed on the password entered for the anonymous user--you must make sure it is correct. If you change the password for the user specified through the User Manager or other means, then this screen must be updated as well. If the true password and the entry on this screen are not the same, no anonymous access will work, which may prevent any access to your Web site.

When attempting to view .asp files on your Web server, it is important to realize which set of permissions you are using. Your page and any components it calls execute in the context of the user account you are logged in as. In general, you will be logged into the server as the anonymous user if you aren't using Windows NT Authentication and you haven't been prompted by the browser to enter a user ID and password. If you receive errors at this point or the page doesn't seem to work properly and you suspect permissions are the problem, there is a quick way to check. Go into the User Manager of your Web server and add the anonymous user to the administrators group. This should give the anonymous user them full control rights on every file. Test your page. If it now works, then permissions are the problem. The error Access Denied usually implies you do not have permissions to the page you are requesting, but other errors (such as ASP:0115) can be caused by insufficient permissions on other files that ASP, or some component of ASP, needs.


CAUTION: If you add the anonymous user to the Administrators group for the purposes of testing, make sure you remove the user afterwards!! Leaving the anonymous user set as a member of the Administrators group would give that userid full access to every single file on your server. Using Front Page or even just FTP, any person on the Internet could potentially destroy, copy, or modify your information.

The following are common areas where the browsing user needs access:

To track down the exact file to which you do not have access, use NT's auditing features, which will log all failed access attempts to the NT Security Log. Tracking down permission problems can be frustrating and time-consuming, and it is often tempting just to give the anonymous user account Full Control rights over the whole drive, but doing so completely removes security on your system and is not a good solution. Further details on NT Security are beyond the scope of this book, but if you need more information on this issue, Que publishes several good references on NT 4.0, such as Platinum Edition Using Windows NT 4.0 and Windows NT Server 4.0 Administrator's Desk Reference, which will be of assistance.

The Directories tab, shown in Figure 37.12, contains the directory setup for use by the Internet Information Server. The first directory listed is the root of your Web server, the directory pointed to when someone goes to http://<your server> with a Web browser. If your root directory is C:\INetPub\wwwroot, then when someone browses to http://<your server>/default.asp, the Web server translates that request (using this list of directories) into C:\INetPub\wwwroot\default.asp.

FIG. 37.12
This is the Directories tab of the WWW Properties dialog box.

The remaining entries in this list are Virtual Roots. Virtual Roots enable you to specify physical locations on your server for subdirectories of your Web server. If you want to have the URL http://<your server>/Training point to a directory other than one physically located under your Web server's root (C:\INetPub\wwwroot\Training), then you must create a Virtual Root. When creating or editing a Virtual Root, as shown in Figure 37.13, you must specify the URL path you want to create a mapping for (such as /Training); the physical path it maps to; and several additional settings that involve access rights. The two check boxes, READ and EXECUTE, control what type of requests are allowed to come through the Web server against files under this Virtual Root. If .asp files are going to exist under a root, then you must check the EXECUTE option, but READ is sufficient for regular HTML files.

FIG. 37.13
Editing a Virtual Root. When the EXECUTE option is selected, Active Server Pages are allowed to exist under this root.

This discussion of URLs and paths brings up a related point: what file is shown to the Internet user when that user requests an URL that doesn't specify a file (such as http://www.online-can.com)? How this common situation is handled is dependent on the two options at the bottom of this page: Enable Default Document and Directory Browsing Allowed.

The first option allows you to specify what page is shown as the default in each directory. This is set to default.htm initially, but you may want to change it to main.htm, or something similar. The second option controls whether Internet users can look at the contents of directories on your Web site. If this option is enabled and the default page is either disabled or doesn't exist for a specific directory, then Web users will see a list of files on your Web site if they browse to that directory.


CAUTION: Be extremely careful with the Directory Browsing option. Leaving this on can make hacking your site easier, allowing people to view files and directories other than those you link to on your Web pages.

The Logging Tab of the WWW Service Properties dialog box contains options allowing you to control your server's logging of HTTP requests. You can set how often new files are created, whether or not a database should be used instead of just logging to text files, and even turn off logging altogether. Many shareware and third-party utilities exist to help analyze the contents of Internet Information Server's log files.

The final tab, containing Advanced options, is shown in Fig 37.14. On this dialog box you can change the settings for two types of restrictions--access by TCP/IP addresses, and how much Internet traffic should be allowed for WWW services. The TCP/IP restriction settings allow you to prevent or grant only certain addresses (or ranges of addresses) to access your Web server. This could be used to limit your visitors to those using the same ISP as your server, while still having your server on the Internet. Denying access by IP address is a little less common but could be used to block certain users or all users connecting from a certain ISP.

The Network Usage options are designed to prevent a busy Web server from creating too much traffic on your network connection. If this option is not set, then surges in HTTP requests could bring down your entire network, but setting it to a low value will reduce the server's ability to respond to multiple requests. It is better to not use this option unless you are encountering network problems during busy periods on the server.

FIG. 37.14
This is the Advanced tab of the WWW Service Properties dialog box.


CAUTION: It is important to note that improper settings in this section of the Properties dialog box could easily prevent all or most of your intended audience from seeing your site.

From Here...

The need for dynamic Web sites is steadily increasing. Current technologies (CGI) are out-of-date and difficult to use. Active Server Pages are the successor to those technologies, and they improve upon them in every way. The open, COM-based architecture of ASP allows the use of existing objects, code, and standards from many other development tools. Programmers, especially Visual Basic programmers, who want to start making dynamic sites need to learn this new technology now.

The programming basics discussed in this chapter only scratch the surface of ASP programming. The following related chapters in this book will be useful as you continue deeper into ASP:


Previous chapterNext chapterContents


Macmillan Computer Publishing USA

© Copyright, Macmillan Computer Publishing. All rights reserved.