Vbscript Free Tutorial

Web based School

Chapter 12

Advanced Objects: ActiveX, Java, and ActiveVRML


CONTENTS


Now you've seen a broad spectrum of ActiveX controls. You have learned the fundamentals, and you've seen the overall approach to integrating these controls. It is time to apply the base of knowledge you've gained so far to some advanced concepts. Today's lesson takes a look at integrating some more advanced objects, including objects other than just ActiveX controls. Strategies for designing effective ActiveX documents around these objects are considered as well.

The first control discussed is the chart control for generating graphs. This is another ActiveX control from Microsoft, but it makes use of some types of features that you haven't encountered yet with the other controls. For example, you can associate much larger quantities of data with this object than the other controls because you must provide the data to be graphed to it. The control also offers many more properties than those considered so far. You can assign a variety of properties to make the data representation take on many different forms. This control makes it easy to graph data from your scripts right before your users' eyes.

Next, the discussion turns to integrating non-ActiveX controls. I discuss issues pertaining to integrating Java applets. Java, a widely used programming language that originated from Sun Microsystems, Inc., is largely targeted for World Wide Web-related applications. A wide variety of Java applets or mini-applications suitable for embedding in a Web page are available, and the number is sure to grow steadily higher. Incorporating such objects can enable you to greatly extend the power of your Web pages, just as incorporating ActiveX controls does. Fortunately, you can incorporate Java applets in much the same manner that you incorporate ActiveX controls. This approach is discussed in some detail so that you know your options when considering such an integration.

The third area addressed today is ActiveVRML objects. VRML, Virtual Reality Modeling Language, pertains to the support of animations, three-dimensional images, and related technologies. With VRML, for example, you can present the user with a three-dimensional ski slope to navigate right on-screen. ActiveVRML is a VRML standard put forth by Microsoft. An ActiveVRML viewer control is available from Microsoft so that you can view VRML within a page. As you probably expect from its mention here, the good news is that you can manipulate this control from VBScript. As a result, you have control over ActiveVRML from your code. I explore the related approaches for integrating this tech-nology.

Finally, today's lesson will present an overview of control download technologies and issues. By the end of today, your scripting horizons will have broadened considerably. You will understand advanced issues of VBScript object integration. The strength of VBScript as an ultimate Web page glue tool for incorporating the power of all types of objects into your page will be clearly in focus.

Working with Objects

Before you consider more advanced concepts, there are just a few more object fundamentals to get straight. Object definitions can encompass several different types of entities that are not, strictly speaking, part of the Visual Basic syntax, but that can be controlled by VBScript code with appropriate references. One example of such entities is the intrinsic form controls and forms themselves. Another example is ActiveX controls and Java applets that can be included in the HTML source through the use of the object tag. In addition, many more objects-such as the intrinsic input controls-are automatically provided by the host browser environment and can be accessed. These include objects such as the page's document, location, and window objects. These are discussed in further detail on Day 18, "Advanced User Interface and Browser Object Techniques."

It is important to realize that these objects are not a part of the VBScript definition. Rather, they are part of the host environment (such as Internet Explorer) that incorporates Visual Basic. Or they are separate controls such as ActiveX objects that the host environment lets you incorporate. Objects provide a set of characteristics you can control; they are called properties. They also provide calls that result in a specific action; they are called methods. And objects can make it possible for code to be associated with certain conditions that are triggered by an object such as a mouse click. So an object in the general VBScript sense is an entity that can be controlled through properties and methods and reacted to through events. You deal only with the well-defined interface and do not have visibility into the code of the object itself.

VBScript itself only has one object that is inherent in the VBScript engine, or the core language definition of VBScript. That is the err object, which is discussed on Day 17, "Exterminating Bugs from Your Script."

Note
The term object is used in several slightly different contexts. HTML has an object tag that is used to explicitly define certain types of objects. On the other hand, many more entities that can be thought of as objects are automatically exposed by the Internet Explorer environment. In the discussion that follows, it is important to realize that an object is any such entity you incorporate into your pages, including those automatically exposed. The object-handling techniques are not limited to just controls defined through the HTML object tag.
You should also keep in mind that objects are specific to the environment that VBScript is hosted in. The core language of VBScript will be the same from environment to environment. However, the objects exposed by the host environment (such as the intrinsic controls or document object of a Web page) might not be the same in every environment that hosts VBScript. You can probably expect a fairly high degree of conformance of available objects between different browsers. Microsoft Internet Explorer's set of objects exposed to scripts (called the Script Object Model) is very similar to the set that Netscape exposes to JavaScript. Other browsers that incorporate VBScript would likely model their approach on many of the same objects.
A much bigger difference in available objects will be evident in non-browser environments that host VBScript as a script language. Suppose you use a file-management application that hosts VBScript as its scripting language. Many of the exposed objects that you are accustomed to using in VBScript code for the browser might not be available to VBScript code in the file-management application environment. For instance, the browser provides a window object with a navigate method you can use to advance to new pages. This probably wouldn't make sense in the context of a file-management application and wouldn't be provided as an object for scripts to use there. Although VBScript keywords and language usage would remain constant between the browser and file-management application, the objects that VBScript can use will differ between environments.

