Полезная информация


Special Edition Using HTML 4

Previous chapterNext chapterContents


- 35 -
Active Server Pages

by Mike Morgan

Understanding ASP

When a Web browser contacts your server, the browser uses the HyperText Transfer Protocol (HTTP) to request some resource by name. A typical request is

GET /index.html HTTP/1.0

This request tells the server that the browser wants the Web page stored in the server's document root (/)whose name is index.html. The message also notifies the server that the client is using version 1.0 of HTTP.

In most cases the server's job is simple--it locates the requested page and sends it back to the client. If the filename ends in a special suffix, however, the server may have to perform additional processing. For example, the Webmaster may turn on server-side includes; if the filename ends in SHTML the server examines the file for special commands and then executes each command. The output of each command is inserted into the file; the finished file is then sent back to the client.

On the Microsoft Internet Information Server (IIS) and its smaller cousin, the Personal Web Server, the server checks to see if the filename ends in ASP. If it does, the server examines the file looking for scripts and then runs each script. The server inserts the output of each script into the file and sends the finished file back to the client.


CAUTION: Don't just change the extension of every file on your server from HTM to ASP. Every time the server has to check a file for scripts, it takes a bit of processing time. If you only use ASP when a file contains a script, the load on the server is small. If you force the server to check every page, the load adds up and can reduce the performance of your server.


NOTE: The IIS supports ASP scripts written in Microsoft's language (VBScript) as well as Microsoft's version of JavaScript (JScript). You can also buy third-party modules (called "scripting engines") for your server that support other languages, such as Perl, REXX, and Python.

Because ASP runs on the server, this technology does not depend on the end user's browser or platform. As long as the ASP scripts generate valid HTML, the resulting page should work as well on a Macintosh running Navigator 4.0 as it does on a Windows 95 machine running Microsoft Internet Explorer 3.02.


ON THE WEB: http://www.microsoft.com/infoservsupport/content/faq/  Microsoft has provided Frequently Asked Questions lists (FAQs) on several aspects of Active Server Pages.

This section introduces ASP scripting and shows two examples: one that reads the contents of a form, and another that retrieves data from a database.

ASP Scripts

When you write an HTML file, you put HTML tags (delimited by <...>) and plain text together. Your HTML may also contain comments, delimited by <!...>. When you add ASP scripts, you add another delimiter: <%...%>. Thus, if you write

<% theSequence = "first" %>

the server passes the string inside the delimiters to the scripting engine for its primary scripting language. By default, that language is VBScript. As a result, VBScript opens a new variable (theSequence) and assigns a string value ("first") to it.

ASP Output Directive  From time to time you'll want to display the value of some expression. Most frequently, you'll do this while you're developing the script in order to check your logic. The syntax for the ASP output directive is

<%= expression %>

Thus, if you wrote

<% theSequence = "first" %>
<%= theSequence %>

you would see "first" appear in the resulting page.

ASP Processing Directive  Use the syntax

<%@ keyword %>

to pass information to the server. For example, to tell the server to use VBScript as the primary scripting language, write

<%@ Language = VBScript %>

