Schongar P.VBScript unleashed.1997
.pdf
Differences Between Visual Basic and VBScript
If you know Visual Basic, you'll probably not have any trouble at all with VBScript. The parts of the language we cover in this chapter are basically the same in Visual Basic, with a few subtle differences. Let's talk briefly about these differences and what you should be aware of as you read this chapter.
One of the things you should be interested in is the safety and security of client machines that access your Web site. Microsoft took this consideration into account when creating VBScript. Potentially dangerous operations that can be done in Visual Basic have been removed from VBScript, including the capability to access dynamic link libraries directly and to access the file system on the client machine.
These security precautions are important because access to the client machine's operating system and internal processes could be disastrous. Of course, people run software that they download from the Internet every day. For some reason, though, people who simply use the Internet, as opposed to those of us who create it, are leery of active content. For that reason, there is a special feature of active controls for the Internet-a digital signature.
A digital signature is a file or piece of code that verifies the authenticity of a program or file. Two distinct things must happen in a secure transaction such as this: The client must be sure of where the active control is coming from and that it hasn't been tampered with along the way.
Programming in VBScript
This section of the chapter doesn't assume that you know anything about programming in Visual Basic. If you're well versed in the language, you can use this section as a review. If you haven't programmed before at all, you'll get the introduction that you need.
To start, we'll create a template that you can use to test various concepts in VBScript. We'll then talk about the things that make up a program and what you need to understand in order to create active HTML pages.
Creating a Test Page
Many new programmers learn how to program by writing small programs that run from the command line. In HTML, there is no command line, so we'll set up a skeleton page that we can use to test some of the concepts and functions covered in this book. We'll call the skeleton program tester.htm. Listing 2.1 contains the code that makes up the skeleton program.
Listing 2.1. tester.htm.
<HTML>
<HEAD>
<TITLE>Tester Page</TITLE>
</HEAD>
<BODY>
<H1>Tester Page for VBS</H1>
<HR COLOR="BLUE">
<INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Click to test the code">
<SCRIPT LANGUAGE="VBS">
<!--
Sub Btn1_OnClick()
End Sub
-->
</SCRIPT>
</BODY></HTML>
In most VBScript programs, you'll need to attach the initialization of a program to some sort of action. In the tester. htm page, use the button click event to trigger the action that takes place. To be able to see what happens, we need to change the property of a control on the page, or we can use a message box. Once we have the skeleton program in place, we can test code in the browser.
To start, we'll create a Hello World program. Hello World is a traditional program created in various forms to test input and output techniques. The first Hello World program is fairly simple. To create the script, the following code is added to the Btn1_OnClick event in tester.htm:
Sub Btn1_OnClick
Dim Message
Message="Hello World!"
MsgBox Message, 0,"Tester Result"
End Sub
To test the new code, save tester.htm and then open it in Explorer 3.0. You'll see the result when you click the button, as shown in Figure 2.1.
Figure 2.1 : Tester program with message.
The great thing about having a program like tester.htm available is that you can test any small piece of code you want. By saving the file to your desktop, you can easily open the file in Notepad and Internet Explorer 3.0 at the same time, as shown in Figure 2.2. You can then edit and save the file and see the results immediately.
Figure 2.2 : Notepad and Internet Explorer working together.
Let's take a look at what's happening in tester.htm. The browser reads in the file just as with any HTML document. Notice that the button we've created on the page is no different from the buttons that we create for forms. Microsoft did this so that the same objects created for forms could easily be used for interaction with scripts. This method also helps HTML designers who are used to working with forms.
So, the <H1> text shows in the browser, followed by a horizontal rule and finally our button. The browser now hits the <SCRIPT="VBS"> tag. Here the browser hands off to the scripting engine, which in turn hands off to the VBScript interpreter. The VBS code is then parsed by VBS, compiled on the fly, and run. Our result shows up in the form of the message box.
If some of this isn't quite clear to you now, it should be by the end of the chapter.
What a Program Is
At this point, it might be a good idea to discuss what constitutes a program. Thinking about what's going on with the machine will help you later when you're trying to come up with applications for VBScript in your Web pages.
A computer program is a set of mathematical instructions that perform a task. To make it easier for programmers to get computers to do things, languages have been developed to allow programmers to write instructions for the computer in terms that humans can deal with.
Many computer languages exist. They can be broken into two broad categories: low level and high level. Low-level languages deal directly with what's going on inside the computer, whereas high-level languages keep the programmer thinking at a different level. Low-level languages get closer to the chip. Assembler is an example of a low-level language. When you write a program in Assembler, you do the same sorts of things that you do in a language such as Visual Basic, except that you are much more precise with the chip. Assembler tends to be a little cryptic to people just getting to know it:
MOV BX,0001H
LEA DX,Msg
MOV CX,My_Msg
MOV AH,40H
INT 21H
Writing programs in a high-level language such as Visual Basic is much more like writing instructions in plain English. The conceptual buffer between a language that is close to the chip and a higher-level language is called abstraction. You know more about what's going on when you read an assembly language program, but you could do it in Basic and not have to worry about moving blocks of memory around yourself.
We can add a layer of abstraction to Visual Basic itself. To teach programming concepts, some instructors use a tool called pseudo code. Pseudo code is simply an instruction translated into plain English. I don't use pseudo code much, but I'll cover it briefly here so that you're familiar with the concept.
If you translated the code in Listing 2.1 into pseudo code, it would look like the code shown in Listing 2.2.
Listing 2.2. tester.htm translated into pseudo code.
Create a button on the page called Btn1
This is the start of a script in the VBS language
This comment hides the code from browsers that can't understand it.
When the user clicks the button:
Create a space in memory called Message
Set the value of Message to "Hello World"
Create a dialog box containing the value of Message
End the routine
End of the comment
End of our script
I won't use this method much in this book because it essentially makes you read the same program twice. I mention it, though, because it shows how you should be thinking when you read through code listings.
When you think about a computer language being mathematical, you don't really need to worry that there are big concepts that you need to understand before you begin to program. To think about what a computer needs to do to process information, think of the game 20 Questions. In 20 Questions, one person has the magic word. Everyone else is allowed to ask 20 questions with a "Yes" or "No" answer. The person who knows the magic word decides whether the question deserves a "Yes" or a "No."
If the magic word is "cow," and the question is, "Is it an animal?", the answer would be "Yes." This is about the level on which the computer works. It remembers things, it compares things, and it can tell you whether two things are the same. Languages such as Visual Basic add features that can work on the things that the machine stores in memory.
Programmers are the people asking the questions. The better the question, the more likely it is that you'll get to the ultimate answer.
Concepts You Should Understand: Variables and Procedures
You should understand some simple concepts before you begin to program. Among these concepts are variables and procedures.
A variable is a value stored in memory. If you wanted to get technical, you could say that variable is a name that represents an address containing information stored in memory. For our purposes, thinking of a variable as being equal to a value is fine.
A program is made up of one or more procedures. A procedure is an instruction block in VBScript. Regular procedures, or Subs, simply act on data, but a special procedure called a Function returns a value to the procedure that called it. Be aware that all your scripts will be made up of procedures and Function blocks.
You know that your VBScript programs will begin with a <SCRIPT> tag and end with a </Script> tag. Your procedures and Functions will work the same way. The procedure is created and it is ended. Your program code goes in between.
The Anatomy of VBScript Code
Let's take a look once again at our tester.htm file. The script section of the page has a definite structure as shown in Figure 2.3.
Figure 2.3 : A VBScript code block is broken down.
The first thing you'll notice in the VBScript code block is the <SCRIPT LANGUAGE="VBS"> line. Keep in mind that you must close out your script code block with a </SCRIPT> tag. If you don't add this tag, your script usually won't run and you won't know what's going on because you aren't going to see any error messages. Errors like this are tough to track down because if your code block is large, you might start hacking away at perfectly good code to see if you can figure out what's wrong. An error like this can waste a lot of time because nothing you try works.
TIP
If your script isn't running and you're not getting error messages from your browser, check your HTML.
The next tag that you should get used to adding to a script block is the comment tag. You won't run into a problem with most browsers if you don't add this tag, but it's a good idea to get used to adding it anyway. If nothing else, this tag helps you to see your scripting blocks more easily in your HTML documents. Like the <script> tag, the comment tag should have a closing tag, although not having a closing tag will not affect your script in a browser that recognizes the
<SCRIPT> tag.
Procedures make up most of the rest of a script code block. They have opening and closing lines and are accessible from one another. The first procedure run in a script depends on what events take place within the HTML page. An event is usually an action taken by a user, such as clicking on a button, but other events can also be triggered within an HTML page. Other possible events include timer events, mouse movement, and messages sent from controls.
To review, an HTML script is enclosed by the <SCRIPT> </SCRIPT> tag pair. The LANGUAGE="VBS" attribute sets the scripting language to VBScript. The VBScript script code should be written inside a comment tag, <!-- -->. Procedures are blocks of code within the script that make up the program.
Data Types
As mentioned, a variable is a name that represents the contents of some space in memory. Thinking of a variable in terms of memory space will help you to understand an important concept in programming: data types.
All variables in VBScript are of the type variant. A variant is a variable that is simply the name for a piece of data. The variant type doesn't differentiate between types of data until the time comes to process that data. This means that a variable can represent literally any value or type of value. We'll talk more about this ahead.
Subtypes of Variant Types
The variant type has a number of subtypes. Let's go through each of the subtypes and discuss how a variable of any given subtype will take up space in memory.
Boolean
One of the most basic data types in programming is the Boolean data type. This subtype in VBScript can have a value of either true or false. The Boolean type takes up very little space in memory.
Byte
The byte subtype can be a whole, positive number in the range of 0 to 255. Like the Boolean subtype, the byte subtype takes up very little space in memory.
Integer
The integer subtype takes up 2 bytes in memory and can be an integer value in the range of -32,768 to 32,767. An extra byte of storage makes a big difference in the value that a variable can hold.
Long
The long variable subtype is 4 bytes in size and can be a whole number in the range of -2,147,483,648 to 2,147,483,647.
Single
The single subtype contains a single-precision, floating-point number. Precision refers to the number of bytes of fractional value storage allotted to the variable. A single-precision number allots 2 bytes for fractional value storage. It takes 4 bytes to store a variable of the subtype single. The range of values that a single can hold is -3.402823E38 to - 1.401298E-45 for negative values and 1.401298E-45 to 3.402823E38 for positive values.
Double
The double subtype takes up 8 bytes of storage, 4 bytes of which are reserved for a fractional value. The double subtype is extremely precise and is usually reserved for advanced mathematical and scientific operations. It has a range of - 1.79769313486232E308 to -4.94065645841247E-324 for negative values and 4.94065645841247E-324 to 1.7976931348632E308 for positive values.
String
The string subtype is a group of up to approximately 2 billion characters. The size of the string variable depends on the length of the string.
Date
The date subtype is a number that represents a date in the range of January 1, 100 to December 31, 9999.
Empty
The empty subtype is returned for variants that aren't initialized. If the variable is a number, the value is 0. If it's a string, the value is "".
Object
The object subtype contains the name of an OLE Automation object. The object can then be manipulated using the variable.
Error
The error subtype contains an error number. You can use the generated error number to generate an expanded explanation of the error.
Using Variables
Now that you know what variables are all about, let's take a look at how they are used in your VBS scripts.
Declaring Your Variables
Strictly speaking, you don't need to declare your variables in VBScript. You could simply set the variables that you need on the fly:
MyString="This is my string"
One of problems with setting the value of variables without first declaring them is that the variables become difficult to track. For example, you set the value of a variable somewhere in code, but you can't remember where the variable started. In addition to just being good programming practice, declaring your variables will make it easier for you to read and maintain your code.
To declare a variable in a VBS script, you use the Dim statement. Dim stands for dimension:
<SCRIPT LANGUAGE="VBS">
<!--
Option Explicit
Dim MyString
MyString="This is my string"
-->
</SCRIPT>
Notice that in addition to declaring our variable with the Dim statement, we added the Option Explicit statement to the beginning of the code. Adding Option Explicit will require you to declare all variables in your script. Using this statement is completely up to you. If you use Option Explicit but don't declare a variable, your script will generate an error when run.
You can declare more than one variable at a time. Just use the Dim statement and put a comma between every new variable name:
<SCRIPT LANGUAGE="VBS">
<!--
Dim Name, Address, City, State, Zip
-->
</SCRIPT>
Assignment
To assign a value to a variable, place the variable on the left followed by an equals sign and the value on the right:
Name="Brian Johnson"
Remember that variables in VBScript are variants. VBScript determines the nature of the variable when you run the script. There are really only two types of data: strings and numbers. String data is always held in quotation marks.
Scope
The scope of a variable refers to where in the script the variable is available for processing. A variable declared inside a procedure is limited in scope to that procedure. If a variable is declared outside of the procedures in the script, it is available to all the procedures in the script. Listing 2.3 illustrates the scope of variables in VBS scripts.
Listing 2.3. Scope of variables in VBS scripts.
<HTML>
<HEAD>
<TITLE>VBS Variable Scope</TITLE>
</HEAD>
<BODY>
<H1>Tester Page for VBS</H1>
<HR COLOR="BLUE">
<INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Local Variable">
<INPUT TYPE="SUBMIT" NAME="Btn2" VALUE="Script Wide Variable">
<INPUT TYPE="SUBMIT" NAME="BTN3" VALUE="Out of Scope">
<SCRIPT LANGUAGE="VBS>
Option Explicit
Dim MyGlobal
MyGlobal="Access Ok"
Sub Btn1_OnClick()
Dim MyLocal
MyLocal="Local access Ok!"
MsgBox MyLocal,0,"Btn1 Clicked"
End Sub
Sub Btn2_OnClick
MsgBox MyGlobal,0,"Btn2 Clicked"
End Sub
Sub Btn3_OnClick
MsgBox MyLocal,0,"Btn3 Clicked"
End Sub
-->
</SCRIPT>
</BODY>
</HTML>
If you run the code, you'll see that you can access the local variable by clicking Btn1. If you click Btn2, you'll access the variable that we declared globally. Finally, if you click Btn3, you'll get an error (see Figure 2.4) because the Btn3_OnClick procedure tries to access the variable declared in the Btn1_OnClick procedure.
Figure 2.4 : An out-of-scope variable generates an error.
When discussing the scope of a variable, you'll often hear the term lifetime. Lifetime refers to the amount of time that the variable exists in memory. At the procedure level, the lifetime of the variable is as long as it takes to run through the procedure. At the script level, the variable is live for as long as the script is live. You can extend the lifetime of a procedure-level variable by declaring the variable as static. A static variable will retain its value between calls to the procedure. To declare a variable as static, simply use the Static keyword:
Static MyVariable
Scalar
The types of variables we have talked about so far have been scalar variables. A scalar variable has only one value assigned to it at a time. Depending on the types of programs you write, you'll probably use scalar variables often in your scripts. When modeling the world, though, you often need to work with sets of values. To work with these values, you need to use a different type of variable known as an array.
Array
An array is like a list. When you go to the grocery store, you often carry a list of the items that you need to purchase. If you were to assign the list to a scalar value, it might look something like this:
MyList = "peas, carrots, corn"
Although it's easy enough to have MyList contain the contents of the list, it's not very easy to figure out which item is which. That's where an array comes in. An array lets you easily specify items in the list and retrieve those items individually. Let's take a look at a simple array.
You declare an array variable in VBScript the same way you do a scalar variable. The difference is that you specify the number of items in the array:
Dim MyList(4)
Arrays in VBScript start their count at zero, so an array is declared with the highest count number in the array. In this case, MyList has a total of five items.
Looking at Listing 2.4, you can see that we've drawn five buttons on the page. An array variable, MyList, is declared with five items, and each item is assigned a different value. In the click event for each button, we attach the value of an array item to a local scalar variable called Item. We then call a procedure named ShowMessage, passing Item as a parameter. The ShowMessage procedure takes the value of Item and plugs it into the MsgBox function, which brings up the message box containing the value of the particular array item.
Listing 2.4. Shopping list of items.
<HTML>
<HEAD>
<TITLE>Tester Page</TITLE>
</HEAD>
<BODY>
<H1>Tester Page for VBScript</H1>