So what does all this mean to your code? There are some rules for dealing with objects in VBScript. VBScript needs an indicator that the data it is dealing with should be handled as an object. You provide this indicator through the set statement. The following is a set statement that assigns an intrinsic text box control to a variable:

Set myVar = txtcontrol

This assigns the object to the variable. You can check to see if a variable currently contains an object with an IsObject keyword, as discussed on Day 4, "Creating Variables in VBScript." For example, to see if myVar does indeed contain an object, you could use this check:

If ISObject(myVar)then

You can also check to see if two object references pertain to the same object. However, the = statement cannot be used for the comparison as you might expect. Once again, rules apply to guide VBScript in dealing with this special data type. The way to compare two object references is with the IS keyword, as discussed on Day 5, "Putting Operators to Work in VBScript." For example, if you need to see if myVar is currently referencing a command button called CMDSubmit, you can use this check:

If myVar is CMDSubmit then

This expression will evaluate to True if both of the references are to the same object entity.

Since an object is treated as just another data type that the variant variable can store, there is much you can do in code with objects. For example, you could define a procedure that checks to see if a certain string is supplied in a text box. The procedure could have a parameter for the text box control to be evaluated:

Function CheckTextControl(txtCurrentTextbox)

This subroutine could then be called with many different text box controls as parameters. For example, you could make this call to check the txtName text box that contains a user's name:

RC = CheckTextControl(txtName)

And you could make this call to have the same check carried out on the txtCompany text box control that contains a company name:

RC = CheckTextControl(txtCompany)

An object, then, is really just another data type that can be handled by variant variables. You will find that your code becomes much more powerful if you take advantage of this fact. VBScript provides all the necessary capabilities to handle objects. Then the host environment, such as a browser or the components that you tell the host environment to integrate (such as ActiveX controls), provides the object entities that VBScript can work with. The specific objects exposed by the Internet Explorer host environment will be addressed in much more detail on Day 18. The rest of today will be devoted to incorporating ActiveX control objects.

The ActiveX Chart Control

The chart control can really pack a punch when it comes to making an impressive, dynamic Web page. It is quite interesting from a VBScript programming standpoint because it enables you to supply rather extensive amounts of data dynamically through your script. The chart control can produce a variety of graphs in response to its property settings. It graphs data that you can initially supply through property values. Then, after the initial load, the graph can be regenerated in response to data changes through the script.

The first step to mastering this control is to understand the range of properties it provides. There are many properties for the control. Some of the main ones are summarized in Table 12.1. You can refer to Microsoft's Web site or use one of the control insertion/inspection tools described on Day 10, "An Introduction to Objects and ActiveX Controls," to see the full list of properties.

Table 12.1. Chart control properties.

PropertyDescription
ChartType Specifies the chart type such as pie or bar chart.
ColorScheme Region fill color set to use, ranges from 0 to 2.
Columns The number of data series columns.
ColumnIndex Indicates the current column index pertaining to the DataItem property.
DataItem Indicates one specific data value, indexed by current RowIndex and ColumnIndex settings.
HorizontalGrid Shows horizontal grids.
Rows The number of data series rows.
RowIndex Indicates the current row index pertaining to the DataItem property.
RowNames Names displayed under each data row.
Scale Percent scale factor for display purposes.
VerticalGrid Shows vertical grids.

A brief explanation of the properties follows. Because the graph is a visual control, the best way to understand the capabilities of the properties is by simply experimenting and observing the results. A sample application, charter.asp, is available on the CD-ROM for this purpose.

The first property that you must understand to use the graph control is ChartType. This affects the type of graph that will be displayed, such as a pie graph or bar graph. There are 20 different types available, which gives you lots of graphing options! Some of the most commonly used types appear in Table 12.2.

Table 12.2. Chart types.

