Combining Different Scripting Languages

Overview

Welcome to the final chapter of this book. In this chapter, you will learn how to develop a new type of script, called a Windows Script File, that allows you to combine VBScript with one or more other WSH supported scripting languages in order to create a single executable script. Doing so will allow you to create scripts that can take advantage of the strengths of each individual scripting language. Specifically, in this chapter I'll demonstrate how to develop Windows Script Files that combine VBScript and JScript. Along the way, you'll be introduced to the Extensible Markup Language, or XML, which allows different scripting languages to be combined into Windows Script Files. Specifically, you will

  • Learn how to combine VBScript with another scripting language to create Windows Script Files
  • Learn how XML is used to format Windows Script Files
  • Get a sneak peek at the JScript scripting language
  • Learn how to execute Windows Script Files


Project Preview The VBScript Game Console

In your final project, you will learn how to create Windows Script Files that combine VBScript with a little bit of JScript in order to create a game console for all your VBScript games. Once started, the game console will display a dynamically created numbered list of your VBScript games and will allow the user to choose which game to play by either typing in the name of the game or its assigned number.

When started, the game console appears in the upper-left-hand corner of the display area. As games are selected, they will appear in the middle of the screen. This keeps the game console handy without making it intrusive. Figures 10.1 through 10.5 demonstrate the overall operation of the game console from beginning to end.

click to expand
Figure 10.1: A JScript that displays the game console's initial splash screen is executed.

click to expand
Figure 10.2: The core logic for the game console is provided by a VBScript, which is responsible for displaying and controlling the execution of your VBScript games.

click to expand
Figure 10.3: The game console remains tucked away in the corner while the player enjoys playing your VBScript game.


Figure 10.4: By selecting the About option, the user can get more information about the game console and its author.


Figure 10.5: When the game console is finally closed, another JScript is run in order to display a closing splash screen.


Introducing Windows Script Files

One of the strengths of the WSH is that it supports a number of different scripting languages, including VBScript, JScript, Perl, Python, and REXX. Microsoft automatically equips the WSH with VBScript and JScript. Third-party software developers provide support for the other scripting languages. In addition to being able to execute scripts written in any of these scripting languages, the WSH allows you to put any combination of these languages into a single script file known as a Windows Script File.

Definition

A Windows Script File is a type of script that allows multiple scripts, written in any WSH-supported scripting language, to be combined to create a single script.

XML provides the glue for combining different scripts into a Windows Script File. In this chapter, I'll cover some of the more commonly used WSH-supported XML statements. However, there simply is not enough space available in this book to completely cover every single XML element supported by the WSH. To learn more about the WSH's support for XML, visit http://www.msdn.microsoft.com/scripting and read through the Windows Script Host documentation posted there.

Definition

The Extensible Markup Language, or XML, is a language similar in design and syntax to HTML. It is used within the context of the WSH to define the structure of Windows Script Files.

Using XML, you specify the components that make up Windows Script Files. For example, you use XML to mark the locations within Windows Script Files where individual scripts (written in scripting languages such as VBScript and JScript) are embedded. Windows Script Files are saved as plain text files with a .wsh file extension and can be created using any plain text or script editor.

XML is case-sensitive and imposes a strict set of rules upon the format of Windows Script Files. For example, within the context of the WSH, most XML tags occur in pairs with one opening and one closing tag. Failure to include a matching closing tag will result in an error.

  TRICK

The WSH currently supports XML version 1.0. Version 1.0 supports both uppercase and lowercase spelling of tag elements. However, lowercase spelling is preferred, and I recommend that you do use only lowercase spelling. This way, if lowercase spelling becomes a requirement in a future version of XML, you will not have to retrofit your Windows Scripts Files in order for them to continue to run.

Examining WSH Supported XML Tags

XML represents an extensive and powerful multipurpose markup language. XML is therefore often used in many environments, including the WSH. However, the WSH only utilizes a subset of XML functionality. In this chapter, I'll introduce you to a number of commonly used XML tags, and I'll provide examples of how they're used to build Windows Script Files.

To begin, take a look at Table 10.1, in which is outlined the XML tags that you'll see demonstrated in this chapter's examples.

Table 10.1: XML TAGS COMMONLY USED IN WINDOWS SCRIPT FILES

Tag

Description

