Introducing VBScript and JScript

Microsoft Visual InterDev offers two scripting languages for Web page development: VBScript and JScript. Both are secure and safe. Script writers cannot perform any actions that will harm another user's system without using some additional type of application or component.

VBScript is a subset of the Visual Basic programming language. It is stripped down so that you can implement it without a large set of support files and so that it can be secure. VBScript programs run on a Web browser, with the VBScript code itself embedded as part of a Web page. This means that you can unknowingly download and execute VBScript programs as you browse the Web. To make browsing safe, Microsoft has removed everything from Visual Basic that might interact with the computer in any kind of dangerous way.

You can use VBScript to generate a Web page dynamically, and you can use it to validate data on a form before you send it to the server. These features reduce the amount of traffic that has to be sent over the Internet and reduces the load on your Web server. In this sense, VBScript makes Web technology increasingly client-server—part of the load is handled by the Web server and part of it is handled by the browser.

Anatomy of VBScript

VBScript is embedded on a Web page between <SCRIPT> tags, as shown below:

<SCRIPT LANGUAGE = VBScript> <!-- Function Cube(num)     Cube = num * num * num End Function --> </SCRIPT> 

These tags mark the beginning and end of a VBScript. The VBScript code itself is also embedded between comment tags if it is sent as part of the HTML stream to the browser. Therefore, if you send your page to a browser that cannot understand VBScript, the code is simply ignored and not displayed. Server-side scripting does not require the comment tags.

Comments