Chart TypeValue
Simple Pie0
Pie with wedge out1
Simple Point Chart2
Stacked Point Chart3
Full Point Chart4
Simple Line Chart5
Stacked Line Chart6
Full Line Chart7
Simple Area Chart8
Stacked Area Chart9
Full Area Chart10
Simple Column Chart11
Stacked Column Chart12
Full Column Chart13
Simple Bar Chart14
Stacked Bar Chart15
Full Bar Chart16
HLC Stock Chart17
HLC Stock Chart WSJ18
OHLC Stock Chart19
OHLC Stock Chart WSJ20

The ColorScheme property enables the user to specify a color scheme for the graphed data. Rows and Columns specify the number of rows and columns in the graph. The VerticalGrid and HorizontalGrid properties can be set to 1 to enable the display of grid lines on the graph.

The three remaining properties, ColumnIndex, RowIndex, and DataItem, are all related to specifying a new data value for a data point on the graph. Data is initially specified in the object declaration as a series of rows and columns, as shown in the ActiveX chart control object declaration in Listing 12.1.


Listing 12.1. ActiveX chart control object declaration.
<!---------------- Chart Object ------------------------>
<OBJECT
CLASSid="CLSID:FC25B780-75BE-11CF-8B01-444553540000"
id=chtData
width=500
height=200
align=center
hspace=20
vspace=20
>
<param name="ChartStyle" value="0">
<param name="ChartType" value="2">
<param name="hgridStyle" value="1">
<param name="vgridStyle" value="0">
<param name="colorscheme" value="0">
<param name="rows" value="3">
<param name="columns" value="4">
<param name="RowNames" value="Week1 Week2 Week3">
<param name="data[0][0]" value="60">  <!-- Mike's Mileage for Week 1 -->
<param name="data[0][1]" value="70">  <!-- Karen's Mileage for Week 1 -->
<param name="data[0][2]" value="60">  <!-- John's Mileage for Week 1 -->
<param name="data[0][3]" value="80">  <!-- Brad's Mileage for Week 1 -->
<param name="data[1][0]" value="10">  <!-- Mike's Mileage for Week 2 -->
<param name="data[1][1]" value="70">  <!-- Karen's Mileage for Week 2 -->
<param name="data[1][2]" value="40">  <!-- John's Mileage for Week 2 -->
<param name="data[1][3]" value="80">  <!-- Brad's Mileage for Week 2 -->
<param name="data[2][0]" value="70">  <!-- Mike's Mileage for Week 3 -->
<param name="data[2][1]" value="80">  <!-- Karen's Mileage for Week 3 -->
<param name="data[2][2]" value="70">  <!-- John's Mileage for Week 3 -->
<param name="data[2][3]" value="90">  <!-- Brad's Mileage for Week 3 -->
</object>

The object attributes are the same as those of the other ActiveX controls we have covered. The properties are specific to the chart control, as outlined in Table 12.1, and you set them through the parameter definitions. You can also use these parameter definitions to supply the individual piece of data to be associated with each row and column data point on the graph. This technique is used in Listing 12.1. The data point at row 2, column 2 will be displayed as the value 70 on the graph that is generated when the page loads.

If you wanted to have a script reassign a value as the user interacts with the page, you would indicate the value to change through the ColumnIndex and RowIndex properties. Then you would supply the new value in the DataItem property. That would change the value at the data point indicated by the current ColumnIndex and RowIndex property values. Listing 12.2 shows an example of this technique.


Listing 12.2. Reassigning the data point in row 2, column 2 through code.
chtData.RowIndex = 2
chtData.ColumnIndex = 2
chtData.DataItem = 50

This capability to reset data as the script is running enables you to generate dynamic graphs in response to changing conditions or new user input. It's not just data that you can change. You can change the graph color, style, and even the number of rows or columns! Any assignments made in a script are performed as soon as that block of code is done executing.

Figure 12.1 shows a sample application to illustrate the code used to change the graph dynamically. It provides the weekly training mileage information for four runners for three weeks. The graph shows the miles trained on the vertical y axis and number of weeks on the horizontal x axis.

Figure 12.1 : The training mileage graph Web page.

Because the graph object supports multiple columns of data, all four runners can be represented on the same graph at once. A line type graph is used to present the data as well as the data trends. Input areas let the user enter replacement data to be immediately graphed. For example, maybe a user notices that Karen's mileage is inordinately low and wants to correct it. He can then supply the runner's name and the week that should be changed in the input field. The name and week essentially define the row and column for the data point. The user can also provide the new data, as well as a graph style indicator. Then, he selects the command button to perform the updates. Listing 12.3 shows the code that is executed in response to clicking the button. The source code for this sample is available on the CD-ROM in file charter.asp.