This tag is used to enable or disabled error handling and debugging for a specified job.

This tag specifies the Windows Script File's XML level.

This tag provides the ability to embed comments within Windows Script Files.

This tag identifies the beginning and ending of a script within a Windows Script File.

This tag identifies the beginning and ending of a job inside a Windows Script File.

This tag allows multiple jobs to be defined within a single Windows Script File.

This tag defines static data (constants) that can be referenced by script within a Windows Script File.

Using the Tag

The tag allows you to enable or disable error reporting and debugging within your Windows Script Files. The use of this tag is optional. Unlike most tags, the tag does not have a closing tag. The syntax for this tag is as follows:

flag" debug=" flag" ?>

Both error and debug are Boolean values. By default, both are set equal to false. Setting error="true" turns on error reporting, thus allowing syntax and run-time error messages to be reported. Setting debug="true" turns on debugging for Windows Script Files, allowing them to start the Windows script debugger.

  TRICK

To take advantage of the tags' debug capability, you'll need to install the Microsoft Windows script debugger utility. This utility is designed to assist programmers in debugging scripts errors. To learn more about this utility, check out http://www.msdn.microsoft.com/scripting.

The following example demonstrates how to use the tag within a Windows Script File:


 
 

As you can see, both error reporting and script debugging have been enabled.

Using the XML Tag

The tag is used to specify the version of XML required to support a Windows Script File. As with the tag, the use of this tag is optional. In addition, the tag does not have a closing tag.

When used, the tag must be the first tag defined as the first statement in the Windows Script File. The syntax for the tag is as follows:

version standalone=DTDflag ?>

Version specifies the version of XML required to support the Windows Script File. The current version is 1.0. Standalone is used to specify an external Document Type Definition, which is a feature not currently supported by the WSH. However, you can still include it if you wish, but you'll have to specify it as having a value of Yes (but it will still be ignored).

When used, the tag enforces stricter interpretation of all XML statements; it also enforces case-sensitivity while requiring that all values be specified within either single or double quotes. Omitting this tag provides for a less restrictive syntax. Let's look at the following example, which demonstrates the placement of a tag at the beginning of a small Windows Script File.



 
 

The < comment> Tags

You can document the XML statements used within your Windows Script Files using the XML and tags. Using these tags, you can spread out comments over multiple lines. The syntax for the and tags is as follows:

 Comment Text 

The following example demonstrates the use of the XML and tags.



 
 The following VBScript displays an information text message
 

The < job> Tags

In order to embed a script into a Windows Script File, you must first define a pair of root tags. The and tags provide one type of root tag pair.

All Windows Script Files are composed of at least one job. The beginning and ending of a job is identified by the and tags. The syntax for the tags is as follows:

JobID]>
 . . .

When only one job is defined within a Windows Script File, the id=JobID parameter can be omitted from the opening tag. However, if two or more jobs are defined within a single Windows Script File, each must be given a unique ID assignment. This assignment allows you to execute any job within the Windows Script File.

The following example shows a Windows Script File that contains a single job. The job itself is made up of two different scripts:




 

 The following VBScript displays an information text message
 

 The following JScript displays an information text message
 



If you double-click on the file, you'll see two popup dialogs appear, as shown in Figures 10.6 and 10.7. The VBScript generates the first popup dialog, and the JScript generates the other. In order to place more than one job within a Windows Script File, you must use the and tags, which I'll explain next.


Figure 10.6: A popup dialog displayed by the Windows Script File's VBScript


Figure 10.7: A popup dialog displayed by the Windows Script File's JScript

The < package> Tags

To place more than one job within a Windows Script File, you must enclose the jobs within the and tags. The syntax for these tags is as follows:


 . . .

To understand their use, look at the following example:



<package>

 The following job contains one VBScript and one JScript
 
 
 The following VBScript displays an information text message
 
 The following JScript displays an information text message
 
 

 The following job contains one VBScript
 
 
 


In this Windows Script File, the and tags are used to define two jobs. The first job is assigned an ID of job1, and the second job has been assigned an ID of job2.

The < resource> Tags

You have already learned about the advantages of defining constants within your VBScripts. However, these constants are only available within the script that defines them. Using the XML and tags, you can define constants within your Windows Script Files that can then be accessed by every script located within the same job. Therefore, when used, these tags must be placed within the and tags.

