BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


VBScript in a Nutshell
VBScript in a Nutshell By Paul Lomax, Matt Childs, Ron Petrusha
May 2000
Pages: 508

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction
Microsoft Visual Basic Scripting Edition, commonly known as VBScript, is a relative of the Visual Basic family, which includes the Microsoft Visual Basic Development System (the retail version of Visual Basic in its Enterprise, Professional, and Learning Editions) and Visual Basic for Applications (the language component of Visual Basic, which is included in the individual applications within Microsoft Office and Microsoft Project, as well as in a host of third-party applications).
VBScript is, for the most part, a subset of the Visual Basic for Applications programming language. It was developed so that the millions of Visual Basic developers could leverage their knowledge of VB/VBA Internet scripting. One of the strengths of VBScript is that it uses the same familiar and easy syntax that has made VBA so popular as a programming language, making it very easy to learn for those who have some Visual Basic background. In addition, VBScript is fairly easy to learn for those without any programming experience.
Ironically, VBScript started as a client-side scripting language to create interactive web pages, but in this area it had a major liability: it was and is not supported by Netscape Navigator. Instead, the two major web browsers on the market, Navigator and Microsoft Internet Explorer, both supported a common scripting language, JavaScript, which became the de facto standard for client-side scripting. Despite its failure in this area, however, VBScript rapidly became the major scripting language in three other areas:
  • Active Server Pages (ASP) applications
  • Outlook forms
  • Windows Script Host (WSH) scripts