Listing 12.3. Graph update script.
<script language="VBScript">
<!-- Option Explicit

sub cmdApply_OnClick
' Update the graph

   dim intRunner ' current runner
   dim intRow ' row translated from week

   ' Determine which runner was specified
   if txtName.value = "Karen" then
       intRunner = 1
   elseif txtName.value = "John" then
       intRunner = 2
   elseif txtName.value = "Brad" then
       intRunner = 3
   elseif txtName.value = "Mike" then
       intRunner = 0
   else
      msgbox "That runner is not known.",0,"Unfamiliar runner"
   end if

   ' Data array starts at index 0
   intRow = txtWeek.Value - 1
 
   ' Update the graph
   chtData.RowIndex = intRow

   chtData.ColumnIndex = intRunner

   chtData.DataItem = txtMiles.Value

   chtData.Scale = txtChartStyle.Value

end sub
 -->
</script>

User input is converted from name to column index, and then the changes are applied. The results will show up to the user immediately. This sample illustrates modification of one data point, but your script could just as easily modify a series of 1000 points by coupling loop control code with the same technique.

The chart is a visually oriented control that scripts can heavily customize. However, it is not a control that the user can directly interact with unless you build special code around it. Even though the chart control has many properties to control its appearance, it has no events to go with it. Likewise, the chart control has only one property-the AboutBox property, which provides version information about the control. Although you might write a lot of code for the chart control, it will be code that modifies the appearance of a chart through properties. It won't be code that gets executed based on chart events or takes advantage of chart method calls (other than AboutBox).

As you can see, you don't have to access a lot of events and methods to be able to heavily customize the display of a control and interact with the user through the control. The chart control has many different graphical representations it can assume. It's a good idea to be familiar with the formats listed in the ChartType property, so when a graphing need does arise, this control can provide a quick, easy-to-implement solution.

Integrating Java Applets

So far you've seen a lot of examples of how to integrate ActiveX controls. Now, the discussion turns to integrating some very important non-ActiveX types of objects, including one of the most famous citizens of the Internet technology world. Anyone who has followed the Internet very closely has probably heard of Java. Java, which originated from Sun Microsystems, Inc., is a language with many facets. Due to the tremendous growth in interest in this language, Sun now has an entire business unit, JavaSoft, which is focused on Java issues. Java is a language used for creating programs on the World Wide Web as well as intranet solutions.

Note
A wealth of information about Java is available on the World Wide Web. A good place to start is the official Java page from Sun Microsystems at http://java.sun.com.

The Java language is particularly well-suited for the Web because it is platform independent. A Java applet downloaded from a server, with appropriate run-time support in a browser, could run on an Apple Macintosh, UNIX workstation, or IBM pc. Java is an object-oriented language with many elements in common with the C++ language. However, it does not provide memory pointers for the programmer. This avoids the memory referencing problems they can introduce. As a result, Java facilitates the creation of stable, safe applications. You can think of Java as existing in three main forms: JavaScript code, Java applets, and Java applications.

You can use the JavaScript form of this language for embedding code into a page and controlling interaction on the page. The concept is similar to that of VBScript, although the language and integration capabilities differ. JavaScript is not directly derived from Java, however, and writing a JavaScript script and a Java applet is considerably different. Java applets are programs created in Java that are then generated in a platform-neutral byte code format. These bytes are not specific to a UNIX workstation, a pc, or an Apple Macintosh but remain in a general, predefined form that cannot be directly executed by a computer. How does an applet ever run? You can download a Java applet with a page as a separate file, and then a browser can launch that Java applet through a piece of software called a run-time interpreter. This run-time interpreter translates the generic byte codes of the applet file into specific actions executed by the computer. The third form of Java is a Java application. A Java application is like a standard application. It is generated in the byte format understood by a computer type. It can then run directly on computers of that type with no additional translation.

Note
After the preceding discussion, you might be wondering if JavaScript and VBScript give you two different ways to do the same thing. The answer is that, to a large extent, they do, although there are some very significant differences between the languages as well. VBScript is viewed by many to be a far easier language to use because of the relatively straightforward Visual Basic syntax. Although the syntax and overall approach of these languages is quite different, they both can be used to produce dynamic Web pages.