The syntax of the and tags is as follows:

resourceID">
 . . .

Id specifies the name of the constant whose value is then assigned when you type it in between the opening and closing tags, as demonstrated in the following example:



 TestScript.wsh
 


The tags in action a number of times in this chapter. They are used to mark the beginning and ending of individual scripts embedded within jobs in Windows Script Files. The syntax for these tags is as follows:


 

Language specifies the scripting language used to create a script. The src argument is used to specify an optional reference to an external script. If used, the external script is called and executed just as if it were embedded within the Windows Script File.

Let's look at an example of how to create a Windows Script File that includes both an embedded VBScript and one that is externally referenced. As you can see, the following Windows Script File includes a reference to two VBScripts:


 

The and tags were not required because this Windows Script File only contains one job. I added them anyway, just in case I ever decide to expand the script by adding another job. For example, if script configurations are ever migrated to the Windows registry, it might be helpful to define a second job to the Windows Script File specifying a setup script.

The and tags were added to help document the function of the Windows Script File. The opening and closing tags define the Windows Script File's only job. As only one job was defined, I did not bother to add the tag's ID attribute. Finally, three separate sets of tags have been created, marking the location at which each script that makes up the Windows Script File will be placed.

Writing the First JScript

Because the focus of this book is on VBScript as a WSH scripting language and not on JScript, I'm not going to attempt to explain in detail the following JScript. This script is relatively simple, and you should be able to tell what's going on by looking at the comments embedded within the script itself.

//************************************************************************
//Script Name: N/A
//Author: Jerry Ford
//Created: 12/20/02
//Description: This JScript displays the .WSF file's initial splash screen
//************************************************************************
//Initialization Section

var WshShl = WScript.CreateObject("WScript.Shell");
var Welcome;
var Instructions;
var Results;
var Reply;
var TitleBarMsg;

Welcome = "Welcome to the VBScript Game Console.";
Instructions = "Click on OK to play your favorite VBScript games!";

//Main Processing Section

//Verify that the user wants to open the VBScript Game Console
Reply = DisplayInitialSplashScreen();

//Reply will be set equal to 2 if the user clicks on the Cancel button
if (Reply == 2) {
 //Close the VBScript Game Console
 WScript.Quit();
}


//Procedure Section

//This procedure prompts the user for confirmation
function DisplayInitialSplashScreen() {

 TitleBarMsg = getResource("cTitlebarMsg");

 //Display a popup dialog using the WshShell object's Popup() method
 Results = WshShl.Popup(Welcome + Instructions, 0, TitleBarMsg, 1);

 //Return the result to the calling statement
 return Results

}


  TRICK

One way to develop each of the three scripts used in this Windows Script File is to create each script as a stand-alone script and get them all working as expected, and then to cut and paste the scripts into the Windows Script File in the areas identified for each script by the XML tags.

As you can see, this JScript is broken down into the same three sections that I've been using to organize this book's VBScripts (that is, the initialization section, the main processing section, and the procedure section). Comments in JScript are created using the // characters, and I have added a number of them to the script to explain its operation. The script's only function, DisplayInitialSplashScreen(), is responsible for displaying the VBScript Game Console's initial splash screen, which it does using the WshShell object's Popup() method. JScript does not provide any functions that work similarly to the VBScript MsgBox() or InputBox() functions. Therefore, to display text in a popup dialog using Jscript, you must use either the WshShell object's Popup() method or the WScript object's Echo() method.

Developing the VBScript Game Console

The VBScript portion of the VBScript Game Console contains the bulk of the complexity and programming logic. The first step in developing this VBScript is to insert your VBScript template and fill it in, as follows:

'************************************************************************
'Script Name: N/A
'Author: Jerry Ford
'Created: 12/20/02
'Description: This VBScript displays the actual VBScript Game
'Console interface and interacts with the user
'************************************************************************

'Initialization Section

Option Explicit

Defining the Elements in the Initialization Section

Next, let's define the variables, objects, and the array used by the VBScript. In most of the VBScripts that you've seen in this book, I've included a constant that defines the titlebar message to be displayed in the script's popup dialogs. However, this time I've omitted this constant in the VBScript because I have, instead, defined this value using the and tags at the beginning of the Windows Script File. This allows me to retrieve the constant and create a standard titlebar message for every script defined in the Windows Script File.