You can place comments within your VBScript code by using either the remark keyword (REM) or an apostrophe ('), as follows:

REM This is a comment ' This is another comment 

Variables

A variable is a temporary storage area for data. You can create variables in one of two ways with VBScript. You can declare a variable using a Dim statement or you can declare more than one variable in the Dim statement by separating the variables with commas, as shown here:

Dim age, height, weight 

You can also implicitly create a variable by referring to it in your code. If the variable has not been created when you first refer to it, it is created at that point in the code. This might seem like a convenient way to create variables, but it is not good programming practice. If you make a habit of not using the Dim statement to declare variables, you increase the chance of accidentally creating a new variable by misspelling the name of an existing one.

VBScript's Option Explicit command forces you to declare variables using the Dim statement. The Option Explicit command should be the first command in your VBScript. Option Explicit disables implicit variable declaration, so if you use a variable without first declaring it, a Variable Is Undefined error is generated. This message contains the variable name and the line number of the statement that has the undefined variable.

Arrays

A variable that holds a single value is said to be scalar. The following example creates the variable Name:

Dim Name 

Name can hold any value, but it can hold only one value at a time. Any value you place in Name will replace the existing value.

You can also dimension an array variable:

Dim  Names(10), Addresses(10,3) 

In this example, Names has space for 11 values, from 0 through 10. All arrays in VBScript are zero-based, so the first element is always 0. The Addresses array is two-dimensional; it has 11 * 4 values. (Remember the zero-based arrays in VBScript.) You can dimension an array with up to 60 dimensions, but if you find yourself using more than two or three, you're probably using the array incorrectly. When you multiply the number of elements in each dimension, you get the total number of elements in the array. If you use several dimensions, you'll quickly allocate space for huge numbers of values—more values than you probably need.

You can also declare dynamic arrays. In a dynamic array, the size is not determined in the Dim statement:

Dim Scores() 

Before you use a dynamic array in code, you must redimension it using the Redim statement to hold as many values as you need. This is useful because you might not know how many values your array needs to hold until run time.

Redim Scores(NumOfStudents) 

You can redimension a dynamic array any number of times in your code. If you want to change the size of the array without losing its contents, you must include the Preserve keyword:

Redim Preserve Scores(NumOfStudents) 

If you redimension the array to a smaller size, you lose the values beyond the end of your array.

Operators

VBScript includes a range of operators for arithmetic, comparison, concatenation, and logical operations on data. Table 10-1 describes the available operators.

For comparison operations on data, you can use combinations of the greater than (>), less than (<), and equals (=) operators.

Table 10-1. VBScript operators.

Operator Description Type
+ AdditionArithmetic
AndConjunctionLogical
&String concatenationConcatenation
/DivisionArithmetic
EqvEquivalenceLogical
^ExponentiationArithmetic
ImpImplicationLogical
\Integer divisionArithmetic
IsObject equivalenceComparison
ModModulusArithmetic
*MultiplicationArithmetic
-NegationArithmetic
NotNegationLogical
OrDisjunctionLogical
-SubtractionArithmetic
XorExclusionLogical

Data types

Visual Basic has several data types, but VBScript has only one—Variant. When you dimension a variable using Dim, the variable is a Variant. The Variant data type can hold any value that you assign to it, so you don't need to use separate data types for dates, strings, numbers, and so on. When you assign a value to a variable, VBScript stores the type of data in that variable along with its value. You can use the VarType function to return the data type in the Variant variable. This can be useful if you need to ensure, for instance, that a user entered a number. The following code snippet shows how to use VarType to determine whether a variable is an integer from 0 through 100:

<SCRIPT> Function ValidScore(num)     Dim IntegerType     IntegerType = 2     If VarType(num) = IntegerType Then         If num >= 0 and num <= 100 Then             ValidScore = True         Else             ValidScore = False         End If     Else         ValidScore = False     End If End Function </SCRIPT> 

The VarType function returns a number that represents the type of data the Variant holds. Table 10-2 shows the value returned by VarType for different types of data.

Table 10-2. The value of VarType for data types.

VarType Type of Variant
0Empty (uninitialized)
1Null (no valid data)
2Integer
3Long integer
4Single-precision floating-point number
5Double-precision floating-point number
6Currency
7 Date
8String
9 Automation object
10 Error
11 Boolean
12 Variant (used only with arrays of Variants)
13 Data-access object
17 Byte
8192Array

Most programming languages support constants, and Visual Basic is no exception. But the VBScript version of Visual Basic has no constants. Even though there is no explicit mechanism for defining constants in VBScript, it is still good programming practice to use a symbol in your code instead of a number. In VBScript, you need to use a variable. In the above example, in which you check the number to see whether it was an acceptable score, the IntegerType variable is assigned the value of 2 and uses the variable in the If…Then statement. You should use this technique in VBScript where you'd normally use constants in Visual Basic.

Flow control

When a procedure or script starts running, it starts at the beginning and runs through to the end. You can change this flow either by using a decision construct or by looping. In this section, we'll cover some of the basic flow control statements, such as If...Then...Else, For...Next, and Do...Loop. Flow control statements not discussed here include the following:

  • While...Wend For executing a series of statements as long as a given condition is True
  • Select Case For executing one of several groups of statements, depending on the value of an expression
  • For Each...Next For repeating a group of statements for each element in an array or collection

If...Then...Else statement

The decision construct is known as the If…Then...Else statement. It lets you test a condition and take one action if the condition is True and take another if the condition is False. It comes in two forms. The first form is the single-line form used for short, simple tests:

If condition Then statements [Else elsestatements ] 

The square brackets surrounding the Else block indicate that the Else clause is optional.

The second form is the block form, which provides more structure and flexibility than the single-line form and which is usually easier to read, maintain, and debug:

If condition Then     [statements] [ElseIf condition Then     [elseifstatements]] [Else     [elsestatements]] End If 

The condition is a logical statement that evaluates to either True or False. The condition can be a comparison, such as the one shown below, or it can be a function that returns a Boolean value (True or False).

If score > 70 Then 

For example, VBScript has a function called IsDate that returns True if the value you pass it is a date, and False otherwise. The function can serve as the condition in your If…Then...Else statement:

If IsDate(MyVariable) Then 

It isn't necessary to have an Else block in your If…Then statement. In fact, you should include an Else block only if you need to do two separate tasks—one if the condition is True, and one if it is False. The following code snippet is a complete If…Then...Else statement:

If IsDate(MyVariable) Then     ' Report back that the variable is a good date Else     ' Report back that we still need a date End If 

If you need to take action only when the condition is True, do not include the Else block:

If username = "Eric" Then     ' Write a welcome statement for Mr. Vincent End If 

It is bad practice not to include any code in the If…Then block and then to include code in the Else block:

If Grade >= 70 Then Else     ' Write a message saying they failed! End If 

If you find yourself writing code like the previous If...Then...Else statement, you need to invert the condition so that you have an If block without an Else block. The above code uses a poor technique and makes for hard-to-read code. Here is the corrected code:

If Grade < 70 Then     ' Write a message saying they failed! End If 

In addition to using If…Then...Else statements to control program flow, you can use looping constructs. A loop is a section of code that executes more than once.

For...Next statement

Use the For...Next loop when you want to execute a block of code a fixed number of times. The syntax for the For...Next loop is as follows:

For counter = start To end [Step step]     [statements]     [Exit For]     [statements] Next 

It uses a variable you supply as a counter to count the number of times through the loop.

You specify the counter's starting and ending values, as shown below:

For MyCounter = 1 To 5     Sum = Sum + Counter Next 

The counter is incremented by one each time the loop gets to the Next keyword.

To increment or decrement the counter by a different value, you can use the Step keyword:

For MyCounter = 5 To 1 Step -1     DisplayCountdown(MyCounter) Next 

Do...Loop statement

For...Next loops are useful if you know how many times you need to execute a block of code. However, in some situations you won't know how many times the loop needs to be executed.

Using the While keyword, the Do loop executes a block of code while a condition is True. Here's the complete syntax:

Do [{While | Until} condition]     [statements]     [Exit Do]     [statements] Loop  

The following code executes the loop as long as the MoreData function returns True:

Do While MoreData(variable)     ProcessData Loop 

You can use the While keyword either at the beginning or the end of the loop. If you place the keyword and the condition at the beginning of the loop, the condition is checked before the first time through the loop. If the While condition is False when it is first evaluated, the contents of the loop never execute.

If you put the While keyword at the end of the loop, the condition is not evaluated until after the first time through the loop. In this case, your code is executed at least once. Here's the complete syntax:

Do     [statements]     [Exit Do]     [statements] Loop [{While | Until} condition] 

And here's an example:

Do     AskUserForAnswer(answer) Loop While DontHaveAnswer(answer) 

The AskUserForAnswer subroutine executes at least once, and it continues to execute as long as the DontHaveAnswer function returns True. The type of loop you use will depend on the problem you're trying to solve; neither one is more correct than the other. The first example requires that you check to see if there's any data to process; if there is, you can try to process the data and then continue to process it as long as there is more data to process. In the second example, you have to ask the user for the answer at least once and continue to ask for the answer only as long as you don't have an acceptable answer.

You can also use the Do loop with the Until keyword. With this keyword, the loop executes as long as the condition is not True. Until is the inverse of While. You can also use the Until keyword at the beginning or end of the loop just as you can with the While keyword. This gives you the same flexibility over the loop block's first execution:

Do     AskUserForAnswer(answer) Loop Until HaveAnswer(answer) 

Procedures

Procedures are the building blocks of VBScript programs. A procedure is a named block of code that is grouped together to perform a job. VBScript has two types of procedures: functions and subroutines. A function can return a value, and a subroutine performs its task without returning a value.

You declare a subroutine by enclosing the block of code that it comprises between the Sub and End Sub keywords. The declaration itself must be enclosed in <SCRIPT> tags. Procedure declarations must come before the procedure is used, so it's good practice to declare your procedures in the Head section of the HTML page. In this way, all of your subroutines and functions are defined before they are used, and all the definitions are located in the same place on the page. In addition to enclosing procedure declarations in <SCRIPT> tags, they should also be within HTML comment tags so that the code is not displayed in a browser that doesn't understand VBScript.

Here's the formal syntax for declaring a subroutine:

[Public | Private] Sub name [(arglist)]      [statements]     [Exit Sub]     [statements] End Sub  

Here's an example that shows the use of the <SCRIPT> tags and HTML comment tags:

<SCRIPT LANGUAGE=VBScript> <!-- Sub Warning     MsgBox "Hey, this is dangerous!" End Sub --> </SCRIPT> 

MsgBox is a VBScript function that displays a dialog box with the message you specify. MsgBox can also display buttons and icons. For more information on MsgBox, see the VBScript Language Reference for the MsgBox function in Visual InterDev's online Help. You can use MsgBox only in client-side script.

You can also declare a procedure with arguments. An argument is a variable that your procedure expects as input. You can have any number of arguments. When a procedure is used, it expects values to be passed in as arguments. Since VBScript has only Variant types of variables, you cannot specify what kind of data you want the procedure to use. You have two options: make sure you pass the right type of data to the procedure, or write code in the procedure to verify the data types before the data is used. One common error is a type mismatch. This occurs when you try to use data of one type (such as a string) as data of another type (such as a date). VBScript is considered a weakly typed language because it doesn't do a lot of type checking automatically. The following is an example of a procedure with arguments:

<SCRIPT LANGUAGE=VBScript> <!-- Sub DisplayMessage(Message, HowManyTimes)     Dim Count     For Count = 1 to HowManyTimes         MsgBox Message     Next End Sub --> </SCRIPT> 

You declare functions in much the same way that you declare subroutines, except you use Function and End Function keywords. Functions return values; you return a value by assigning a value to the function name as if it were a variable within the function.

Here's the formal syntax for declaring a function:

[Public | Private] Function name [(arglist)]     [statements]     [name = expression]     [Exit Function]      [statements]     [name = expression] End Function  

Here's a function that takes a number and raises it to the third power using the exponentiation operator (^):

<SCRIPT LANGUAGE=VBScript> <!-- Function Cube(number)     Cube = number ^ 3 End Function --> </SCRIPT> 

Using a function or a subroutine

Once the procedure is declared, you can use it by referring to it in VBScript code. Since a subroutine does not return any values—you simply name it in code and pass it values (separated by commas) for any arguments it might have.

' Call the DisplayMessage subroutine DisplayMessage "Hello there", 3 

Functions return a value, so you should be ready to use the value being returned. You can use the function name as if it were a variable and use it in an expression:

' Use the Cube function to calculate a new variable Dim Num1, Num2 Num1 = 10 Num2 = Cube(Num1) 

You can also design a function that returns either True or False, and then use the function as a condition in a Do loop or an If...Then statement. The functions HaveAnswer and DontHaveAnswer from earlier in the chapter are examples of functions that return Boolean values.

Built-in VBScript functions

VBScript makes many intrinsic functions available. See Visual InterDev's online Help for more information on all of them, including math functions such as sine and cosine. You can derive the trigonometric functions not supplied in VBScript from the mathematical functions that are available.

VBScript comes with a set of functions that help you determine the type of data stored in a variable. Table 10-3 describes these functions.

Table 10-3. VBScript functions.

Function Description
IsArray True if variable is an array of values
IsDate True if variable is a date value
IsEmpty True if variable has been initialized
IsNull True if variable is the Null value
IsNumeric True if variable is recognized as a number
IsObject True if variable refers to an Automation object

Objects

VBScript includes several Automation objects that can be accessed via scripting. The objects are as follows:

  • Dictionary
  • Err
  • FileSystemObject
  • TextStream

Using VBScript with ASP

When using VBScript on the server with ASP, two VBScript features are disabled:

  • Statements that present UI elements, such as InputBox and MsgBox
  • The VBScript function GetObject

Use of these statements will cause an error.

When you use CreateObject, you are actually using the default method of the Server object. CreateObject lets you integrate ActiveX Server components within your Web application.

All ASP script processing is performed on the server side. There is no need to include HTML comment tags to hide the scripts from browsers that do not support scripting, as is often done with client-side scripts. All ASP commands are processed before content is sent to the browser and stripped out of the document before the document is sent to the browser.

VBScript supports basic REM and apostrophe style comments. Unlike HTML comments, these are removed when the script is processed. They are not sent to the client.

Anatomy of JScript

While VBScript is a powerful client-side and server-side scripting language, other scripting languages are also available to Visual InterDev developers. JScript is Microsoft's implementation of the ECMAScript language, which is the Web's only standard scripting language. While you might think that JScript is a derivative of Java, it is actually an independently conceived, object-based programming language. JScript has similarities to Java, as well as to C++. Developers comfortable with these programming languages will find many of JScript's constructs familiar.

JScript code is embedded in the HTML or ASP Web page with the <SCRIPT> tag. Use the Language attribute to specify that the script block is JScript, as opposed to VBScript, like this,

<SCRIPT LANGUAGE=JAVASCRIPT> // // JScript code // </SCRIPT> 

or like this,

<SCRIPT LANGUAGE=JSCRIPT> // // JScript code // </SCRIPT> 

Statements and comments

A statement in JScript consists of a line of code, much like VBScript. Although a new line indicates a new statement, you can also end a statement with a semicolon. This construct is testimony to JScript's heritage in Java and C++, and it is optional. Unlike the following example, however, it is good programming practice either to use the semicolon statement delimiter throughout all code or not to use it at all.

// These are all legal JScript statements energy = mass * (Speed_of_light * Speed_of_light); paycheck = rate * hour sum = num1 + num2; 

JScript supports a block construct that is defined by a series of statements delimited by curly braces. You use blocks of statements to define functions, as well as in conditional and other flow control operations.

Comments in JScript also follow Java and C++ convention. Two forward slashes (//) begin a comment when all characters after it on the current line are to be ignored. For multiple-line comments, you can use the /* and */ characters to delimit the comment block.

Variables

You do not have to declare variables in JScript, but it is good programming practice to do so using the var statement. JScript variables are case-sensitive, so the following two variables (MyName and myName) are different, even though they have the same name:

var MyName MyName = "Eric" window.document.write(myName) 

Inspection of this code reveals a flaw. Assuming that window.document.write is a method that sends its arguments to the HTML stream, what does this code segment print? Nothing! MyName is a different variable from myName. Because JScript does not require that new variables be declared, when it sees myName it assumes that a new, empty variable should be created, which is probably not the author's intention. Developers familiar with case-insensitive languages should beware—mistakes in case are a leading cause of troublesome bugs that are difficult to spot when you browse over source code. Good discipline in coding techniques is more important than ever in this situation.

Operators

JScript includes a range of operators for arithmetic, assignment, bitwise, and logical operations on data. Table 10-4 summarizes the available operators.

Table 10-4. JScript operators.

OperatorDescriptionType
-Unary negationArithmetic
++IncrementArithmetic
- -DecrementArithmetic
*MultiplicationArithmetic
/DivisionArithmetic
%ModulusArithmetic
+AdditionArithmetic
-SubtractionArithmetic
!NotLogical
==EqualityLogical
!= InequalityLogical
&&AndLogical
||OrLogical
?:ConditionalLogical
,CommaLogical
~NotBitwise
<<Shift leftBitwise
>> Shift rightBitwise
>>>Unsigned shift rightBitwise
&AndBitwise
^XorBitwise
|OrBitwise
=AssignmentAssignment

As with VBScript, you can use combinations of the greater than (>), less than (<), and equals (=) operators for comparison operations on data.

Data types

The basic data types in JScript are numbers, strings, and Booleans. The other data types are functions, methods, arrays, and objects.

Numbers can be either integer or floating point and can be represented in decimal (base 10), octal (base 8), and hexadecimal (base 16) notations. Octal and hexadecimal representations cannot, however, represent the decimal part of a number. Here are a few examples:

128.83    // Base 10 representation of a float 221       // Base 10 integer 0xFF92    // Hex notation. Note the leading "0x" 02265     // Octal notation. Note the leading zero 

JScript's Boolean variables are the familiar True and False. However, unlike in some other programming languages, True and False are not equal to 1 and 0; each is an actual, separate data type.

Arrays and objects

You handle arrays and objects almost identically in JScript. At times, it seems that there is no difference between them. An object is an entity that has properties and methods. A property can be a simple data type or another object. A method is a function that belongs to the object.

For example, JScript has a built-in object called Math. Math has, among others, the properties LN10 and PI. This means that Math can supply the values for the natural logarithm of 10 and pi.

var x var y x = Math.PI; y = Math.LN10; 

The Math object also has methods, such as max and round. The max method returns the larger of two numbers, and the round method returns a number rounded to the nearest integer.

var num1 var num2 var biggest var my_integer ... biggest = Math.max(num1, num2); my_integer = Math.round(12.84521); 

JScript also provides other intrinsic (built-in) objects, such as Date, String, and Array.

Strings

You can delimit a string literal in JScript using either single or double quotes. This is handy if you need to represent a single or double quote as part of the string. For instance, to represent the text "JScript's string literals," you can use the following string literal:

"JScript's string literals" 

But to represent the following text,

The cop said "STOP," so he did.

you can use single quotes:

'The cop said "STOP," so he did.' 

String variables in JScript are actually objects. Although you can implicitly create them by assigning a variable name to a string literal, string variables also have methods that make them a powerful and intuitive string manipulation tool:

myName = "Eric F. Vincent";    // Implicitly creates string myName.toUpperCase();          // Value is now 'ERIC F. VINCENT' 

Flow control

JScript uses similar constructs to control the flow of a script, as does VBScript and most other popular languages. The if construct is the primary decision-making mechanism. for and while implement loops. For the most part, the difference is in the syntax.

if...else statement

The JScript syntax for the if...else statement is as follows:

if (condition) {     // block of code } [else {     // block of code }] 

In this example, condition is a Boolean expression that evaluates to either True or False. The square brackets surrounding the else block indicate that the else clause is optional, like the Else clause in VBScript. JScript uses curly braces to indicate a block of code.

Curly braces are unnecessary if the block has only one statement:

if (current < top) {     next = next + 1;     TakeAction(current); } else     Finalize(current); 

In this example, the two statements following the if statement are grouped together. When the condition is True, both statements are executed because the if statement considers the statements in a block of code to be a unit.

The else clause has no block of code; it has only one statement. When the condition is False, the one statement is executed and program flow continues. There is no need for an End If construct because the curly braces delimit blocks of code.

for statement

Again, the concept of the for statement is similar to the For loop in VBScript but is implemented a little bit differently. JScript's syntax for a for loop is

for (initializer ; condition ; increment ) {     // block of code } 

The loop has three parts: The first is the initializer, a statement that is executed only once before the first time through the loop. You typically use it to initialize a variable that will count as the loop progresses. The second is the condition, a Boolean expression that evaluates to True or False. The condition is evaluated before the first time through the loop, and again each time through the loop until it returns False. The condition typically tests a counter to see if it has reached a certain number. The block of code won't execute if the condition is False the first time through the loop. The third part—the increment—is a statement that is executed at the end of each loop. You typically use it to increment a counter by one each time through the loop. When you use these three parts together, they can behave the same as the For...Next loop in VBScript.

The following is a for loop in which x varies from 1 through 10 in increments of one. Each time though the loop, x is added to a variable called total. This example introduces two new operators. The first is used in the increment part of the loop.

for (x = 1; x <= 10; x++)     total += x; 

The increment operator, x++, is the third part of the loop. It adds one to its operand (in this case, x). There is also a decrement operator (--) that subtracts one from its operand, as well as a compound assignment.

The compound assignment operator is little more than a shortcut. The statement

total += x; 

is equivalent to

total = total + x; 

while statement

The while statement is also straightforward:

while (condition) {     // block of code } 

Again, the condition is a Boolean expression, and the block of code can be either several lines of code surrounded by curly braces or a single line of code. The condition is checked before the first time through the loop, so if it starts off as False, the block or statement never executes.

while (theTime == right) {     DisplayAds();     Feed(theHungry); } 



Programming Microsoft Visual InterDev 6. 0
Programming Microsoft Visual InterDev 6.0
ISBN: 1572318147
EAN: 2147483647
Year: 2005
Pages: 143

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net