By this point, you might be thinking, "Okay, all this stuff about Java is fine, but if I wanted to know about JavaScript, I'd be reading a JavaScript guide instead of a VBScript guide!" The payoff for VBScript programmers is in the Java applet arena. Think of it: A lot of files full of function in platform-neutral format are sitting around, waiting to be integrated into Web pages. JavaScript isn't of much interest because you can just use VBScript instead. Java applications might not be of direct interest because you don't want to deliver a platform-specific application to your users; you want to provide them with a smart Web page. The payoff sits squarely in the Java applet domain. VBScript lets you take advantage of all the Java applets out there right from your script. There are lots of Java applets today, and you can bet that there will be more and more coming in the future.

You can integrate the applets into your programs and directly use their capabilities from your script. Sound familiar? In many respects, it's very much like the ActiveX object integration model. There are some important differences, such as the events that ActiveX provides, but there are also a lot of similarities. You incorporate a Java applet through an object definition. You provide a name for it that you will reference from your code. You interact with it through the properties and methods that it has defined. An applet can show up on the page as a visible component that the user sees and interacts with, but it doesn't have to. It can also do its job relatively out of sight. A Java applet, like an ActiveX control, can be included in a page even if a script doesn't reference it. It will still appear on the page and provide whatever inherent capabilities it has. Your script can become the glue that enables you to drive the Java applet in response to user input and make the page smarter, more active, and more dynamic through its capabilities.

Listing 12.4 shows a sample of a Java applet object declaration. The discussion that follows outlines the probable implementation of Java applets. As this guide went to print, this support is not yet in the Internet Explorer beta so final details may change. This applet provides an estimate of the time needed to develop a simple Web page based on the lines of HTML and the lines of code planned. Your script will be able to reference this Java applet object by the name jvaEstimator because that is the name assigned through the ID attribute. The java: portion of the CLASSID attribute indicates to the browser that this is a Java applet. ActiveX controls, by contrast, start with a clsid: prefix to indicate they are an entity that you can reference by standard system class IDs. The remainder of the CLASSID attribute indicates the class name of the Java applet, which is estimator.process.

Note
Don't get confused by the two levels of class IDs used here! An object has a CLASSID attribute that specifies the class or type of object it is. Then, some objects, such as ActiveX controls, define this further in terms of clsid:classname to provide a reference to a system-wide class for that control. Other objects, such as Java, define it further in terms of an application-type indicator and the class that application supports, as in java:app.class. All approaches have the same purpose-to provide an ultimate pointer to the object methods and properties available.


Listing 12.4. An object declaration for a Java applet.
<OBJECT
       id="jvaEstimator"
       CLASSid="java:estimator.process"
       CODETYPE="application/java-vm"
       CODEBASE="http://w3.softlookup.com/pathinfo/"
       HEIGHT=100
       WIDTH=100
    >
Get a 20th century browser, buddy!
</OBJECT>

The CODETYPE attribute in Listing 12.4 identifies the general type of the object defined. This is a similar but much more general piece of information than the CLASSID, which defines specifics of what the object is and the class to use to reference it further. One of the uses of the CODETYPE attribute is that the browser can see what the supported type is and then determine whether that type is supported by the client's browser and installed support software before it attempts to download the object. If a script referenced a Java applet but the user's browser and extensions didn't support Java, the object would not be downloaded. Instead, the message that precedes the end of the object declaration, Get a 20th century browser, buddy!, would be displayed on the page. This is commonly called an "apology message." It provides more information for those users whose browsers are not up to speed with the technology of your page. (Of course, you should use your own more subtle version of an apology for real pages.) CODETYPE is an optional attribute. What would happen if CODETYPE was not included in the declaration? The applet file would be downloaded even though it could not be used by the current page.

The next attribute is CODEBASE. You can use this to specify the URL where the Java applet is located. If the applet was at the same location as the page itself, the optional CODEBASE could be omitted, and the applet would still be located correctly. HEIGHT and WIDTH specify the visible area where the object is displayed. You could also use the ALIGN attribute discussed on Day 10 to control alignment. The Estimator applet, for example, might display the resulting estimate itself in its applet area. You would then want to control the size and alignment of this area on the page. On the other hand, the applet could also be written to simply store the resulting estimate in an applet property for your script to retrieve. If that were the case, no visible display of the applet would be needed.

Note
At the time of this writing, this method of declaring Java applets as objects was likely but not yet reflected through official Microsoft documentation. If you want to verify the implementation at the time you read this, you can refer to the Microsoft VBScript object information page at http://www.microsoft.com/vbscript/us/vbstutor/vbsobjs.asp. Most aspects of this implementation are also documented as part of the W3C standard committee working draft at http://www.w3.org/pub/WWW/TR/WD-object.asp.