Dim FsoObject, WshShl, PlayOrNot, ConsoleStatus, SafetyNet, X
Dim GameFolder, Games, Selection, WordList, FileString, Count
Dim DisplayString, NoFilesFound

Dim ConsoleArray()

'Set up an instance of the FileSystemObject
Set FsoObject = CreateObject("Scripting.FileSystemObject")

'Set up an instance of the WshShell
Set WshShl = WScript.CreateObject("WScript.Shell")

'Retrieve the titlebar message to be displayed in popup dialogs
TitleBarMsg = getResource("cTitlebarMsg")

Building the Main Processing Section

The statements listed in the Main Processing section are straightforward. First, I used the FileSystemObject object's GetFolderMethod() to establish a reference to the location where the VBScript games to be displayed in the game console are stored. Then a For Each loop that spins through the list of files stored in this folder, keeping a record of the number of files counted, is executed.

  TRAP

Note that as the VBScript is currently written, it expects to find only VBScript files stored in the game folder. Therefore, no steps have been taken to filter out other file types. If you plan to store different files in the game folder, you will need to add additional logic to the VBScript to prevent it from displaying those files as well.

Next, the VBScript's array is resized according to the number of files found. This array will be used to store the names of each VBScript game and to associate each VBScript game with its assigned number as shown in the game console's dialog. Finally, the ConsoleLoop() function is called. This function is responsible for the overall operation of the VBScript game console.

'Main Processing Section

'Specify the location of the folder where script files are stored
Set GameFolder = FsoObject.GetFolder("C:VBScriptGames")
'Get a list of files stored in the folder
Set Games = GameFolder.Files

'Look and count the number of script files
For Each WordList In Games
 NoFilesFound = NoFilesFound + 1
Next

'Redefine the script's array based on the number of script files found
ReDim ConsoleArray(NoFilesFound)

'Call the function that displays and controls the VBScript Game Console
ConsoleLoop()

Creating the ConsoleLoop() Function

The VBScript Game Console is controlled by the ConsoleLoop() function. This function is responsible for assigning a number to each VBScript, for loading the VBScript's array, for interrogating user input, and for performing the appropriate action based on that input.

'This function displays the VBScript Game Console, accepts user input,
'validates the input, and starts other VBScript games
Function ConsoleLoop()

 'This string will contain a list of all the script files discovered
 'in the target folder
 Selection = ""

 'This counter will be used to track individual script files and will
 'be kept in sync with array entries
 Count = 0

 'Loop through the list of script files
 For Each WordList In Games

 'Increment count each time through the loop
 Count = Count + 1

 'Build a master string containing a list of all the word files
 'But exclude the VBScriptGameConsole.wsf file from this list
 If WordList.Name <> "VBScriptGameConsole.wsf" Then
 FileString = FileString & ""& WordList.Name

 'Build another list, adding number for later display
 Selection = Selection & Count & ". "& WordList.Name & vbCrLf

 'Load the name of each script into the array
 ConsoleArray(Count) = WordList.Name
 End If

Next

'This variable will be used to determine when to close the console
ConsoleStatus = "Active"

'Create a loop & keep it running until the user decides to close it
Do Until ConsoleStatus = "Terminate"

 'Interrogate the user's input
 PlayOrNot = UCase(PickAGame())

 'If the user did not type anything or if he or she clicks on Cancel
 'then exit the function and let things come to an end
 If PlayOrNot = "" Then
 Exit Function
 End If

 'Define a Select Case statement and use it to test the various
 'possible types of user input
 Select Case UCase(PlayOrNot)

 'If the user typed QUIT then exit the function and let things come
 'to an end
 Case "QUIT"
 Exit Function

 'If the used typed ABOUT call the function that displays
 'additional information abut the VBScript Game Console
 Case "ABOUT"
 AboutFunction()
 'If the user typed HELP, call the function that provides additional
 'help information
 Case "HELP"
 HelpFunction()

 'Otherwise, call the function that will run the selected VBScript
 Case Else
 ValidateAndRun()'

 End Select

 Loop

End Function

Creating the ValidateAndRun() Function