as the top line of your file. (The scripting language is VBScript by default, but it's considered "good form" to set it explicitly.)

You can set five different variables in the processing directive:

The effect of each of these keywords is explained later in this chapter.

Working with Forms

Suppose you have the HTML form shown in Listing 35.1 in your Web page:

Listing 35.1  form.htm--The Fields of This Form Will Be Read by an ASP

<FORM METHOD="GET" ACTION="process.asp">
<BR>First name: <INPUT TYPE="text" NAME="first">
<BR>Last name: <INPUT TYPE="text" NAME="last">
<BR><INPUT TYPE="submit" VALUE="Enter">
</FORM>

When a user submits this form, the contents are sent to the page named process.asp. The browser packages the fields of the form into a query string; the server makes this string available through an object called Request. You can read fields in the query string by using Request's QueryString() method. Listing 35.2 shows a simple ASP script to process the contents of form.htm.

Listing 35.2  process.asp--Use This Simple ASP Script to Process the Contents of the Form

<%@ Language = VBScript %>
<HTML>
<HEAD><TITLE>Welcome</TITLE></HEAD>
<BODY>
<H1>Welcome</H1>
<P>Hello, <%= Request.QueryString("first") %> 
<%= Request.QueryString("last") %> </P>
<P>Welcome to my site.</P>
<P><A HREF="next.htm">Next</A></P>
</BODY>
</HTML>

Handling Multi-Item <SELECT>s  If you have a multi-item <SELECT> in your form, use the alternate version of QueryString() as shown in Listings 35.3 and 35.4.

Listing 35.3  multi.htm--One of the Fields of This Form May Have Multiple Values

<FORM METHOD="GET" ACTION="doMulti.asp">
<BR>First name: <INPUT TYPE="text" NAME="first">
<BR>Last name: <INPUT TYPE="text" NAME="last">
<BR>Occupation (select all that apply): 
<SELECT NAME="Occupation" MULTIPLE SIZE=5>
<OPTION Executive>Executive
<OPTION Professional>Professional
<OPTION Engineer>Engineer
<OPTION Skilled>Skilled Labor
<OPTION Clerical>Clerical
</SELECT>
<BR><INPUT TYPE="submit" VALUE="Enter">
</FORM>

Listing 35.4  doMulti.asp--Use This ASP Script to Read the Values from "Occupation"

<%@ Language = VBScript %>
<HTML>
<HEAD><TITLE>Welcome</TITLE></HEAD>
<BODY>
<H1>Welcome</H1>
<P>Hello, <%= Request.QueryString("first") %> 
<%= Request.QueryString("last") %> </P>
<P>Welcome to my site.</P>
<P>
<% theNumberOfOccupations = Request.QueryString("Occupation").Count %>
<% if theNumberOfOccupations = 0 %>
You must be unemployed 
<% else if theNumberOfOccupations = 1 %>
Your occupation is 
<% Request.QueryString("Occupation")(1) %>
<% else %>
Your occupations are 
<% Request.QueryString("Occupation")(1) %>
<% For i = 2 to theNumberOfOccupations - 1 %>
  ,<% Request.QueryString("Occupation")(i) %> 
<% Next %>
and <% Request.QueryString("Occupation")(theNumberOfOccupations) %>
<END IF>
.</P>
<P><A HREF="next.htm">Next</A></P>
</BODY>
</HTML>

Using METHOD="POST"  Many Web designers prefer to use POST rather than GET to send form data back to the server. The advantage of POST is that there is no limit to the number of characters that can be sent back, while some combinations of software truncate GET strings. If you're reading data from a <FORM> that uses POST, use Request's Form collection to read the contents of the form. For example, if the form shown in Listing 35.3 had used POST instead of GET, we could have used the following line to retrieve the data from the field named "first":

<%= Request.Form("first") %>

Accessing a Database

One of the most useful things you can do with an ASP script is give the user access to a database. Microsoft makes this step particularly easy by allowing you to write ActiveX Data Objects (ADOs) based on Microsoft's Open Database Connectivity (ODBC) standard.


NOTE: For a different approach to connecting to a database, see your server documentation's section on the "Internet Database Connector," or IDC. With the IDC you can send queries to a database (through ODBC), format the returned data, and send the resulting page to the user's browser.
Microsoft recommends that users migrate to ADOs, but it will continue to support other methods into the near future.


What is ODBC?
ODBC is Microsoft's implementation of the X/Open and SQL Access Group (SAG) Call Level Interface (CLI) specification. By using ODBC, your program can read and write records from an idealized database by using standard Structured Query Language (SQL) statements. The ODBC drivers take care of translating the standard SQL into the exact calls necessary for each database. In the case of SQL databases such as Microsoft SQL Server, little translation is required. In the case of "databases" such as text files and Microsoft Excel spreadsheets, the drivers are more complex.
Figure 35.1 illustrates ODBC's architecture, which has five logical layers:


Connecting your ASP script to the database is a three-step process:

1. Make a Data Source Name (DSN) file

2. Connect to the database

3. Retrieve data

In addition to these three steps, you should consider whether or not you need to use transactions to manage your database access. This section addresses each of these points.

Making a Data Source Name File  In order for an ODBC application to connect to a data source, the application uses a Data Source Name, or DSN. ODBC supports a variety of DSNs, many of which are stored in the system registry. Microsoft recommends that ADO developers use a file-based DSN, so that the DSN can easily be moved or shared. To make a new DSN file, open the ODBC control panel and choose the File DSN tab, shown in Figure 35.2.

FIG. 35.1
ODBC consists of five distinct layers.

FIG. 35.2
Use the File DSN tab when you're connecting from an ADO.

If you don't already have a file DSN that is suitable for your data source, click on Add and select the driver that's right for your data source. Figure 35.3 shows eight drivers available on this machine.

FIG. 35.3
Choose the driver that matches your data source.

Once you name the new DSN file and click Finish, the driver may display a series of dialogs. Uses the dialogs to tell the driver where to find the data and how to interpret it. When you're done you'll have a new DSN file in your Data Sources directory.

Connecting to the Database  The ActiveX component that implements the ADO is called Connection. Tell the ASP script about the database by making a new Connection object. Then use Connection's Open method to access the DSN file you built in the preceding step.

<%
  Set cnnConn = Server.CreateObject("ADODB.Connection")
  `For convenience, keep your DSN file in \Program Files\Common Files\
  `  ODBC\Data Sources
  cnnConn.Open "FILEDSN = theDatabase.dsn"
%>

Retrieving Data  Once you have a connection to your database open, you can send standard SQL statements through ODBC. Suppose your database includes a table called FruitTable with two columns: fruitNumber and fruit. To list the table, you could write the following:

<%
`This script assumes we have already instantiated a new Connection
`object and opened a connection to the data source through our
`DSN file.
`Now lets issue the query:
strSQL = "SELECT fruitNumber, fruit FROM FruitTable"
Set rstFruits = cnnConn.execute(strSQL)
Response.Write("<TABLE><TR><TH>Fruit Number</TH><TH>Fruit</TH></TR>")
Do Until rstFruits.EOF
  Response.Write("<TR><TD>" & rstFruits(`fruitNumber') & "</TD><TR>" &
    rstFruits(`fruit') & "</TD></TR>")
Loop
Response.Write("</TABLE>")
%>

If you're using ASP scripts to access a database, be sure to read your server's documentation on other access tools. For example, Microsoft supports a RecordSet object that gives you more precise control over which records are displayed, and a Command object that allows you to impose high-level control over the way requests to the database are managed.


CAUTION: Be sure to observe any licensing limits imposed by your database manager. If you are licensed for, say, 15 simultaneous connections, you may use up those connections quickly once your application is placed into service. Read your server's documentation on connection pooling to learn how to live within your database manager's limits, and be sure to close your connections once you're through with them.
To learn more about connection pooling, read about it in the Microsoft KnowledgeBase at http://www.microsoft.com/kb/articles/Q164/2/21.htm and http://www.microsoft.com/kb/articles/Q166/8/86.htm.

You can release a database connection by placing the following lines in your ASP, after the </BODY> tag:


cnnConn.Close
Set cnnConn = Nothing

Selecting a Transaction Model  When you allow more than one user to access the same database at the same time, it's time to think about transactions. Transactions provide four behaviors, often summarized by the acronym ACID:

The following steps illustrate how an airline reservation system might work, without transactions:

1. You contact Travel Agent #1 to book a flight to Hawaii. Travel Agent #1 opens the database and reads out the available seats. She finds that there is only one seat left on the flight that you want.

2. While you are considering taking the seat, a different passenger contacts Travel Agent #2 about the same flight. Travel Agent #2 queries the database, finds out about the one open seat, and tells her prospective traveler about it.

3. Both you and the other passenger decide to take the seat. Both travel agents enter the data at about the same instant. Travel Agent #1 happens to be just a bit faster--she changes the database and tells you that you have a confirmed ticket. Then Travel Agent #2's booking goes through, changing the database so that the seat appears to have been sold to the other passenger.

4. Both you and the other passenger arrive at the airport. The other passenger's name is in the database with a reservation. To your dismay, the agent at the counter tells you the computer has no record of your reservation. Sorry about that!

Now suppose that this system had been designed with transactions:

1. You contact Travel Agent #1 to book a flight to Hawaii. Travel Agent #1 opens the database and reads out the available seats. She finds that there is only one seat left on the flight that you want.

2. While you are considering taking the seat, a different passenger contacts Travel Agent #2 about the same flight. Travel Agent #2 queries the database, finds out about the one open seat, and tells her prospective traveler about it.

3. Both you and the other passenger decide to take the seat. Both travel agents enter the data at about the same instant. Travel Agent #1 happens to be just a bit faster--she starts a transaction and changes the database. Once the transaction has committed she tells you that you have a confirmed ticket. At about the same time Travel Agent #2's booking arrives at the database; when Agent #2 attempts to acquire a write-access transaction, she is told that the database is currently being changed. When your transaction is complete, she finds that she cannot sell the seat, because you have already bought it. She works with the other passenger to find a different flight.

4. You arrive at the airport. Your name is in the computer, and your reservation is confirmed. Aloha!

If you decide that you need the protection of transactions, you need to install Microsoft Transaction Server (MTS). Follow your IIS and MTS documentation to make MTS packages. Once you have set up MTS packages, you can write your scripts so that database accesses generate new transactions. Use the MTS Explorer to register the components responsible for database access with MTS.


CAUTION: If you register a component with MTS that has application- or session-scope, the MTS and the script are likely to become confused. Transaction resources are deactivated when they are not in use; you cannot be assured that the component will maintain state properly.
If you need to maintain state on a page that uses MTS-registered ActiveX components, give page scope to the components themselves, and then use Application or Session properties to record the scope. Pass that scope to and from the components as required.

You tell the IIS to enforce your database access with transactions by using the Transaction directive:

<%@ Transaction = value %>

where value can take one of four character strings:

Although a script can explicitly tell the MTS (by calling ObjectContext.SetAbort) that it wants to exit a transaction before the transaction has committed, in general the script cannot tell that an access failed. The failure may be associated with a network failure or a disk drive filling up. You should include two procedures in each page where transactions are used:


TIP: If the transaction aborts the database server will take care of restoring the database to its pre-transaction state. You should use your OnTransactionAbort event handler to reset any application, session, or local variables as necessary.

Using Components to Build Scripts

Both VBScript and JScript use objects to encapsulate some aspects of program behavior. If you're familiar with client-side VBScript, you know that you use CreateObject() to make a new instance of an object. In your ASP scripts you can use both built-in objects and ActiveX components. This section describes both kinds of objects. Once you know how to use components, you can assemble pages with ASP scripts and ActiveX components into ASP applications. ASP applications are described later in this chapter, in the section "ASP Applications."


CAUTION: In an ASP script, calling CreateObject() produces an error--use Server.CreateObject() instead.

In addition to using objects, you can also encapsulate behavior by using #include files and by writing procedures (such as VBScript subroutines or JScript functions). If you're already familiar with JavaScript, you may prefer to work in Microsoft's version of that language, JScript. You can learn more about JavaScript and its cousins in Chapter 16, "Adding JavaScript and VBScript to HTML."

You can direct the server to include another file in your ASP script by using the server-side include #include directive. If you write

<!--#include file="myFile.inc"-->

the server will look in the directory that includes your ASP file for the file named myFile.inc, and it will use that file as though it were actually included in your ASP file.


NOTE: You should avoid exposing the actual paths on your hard drives to Web users. IIS allows you to declare virtual directories, which serve as roots for Web applications or other sites on your server.
If you use virtual directories on your server, use the form

<!--#include virtual="/myApp/myFile.inc"-->

to tell the server to look for the included file in the myApp virtual directory.


Built-In Objects  We've already seen some of the objects built into the server, such as Request and Response. The full list of built-in objects includes these six objects:


TIP: To take maximum advantage of Microsoft-supplied objects, be sure to read about their methods and properties in the "Scripters Reference" section of your server's documentation.

ActiveX Components  In addition to procedures and built-in objects, you can write your own objects in a programming language such as Visual Basic.


NOTE: You can write ActiveX components in any language that supports the Component Object Model (COM), such as C, C++, or Java, as well as Visual Basic.

Once you have written them, you can call ActiveX components on a Microsoft server from ASP scripts, ISAPI applications, or other ActiveX components.


Microsoft has already supplied 12 ActiveX components that are useful in ASP scripts:


NOTE: Microsoft does not officially support the Content, PageCounter, or PermissionChecker components. You can get support from other users of these components in the microsoft.public.inetserver.iis.activeserverpages newsgroup or through the Active Server Pages mailing list. If you don't have that newsgroup on your local news server, read it on news:msnews.microsoft.com.

To subscribe to the Active Server Pages mailing list, send mail to
listserv@listserv.msn.com
with

subscribe Denali [firstname lastname]
in the body of the message.

Unlike supported components, the full name of these components begins with ISSample. Thus, to make a new instance of PermissionChecker in VBScript, write
Set thePermissionChecker =
Server.CreateObject("IISample.PermissionChecker")


To make a new instance of an ActiveX component, use the Server.CreateObject() method and specify the registered name (PROGID). Thus, to make a new ad rotator in VBScript, write

<% Set theAdRotator = Server.CreateObject("MSWC.AdRotator") %>

You can also use a special version of the <OBJECT> tag to make a new object:

<OBJECT RUNAT=Server ID=theAdRotator PROGID="MSWC.AdRotator">
</OBJECT>

Be sure to include the RUNAT=Server attribute so that the instance is made on the server, and not on the client computer.

Setting Component Scope  When you make a new instance of an ActiveX component, you can decide to make that instance accessible from any of three levels:

Professional programmers generally avoid global variables such as application-scope components. Most ASP scripters prefer to use page-scope or, at most, session-scope.

By default, new instances have page-scope. You can set session-scope or application-scope with the <OBJECT> tag:

<OBJECT RUNAT=Server SCOPE=Session ID=MyAd PROGID="MSWC.Adrotator">
</OBJECT>

or

<OBJECT RUNAT=Server SCOPE=Application ID=MyID
CLASSID="Clsid:00000293-0000-0010-8000-00AA006D2EA4">
</OBJECT>


NOTE: If you choose to set up application-scope instances, place the <OBJECT> tag in the file Global.asa.

You can also use Server.CreateObject() to specify the scope by making the new instance a property of the session or application:

<% Set Session("MyAd") = Server.CreateObject("MSWC.Adrotator") %>


TIP: If you use Server.CreateObject() to make a new instance, the instance comes into existence immediately. If you use the <OBJECT> tag, the instance isn't built until it is referenced. For session-scope instances, therefore, you get better performance if you use <OBJECT> tags.
For additional performance improvements, make sure that components with application- or session-scope have their threading model set to "Objects Marked as Both." These objects will be shared among more than one user--if you use a single-threaded or free-threaded model, one user may be blocked while another user is using the instance.

ASP Applications

Once you know how to write ASP scripts and call components, you can assemble Active Server Pages and components into ASP applications. Define a directory to hold the pages; all of the ASP files inside that directory or its subdirectories are part of a single application. By using that design, you can have more than one application on your server.

When you write Web applications you must address the fact that HTTP is a stateless protocol. That is, the server cannot tell whether two HTTP requests come from the same user or two different users. Similarly, if a user makes a particular choice on one page, HTTP does not give the server a way to remember that choice and use it on future pages.

Recall from the previous section that Microsoft has built Application and Session objects into the ASP model. You can use these two objects to remember information from one HTTP request to the next. If you store information in the Application object, that information will be shared among all users of the application. If you store the information in the Session object, the information will be associated with a single user as he or she moves through the application.


NOTE: Often a user abandons an application without completing the last page. For example, an on-line shopper may fill a "shopping cart" with items and never check out. You should set the session time-out so that, after some period of inactivity, the server resources associated with the session are released. (The default time-out period is 20 minutes.)

Managing Applications

You should place a file named Global.asa in your application's root directory. Here you can declare object instances that have application- or session-scope.

Starting and Ending an Application  When a user first accesses a page of the application, the server looks at the Global.asa file and calls the Application_OnStart procedure, if it exists. Similarly, when the server is shut down, the application stops, and the server calls Application_OnEnd. Listing 35.5 shows how to write an Application_OnStart procedure.

Listing 35.5  global.asa--Add an Application_OnStart Procedure to global.asa to Provide Start-Up Processing

<SCRIPT LANGUAGE=VBScript RUNAT=Server>
Sub Application_OnStart
...
End Sub
</SCRIPT>


NOTE: You can also use the Unload button in Internet Service Manager to stop an application. The server will call Application_OnEnd, just as it does when the server is shut down.

Storing Data at the Application Level  One way to think of the Application object is as a dynamic array. You can store variables and their values in the Application object; such variables are available to any page of the application. For example, suppose you want to feature a particular product in a sales application. You might place the following line in Global.asa.

<% Application("FeaturedProductSKU") = "1269109" %>

Now, on any page, you can use Application("FeaturedProductSKU") to find the current featured product. You might pass this number to a database, look up a product description and price, and place that information on various pages.

Managing Sessions

When a user first accesses any ASP page in an application, the server generates a unique number, called the SessionID. Then it sends that SessionID to the user's browser, asking the browser to make a cookie for the SessionID.


CAUTION: Not all browsers support cookies, and not all users accept cookies. Some users ask their browsers to warn them when they are offered a cookie--the users get a warning such as the one shown in Figure 35.4.
If a user doesn't accept the cookie, or the browser can't store it, none of the Session information will be available to the application.
To learn other methods of preserving state, see Chapter 20, "Preserving Data," of Webmaster Expert Solutions (Que, 1996).

FIG. 35.4
Some users prefer not to accept cookies, or want to be warned before they accept them.

Starting and Ending a Session  As an ASP scripter, you can use the Session to maintain user state in any of three ways:

A session will end when the session time-out expires. For example, if the time-out value is 20 minutes, the server resources associated with the session are released 20 minutes after the user last requests or refreshes a page.

You can explicitly end a session by calling Session.Abandon. For example, if you are writing a shopping-cart application, you may want to end the session after the user has checked out. This design prevents a user from returning to a completed order, modifying it, and checking out again.


NOTE: The cookie set by the server does not have an expiration date, so it won't be stored on the user's hard drive. If a user starts a session then exits the browser and restarts it, the SessionID is lost and the user must start a new session when he or she returns to the application.
If you need to store data on the user's hard drive (so that it will be available after the user has closed the browser) write a cookie with an expiration date:
<%
Response.Cookie("preference") = "text-only"
Response.Cookie("preference").Expires = "January 1, 1999"
%>


CAUTION: Browsers differ regarding whether the elements of a URL are case-sensitive. To Netscape Navigator, the intranet application http://myapp/ has a different URL from http://MyApp/. To Microsoft Internet Explorer, both URLs are the same. If you set a cookie on a page named http://myapp/page1.asp and attempt to retrieve it from http://MyApp/page2.asp, Explorer will give you the cookie, but Navigator will not.
The solution is to make sure that you use case consistently whenever you write a link in your application.

If you don't plan to use the Session object or its associated capabilities on a particular page, you can get a performance boost by marking a page as sessionless. Place the following line as the top line of your ASP file:

<%@ EnableSessionState=False %>

Suppose you have an application with two frames. If Frame 1 needs to use Session features but Frame 2 does not, mark Frame 2 as sessionless. Many browsers will then request both frames--Frame 2 may well be downloaded to the user's machine while the server is processing the scripts in Frame 1.

Storing Data at the Session Level  You can associate user-specific data with the Session object. Suppose you have the user fill out a form that requests the user's first and last name. You might write

<% Session("FirstName") = Request.QueryString("first") %>
<% Session("LastName") = Request.QueryString("last") %>

Then, on subsequent pages, you might write

<H1>Welcome, <%= Session("FirstName") %></H1>

Application Security

If you're operating a Microsoft Internet Information Server, you should take the time to become familiar with Windows NT security. Microsoft uses system-level security as the foundation for ASP application security when the user accesses the application locally.

In order for a user to access your application over the Web, you must set up to three access permissions:

If you want to restrict access to authorized users only, use your Web server to set either Basic Authentication or Windows NT Challenge/Response Authentication, and disable anonymous access.

If you choose Basic Authentication, the user is prompted for a username and password.

If you choose Windows NT Challenge/Response Authentication, the server requests an X.509 certificate from the client browser. This method is more secure than Basic Authentication, but not all browsers support it, and many users do not yet have certificates. (You can refer users to Verisign, at http://www.verisign.com/, to get a personal certificate, or your organization can operate its own Certificate Server.)

Internationalization

Sometimes you need to make an application accessible to people who prefer a language other than English. Some of these users can work with a variant of the Latin character set; others, such as readers of Japanese, Chinese, and Korean, need a much larger character set. In order to internationalize your application, you may need to make two changes:

Setting the Code Page  The code page specifies the character set used on the page. Internally, Microsoft Internet Information Server uses Unicode, the 16-bit per character standard. If your page uses characters that fall outside the standard ASCII range (0-127) some characters may not be displayed properly unless the browser is set to use the same character set as the page.


NOTE: Character encodings are typically specified by the number of their international standard (for example, ISO-8859-1). Code pages are proprietary--the most common ones are specified by IBM and Microsoft. Code pages are specified by number (for example, code page 950 specifies some common Chinese characters). Table 35.1 shows common code pages and their character set (charset) equivalents.

Table 35.1  Charsets and Code Pages

Charset Name Codepage Number
U.S. 437
Baltic 775
Multilingual (Latin I) 850
Slavic (Latin II) 852
Cyrillic (Russian) 855
Turkish 857
Portuguese 860
Icelandic 861
Hebrew 862
Canadian-French 863
Arabic 864
Nordic 865
Russian 866
Modern Greek 869
Thai 874
Japanese 932
Chinese (PRC, Singapore) 935
Korean (Hangul) 949
Chinese (Big 5) 950

Windows NT does all of its internal processing in Unicode. If you are working with ActiveX components that work with Unicode, and all of the visitors to your site are on systems that handle Unicode, you may never need to set the code page. On the other hand, most computers will need to switch from Unicode to some single-byte encoding for many years to come. Windows 95, for example, does not use Unicode. When Windows 95 is sold, it is typically sold with a single language pack--machines sold in the U.S. are set up to work in English, while machines sold in Brazil are loaded with Portuguese. Microsoft supports three language platforms with Windows NT. Platform WE is associated with Western languages such as English, Spanish, French, and German. The number of characters and symbols is small--below 256--and the characters are read from left to right. Platform ME is associated with languages such as Turkish, Hebrew, and Arabic. The size of the alphabet is still small, but the text flows from right to left. Platform FE is used for Asian languages such as Chinese, Japanese, and Hangul (the major character set in Korea). There are thousands of characters. In print, the characters are read from top to bottom, though on computers a left to right ordering is culturally acceptable.

You can set the code page for a single ASP page by placing the following directive in the first line of the page:

<%@ CODEPAGE= 932 %>

Occasionally you will need to set the code page to a different value temporarily while the script is running. You can make this change by following a six-step procedure:

1. Use a CODEPAGE directive to set the page's default code page.

2. Store the code page as a Session property. For example, in VBScript you might write
<% Session("OriginalCodePage") = Session.CodePage %>
3. Set Session.Codepage to a new value.

4. Work in the new code page.

5. Restore the original code page.

6. Send content back to the client.

Setting the Locale  Many elements of computer processing depend upon the country and culture where the processing is being done. Some obvious points include how dates and currency are displayed. Some less obvious changes include how items are compared and sorted into lists. The Windows operating system provides for many different locales; you can set the locale by specifying the Locale ID (LCID) in the first line of the page:

<%@ LCID = LCID %>

Tools and Techniques for Building Your Active Server Pages

Previous sections of this chapter focused on the technology used in Active Server Pages. This section describes the mechanics of writing an ASP. This section shows:

Writing ASP Pages and Applications

You can learn about Active Server Pages by using the Personal Web Server (which runs on Windows 95 and Windows NT 4.0 Workstation machines). For simple pages and small applications, all you need to get started is a text editor. As your applications grow, you'll find yourself spending much of your time maintaining links, adding new features, and managing database connections. This section describes three tools you may want to use to reduce your workload:

Working on a Single Page  Begin your experience with ASPs by writing a few ASP-enhanced pages. While you may eventually write complete applications, you'll learn fastest if you work through one of Microsoft's tutorials or just build a few pages on your own.


TIP: Use the sample ASPs that come with your server's Roadmap as a starting point for learning to script. Microsoft's documentation also includes nice tutorials on both VBScript and JScript.
After you've had enough experience to determine which language you prefer, get a comprehensive reference book on that language.

When you're writing a single Active Server Page, start by writing the page's HTML. You can use any tool you like to lay out the HTML, including a simple text editor such as WordPad. Include some "placeholder" HTML for the results of your ASP scripts. Later, when you write the scripts, you can comment out or even remove the placeholder code.

Next add any processing directives you need; make sure they appear in the top line of the file. Finally, add the ASP scripts and test the page with your browser.

Writing a Small Application  If you're building a full application, set up a virtual directory to hold the application's pages. Consider starting your implementation by writing the global.asa page. Use the techniques given for a single page to write the first page in the application. Use this page to check application-scope and session-scope variables and components. Make sure they're working as expected. Continue building the site by adding the rest of the pages. Some of these pages will end up being Active Server Pages; others will be built with static HTML only. Build a mock-up of your application entirely out of static HTML, and show that mock-up to the people who will use the application. (If the application is for an intranet, you may be able to get input from the whole user community. If you're developing an Internet application, get input from representative users.)

Once you and your users are satisfied with the design, add ASP scripts and components, and include any database connections you need. Keep an eye on the total number of ASPs in your application. Remember, the more ASPs you have, the slower your server will run. If you're running a database server and a Microsoft Transaction Server on the same machine that hosts your IIS, your host may become overloaded. If you spread the load over multiple machines, watch the load on your network to make sure it doesn't slow your application down.


TIP: Many professional software developers allocate 50 percent of their time on a project to requirements analysis and design, and another 25 percent or so to testing. Before you start writing VBScript or JScript, take some time to lay out the application on paper. You may even want to use index cards to represent each page, and then move them around until you and the end users are happy with the design.


ON THE WEB: http://www.microsoft.com/frontpage/  If you want to stick with Microsoft products and need some help getting your HTML together, consider Microsoft FrontPage 98. From this page follow links to a downloadable beta copy or an on-line demo. (Mac users, learn about the Macintosh version of the product at http://www.microsoft.com/frontpage/brochure/macpd.htm.)

Using Visual InterDev

While a simple text editor is sufficient to get you started with Active Server Pages, you'll find that the amount of time maintaining the pages grows dramatically when you have a multi-page application, particularly if you are using the application to access databases. You can reduce the amount of maintenance time by using Microsoft's development tool, Visual InterDev.


ON THE WEB: http://www.microsoft.com/products/prodref/177_ov.htm  Visit Visual InterDev's home page to learn more about its features, system requirements, and pricing.

You can run Visual InterDev on a Windows 95 machine or under Windows NT. To help you evaluate the product, you might want to download a 12-minute demo from http://www.microsoft.com/vinterdev/us/download/autodemo.htm.

Debugging ASP Scripts

Microsoft introduced the Script Debugger for client-side scripts in VBScript and JScript with MSIE 3.02. Starting with MSIE 4.0, they have offered a script debugger that will work with ASP scripts as well as client-side scripts.

Like most symbolic debuggers, you can use the Script Debugger to do the following:

In addition, the Debugger understands HTML syntax and can show you an outline of your page. The Debugger also understands both VBScript and JScript and uses color codes to show the syntax of your scripts.

The latest pre-release of the Script Debugger understands Java and ActiveX; Microsoft promises that these capabilities will be integrated into a coming release of the Debugger.


ON THE WEB: http://www.microsoft.com/intdev/scriptie/dbgdown-f.htm  You can download a copy of the Script Debugger from Microsoft's site. Learn about the debugger in general at http://www.microsoft.com/workshop/prog/scriptIE/default.HTM.


Previous chapterNext chapterContents


© Copyright, Macmillan Computer Publishing. All rights reserved.