Listing 12.5 shows another declaration for this applet without some of the optional attributes. Because CODEBASE is not supplied, the Java applet will be located in the base directory of the page itself. No CODETYPE attribute means that the applet will be downloaded for all users of the page, even if they have an old browser and it won't work for them. Because this applet will have no visible interface that it directly supports, no WIDTH and HEIGHT are defined.


Listing 12.5. An object declaration for a Java applet without optional attributes and with parameters.
<OBJECT
   id="jvaEstimator"
   CLASSid="java:estimator.process"
>
   <PARAM NAME="LinesHTML" VALUE="300">
   <PARAM NAME="LinesScript" VALUE="200">
</OBJECT>

The declaration in Listing 12.5 also uses something that should look familiar from the ActiveX controls: the parameter tag. You use the parameter tag <PARAM> to supply initial values for properties of the Java applet. Properties are referenced through the NAME field, and the starting value is supplied by the VALUE field. In the preceding example, LinesHTML and LinesScript are both properties defined in the applet itself. The <PARAM> statements load those properties with the specified default values when the page is loaded. The Estimator applet also makes use of several more properties. However, if this page doesn't need to supply custom default values, they do not need to be initialized as the page loads, and therefore you don't need to specify them at the beginning of the code. You can still reference and modify all the properties from the VBScript code that uses the applet, even if they're not specified in the initial object declaration.

As you can see, the declaration approach is very much like that used for other controls. Using a Java applet object from code is even more similar. Listing 12.6 shows code that uses the applet. This code is executed in response to a user click on a command button defined on the page. The code assigns the values supplied by a user in text boxes on the page to the properties of the applet. Then, a Calculate method is called to calculate the estimate itself, which results in the assignment of the correct estimate to the applet's EstimatedTime property. The script then displays this estimate to the user by referencing the property in a message box call.


Listing 12.6. Using a Java applet from VBScript.
<SCRIPT LANGUAGE="VBScript">
<!--
   sub cmdEstimate_OnClick
   '  This routine is called when the user clicks Calc button on the page
     'Assign applet properties from user supplied values in page's textboxes
     '  If no user input is supplied, default property values used
     if len(txtUserDistance.Value) > 0 then
         jvaEstimator.LinesHTML = txtUserDistance.Value
     end if
     if len(txtUserTime.Value) > 0 then
        jvaEstimator.LinesScript = txtUserTime.Value
     end if

     ' Use the applet to calculate the estimate, then display the results
     jvaEstimator.Calculate
     msgbox "The estimated time for this job is " & jvaEstimator.EstimatedTime
end sub

The ActiveVRML Viewer Object

ActiveVRML is a fascinating technology laden with potential. ActiveVRML is the control of 3-D animations, multimedia, and virtual reality type applications. You can integrate ActiveVRML with VBScript. The information that follows is not intended to show you all the details of how to use ActiveVRML. That will require further study of your own if you want to pursue it. It is quite a broad area that justifies a guide in its own right. The information that follows will show you one more side of the VBScript component integration model.

Note
ActiveVRML is certainly worth learning and learning well if you have an interest in it or see applications for your Web page. Refer to http://www.microsoft.com/intdev/avr.

ActiveVRML instructions are based on the Active Virtual Reality Modeling Language. The approach of this language is script-like in many aspects, and it's sometimes referred to as ActiveVRML script language. However, ActiveVRML is different from VBScript. ActiveVRML scripts deal with the ActiveVRML content itself. You can use an ActiveVRML viewer control to view the ActiveVRML contents on a page. VBScript can control this viewer control. The events and methods of the viewer control essentially provide a communications conduit between VBScript and the ActiveVRML script that controls the ActiveVRML display contents. The viewer control provides just one method and one event that you use to shuffle information between the two. To effectively integrate the ActiveVRML viewer in your VBScript, you need a fair amount of familiarity with ActiveVRML itself. The viewer is integrated much like other components you have seen before. Listing 12.7 shows the familiar object declaration.


Listing 12.7. Declaring the ActiveVRML viewer control object.
<OBJECT
CLASSid="CLSID:389C2960-3640-11CF-9294-00AA00B8A733"
id="avViewer"
WIDTH=50
HEIGHT=50>
<PARAM NAME="DataPath" VALUE="http://www.address.yours/its_location/avr_
                              yourfile.avr">
<PARAM NAME="Expression" VALUE="myImage">
<PARAM NAME="Border" VALUE=False>
<PARAM NAME="Frozen" VALUE=True
</OBJECT>