Version 1.0 of VBScript was initially introduced in Microsoft Internet Explorer (MSIE) 3.0, which was released in 1996. Its intended use at that point was to allow web page developers to enhance their pages through client-side scripting. In contrast to plain HTML, which supported the creation of only static web pages, the combination of HTML and client-side script allows the creation of web pages that are both interactive and responsive to the user. For instance, a script could allow the web page to display extended information about hyperlinks as the user's mouse passes over them, or it could be used to validate data entered by the user without submitting it to the server. A script could even be used to generate a web page on the fly, without using any "hard-coded" HTML. The only limitation to VBScript as a language for client-side scripting was that VBScript could be used only inside of Internet Explorer, the only browser to support it, and thus was suitable only for use on corporate intranets that had standardized on MSIE. Using VBScript for client-side scripting on MSIE is discussed in Chapter 8.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
VBScript's History and Uses
Version 1.0 of VBScript was initially introduced in Microsoft Internet Explorer (MSIE) 3.0, which was released in 1996. Its intended use at that point was to allow web page developers to enhance their pages through client-side scripting. In contrast to plain HTML, which supported the creation of only static web pages, the combination of HTML and client-side script allows the creation of web pages that are both interactive and responsive to the user. For instance, a script could allow the web page to display extended information about hyperlinks as the user's mouse passes over them, or it could be used to validate data entered by the user without submitting it to the server. A script could even be used to generate a web page on the fly, without using any "hard-coded" HTML. The only limitation to VBScript as a language for client-side scripting was that VBScript could be used only inside of Internet Explorer, the only browser to support it, and thus was suitable only for use on corporate intranets that had standardized on MSIE. Using VBScript for client-side scripting on MSIE is discussed in Chapter 8.
Version 2.0 of VBScript was introduced in Internet Information Server (IIS) 3.0 in 1997. The most notable additions to the language were "web-friendly" language elements (such as lightweight Format... functions and the Filter, InStrRev, Reverse, and Join functions) that in most cases were incorporated into the VBA language only with the release of VBA 6.0. In addition, VBScript 2.0 added support for a number of intrinsic constants to make code more readable and also implemented the Const statement to allow user-defined constants. Finally, the CreateObject and GetObject functions were added to instantiate external COM objects; these functions, which are inoperative in a client-side scripting environment, are essential for supporting components that are capable of extending a scripted server-side application.
This new version of VBScript was released with IIS to support server-side scripting using ASP. ASP is itself the object model exposed by IIS that allows your script to access information about the client's request and to write to the server's output stream. An
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What VBScript Is Used For: Gluing Together Objects
We've outlined the four major areas in which VBScript is used, but if we were to look at how scripts are written in each of these environments, we'd quickly note far more differences than similarities. (Because of this, we've devoted a separate chapter to each area in which VBScript is commonly used.) Yet this is misleading. If we take a more high-level view, we can see that the role of VBScript and the role of the environment in which its scripts are run are broadly similar, regardless of the environment's unique features.
Typically, scripting languages are described as "glue" languages. That is, they are used to glue things together. That means that the glue itself does relatively little—it simply binds the rest of the script together. The "things" that the scripting language binds together are components or objects—that is, the objects exposed by the environment for which the script is being written (like ASP, MSIE, Outlook, or WSH), as well as objects that are exposed by external applications, environments, or components (such as ActiveX Data Objects, Collaboration Data Objects, Microsoft Word, Microsoft Excel, or custom components created in Visual Basic). A map of a single high-level object (such as the Microsoft Word application, for instance, which is represented by the Application object) along with its child objects is known as an object model .
One type of object model that's particularly suitable for scripting is shown in Figure 1.1. In this particular case, the figure shows the ASP object model. Two features are particularly noteworthy: its flatness and its lack of interdependence. (Contrast it, for example, with the Microsoft Word object model, a portion of which is shown in Figure 1.2.) In particular, a flatter object model and/or one whose objects have a fair degree of independence has a number of advantages:
Ease of navigation
Since the object model is flat, you don't have to be concerned with navigating upward and downward through the object hierarchy. This makes coding easier, reduces the time spent debugging, and improves performance.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Differences Between VBScript and VBA
VBScript is a subset of the Visual Basic for Applications language. There are several features that VB and VBA programmers have become accustomed to that are not present in VBScript. This does not lessen the usability of VBScript: it only serves to reinforce that VBScript is meant for scripting and not full-blown client/server application development or COM component development. Let's take a look at a few of the larger differences between VBScript and VBA:
VBScript is an untyped language.
Unlike Visual Basic and Visual Basic for Applications, in which the developer can define the data type of a variable in advance, all variables in VBScript are variants. There are subtypes to handle different types of data, and you can use these as you would the traditional data types in Visual Basic. For more information, see Chapter 3.
VBScript is not compiled.
Although we speak of VBScript code being " compiled" as it is downloaded, VBScript is nevertheless an interpreted language. That means that the code that you write is interpreted into machine language each time you run the script, which imposes a definite performance penalty. Visual Basic programmers who have worked with the language for a long time can remember when Visual Basic was also an interpreted language. Is this a big deal for VBScript? We don't believe so, since most scripting languages (JavaScript, Perl, Python, etc.) are interpreted rather than compiled. And code portions whose performance are particularly sensitive can be removed from the VBScript code and placed in a compiled COM component that the VBScript code instantiates.
VBScript does not support early binding.
Because variables are untyped and code is not compiled, all external objects instantiated in VBScript code are necessarily late-bound. This has a number of implications. First, late binding typically entails a substantial performance penalty in comparison to early binding. Second, while the properties and methods of early-bound objects can be examined in Visual Basic or hosted VBA environments using the Object Browser, this is not the case with late-bound objects. Finally, the help facilities available for early-bound objects in VB and VBA (like Auto List Members and Auto Quick Info) are not available, making syntax errors more likely and ready access to good documentation all the more necessary.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Program Structure
In order to write VBScript, you have to know how to structure your code so that your scripts and programs execute properly. Each of the different types of VBScript that you write has different rules regarding its structure. We'll look at each of these in turn. We'll also examine the ways in which your host environment allows you to import VBScript code libraries, thus allowing you to create reusable code. Finally, we'll end the chapter with a discussion of VBScript usage to write class modules. First, though, it's important to cover the basic structures of VBScript that are relevant to all of the different script types: that script-level code calls code in individual functions or procedures.
Functions and procedures (or subroutines) are central to modern programming. Dividing our script into subroutines helps us to maintain and write programs by segregating related code into smaller, manageable sections. It also helps to reduce the number of lines of code we have to write by allowing us to reuse the same subroutine or function many times in different situations and from different parts of the program. In this section, we'll examine the different types of subroutines, how and why they are used, and how using subroutines helps to optimize code.
The Sub...End Sub construct is used to define a subroutine; that is, a procedure that performs some operation but does not return a value to its calling program. Blocks of code defined as subroutines with the Sub...End Sub construct can be called in two ways:
Automatically
Some subroutines provide the means by which an object interfaces with the script. For instance, when a class defined with the Class...End Class construct is initialized, its Initialize event, if one has been defined, is executed automatically. For subroutines of this type, the routine's name can be constructed in only one way, as follows:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Functions and Procedures
Functions and procedures (or subroutines) are central to modern programming. Dividing our script into subroutines helps us to maintain and write programs by segregating related code into smaller, manageable sections. It also helps to reduce the number of lines of code we have to write by allowing us to reuse the same subroutine or function many times in different situations and from different parts of the program. In this section, we'll examine the different types of subroutines, how and why they are used, and how using subroutines helps to optimize code.
The Sub...End Sub construct is used to define a subroutine; that is, a procedure that performs some operation but does not return a value to its calling program. Blocks of code defined as subroutines with the Sub...End Sub construct can be called in two ways:
Automatically
Some subroutines provide the means by which an object interfaces with the script. For instance, when a class defined with the Class...End Class construct is initialized, its Initialize event, if one has been defined, is executed automatically. For subroutines of this type, the routine's name can be constructed in only one way, as follows:
Sub objectname_event
                        
For example, Sub Class_Initialize is a valid name of a subroutine. This type of subroutine is known as an event handler or an event procedure .
Referring to it by name
A subroutine can be executed at any time by referring to it by name in another part of the script. (For additional details, including the syntax required to call subroutines, see Section 2.1.2 later in this chapter.) While it is possible to execute event procedures in this way, this method is most commonly used to execute
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Class Modules
Since VBScript 5.0, developers have been able to create classes to use in their scripts—a definite step along the road of object-oriented programming in VBScript. Writing classes with VBScript is very similar to writing COM objects with VB. Before we look at writing an actual class, let's go over some of the terminology so we are clear on what we are doing and what we are referring to.
A class is simply the template for an object. When you instantiate an object (that is, create an instance of a class) in code, VBScript makes a copy of the class for your use. All objects come from a class. Writing the class is simply a matter of creating a design for the objects that you want to use.
So naturally, it follows that an object is simply a copy of the class that you are making available to your program. You can make as many copies as you like for your use. The copies are temporary structures for holding information or creating interactions. When you are done with the objects, you can release them. If you need another one, you can instantiate another copy.
In VBScript, classes must be created in the scripts where you want to use them or they must be included in the scripts that use them. Since VBScript isn't compiled, you don't have the advantage of being able to write a set of VBScript COM classes that are usable outside of the scripts in which they're defined, or that can be easily accessed by programs and scripts written in other languages.
You declare a class using the Class...End Class construct. The syntax of the Class statement is:
Class classname
               
where classname is the name you want to assign to the class. It must follow standard VBScript variable naming conventions.
Classes can contain variables, properties, methods, and events. How many of these and of what types is completely up to you. It is possible to have an object that has no properties or methods and supports only the two default events, but it won't be a very useful class.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Script Level
We've seen that code can be organized into functions, subroutines, and classes, and that some subroutines (and an occasional function) can be executed automatically if they are event handlers and the event they handle fires. However, that seems to offer a relatively limited "hook" for script to run, nor does it seem to make it possible for a script to perform whatever initialization might be required in order for its event handlers to function successfully.
The script level is the answer to this dilemma. Script-level code—that is, code outside functions and subroutines—is executed automatically when the script loads or as the HTML on the page is parsed. The precise meaning of script-level code and the exact way in which code at script level is executed depends on the host environment for which the script is written. We'll examine these in turn.
In ASP, script-level code is synonymous with code in direct ASP commands—it is script that is preceded by the <% or <%= tags and terminated by the %> tag. (For details on how script is embedded within in ASP page, see Chapter 5.) This code is executed automatically as the page's HTML is parsed.
It is also possible to include script-level code in <SCRIPT>...</SCRIPT> tags in an ASP. However, this is not genuine script-level code: aside from variable declarations, the order in which this code is executed is undefined.
Figure 2.1 shows the web page produced by Example 2.7, which illustrates script-level code in an Active Server Page. Note that although the variable x is defined and assigned a value at script level within the <SCRIPT> tag, the variable declaration is recognized but the variable assignment isn't. We can determine this because we've used the Option Explicit statement to require variable declaration, but the VBScript language engine did not raise an error when it first encountered the use of x on the second line after the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Reusable Code Libraries
We've now discussed all of the basic principles of structuring VBScript programs, of constructing subroutines that can be used by various parts of your program, of building functions that perform calculations and other manipulations and pass the result back to the calling part of the program, and of creating classes that allow you to encapsulate real-world processes and objects. The emphasis on subroutines, functions, and classes, though, raises another issue—that of code reuse. Typically, classes are defined so that they can be used in a variety of applications. Similarly, many subroutines and functions are intended not only to reduce code in a single application, but also to be "black boxes" that can provide some service to multiple applications.
Although it generally hasn't been emphasized, and is dependent on the host platform, VBScript code can be reused on three of the four host platforms discussed here. The only platform that doesn't support code reuse is Outlook forms. That means that if you're scripting for WSH, ASP, or MSIE, you can develop code libraries that you import into your script.
You can import HTML, client-side script, or server-side script into an ASP file by using the #include server-side directive. Its syntax is:
<!-- #include PathType = sFileName -->
where PathType is one of the following keywords:
File
Indicates that sFileName is relative path from the current directory
Virtual
Indicates that sFileName is a full virtual path from the web server's root folder to the file to be included
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Data Types and Variables
In this chapter, we'll discuss VBScript's rather unusual support for a single data type before turning to variables and constants in VBScript.
Unlike Visual Basic and Visual Basic for Applications, VBScript has only one main data type, called a variant. A variant is a very special data type, though, since it can contain many different types of data, and can automatically select the most appropriate data type for the particular context in which it is being used. A simplified view of a variant is that it can hold both string data (characters) and numerical data; however, internally it is much more complex, which permits it to hold a wide range of different numeric types.
While the only data type recognized by VBScript is the variant, any item of variant data belongs to a particular subtype. Let's look at the range of subtypes—or the different types of data—that a variant can hold:
Empty
The Empty subtype is automatically assigned to new variables when you declare them, but before you explicitly assign a value to them. For instance, in the code fragment:
Dim var1, var2
var2 = 0
the subtype of var1 is Empty, whereas var2 is only Empty for the brief period of time between the execution of the Dim statement on the first line (which declares a variable; it is discussed later in this chapter in Section 3.2.5) and the assignment statement on the second line. In addition, a variable's subtype is Empty if it has been explicitly assigned a value of empty, as in the following code fragment:
Dim var1
var1 = Empty
Null
Null is a special data subtype used to indicate that a variable does not contain any valid data. Usually, a variable is assigned a null value to indicate that an error condition exists. In order for its subtype to be Null, a variable must have a Null value assigned to it explicitly, as in the following line of code:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
VBScript Data Types: The Many Faces of the Variant
Unlike Visual Basic and Visual Basic for Applications, VBScript has only one main data type, called a variant. A variant is a very special data type, though, since it can contain many different types of data, and can automatically select the most appropriate data type for the particular context in which it is being used. A simplified view of a variant is that it can hold both string data (characters) and numerical data; however, internally it is much more complex, which permits it to hold a wide range of different numeric types.
While the only data type recognized by VBScript is the variant, any item of variant data belongs to a particular subtype. Let's look at the range of subtypes—or the different types of data—that a variant can hold:
Empty
The Empty subtype is automatically assigned to new variables when you declare them, but before you explicitly assign a value to them. For instance, in the code fragment:
Dim var1, var2
var2 = 0
the subtype of var1 is Empty, whereas var2 is only Empty for the brief period of time between the execution of the Dim statement on the first line (which declares a variable; it is discussed later in this chapter in Section 3.2.5) and the assignment statement on the second line. In addition, a variable's subtype is Empty if it has been explicitly assigned a value of empty, as in the following code fragment:
Dim var1
var1 = Empty
Null
Null is a special data subtype used to indicate that a variable does not contain any valid data. Usually, a variable is assigned a null value to indicate that an error condition exists. In order for its subtype to be Null, a variable must have a Null value assigned to it explicitly, as in the following line of code:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables and Constants
With all this data flying around inside your script, you need some way to keep track of it. In reality, the data you are using—whether it is data you create as part of the program, or data that is entered by the user, or data that you access from a database—is held somewhere in the computer's memory. Think of the nightmare you'd have trying to keep track of just which memory location your particular piece of data was occupying (completely ignoring the possibility that its memory location might change while the program executes). Those nice people who write the software we use to create our programs and scripts solved this problem a long time ago by giving us variables and constants.
A variable is a placeholder or recognizable name for a memory location. This location is of no consequence to us; all we have to do is remember the name. When we use the name, the script engine will go to the correct memory location and either retrieve the data stored there or change the data, depending upon our instructions. It is important therefore to learn the rules for naming variables:
  • Variable names can be no more than 255 characters in length. Variable names tend to become pretty unreadable after about 20 characters anyhow, which then defeats the purpose of having longer variable names.
  • The name must be unique within the scope it is being used. Don't worry too much about scope; we'll go through that a little later. For now, remember not to use the same name for more than one variable in the same procedure—it makes sense, really.
  • The variable name must start with an alphabetic character. 2myVar is illegal, but myVar2 is good.
  • Variable names cannot include either a period or a space. If you need to split up the variable name in some way to improve its readability, use the underscore character, like this:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Error Handling and Debugging
Errors, bugs, and therefore debugging are a part of life for a programmer. As the saying goes, if you haven't made any mistakes, then you aren't trying hard enough.
Dealing with errors actually involves two very different processes: error handling and debugging. Error handling is a combination of coding and methodology that allows your program to anticipate user and other errors. It allows you to create a robust program. Error handling does not involve weeding out bugs and glitches in your source code, although some of the error handling techniques covered in this chapter can be used to great advantage at the debugging stage. In general, error handling should be part of your overall program plan, so that when you have an error-free script, nothing is going to bring it to a screeching halt. With some sturdy error handling in place, your program should be able to keep running despite all the misuse that your users can—and certainly will—throw at it.
The following ASP page illustrates some simple error handling:
<HTML>
<HEAD><TITLE>Error Checking</TITLE>
<BODY>
<SCRIPT LANGUAGE=VBSCRIPT RUNAT=SERVER>

Dim n, x

n = 10 
x = Request.Form.Item("txtNumber")

If x = 0 Or Not IsNumeric(x) Then
  Response.Write "x is an invalid entry"
Else
  y = n / x
  Response.Write y
End If

</SCRIPT>

</BODY>
</HTML>
The error handling in this example is the best kind—it stops an error before it can occur. Suppose you hadn't used the conditional If...Else statement and had allowed any value to be assigned to x. Sooner or later, some user will fail to enter a value or will enter a zero. Possibly in both cases, and certainly in the latter case, this would generate the "cannot divide by zero" runtime error. So error handling, as this code fragment illustrates, is as much about careful data validation as it is about handling actual errors.
While preventing an error before it can occur is one approach to handling errors, the second is to handle the error after it occurs. For example, the following code fragment is a "real" error handler that we'll examine later in this chapter, so don't worry about the syntax at this stage. Like the previous code fragment, it aims at handling the "cannot divide by zero" runtime error, in this case only after it occurs:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Debugging
You've designed your solution and written the code. You start to load it into the browser with high hopes and excitement, only to be faced with an big ugly gray box telling you that the VBScript engine doesn't like what you've done. So where do you start? Well, I find that another cup of coffee helps, but most of the time the error's still there when I rerun the script.
When confronted with a problem, you first need to know the type of error you're looking for. Bugs come in two main flavors:
Syntax errors
You may have spelled something incorrectly or made some other typographical or syntactical error. When this happens, usually the program won't run at all.
Logical errors
Although syntactically correct, your program either doesn't function as you expect, or it generates an error message.
Bugs appear at different times, too:
At compile time
If a compile-time error is encountered, an error message appears as the page is loading. This usually is the result of a syntax error.
At runtime
The script loads OK, but the program runs with unexpected results or fails when executing a particular function or subroutine. This can be the result of a syntax error that goes undetected at compile time or of a logical error.
Let's look at each type of bug individually. We'll begin by looking at syntax errors, first at compile time and then at runtime, before looking at logical errors.
Ordinarily, objects containing script are compiled as they are loaded, and are then immediately executed. Errors can occur at either stage of the process. And although the distinction between compile-time and runtime errors is rapidly losing its importance (error messages, for instance, describe only runtime errors, even if they occur at compile time), it is sometimes helpful to know that the entire script compiled successfully and that the error was encountered at a particular point in the script.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Error Handling
Error handling does not involve finding errors in your scripts. Instead, use error handling techniques to allow your program to continue executing even though a potentially fatal error has occurred. Ordinarily, all runtime errors that are generated by the VBScript engine are fatal, since execution of the current script is halted when the error occurs. Error handling allows you to inform the user of the problem and either halt execution of the program or, if it is prudent, continue executing the program.
There are two main elements to error handling in VBScript. The first is the On Error statement, which informs the VBScript engine of your intention to handle errors yourself, rather than to allow the VBScript engine to display a typically uninformative error message and halt the program. This is done by inserting a statement like the following at the start of a procedure:
On Error Resume Next
This tells the VBScript engine that, should an error occur, you want it to continue executing the program starting with the line of code which directly follows the line in which the error occurred. For example, in the simple WSH script:
On Error Resume Next
x = 10
y = 0
z = x / y
Alert z
a "Cannot divide by Zero" error is generated on the fourth line of code because the value of y is 0. But because you've placed the On Error statement in line 1, program execution continues with line 5. The problem with this is that when an error is generated, the user is unaware of it; the only indication that an error has occurred is the blank Alert box (from line 5) that's displayed for the user.
A particular On Error statement is valid until another On Error statement in the line of execution is encountered. This means that if Function A contains an On Error statement, and Function A calls Function B, but Function B does not contain an
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Common Problems Areas, and How to Avoid Them
There is much to be said for the old maxim, "The best way to learn is by making mistakes." Once you have made a mistake, found out what you did wrong, and rectified the error, you will—in general— have a much better understanding of the concepts involved and of what is needed to build a successful application. But to save you from having to experience this painful process of trial and error in its entirety, we'd like to share with you some of the most common errors that ourselves and other programmers we've worked with have made over more years than we care to remember. These types of errors are actually not unique to VBScript, nor in fact to VB, but to programming in general. In approximate order of frequency, they are:
  • Straight in at No. 1 in the charts this week are syntax errors generated by typing errors. This is a tough one; typing errors —the misspelled function call or variable name—are always going to creep into code somewhere. They can be difficult to detect, particularly because they are typing errors—we frequently train our eyes to see what should be there, rather than what is there. When the effect of the typing error is subtle, it becomes even more difficult to detect. For instance, in a client-side script, we had spelled LANGUAGE as LANGAUGE in coding the <SCRIPT> tag. The result was that MSIE immediately began reporting JavaScript syntax errors. This isn't surprising, given that in the absence of a valid LANGUAGE attribute, MSIE used its default scripting language, JScript. But when confronted with this situation, it takes a while to recognize the obvious—that the LANGUAGE attribute for some reason is improperly defined; instead, it seems that Internet Explorer and VBScript are somehow mysteriously "broken." The only real way to reduce the time spent scratching your head is to build code in small executable stages, testing them as you go. Another good tip is to use individual small sample scripts if you are using a function or set of functions for the first time and aren't sure how they'll work. That allows you to concentrate on just the new functions rather than on all the rest of the script as well. And perhaps the most effective technique for reducing troublesome misspelling of variables is to include the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: VBScript with Active Server Pages
At root, web servers are pieces of software: they receive an incoming client request and handle it by transmitting a stream of bytes back to the client. Getting the web server to do something else—for instance, to respond to user interaction by sending back one byte stream rather than another, to save user state information from page to page, to add data from a database to the byte stream returned to the client, or to perform backend processing on the client request—requires a web server extension. Traditionally, web server extensions for Windows were developed using two technologies: Common Gateway Interface (CGI) and Common Gateway Interface for Windows (WinCGI). These are out-of-process extensions that communicate with the web server through standard input and output (in the case of CGI) or initialization files (WinCGI), very inefficient methods that do not scale well. Microsoft Internet Information Server 1.0 added a new technology, ISAPI (Internet Server Application Programming Interface), that allowed developers to create applications or filters that ran in the same process as the web server, thus achieving better performance and greater scalability. Unfortunately, developing ISAPI applications and filters required an experienced C or C++ programmer, and thus was out of the reach of the vast majority of web content providers.
Active Server Pages was first introduced in Microsoft Internet Information Server 3.0 and allows web server extensions to be developed using scripts that can be written in any language that supports Microsoft's Component Object Model (COM) (although the most common language for developing ASP scripts is VBScript). This makes ASP application development accessible to more web content providers than any previous technology for creating shell extensions.
In addition, Active Server Pages allows for the use of server-side components (that is, of COM components written in any of a number of programming languages, most notably Visual Basic) to enhance and better control web applications. The reasons for developing an ASP component rather than a simple script include:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
How ASP Works
Active Server Pages is implemented as an IIS component—in fact, as an ISAPI filter—that resides in a dynamic link library named ASP.DLL . (ISAPI filters are custom web server extensions that are called for every HTTP request received by the web server.) If the file extension of the resource requested by the client is .asp , Active Server Pages is used to parse the file and handle the client request; otherwise, it is bypassed.
ASP does not view pages purely on a one-by-one basis. Instead, it organizes its pages into applications. An ASP application is the entire set of files that can be accessed in a virtual directory and its subdirectories. This notion of an ASP application allows you to define global variables whose values are shared across all users of your ASP application, as well as to have ASP save state information from a particular client's session.
When ASP is used to parse a web page, it first checks to see whether the request has originated from a new client. If the client is new, ASP checks the global.asa file (which is stored in the application's virtual root directory) to determine whether any session-level data is to be initialized. If the client's is the first request for the ASP application, ASP also checks global.asa for any application-level data as well. ASP then parses the HTML page, executes any script contained on the page, and includes any output from scripts into the HTML stream. Note that the output of ASP is HTML with or without client-side script; no server-side script contained in the ASP page is passed on to the client.
As we've noted, when ASP receives a request from a new user, it checks the global.asa file, which must be located in the ASP application's virtual root directory. If the request from the new user is the first request for the ASP application, the Application_OnStart event procedure, if it is present, is executed before the Session_OnStart event. When a user session ends, usually because the session has timed out, ASP checks
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Active Server Pages Object Model
Although VBScript is a powerful, flexible scripting language when used to develop ASP applications, you can do relatively little with VBScript by itself. That is, most of the power and efficiency of ASP becomes available only when you use VBScript to access the Active Server Pages object model. In an ASP application, each of the objects in the ASP object model is globally available throughout your script; you don't have to do anything special to instantiate ASP objects.
ASP includes six intrinsic objects, each of which are detailed in the following sections.
An object whose collections and property values are shared across all instances of the application. (An ASP application , once again, is the entire set of files that can be accessed in a virtual directory and its subdirectories.) The Application object supports the members listing in Table 5.1.
Table 5.1: Members of the Application Object
Name
Description
Contents Collection
Contains all application-scoped variables and objects added by script.
Lock Method
Locks the Contents collection, preventing other instances from accessing it until it is unlocked. Its syntax is Application.Lock( ).
OnEnd Event
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 6: Programming Outlook Forms
Until the release of Microsoft Office 2000, Microsoft Outlook was clearly an idiosyncratic member of the Office suite. First released in Office 97 and later released in an interim version as Outlook 98, Outlook was the sole member of the Office family to feature VBScript as its programming language. Outlook 2000 finally features support for VBA and for the VBA integrated development environment. However, VBScript remains in Outlook 2000 as the programming language behind Outlook's custom forms.
Designing and programming Outlook forms is a large topic that has been the sole focus of a number of books, most notably Building Applications with Microsoft Outlook, published by Microsoft Press and available in various editions covering different versions of Outlook. Our focus in this chapter will not be on designing, creating, or modifying Outlook forms, but rather on programming those forms with VBScript.
As a general purpose personal information management system (or PIM), Microsoft Outlook includes most of the general features that an individual or a group must perform, including such tasks as reading, sending, and organizing email, scheduling meetings, keeping notes, and maintaining a contacts list. The emphasis here, though, is on general; Outlook offers the basic set of features that most users require. In order to make Outlook capable of addressing the particular needs of individual users or groups of users, Microsoft added a number of customization and extensibility features to the product. These include Outlook's programmability (at an application level using VBA or a forms level using VBScript) and the ability to create custom forms.
By attaching VBScript code to either existing forms or new forms, you can modify the appearance or the behavior of the form, thus making it suitable for special applications. For example, you can:
  • Change the recipient of an email message based on the content of the message to which you are replying
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Why Program Outlook Forms?
As a general purpose personal information management system (or PIM), Microsoft Outlook includes most of the general features that an individual or a group must perform, including such tasks as reading, sending, and organizing email, scheduling meetings, keeping notes, and maintaining a contacts list. The emphasis here, though, is on general; Outlook offers the basic set of features that most users require. In order to make Outlook capable of addressing the particular needs of individual users or groups of users, Microsoft added a number of customization and extensibility features to the product. These include Outlook's programmability (at an application level using VBA or a forms level using VBScript) and the ability to create custom forms.
By attaching VBScript code to either existing forms or new forms, you can modify the appearance or the behavior of the form, thus making it suitable for special applications. For example, you can:
  • Change the recipient of an email message based on the content of the message to which you are replying
  • Display or hide particular elements of a form depending on the attributes or content of a message, an appointment, or a contact
  • Automatically store an item in a nondefault folder based on the item's attributes or content
  • Get at data in some other document—like a Word document or an Excel spreadsheet—to include as your form's data
  • Manipulate data stored in Outlook to summarize or display in an Outlook form
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Form-Based Development Environment
Although this chapter will discuss attaching code to Outlook forms, rather than creating and modifying Outlook forms themselves, we'll begin by looking at how the Outlook object model views the Outlook user interface and by briefly examining how you access and work with Outlook forms in design mode; both topics provides provide background that is necessary in order to begin coding. Then we'll look at Outlook's rather primitive VBScript environment.
Figure 6.1 shows a more-or-less standard Outlook window with Outlook displaying a mail folder. The Outlook window is divided into three parts, which correspond to four elements of the Outlook object model.
Figure 6.1: The Microsoft Outlook interface
The Folder List
On the left of the Outlook window is the Folder List. In the Outlook object model, this corresponds to the NameSpace object, which has a Folder collection in which each Folder object represents a folder in the MAPI store.
The Explorer
On the upper right of the Outlook window is the Explorer pane. (The term "Explorer" here is unrelated to Windows Explorer, the utility for displaying the Windows namespace and filesystem.) The Explorer pane is responsible for listing the items in the current folder. Each type of item has its own Explorer object, which is a member of the Explorers collection.
The Inspector
On the lower-right of the Outlook window is the Inspector pane. In other cases, when the entire right side of the Outlook window is occupied by the Explorer pane, the Inspector window appears when the user selects an item in the Explorer pane. The Inspector pane is responsible for displaying the item selected in the Explorer pane and corresponds to an Inspector object in the Outlook object model. Note that the Inspector object uses an Outlook form to present a particular view of an Outlook data item.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Running Your Code
The "hook" that allows your code to run is an event handler or an event procedure . Outlook recognizes particular external events—like an instance of a form being opened, or the user clicking on the Send button to send a mail message—and responds by firing an event. If a procedure exists to handle that event, its code is executed automatically. The event procedure can in turn call other procedures or functions, which can also call other procedures and functions, and so on.
Using VBScript, you are able to access only form-level events and control-level events; events at other levels, such as the application or even the Items collection level, cannot be trapped within the scripted environment. You can examine a list of some of the available events in the VBScript editor by selecting Script Event Handler. The editor opens the Insert Event Handler dialog like the one shown in Figure 6.4. If you select one of the events from the list box, the editor automatically creates the code shell for the event procedure. For example, if you were to select the Open item (which is fired just before a form is opened) in Figure 6.5, the editor would automatically generate the following code:
Function Item_Open( )

End Function
Figure 6.4: The Insert Event Handler dialog
Note that Outlook identifies the object whose Open event is being fired as " Item." Each form represents a particular kind of Item object—an email message, for instance, is represented by a MailItem object, while an appointment is represented by an AppointmentItem object. In other words, "Item" generically identifies the current form in much the same way that "Form" in Visual Basic identifies the current form. Each of the Outlook item object types listed in Table 6.1 supports the events for which the VBScript editor automatically generates a code shell.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Program Flow
As we have seen, the entry point into an Outlook program is an event handler, which is executed automatically based on some user action or other event. Program flow proceeds sequentially through the event procedure, with branches to all procedures and functions called by the event procedure (and of course, with branches to all procedures and functions called by those procedures or functions, and so on).
The code behind an Outlook form is finite, and consists of the code displayed by the VBScript editor for a single form. That is to say, Outlook forms provide no facility for importing or including additional code. Nor can the code in one form be called by the code in another form; the flow of program control is confined to the code behind a single Outlook form.
The code in an Outlook form itself consists of three components:
Script-level code
Code outside of any procedure or function. Generally, this code appears anywhere from the beginning of the script to the script's first procedure or function. All of this code is executed when the form first loads, and before the Item_Load event procedure (if one is present) is invoked. In Visual Basic and VBA, this is known as a module's general declarations section, and it can contain only constant and variable declarations (such as Const, Dim, Private, Public, and Declare statements). In Outlook, it can contain a far larger range of statements; object assignments and access to the Outlook object model, however, tend to be problematic if their code is placed here. All variables defined at the script-level, regardless of whether they are defined using the Dim, Private, or Public keywords, are public to the script.
Code for event procedures
Event procedures, as we discussed in the earlier section "Running Your Code" are functions or procedures that are automatically executed based on some event, typically one that results from some action of the user. The scope of all variables declared in event procedures or in supporting procedures and functions is limited to that routine itself; in order to be visible in some routine other than the one in which they are declared, they must be explicitly passed as arguments. Finally, variables in event procedures and in supporting procedures and functions must be declared using the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Outlook Object Model
Although VBScript allows you only to program an Outlook form, it nevertheless gives you relatively complete access to the Outlook object model, which is shown in Figure 6.6. Since the object model is fairly large, we'll focus only on some of its highlights here, and in particular on those objects that you are most likely to use when programming an Outlook form. You can explore the Outlook object model by opening the object browser in the VBScript editor, or by using the Object Browser included with the VBA integrated development environment.
Figure 6.6: The Outlook 2000 object model
Note that when you're attempting to access the Outlook object model using VBScript, the context of your script is the current item, which can be represented by the Item keyword. In other words, as your script is executing, the Item object is the current object; to access other objects in the object model, you have to navigate to them from the Item object.
This also means that a reference to the current item is assumed in any attempt to navigate the object model or access a particular object, property, or method. For example, the code:
MsgBox Item.Application.Version
is identical to the code:
MsgBox Application.Version
This second line of code is interpreted as an attempt to retrieve the value of the Application object of the current item, and to retrieve its Version property.
If you're making extensive use of the properties and methods of other objects, your script's performance can be enormously improved by establishing references to those objects. For example, if your script involves accessing the object representing the form's current page, rather than having to navigate downward through the object model each time you want to access it, you can define an object reference, as the following code does:
Dim objPage
Set objApp = Item.Application
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Accessing Other Object Models
Although most of the programming done with Outlook forms is likely to involve the Outlook object model, there may be times when you want to access data from some other application or draw on some system service provided by a particular object model. The VBScript CreateObject function is used for this purpose to access the object model of some other application, while the VBScript GetObject function is the only means available to get a reference to an existing instance of an application (that is, to a running application). (For the syntax of both functions, see their entries in Chapter 9 The Language Reference.)
The Outlook object model's Application object also has a CreateObject method. Although you can call this method, its use is not recommended from within Outlook. The GetObject function exists solely within VBScript, and is not implemented as a method of the Outlook Application object.
As Table 6.15 shows, you can instantiate objects like the following using these methods:
ActiveX Data Objects (ADO)
ADO is a data access technology that offers a uniform methodology for accessing data regardless of location or format. ADO has a relatively "flat" object model, and many objects (like the Recordset object, or the Connection object) can be instantiated independently of one another.
Data Access Objects (DAO)
DAO is a data access technology intended primarily for use with Access databases. Its top-level object is named DBEngine.
The Dictionary object
A part of the Scripting Runtime Library, the Dictionary object provides high-performance access to data sets that have identifiable keys.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 7: Windows Script Host
Content preview·