When called by the ConsoleLoop() function, the ValidateAndRun() function, shown below, validates user input by making sure that the user has supplied either a valid game number or valid game name. If a valid number or name is not supplied, then the function calls the InvalidChoice() function, which displays a generic error message telling the user how to properly operate the VBScript Game Console. If a valid number or name is supplied, then the function calls the RunScript() function, which then executes the specified VBScript game.

'This function validates user input and if appropriate, calls
'functions that display further instructions or runs the selected
'VBScript
Function ValidateAndRun()

 'Check to see if the user provided a valid game number
 If IsNumeric(PlayOrNot) <> 0 Then
 'Make sure that the user did not type a negative number
 If PlayOrNot > 0 Then
 'Make sure that the user did not type an invalid number
 If CInt(PlayOrNot) < CInt(Count) Then
 'If the number is valid, then find the associated script
 PlayOrNot = ConsoleArray(PlayOrNot)
 'Call the procedure that will then run the selected script
 RunScript()
 Else
 'Call this procedure when the user did not type a valid
 'script number
 InvalidChoice()
 End If
 Else
 InvalidChoice()
 End If

 'Check to see instead if the user provided a valid game name
 Else
 'Proceed only if the input typed by the user is a valid VBScript
 'game (e.g. its name appears in the previously built list of
 'VBScript game names
 If InStr(1, Selection, PlayOrNot, 1) > 1 Then
 'If the user did not type the scripts .vbs file extension, add it
 If InStr(1, PlayOrNot, ".VBS", 1) = 0 Then
 PlayOrNot = PlayOrNot & ".vbs"
 'Recheck to make sure that the script name is still valid
 If InStr(1, Selection, PlayOrNot, 1) > 1 Then
 'Call the procedure that will then run the selected script
 RunScript()
 Else
 'Call this procedure when the user did not type a valid
 'script name
 InvalidChoice()
 End If
 Else
 'If the user specified the script's .vbs file extension and it is
 'found in the previously built list of VBScript game names then go
 'ahead and call the procedure that will run the script
 If InStr(1, Selection, PlayOrNot, 1) > 1 Then
 RunScript()
 Else
 'If the user did not type a valid script name, call this procedure
 InvalidChoice()
 End If
 End If
 Else
 'This is the input typed by the user if not found in the previously
 'built list of VBScript game names call this procedure
 InvalidChoice()
 End If
 End If

End Function

Creating the PickAGame() Function

The PickAGame() function, shown next, is charged with displaying the contents of the VBScript game console whenever it is called. It does this by first building a primary display string that consists of a list of all VBScripts games that have been found, as well as instructions for getting Help, information about the script and its author, and for closing the game console.

The display string, which is aptly named DisplayString, is then plugged into a VBScript InputBox() function, thus displaying information about your VBScript games and providing the user with a means of selecting those games.

'This function displays the main VBScript game console and collects
'user input
Function PickAGame()

 DisplayString = Selection & vbCrLf & _
 "Or Type: [Help] [About] [Quit]" & vbCrLf

 PickAGame = InputBox("W e l c o m e t o t h e" & vbCrLf & _
 vbCrLf & "V B S c r i p t G a m e C o n s o l e !" & vbCrLf & _
 vbCrLf & "Pick a Game:" & vbCrLf & vbCrLf & _
 DisplayString, TitleBarMsg, "", 50, 50)

End Function

By default, all WSH and VBScript popup dialogs are displayed in the middle of the display area. However, in the previous example I specified values of 50 and 50 as the last two attributes of the InputBox() function. These two values specify the location where the popup dialog should be displayed on the user's screen. In this case, the popup dialog will be displayed in the upper-left-hand corner of the screen. This will keep it handy without crowding the display area in the middle of the screen, where the VBScript games will be displayed.

Creating the RunScript() Function

The RunScript() function, shown below, is very straightforward. When called, it uses the WshShell object's Run() method to execute the VBScript selected by the user, as specified in the ariable called PlayOrNot.

'This function starts the VBScript selected by the user
Function RunScript()

 WshShl.Run "WScript "& PlayOrNot

End Function

Creating the InvalidChoice() Function

The InvalidChoice() function, shown below, is responsible for displaying a generic error message using the VBScript MsgBox() function whenever the user provides the VBScript Game Console with invalid input. Examples of invalid input include numbers that have not been assigned to a VBScript listed in the console, such as -4 or 9999, as well as misspelled names of listed VBScript games.