The attributes of the object probably look familiar at this point. The use of CLASSID, width, and height is the same as for other objects. However, the parameter properties are unique to this control. Datapath indicates the URL of the file. Expression is the ActiveVRML expression that the viewer will display. Border specifies whether a border will appear around the viewer control. Frozen indicates whether script-level changes to the properties will cause the viewer display to be refreshed.

The ActiveVRML viewer provides one key method and one key event, but they are very powerful. Just the one method enables you to trigger a wide variety of actions. The single event allows you to respond to a wide variety of events from within the ActiveVRML. This is because additional information is passed in parameters for both the event and the method. The method shown in Listing 12.8 is used to trigger action in the viewer control.


Listing 12.8. Triggering a method for the ActiveVRML control.
<script Language="VBScript">
<!--
    sub cmdTest_OnClick
        AVViewer.FireImportedEvent 50, 40
    end sub
--!> </script>

In this case, FireImportedEvent generates the event for the ActiveVRML script to receive. It supplies the user-defined event ID of 50 and an additional parameter of 40. This technique demonstrates the interaction possible with ActiveVRML.

Receiving events uses an approach that is similar to that used for triggering a method. Listing 12.9 shows code that handles an event from the viewer control.


Listing 12.9. A script event handler for the ActiveVRML viewer control.
<script for="AVViewer" event="ActiveVRMLEvent(EventId, Param)"_
                              Language="VBScript">
<!--
    ' Respond to event from viewer control
    MsgBox "Event in viewer control occurred, it is id=" & _
       EventId & "  Param=" & Param, 0, "Event Notification"
--!>
</script>

The ActiveVRMLEvent that is generated by the ActiveVRML script can be caught and handled by VBScript with an event handler such as that shown in Listing 12.9. You could also use the subroutine declaration syntax

sub AvViewer_ActiveVRMLEvent (EventId, Param)

within a script to catch this event. When this event occurs, the EventId parameter will indicate the event identification supplied by the ActiveVRML script. The parameter supplied could be empty, a string, or a number, depending on what the ActiveVRML script supplied when it generated the event.

You've had a taste of integrating ActiveVRML into your scripts through the ActiveVRML viewer. ActiveVRML is an area that takes some study to master, and the preceding discussion is not intended to be sufficient for you to churn out your own 3-D virtual Web pages. For that, you will also need to master the ActiveVRML concepts and script language. However, you have seen how this object, like the others before it, follows the same set of integration principles. Declare the object with an object declaration, and then reference its properties and methods and respond to its events. The viewer takes a somewhat special approach to the method, supplying a general-purpose method that you can use to communicate a variety of user-defined events back to the ActiveVRML script. Likewise, the viewer generates just one generic event for VBScript to respond to. By inspecting the parameters that are supplied with that event, the VBScript code can determine full details of the information supplied from the ActiveVRML script. You can see that VBScript once again serves as a kind of nerve center for the page. It is a capable glue for pulling all the pieces together into a comprehensive Web page and providing script-level control of those pieces.

Component Downloading Issues

There are some important issues to consider beyond just declaring objects and referencing them from code. What happens when a user downloads a page that utilizes a dozen of the latest and greatest objects on the scene? She might have some of the controls present on her system, or maybe she has none of them present. Should the page notify the user? Fail to work? Carry out the download across the Internet?

The ideal solution, and the solution now in place, is to supply the user with the component. To get the most productivity out of the Web, the user should be able to wade between pages and links counting on the fact that the pages are usable. The ideal situation for the user is that when she needs a capability from an object, she's transparently provided with that capability through the object download.

It turns out that this approach has quite a few complications. One is download time. It can take a while to download a lot of controls across the network. Another issue is installation. Many objects such as ActiveX controls require some installation for system registration and other aspects in addition to just merely downloading the file. Still another issue is control. If a company sells a control, they don't want copies of it to bounce willy-nilly across the Internet free of charge. Perhaps the most important issue is security. Because of its importance, it is addressed in detail on Day 21, "Security, Stability, and Distributed Source Control Issues." Component certification, the capability to track components through unique signatures, and browser capabilities to allow or prevent downloads are all ways of addressing different sides of the issue.