'This function is called whenever the user provides invalid input
Function InvalidChoice()

 MsgBox "Sorry. Your selection was not valid. A valid selection "& _
 "consists of one of the following:" & vbCrLf & vbCrLf & _
 "* The number associated with one of the listed VBScript games" & _
 vbCrLf & "* The name of a listed VBScript game" & vbCrLf & _
 "* The name of a listed VBScript game plus its file extension" & _
 vbCrLf & "* Help - To view help information." & vbCrLf & _
 "* About - To view additional information about this game and "& _
 "its Author" & vbCrLf & "* Quit - To close the VBScript Game "& _
 "Console" & vbCrLf & vbCrLf & "Please try again.", , TitleBarMsg

End Function

Creating the HelpFunction() Function

The HelpFunction() function, shown next, uses the VBScript MsgBox() function to display additional help information about the VBScript Game Console. It is called anytime the user types help and clicks OK.

'This function displays help information in a popup dialog
Function HelpFunction()

 MsgBox "Additional help information for the VBScript Game Console" & _
 "can be found at:" & vbCrLf & vbCrLf & _
 "www.xxxxxxxxx.com.", , TitleBarMsg

End Function

Creating the AboutFunction() Function

The final function in the VBScript, shown next, is responsible for displaying information about the VBScript Game Console and its author. It is called whenever the user types about in the VBScript Game Console and clicks on OK. As you can see, the function consists of a single statement that uses the MsgBox() function. The information included here is really just a brief template; I leave it to you to finish adding whatever content you think is appropriate.

'This function displays information about the VBScript Game Console and
'its author
Function AboutFunction()

 MsgBox "VBScript Game Console  Jerry Ford 2002" & vbCrLf & vbCrLf & _
 "Email the author at: xxxxx@xxxxxxxx.com.", , TitleBarMsg

End Function

Writing the Second JScript

The final script defined in this Windows Script File, shown next, is JScript. It displays the game's closing splash screen and is designed in the same basic manner as the first Jscript, using the WshShell object's Popup() method to display its graphical popup dialog.

//************************************************************************
//Script Name: N/A
//Author: Jerry Ford
//Created: 12/20/02
//Description: This JScript displays the .WSF file's closing splash screen
//************************************************************************

//Initialization Section
var WshShl = WScript.CreateObject("WScript.Shell");
var Message;
var Author;
var Date;
var TitleBarMsg;

Message = "Thank you for using the VBScript Game Console  ";
Author = "Jerry Ford ";
Date = "2002";

//Main Processing Section

TitleBarMsg = getResource("cTitlebarMsg");

//Display a popup dialog using the WshShell object's Popup() method
WshShl.Popup(Message + Author + Date, 0, TitleBarMsg);

The Final Result

That's it. Let's assemble the entire Windows Script File as shown next. Before you run it for the first time, make sure that you've first created a folder called C:VBScriptGames and that you've copied both the VBScript game console script as well as a few other of your VBScripts games into the folder.



 This .WSF file builds a VBScript Game Console

 

 VBScript Game Console

 

 

 

 




Summary

In this final chapter you learned how to combine two or more different scripts into a single script using Windows Script Files. Windows Script Files are created using XML and a combination of different scripting languages. In addition, you got the opportunity to demonstrate your ability to work with Windows Script Files by developing the VBScript Game Console.

At this point, you should have a solid understanding of both VBScript and the Windows Script Host and should feel confident, not just of your game development capabilities, but also in your ability to apply the knowledge and skills that you've learned here in real-world situations.


Challenges

  1. Modify the information presented in the AboutFunction() and HelpFunction() procedures to make them more useful.
  2. Modify the Windows Script File so that the Windows Game Console script does not have to reside in the same folder as the games that it supports, and then modify the script to retrieve the location of the VBScript game folder from the Windows registry.
  3. Right now, the VBScript Game Console script only works with VBScripts. Modify it so that it will support any other script types that you plan to work with (such as Windows Script Files).




Microsoft WSH and VBScript Programming for the Absolute Beginner
Microsoft WSH and VBScript Programming for the Absolute Beginner
ISBN: 159200072X
EAN: 2147483647
Year: 2005
Pages: 137
Similar book on Amazon

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