Currently, the state of browser support for object download varies based on the browser and the version, but the early framework is largely in place. In the discussion of Java applets earlier today, you saw that a download location for the applet can be specified through the object's CODEBASE attribute, and if that's not provided, the applet can be retrieved from the same path as the page. According to the current draft W3C standard, this would apply to any object. Microsoft early beta plans and implementation go even a step beyond this. Specific guidelines have been formulated to describe how downloading ActiveX controls can be addressed by browser writers and component creators. This includes specific download Application Program Interface calls, component packaging guidelines, and areas of component storage and cache. Some interesting issues addressed as part of this approach include providing the release number of objects as part of the URL and providing a configuration file to control installation for a group of files that can be processed by download service software.

These issues are all at various stages of draft proposal and evolution. As they are resolved, the low-level technical details will probably most directly affect browser writers and component creators more than they will affect VBScript writers. The high-level end results will affect you and the distribution of the scripts you write. You must be aware that these issues exist because they do affect the ability of users to take advantage of your object-based scripts. Soon the technology will be at the point where any leading browser will magically provide users with everything they need to interact with a page. The leading browsers are largely there already. But still, VBScript writers will have to keep an eye toward these evolving standards and the capabilities of the browsers the users view their pages with.

Summary

Today you have learned about the ActiveX chart control. This is more complex than some of the other ActiveX controls examined on earlier days in the sense that you can assign sets of data to it. The control then renders a graph based on this information. You can change the properties of the chart control from a script just as you can for any other control. You can even change the graphed data and graph type itself from a script. When such changes occur, the graph updates as soon as the code completes. The chart control makes it possible to dynamically produce charts based on changing user data as the user interacts with a page.

Another way to extend the power of Web pages is through Java applets. Java applets are written in the Java language and distributed as files of byte code. This byte code can then be interpreted by browsers on a variety of platforms to execute the applications. You can include Java applets in a Web page through the object declaration. The best news is that VBScript can use them! The techniques for controlling a Java applet from code are much the same as those for controlling ActiveX control objects. The applet is referenced by an ID attribute that is declared as part of the object declaration. Its properties and methods can be called directly from the code.

An additional control that offers another type of capability to your scripts is the ActiveVRML viewer control. This object lets you control the display of ActiveVRML sessions, which can display 3-D displays including animations and multimedia. A fairly high degree of integration is possible with the capabilities offered by this control.

Finally, this lesson discusses the issue of downloading objects on demand. Objects that are embedded in Web pages are downloaded across the network when a page requires them. This requires that the object is present on the network and correctly specified in the page object declaration. It is also a capability not present in older browsers. The security implications are addressed on Day 21. This distribution model makes it even easier to share dynamic pages rich in functionality across your company or across the world.

Q&A

Q Can you reference Java applets, ActiveX controls, and ActiveVRML control objects all from the same script, or are you restricted to just one type of object per page?
A There is no restriction. The script can reference any object definition on the page, and all types can be present on the same page.
Q Suppose you have a page where you want to calculate and present the result of the average wage and standard deviation wage of five workers. You could write this in VBScript, but you also hear that there is a large ActiveX math control available, as well as a Java applet that does wage calculations. Is there an obvious choice as to the best way to proceed?
A Not necessarily. There are tradeoffs in choosing any of the options. If you use VBScript, you have to write the calculation yourself. On the other hand, if you use the objects, you're taking advantage of code that has already been written (and debugged!) by others. It could be quicker to integrate the object. On the other hand, if you use an object, the user will have to wait for an additional file to download if it must be downloaded across the network.
Q Does an object have to be present in advance on the user's computer for him to make use of a page that requires it?
A No. Objects that have URLs defined as part of their location or objects that are in the same path as the home page will be downloaded when needed. However, depending on browser settings, the user will be warned when these downloads take place.

Note
Downloading components on demand is a maturing technology. If you have an early browser-for example, the beta version of Internet Explorer 3.0-this capability might not yet be supported.

Workshop

Create a Web page that utilizes the ActiveX chart object and scripting. The graph should come up by default with a graph of the hours of sleep and the hours of computer time you've had over the last seven days. Provide two command buttons. The first button should update the graph to display your ideal data if you could choose any amount of computer time. The second button should present the actual data that is also used for the default presentation.

Quiz

Note
Refer to Appendix C, "Answers to Quiz Questions," for the answers to these questions.

Show the object declaration you would need to use to declare a Java applet that you can access by the name jvaGifts in your script. This applet suggests birthday gifts when supplied with user demographics. The applet has a class name of Birthday.Logs. Assign a default value of 200 to the applet's MaxSpend property in the declaration. Assume the applet is located at the fictitious path given in http://w3.softlookup.com/ and that this is different from the location of the page that uses the applet. Show the code statement that you could use within a script procedure to change the MaxSpend property to $300.