Using Visual Basic 6

Previous chapterNext chapterContents


- 28 -
Creating VB Programs for the Internet


Working on the Internet


Advantages of using VB and VBScript on the Internet

More than likely, you already have a general idea of what the Internet is, and you use it every day for email, Web browsing, and downloading files. Also, many of you probably already develop Internet applications with C++ or Java. You can use any document on the Internet, including spreadsheets and databases, but sometimes you need to do a little programming to force the application to do what you want it to do. Learning Visual Basic and VBScript in relation to Internet programming puts you one step ahead, and your Web pages will work and look much better.


Before you look at how to use Visual Basic to do Internet programming, it's useful to have a fundamental concept of how the Internet works. In a nutshell, the Internet is a very large network with millions of users and computers interacting with each other. To expand on this concept, the entire Internet is nothing more than millions of computers communicating with each other by means of special documents. These documents are written in special code that all computers can understand. Some of these documents are interactive, meaning that any user can change the information that the document contains. One example of this is the Web page, which is one or many documents in which users can add or change information.

As complex and unwieldy as the Internet is, its fundamental dynamics concern the relationship between a client PC and server computer. A client is something that needs a service, and a server is something that provides a service. In the case of the Internet, the client is the computer in your home or at your office, and the server is a computer somewhere on the Web that provides data to the client.

The way by which the client can talk to the server is via protocols. A protocol is a set of rules by which the client knows how to pass requests for data to the server. Likewise, the server knows how to send responses back to the calling client. Protocols are useful because they don't rely on platform specifics. A client doesn't need to know whether a server is an HP running an operating system such as UNIX or an IBM running OS/2; the server doesn't need to know whether the client computer is a Macintosh or a Gateway PC.

The protocol used most often on the Internet is HTTP (Hypertext Transfer Protocol). Another widely used protocol is FTP (File Transfer Protocol), and there are others. Any computer that can talk HTTP or FTP can communicate with servers on the Internet, and vice versa.

For a computer to be a server on the Internet, it must have two things: an address by which other computers can locate it and the capability to understand and process the various protocols. A server is assigned a unique numeric ID called an IP (Internet Protocol) address. Normally, however, you don't use the numeric address when calling a server on the Internet; instead, you use the server's associated domain name. The domain name is the friendly addressing format, www.domainname.com, that you've come to know from using the World Wide Web (see Figure 28.1).

FIGURE 28.1 The Internet is based on discrete conversations between a client computer and an Internet server.


Many ISPs out there

The ISP that you use might depend on your local area. This book doesn't recommend any particular service because they all provide one basic function--connecting you to the rest of the world. Each ISP is unique because each has a slightly different format. You might try several before settling on one. Some services, such as AT&T Worldnet and America Online, offer trial memberships in which you can "try before you buy."


The software used on the physical computer to make it a server that can speak the protocols of the Internet and respond accordingly is called Internet server software. The particular Internet server software manufactured by Microsoft is Internet Information Server (IIS).

For a client computer to be able to communicate with a server on the Internet, it must have a connection to the Internet. Then, when connected, it must have a way to contact and receive data from Internet servers through the various protocols. The connection is accomplished via an Internet service provider (ISP), such as America Online, CompuServe, MSN, AT&T Worldnet, MCI, or Sprint. The tool to communicate to the server and decipher the data returned by the Internet server is handled by the Internet browser, such as Microsoft's Internet Explorer or Netscape Navigator.

Where does Visual Basic fit in all this? Microsoft has positioned Visual Basic to play an important role on the client side and the server side. On the client side, you can use a derivative of Visual Basic, VBScript, to create Web page programs that can run from within Internet Explorer. You also can use Visual Basic to create custom ActiveX components that you can embed in Web pages and run as any custom ActiveX component would.


Client side versus server side

If you write a program that resides and executes on a client computer, that program is called a client-side program. If you create a program that runs on an Internet server, that program is called a server-side program. Microsoft Word is considered a client-side program. Yahoo Search, a program that searches for articles on the Web, is a server-side program.


On the server side, you can use VBScript to create Active Server Pages (ASP) in order to create logic that enables IIS to respond to various input from client computers. Also, you can use Visual Basic to create custom ActiveX components designed to work as extensions and enhancements to the IIS environment. These components are called server-side components.

You can use VBScript with server-side ActiveX components to access databases connected to the Internet server to return data to the client. You can keep track of the various activities of the users accessing your server. You can handle mail and deliver files. You can create responses custom-tailored to the specific requester. You can transact business.

On the client side, you can use VBScript to make decisions about what information to send back to the server, to create animation effects, and to interact with other programs on the client computer, to name a few examples.

Microsoft is very serious about the Internet and is trying to position Visual Basic as the language by which to program for the Internet, provided that you use Internet Explorer as the client browser and Internet Information Server as the Internet server software on the back end. Therefore, using Visual Basic or VBScript within the context of the Internet is a skill that's more and more expected of programmers.

Making a Simple Program with VBScript

When you install Internet Explorer on your computer, you have access to some benefits of the Visual Basic programming environment. Although IE isn't a complete programming environment, you still have a lot of programming potential at your disposal. Most commands, statements, and functions available to you in Visual Basic are also accessible to you in Internet Explorer.


Programs versus scripts

Most often you can think of a script as a small program. However, there are subtle differences between a program and a script. In the traditional sense, you can think of a script as a set of tasks performed in sequence. On a Web page, a script is a set of tasks that the page executes as it loads. Programs, on the other hand, are a collection of sets of tasks that can be performed sequentially or at random. For instance, you can have a program that runs a set of tasks on startup and another set of tasks when a user clicks a button (event-driven). As scripting languages such as VBScript become more powerful, however, the boundary between where a script ends and a program begins becomes more and more complicated.


When used to its full potential, VBScript is a useful but not really powerful script language that lets you write programs to control the way things happen on the Internet and in other environments. There has never been a script language that can compete with a programming language such as Visual Basic. You could probably achieve the most power by combining the two environments and using both VBScript and Visual Basic. Other VBScript limitations include the following:

Also, you can't do the advanced things that Visual Basic enables you to do, such as create custom controls and classes or access the Windows API. However, with VBScript you can access ActiveX controls. The more you use VBScript, the more ways you will discover to make it work to your benefit.

Because VBScript is a text-based programming language, you don't need to have a copy of Visual Basic to program in VBScript. All you need is a text editor such as Notepad to create HTML pages with VBScript embedded in it. Advanced tools such as Visual InterDev offer the benefit of visual programming enhancements and editing capabilities that enable you to write VBScript more easily.

VBScript executes as a Web page loads into Internet Explorer. For example, you can use VBScript to write text to a browser window, thus avoiding the need to write the page in HTML. Although it's far from being a replacement for HTML, VBScript does most of the same functions, providing you with a quick solution to some Web programming problems.

Creating an Hello World program in VBScript

1. Open Notepad or another text editor and enter the following text:
<SCRIPT LANGUAGE="VBScript">
    document.write "Hello World"
</SCRIPT>

2. Save the text as Test.htm.

3. Open Internet Explorer.

4. Drag the Test.htm file from Windows Explorer to the client area of Internet Explorer (see Figure 28.2).

FIGURE 28.2 VBScript enables you to control output to Internet Explorer.

Using VBScript with Internet Explorer

You can use VBScript with HTML to make Web pages that appear and behave like Visual Basic programs. This is possible because, as you read earlier, much of Visual Basic functionality is built into Internet Explorer. Figure 28.3 shows a simple page of HTML, 28htm01.htm (see Listing 28.1), presented in Internet Explorer. If users enter Fred Flintstone in the top text box, the bottom text box returns the validation string You are in!. Any other text produces the response You are out. If you're interested in more information on HTML programming, look into some of the books on the subject at http://www.mcp.com.

FIGURE 28.3 You can process data by using VBScript and HTML.


Placing VBScript on a Web page

You place VBScript between the <SCRIPT></SCRIPT> tags on a Web page. As the script is loaded from the Web page, script is executed as each line is encountered. If you have script at the top of a page, that script executes even if the page is still loading. If the script is a procedure, however, it's not executed until it's called from other areas in the page. Usually, procedures are placed within the <HEAD></HEAD> tags at the beginning of the page.


LISTING 28.1  28HTM01.HTM--A Simple Page of HTML That Processes Data

01 <HTML>
02 <TITLE>Using VB6: VBScript</TITLE>
03 <HEAD>
04 <!--This is how you make a commented line in HTML-->
05 <SCRIPT LANGUAGE=VBSCRIPT>
06 <!--
07 `This is a commented line in VBScript. You only use
08 `the apostrophe within the SCRIPT tag.
09
10 Sub cmdValidate_OnClick()
11 `This Sub examines the value of the text
12 `entered in the first TEXT element.
13 If txtName.Value = "Fred Flintstone" Then
14 `If TRUE, then ALLOW Login
15 txtValidate.Value = "You are in!"
16 Else
17 `If NOT, then DISALLOW Login
18 txtValidate.Value = "You are out!"
19 End if
20 End Sub
21 -->
22 </SCRIPT>
23 </HEAD>
24
25 <BODY>
26 <!--Create heading using the heading
27 H1 tag and center the heading -->
28 <CENTER>
29 <H1>Secret Login</H1>
30 </CENTER>
31
32 <!--Put in a paragraph break; create a
33 textbox using the INPUT TYPE= HTML
34 element. Make sure to put some labeling
35 text above the textbox. -->
36 <P>
37 Name:
38 <BR>
39 <INPUT TYPE=Text Size=40 ID=txtName>
40
41 <!--Put in a paragraph break; create another
42 textbox using the INPUT TYPE= HTML
43 element. Make sure to put some labeling
44 text above the textbox. -->
45 <P>
46 Authentication:
47 <BR>
48 <INPUT TYPE=Text Size=40 ID=txtValidate>
49
50 <!--Put in a paragraph break; create a
51 button. Give it an ID of cmdValidate
52 so that it will call the event handler
53 coded in the above SCRIPT tag. The
54 event handler is cmdValidate_OnClick. -->
55 <P>
56 <INPUT TYPE=Button Value="Validate" ID=cmdValidate>
57 </BODY>


Download this code

A fully commented, unnumbered version of this code is available from http://www.mcp. com/info. The code for this chapter is in the file VB6CH28.zip.



What are HTML elements?

Think of HTML elements as controls embedded in the Internet Explorer browser and accessed via HTML. HTML elements are covered in more detail in the following section.


What's interesting about this program is that although it appears to be using an intrinsic Visual Basic ActiveX control, it's not; it's made completely from HTML and HTML elements.

The way the program works is that two HTML <INPUT TYPE=Text> elements (lines 39 and 48) and an <INPUT TYPE=Button> HTML element (line 56) are created. When users click the button, a click event handler written in VBScript (lines 10-20) processes the data input into the first text element (line 13). A response is output in line 15 or 18.

Working with HTML Elements

If you don't have a working knowledge of HTML, this code might be difficult to grasp. A fundamental understanding of HTML and HTML elements is a prerequisite for working with VBScript on the Internet. HTML, the language of the Internet, is a tagged language, which means that tags are used to issue instructions to the HTML interpreter about how to process data sent from the server to the calling client. For instance, the following piece of HTML instructs the browser to make the words Hello World boldface.

<B>Helllo World</B>

In addition to tags that tell the browser how to handle text are tags that tell the browser about the structure of the HTML page. Also, some tags create elements very similar to the intrinsic ActiveX controls. Table 28.1 lists these elements.

TABLE 28.1  HTML Elements Compared to Intrinsic ActiveX Controls

HTML Element ActiveX Intrinsic Control
<INPUT TYPE=CHECKBOX> CheckBox
<SELECT> ComboBox
<INPUT TYPE=BUTTON> CommandButtons
<FRAME> Frame
<INPUT TYPE=IMAGE> Image
<SELECT MULTIPLE> ListBox
<INPUT TYPE=RADIO> OptionButton
<INPUT TYPE=TEXT> TextBox
<TEXTAREA> TextBox with multiple lines and scrollbars
<INPUT TYPE=BUTTON> CommandButton
<SELECT> DropDownCombo or ListBox

HTML elements have properties that you can set at design time, as you would an ActiveX control. HTML element properties are called arguments. The syntax for these arguments is a bit different from properties of ActiveX controls. To create an <INPUT TYPE=TEXT> element with the text Hello World in it, you would use the following:

<INPUT TYPE=TEXT SIZE=40 VALUE="Hello World">

In this syntax,

The following sections provide a more detailed description of the HTML elements that you use with VBScript.

The <FORM> element

HTML forms begin with the tag <FORM> and ends with the tag </FORM>. The <FORM> element takes the following format:

<FORM ACTION = URL METHOD= post|get NAME=aname>
...
</FORM>

In this syntax,


Working with CGI

The common gateway interface (CGI) is a specification that defines a set of standards by which data consistently and predictably enters and leaves an Internet Server. Originally developed for the UNIX environment, CGI is used for Internet-based data-processing and decision-making routines such as queries and lookups. Programs that do this sort of server-side processing are called CGI scripts and are usually written in a language such as Perl or C++.


Therefore,

<FORM ACTION=http://www.mysite.com/cgi-bin/myscript.exe
 METHOD=post NAME-myform>
...
</FORM>

denotes a form that will pass its data to a CGI script, myscript.exe, on the server www.mysite.com. The form will use the post method. The name of the form is myform.

Forms are parent elements, which means that the information gathered is generated by other HTML elements living between the <FORM> and </FORM> tags. An element that lives within a <FORM> is called a child element.

You can think of the <FORM> element as a nongraphical version of a Visual Basic form. A VB form can contain buttons, text boxes, labels, and a host of other controls. When you reference a control within a VB form, you do so through the form. For instance, if you had a CommandButton named Command1 on a form named Form1, you would reference the CommandButton with the following piece of code:

Form1.Command1.


The Document Object Model (DOM)

The Document Object Model is the hierarchical relationship of data in a Web page. For example, the window object contains the document object, which can contain a form object. Modern VB Internet programming is about using the DOM. In earlier versions of HTML, the DOM was much less complex. Now the DOM has hundreds of objects, attributes, and methods. For an in-depth look at the DOM, visit Microsoft's Web page at http:// www. microsoft.com/msdn/sdk/inetsdk/help/ dhtml/references/ domrefs.htm.


The same is true of an HTML <FORM>. You can have <INPUT>, <TEXTAREA>, and <SELECT> elements that reside with a <FORM>. Therefore, if you have a <FORM NAME=MyForm> element that contains an <INPUT TYPE=TEXT NAME=MyText> element, you would reference it with VBScript as

MyForm.MyText

This notion of parent and child elements becomes very important when you work with VBScript and the Internet Explorer Document Object Model (DOM).

The <INPUT> Element

The <INPUT> elements are what you provide for users to enter in form data and trigger a submission of the form's data onto a server on the Internet.

HTML has a standard set of <INPUT> types, just as VB has a standard set of controls that you adapt to a particular purpose. Also, as with VB control properties, each <INPUT> element has attributes that you configure to accommodate a particular layout need.

The <INPUT> element attributes are as follows:

Attribute Description
NAME Defined name of <INPUT>'s data, similar to a variable name
VALUE <INPUT>'s data, similar to the value of a variable
TYPE Defines the type of <INPUT> element, such as Text, Radio, Checkbox, and so on
MAXLENGTH Specifies the maximum number of characters that may be entered in an <INPUT> field
SIZE Defines the size (width) of the <INPUT> field, is used for Text or Password
CHECKED Marks a check box or sets a radio button to True

The <INPUT> element types are as follows:

<INPUT TYPE=Text SIZE=40 NAME=txtName>






<INPUT TYPE=Password NAME=pswMain>






<INPUT TYPE=Submit Value="Submit Profile"
 NAME=Submit>






<INPUT TYPE=Reset Value="Clear Profile"
 NAME=Reset>






<INPUT TYPE=Button NAME=cmdValidate
 Value="Validate>






<INPUT TYPE=RADIO NAME=opFlintstones
 VALUE="Fred">Fred<BR>
<INPUT TYPE=RADIO NAME=opFlintstones
 VALUE="Wilma">Wilma<BR>
<INPUT TYPE=RADIO NAME=opFlintstones
 VALUE="Betty">Betty<BR>
<INPUT TYPE=RADIO NAME=opFlintstones
 VALUE="Barney">Barney<BR>






<INPUT TYPE=CHECKBOX NAME=chkCartoon
 VALUE=IsCartoon CHECKED>






<INPUT TYPE=Hidden NAME=hidAuthor
 VALUE="Bob Reselman">






INPUT TYPE=image NAME=imgMain SRC=gifs/gifbut.gif>

The <SELECT> Element

A <SELECT> element is similar to an <INPUT> element in that it enables users to input data to be submitted to a server on the Internet. The <SELECT> element is a little more powerful, how-ever, in that it has the behavior of a Visual Basic ListBox or ComboBox.

The tag begins with <SELECT> and ends with </SELECT>. Between the tags, you place <OPTION> elements:

<SELECT NAME="lstUser">
<OPTION VALUE="Admin">Admin
<OPTION VALUE="Employee">Employee
<OPTION VALUE="Guest">Guest
</SELECT>

If you use the MULTIPLE attribute in the tag definition, the element will appear as a list, similar to the Visual Basic ListBox. When the element appears as a list, you can submit multiple <OPTION> elements to the server. If you omit the MULTIPLE attribute, the element will appear as a drop-down box, similar to a VB ComboBox, from which you can choose only one <OPTION>.

The <TEXTAREA> Element


Some things in common

Although various HTML elements have common arguments, the behavior associated with these elements is different. Fortunately, the VB6 IDE has created a way to set HTML elements just as you would an ActiveX control. This topic is covered later in the section "Using DHTML with ActiveX Components."


The <TEXTAREA> element is similar to a TEXT <INPUT> type, except that a <TEXTAREA> element can accept multiple lines of text. The tag definition begins with <TEXTAREA> and ends with </TEXTAREA>:

<TEXTAREA NAME=txtComments ROWS=5 COLS=30>
</TEXTAREA>

Any text that appears between the tags will show up in the field of the <TEXTAREA>. These tags will also accept a default value.

The <TEXTAREA> element has three attributes:

Attribute Description

NAME The name of the element (required)

ROWS The number of rows in the <TEXTAREA> field

COLS The width of the field in characters

More on Scripts

From the browser's point of view, the only difference between Web pages that contain a script and those than don't is the presence of the <SCRIPT> tag in the page's HTML. A <SCRIPT></SCRIPT> tag indicates that everything between the tags is VBScript or JavaScript. The syntax of the <SCRIPT> tag is

<SCRIPT LANGUAGE = scripting language>...</SCRIPT>

When a browser sees the <SCRIPT> tag, it says to itself, "I have some script stuff coming up to consider." When the browser sees the </SCRIPT> tag, it stops that consideration. Unless the script is code for an event handler, sub, or function, the script will be executed in the order in which it's encountered.

The <SCRIPT> tag has a LANGUAGE attribute that indicates the scripting language used. The <SCRIPT> tag supports VBScript, Jscript, and JavaScript.

You code VBScript between the <SCRIPT></SCRIPT> tags just as you would code VB within the Visual Basic IDE. You Dim variables, write code, and use apostrophes to begin comment lines. If you declare a variable within a Sub or Function, that variable is local to the Sub or Function; variables declared outside a Sub or Function are global. As mentioned earlier, all variables are variants, but you can typecast values by using the conversion functions of Cint(), CLng(), CStr(), and so forth.

As mentioned earlier, scripts can run from a server on the Internet or from your local hard drive. The browser considers only the structure of the script, not its source. Therefore, you load and run client-side scripted HTML as you load any other Web page. This might not be entirely true in all cases if you're trying to run scripts by using objects that will run on the client or the server based on where the page resides.

In Listing 28.1, lines 5-22 are the <SCRIPT> portion of the page. The script contains the code for a click event handler for the Button element cmdValidate. The code for the event handler starts at line 10 and ends at line 20.

Incorporating VBScript with HTML

Figure 28.4 shows a Web page that contains the <TABLE>, Form, CheckBox, Radio, Text, <TEXTAREA>, <SELECT>, Password, and Button HTML elements. At the bottom of the page is a button that, when clicked, displays the Internet Explorer Alert dialog. If users enter the correct password, the Alert dialog--the HTML equivalent of a MessageBox--reports back the type of user, any comments from the Comment text area, the selected Radio elements, and an indication of which check boxes have been selected. The code that executes this logic is written in the VBScript click event procedure cmdValidate_OnClick. Listing 28.2 shows the HTML and VBScript for this page.

FIGURE 28.4 The <TABLE> element, part of the HTML 3.0 standard, creates a table that contains a caption (<CAPTION>) and any number of rows (<TR>). More new tags are being added to this element every day.

LISTING _28.2  28HTM02.HTM--A Web Page with the HTML elements

01 <html>
02 <!--Created by Bob Reselman
03 Copyright 1998 Macmillan Publishing -->
04 <head>
05 <title>Using VB6: HTML Elements</title>
06 </head>
07


Commenting HTML

You comment HTML code by putting comments between the characters, <!-- and -->. For example, the code <!-- _Created by Bob Reselman --> indicates that the string Created by Bob Reselman won't be interpreted as HTML; it will be ignored as comments. You can have as many lines between the begin and end comment characters as you want.


08 <body>
09 <script language="VBScript"><!--
10 Sub cmdValidate_OnClick()
11 Dim br `Line Break variable'
12 Dim strBuffer `String buffer to hold
13 `alert message
14 Dim i `Counter variable
15 Dim j `Another counter variable
16
17 `Set the line break var to the line break chars
18 br = Chr(10) & Chr(13)
19
20 `Set the string buffer to report who is entering
21 `by getting the value from the SELECT element.
22 strBuffer = strBuffer + "User: " & _
frmLogin.lstUser.Value + br + br
23 `Cycle through all the forms in the document in the
24 `browser window
25 For i = 0 to document.forms.length - 1
26 + document.forms(i).name + br
27 strBuffer = strBuffer + "Form Name: " _
For j = 0 to document.forms(i).elements.length - 1
28 `Within each form, check all the child elements
29 `to see if the type is a RADIO
30 If document.forms(i).elements(j).type = "radio" Then
31 `If you find a RADIO, see if it is checked
32 If document.forms(i).elements(j).checked Then
33 `Concatenate the string by adding an indication
34 `of which RADIO has been checked.
35 strBuffer = strBuffer + "Selected Option: "
36 strBuffer = strBuffer _
+ document.forms(i).elements(j).value
37 `Put in a line break
38 strBuffer = strBuffer + br
39 End If
40 ElseIf _
`check to see if the element is a checkbox
41 document.forms(i).elements(j).type = "checkbox" Then
42 If document.forms(i).elements(j).Checked Then
43 `If the checkbox is checked, concatenate the string
44 `buffer to indicate the check means the show is
45 `a cartoon.
46 strBuffer = strBuffer + "Show type is a cartoon." _
+ br
47 End If
48 End If
49 Next
50 Next
51 `Concatenate the string buffer to line break and
52 `report the comment that is entered.
53 strBuffer = strBuffer + br + "Comments: " + br
54 `in the TEXTAREA element of the FORM, frmLogin (read
55 `the value property)
56 strBuffer = strBuffer + frmLogin.txtComments.Value
57 `Check to see if the user entered the proper password
58 `("TV") in the PASSWORD element.
59 If frmLogin.pswMain.Value = "TV" Then
60 `If the entry is valid, display the string buffer
61 Alert strBuffer
62 Else
63 `If not, report an error message
64 Alert "You did not login correctly"
65 End If
66 End Sub
67 -->
68 </script>
69 <!--Create heading using the H1 tag and
70 center the heading -->
71
72 <H1 align="center">HTML Elements</H1>
73
74 <!--Make a table 1 row by 2 colswhich creates
75 a layout structure for the FORM, frmLogin.
76 Set the Border value to one so that the lines
77 show up.-->
78 <TABLE BORDER="1">
79 <!-- Create a form using the <FORM> tag. -->
80 <FORM NAME="frmLogin">
81 <TR>
82 <!--Put the user drop-down in the first cell of the
83 first row. -->
84 <TD>
85 <SELECT NAME="lstUser" SIZE="1">
86 <OPTION VALUE="Admin">Admin </OPTION>
87 <OPTION VALUE="Employee">Employee </OPTION>
88 <OPTION VALUE ="Guest">Guest </OPTION>
89 </SELECT >
90 </TD>
91 <!--Add the Password element and the TextArea
92 Comment box to the second cell in the first row of
93 the table. -->
94 <TD>
95 Password:<BR>
96 <INPUT TYPE="PASSWORD" SIZE="20" NAME="pswMain"><BR>
97 Any Comments?: <BR>
98 <TEXTAREA NAME ="txtComments" ROWS="5" 102:COLS="30">
99 </TEXTAREA >
100 <!--Put in the closing tags for the Table and the
101 form. -->
102 </TD>
103 </TR>
104 </FORM>
105 </TABLE>
106
107 <P>
108 <!-- Create another table, 1 row by 2 cols to
109 hold all the TV radio elements and the checkbox
110 elements. -->
111 <TABLE BORDER="1">
112 <TR>
113 <TD>
114 <!-- Put the form to hold the elements for the
115 Flintstones in the first row, first column. -->
116 <FORM Name="frmFlintstones">
117 <!-- Make the font for the heading of these groups
118 larger, bold and Arial. Put a line break at the end
119 of the heading-->
120 <FONT SIZE="4" FACE="ARIAL">Flintstone</FONT><BR>
121 <!-- Make the label bold and put a space after the
122 end of the label and then a line break. -->
123 <B>Choose a Character:&nbsp;</B><BR>
124 <!-- Create some radio buttons for the
125 Flintstones. Put a page break between
126 each radio button.-->


Case sensitivity

Because VBScript and HTML aren't case-sensitive languages, <INPUT TYPE=Text> is the same as <input type=text>. However, JavaScript is case- sensitive.


127 <INPUT TYPE="radio" NAME="opFlintstones"
128 VALUE="Fred">Fred<BR>
129 <INPUT TYPE="radio" NAME="opFlintstones"
130 VALUE="Wilma">Wilma<BR>
131 <INPUT TYPE="radio" NAME="opFlintstones"
132 VALUE="Betty">Betty<BR>
133 <INPUT TYPE="radio" NAME="opFlintstones"
134 VALUE="Barney">Barney<P>
135 <!--Put in a checkbox to denote a cartoon. -->
136 <INPUT TYPE="checkbox" CHECKED NAME="chkCartoon"
137 VALUE ="IsCartoon">Cartoon?
138 <!-- Close off the Flintstone form -->
139 </FORM>
140 <!-- Close off the first cell -->
141 </TD>
142 <!-- Make the next cell in the first row hold
143 the Star Trek stuff. -->
144 <TD>
145 <!-- Make the form name, frmStarTrek >
146 <FORM NAME="frmStarTrek">
147 <!-- Set the heading font as above -->
148 <FONT SIZE="4" FACE="ARIAL">Star Trek</FONT><BR>
149 <!-- Bold and line break as before. -->
150 <B>Choose a Character:&nbsp;</B><BR>
151 <INPUT TYPE="radio" NAME="opStarTrek"
152 VALUE="Kirk">Kirk<BR>
153 <INPUT TYPE="radio" NAME="opStarTrek"
154 VALUE="Spock">Spock<BR>
155 <INPUT TYPE="radio" NAME="opStarTrek"
156 VALUE="McCoy">McCoy<BR>
157 <INPUT TYPE="radio" NAME="opStarTrek"
158 VALUE="Scotty">Scotty<P>
159 <!--Put in a checkbox to denote a cartoon. -->
160 <INPUT TYPE="checkbox" NAME="chkCartoon"
161 VALUE="IsCartoon">Cartoon?
162 <!-- Close off the Form and Table -->
163 </FORM>
164 </TD>
165 </TR>
166 </TABLE>
167 <!--Make a button; put the word Validate in the button
168 face. Make the name of the button cmdValidate. -->
169 <P><INPUT TYPE ="button" VALUE="Validate"
170 NAME="cmdValidate">
171 <!-- Close off the Body of the page. -->
172 </BODY>
173 </HTML>

This VBScript code shows you how to program the various standard HTML elements. Notice on line 26 that the code uses the length property of the document.forms element to determine how many forms are within the HTML document. In HTML, the length property is similar to the Visual Basic count property for collections. The use of the length property on line 26 and again on line 29 for the elements collection should give you a sense that an HTML document is a series of collections within collections (or arrays within arrays, to use non-language-centric terminology). As you program more with HTML and DOM, you will find yourself traversing and manipulating the various collections of elements in a document. Therefore, an understanding of the different collections and parent-child hierarchies with the DOM is fundamental for developing more complex Web pages with VBScript. The SideNote titled "The Document Object Model (DOM)" earlier in this chapter shows you the URL for the Microsoft site that provides documentation for the DOM.


Static versus dynamic Web pages

A static Web page is one in which the content is hard-coded in HTML and not subject to quick change. For instance, if you wanted to make a Web page that presents the works of Shakespeare, you could type up all the plays in a word processor, save the document as HTML, and put it on a Web site. You probably wouldn't expect the data to change at all after you posted it on the site. Dynamic data, on the other hand, changes all the time and is usually written using an HTML script. For instance, if you wanted to have a Web page that reports the current price of your favorite stock, you would do it by writing a small program in a scripting language such as VBScript. The program would go to a stock-reporting server, ask for the current price of your stocks, and then forward those prices to you.


As you can see, making the page in Figure 28.4 (refer to Listing 28.2) is a laborious effort because of manipulating the HTML elements necessary to organize the page into an acceptable presentation and writing the VBScript to handle the events and actions within the page. DHTML is much more difficult and time-consuming in this respect. Before Visual Basic 6, this sort of scripting was the only way that you could make dynamic Web pages. Although powerful, scripting of this sort is tedious and exposed. The code that you write is open for the world to see--not advantageous if you are at all concerned with protecting your intellectual property. However, Visual Basic 6 lets you write VBScript with HTML in a way that's less burdensome and more protective of your code--using dynamic HTML.

Handling Events with VBScript

You write an event procedure for an HTML element or ActiveX control in VBScript by using the standard Visual Basic syntax. The only difference is that, whereas the Visual Basic IDE creates the event-procedure code block for you, in VBScript you must create the code block yourself. Therefore, if you want to write a click event procedure for the element <INPUT TYPE=BUTTON NAME=MyButton>, you write

<SCRIPT Language=VBScript>
Sub MyButton_OnClick()
`Enter code here.
...
End Sub
</SCRIPT>

Plenty more information on VBScript and ActiveX controls is available. The Internet contains so much on subjects related to Internet programming that it would probably take a normal person several thousand years to research only a small percentage of it. I make this statement with the intention of motivating you to discover how huge the resources are. Some of these resources can be found at Microsoft's Knowledge Base (http://www.microsoft.com) and at Netscape (http://www.netscape.com). You also can refer to http://www.mcp.com, particularly for Java 97 Unleashed, FrontPage 97 Unleashed, and other books on HTML.

FIGURE 28.5 You select a DHTML application project from the New Project dialog.

Understanding a DHTML Application


Working with designers

A designer is a helper application that you load into the Visual Basic IDE. Designers automate many programming functions that you need for a particular activity or type of program. VB6 has introduced numerous new designers, including designers for data projects and add-ins. The DHTML Page Designer provides a visual way to lay out, format, and code DHTML pages. As of this writing, designers are written in C++.


Visual Basic has a new project type, the DHTML application (see Figure 28.5). A DHTML application is a program that you design within the DHTML Page Designer in the Visual Basic IDE (see Figure 28.6) and program in Visual Basic (see Figure 28.7), but it runs as HTML in Internet Explorer (see Figure 28.8).

FIGURE 28.6 The DHTML Page Designer for a DHTML application is very similar to the standard Visual Basic IDE.

FIGURE 28.7 You code DHTML applications as you would a standard VB program.

FIGURE 28.8 DHTML applications run within Internet Explorer as HTML.

There's a slight twist, however--the code that you write for your DHTML application is compiled into a DLL that's embedded in a Web page that the Visual Basic IDE creates as part of the DHTML project. All the code--event procedures, variables, functions, subs, and so on--is contained in that DLL. The only thing exposed is the HTML that defines and positions the HTML elements (see Figure 28.9).

FIGURE _28.9 The DHTML application compiles into a DLL that the Visual Basic IDE embeds in a Web page and references with a class ID.

Programming a Simple DHTML Application

You create a DHTML program as you would a standard Visual Basic application. The only difference is that the IDE for a DHTML application contains a Toolbox for HTML elements. Rather than use intrinsic ActiveX controls on a form, you use HTML elements within a Web page. For example, rather than call the Text property to find out the contents of a TextBox control, you call value. This is because DHTML uses the <INPUT TYPE=Text> element instead of a TextBox. You can use ActiveX controls within a DHTML application, but you use only those ActiveX controls that ship as an OCX or ActiveX DLL. You can't use the intrinsic controls in the VB6 runtime DLL.


Using multiple browsers

As of this writing, DHTML applications aren't supported by any browser other than Internet Explorer. Although Netscape supports a version of DHTML, it's not officially recognized by the W3C consortium and isn't compatible with Microsoft's Internet Explorer.


Another noteworthy difference between standard VB and a DHTML application is the use of the property id instead of Name. You use the id property for an element or ActiveX control in DHTML as you would use the Name property for a control in VB. This use is particular to Microsoft's enhancement of DHTML as it relates to use under Internet Explorer. You can use the Name property when scripting standard HTML.

If you're unfamiliar with the DOM and the properties associated with DHTML elements, you might have a little period of adjustment ahead of you. The Microsoft Web site is an excellent learning resource. Also, you can use the Books Online reference that comes on your Visual Basic CD-ROM.

Create a simple DHTML application


Download this project's code

The code for this project is in the file VB6CH28.zip, which you can download from http:// www.mcp.com/info. The project file is DHTMLProject. vbp.


1. Open a New DHTML application project.

2. Double-click the DHTMLPage Designer in the Project window to open the DHTML form (see Figure 28.10).

FIGURE 28.10 The DHTML Page Designer automates code generation.

3. Double-click the TextField element to add it to the form.

4. Double-click the Button element to add it to the form (see Figure 28.11).

FIGURE 28.11 You can drag and drop HTML elements around a form just as you would in the standard Visual Basic IDE.

5. Position the TextField and Button elements one on top of the other.

6. Select Button1's value property in the Properties window. Change the value property from Button1 to Click Me.

7. In the page view pane, double-click the Button1 element to open a code pane to the Button1_onclick() event procedure.

8. Enter the code shown in Figure 28.12 in the Button1_onclick() event procedure.

9. Save the project and press the F5 key to run the code.

FIGURE 28.12 Notice that the event procedure for a button click is OnClick.

When you run the code for this simple application, Visual Basic compiles the code into a temporary DLL, generates the HTML around the DLL, and automatically embeds the DLL on the page. Then the code is run in Internet Explorer. When you look at the source HTML that loads into the browser, you see no VBScript of any kind--the code is embedded in the DLL, and your intellectual property is safe.

Rapid Development with DHTML Applications

The capability to quickly create powerful, interactive Web pages is a major benefit of VB6's DHTML application feature. Figure 28.13 shows a simple login page with a validation button.

FIGURE 28.13 DHTML applications present the same appearance as HTML pages in a Web browser.

Listing 28.3 shows the HTML/VBScript code for the login page. Listing 28.4 shows the same login page, only generated as part of the Visual Basic DHTML application project. (I've altered the text layout of both listings for the code to be more readable; the syntax of the code hasn't been altered in any way.)


Download this project's code

The code for this project can be found in the file VB6CH28.zip, which you can download from the Web site dedicated to this book. The project file is prjSimpleLogin.vbp.


LISTING 28.3  28HTM03.HTM--A Login Screen That Uses VBScript with HTML

01 <!--Copyright 1998 Macmillan Publishing
02 by Bob Reselman -->
03 <HTML>
04 <TITLE>Simple Login in Standard HTML</TITLE>
05 <HEAD>
06 <SCRIPT LANGUAGE=VBScript>
07 <!--
08 Sub cmdValidate_OnClick()
09 `Declare variables to which to assign
10 `the values of each element
11 Dim strName
12 Dim strPWD
13 Dim strRole
14 Dim strStatus
15 Dim strMsg
16 Dim br
17
18 `Set the line break var to the line break chars
19 br = Chr(10) & Chr(13)
20
21 `Assign the values
22 strName = txtName.Value
23 strPWD = pwdMain.Value
24 strRole = selectMain.Value
25 If Option1.Checked Then
26 strStatus = Option1.Value
27 Else
28 strStatus = Option2.Value
29 End If
30
31 `Make a string that reports all
32 `the values of the various elements
33 strMsg = strMsg & "Your Name: " & strName & vbCrLf
34 strMsg = strMsg & "Password: " & strPWD & vbCrLf
35 strMsg = strMsg & "Role: " & strRole & vbCrLf
36 strMsg = strMsg & "Status: " & strStatus & vbCrLf
37
38 `Show the string
39 window.alert(strMsg)
40 End Sub
41 -->
42 </SCRIPT>
43 </HEAD>
44
45 <P>Type your Login Name:</P>
46 <P>
47 <INPUT TYPE=TEXT NAME=txtName></P>
48 <P>Type your password:</P>
49 <P>
50 <INPUT TYPE=PASSWORD NAME=pwdMain></P>
51 <P>Select your role:</P>
52 <P><SELECT NAME=selectMain>
53 <OPTION SELECTED VALUE=Guest>Guest
54 <OPTION VALUE=Employee>Employee
55 <OPTION VALUE=Contractor>Contractor
56 </SELECT>
57
58 </P>
59 <P>Click your status:</P>
60 <P><INPUT NAME=Option1
61 TYPE=RADIO
62 VALUE=Salary CHECKED> Salary</P>
63 <P><INPUT NAME=Option2
64 TYPE=RADIO
65 VALUE=Hourly>Hourly</P>
66
67 <P><INPUT NAME=cmdValidate
68 TYPE=button
69 VALUE=Validate></P>
70 </BODY>
71 </HTML>


Class ID

DHTML references functionality that's created within a DHTML application DLL through a class ID. A DHTML project compiles into a DLL. When you compile the code, VB assigns a unique number--a class ID--to the DLL. When you deploy your DHTML application to Internet Explorer via the Internet, the browser automatically registers the class ID of the DLL in the Windows Registry. Then, when Internet Explorer encounters the class ID in the page, it automatically looks up the classid in the Registry to find the location of the DLL and other particulars.


Notice that lines 6-42 in Listing 28.3 show the script that captures the button click event procedure, whereas Listing 28.4 shows no script whatsoever. This is because the button click event procedure for Listing 28.4 is encapsulated within a DLL referenced by the classid, as shown on line 3.

LISTING 28.4  SIMPLELOGIN.HTM--DHTML Code Generated by a VB DHTML
Application

01 <!--METADATA TYPE="MsHtmlPageDesigner" startspan-->
02 <object id="DHTMLPage1"
03 classid="clsid:9318A4D8-12D7-11D2-A58E-B6A734C6C111"
04 width=0 height=0>
05 </object>
06 <!--METADATA TYPE="MsHtmlPageDesigner" endspan-->
07 <BODY>
08 <P>Type your Login Name:</P>
09 <P>
10 <INPUT id=txtName name=txtName ></P>
11 <P>Type your password:</P>
12 <P>
13 <INPUT id=pwdMain name=PasswordField1 type=password></P>
14 <P>Select your role:</P>
15 <P><SELECT id=selectMain
16 name=selectMain
17 style="HEIGHT: 22px; WIDTH: 161px"
18 value = Select1>
19 <OPTION selected value=Guest>Guest
20 <OPTION value=Employee>Employee
21 <OPTION value=Contractor>Contractor</SELECT>
22 </P>
23 <P>Click your status:</P>
24 <P><INPUT id=Option1
25 name=Option1
26 type=radio
27 value=Salary CHECKED> Salary</P>
28
29 <P><INPUT id=Option2
30 name=Option2
31 type=radio
32 value=Hourly>Hourly</P>
33 <P><INPUT id=cmdValidate
34 name=cmdValidate
35 type=button
36 value=Validate></P>
37 </BODY></HTML>

Making an interactive page like this login page by using HTML with VBScript requires paying a lot of attention to the detail of HTML and how it interacts with VBScript. The programming experience isn't at all visual. Everything is character based, thus giving you ample opportunity to make time-consuming syntax errors. On the other hand, making the same page as a DHTML application enables you to use your existing VB programming skills and visually create pages. Also, because you're using the Visual Basic IDE, you can take advantage of VB's debugging capabilities. You'll find that VB DHTML applications enable you to make more robust dynamic pages for the Web in half the time it takes using HTML, VBScript, and a text editor.

Using DHTML with ActiveX Components

Add a Slider ActiveX control to a DHTML application


Download the code for this project

The code for this project can be found in the file VB6CH28.zip, which you can download from http://www.mcp.com/info. The project file is prjSlider.vbp.


1. Open a new DHTML application project.

2. Open the Components dialog by choosing Components from the Project menu.

3. Select the Microsoft Windows Common Controls 6.0 ActiveX control to add Common Control icons to the Toolbox.

4. Select the DHTMLPage Designer in the Project window.

5. Click the icon to view the DHTML Designer Form (see Figure 28.14).

FIGURE 28.14 The DHTML Designer Form contains the page view pane on the right and the HTML element hierarchy on the left.

6. Click the page view pane of the DHTML Designer Form. Type This is a slider control and then press Enter to create a new line.

7. Select the General tab in the Toolbox and then drag the Slider control to the new line in the page view pane.

8. Press Enter to create a new line.

9. Type This is the value of the slider control: and then press Enter to create a new line.

10. Select the HTML tab in the Toolbox and then drag the TextField element to the new line in the page view pane.

11. In the Properties window, set the id of the TextField to txtMain. Also, set the name to txtMain and the value to blank (no text).

12. Double-click the Slider control to expose its code.

13. Select the Scroll event from the event procedure drop-down (see Figure 28.15).

FIGURE 28.15 You code event procedures in DHTML applications just as you do in standard VB programs.


Saving DHTML application projects

You name and save a number of files when you save a DHTML application. You save the designer, the default module, and the project file. Designers end with the extension .dsr, whereas modules have the familiar .bas extension and projects have the .vbp extension.


14. Add the following line of code in the scroll event procedure:

txtMain.Value = Slider1.Value


15. Save the project and run it by pressing F5 (see Figure 28.16).

FIGURE 28.16 ActiveX controls can interact with HTML elements in a DHTML application.

Compiling a DHTML Application


Compiling your project

When you compile your project, it's a good idea to save the project files, the DLL, and the HTML page to the same folder. When it comes time to deploy your DTHML application, you can more easily find the files you need. Pay particular attention to this situation because when you want to deploy your application, you will know where all your project files are located. It's important to keep them all in the same directory.


You compile a DHTML application as you would for any other ActiveX DLL--you choose Make MyDLLName.DLL from the File menu. However, behind the scenes a little more work happens; in addition to making the DLL, Visual Basic generates the Web page for the DHTML application. You will be prompted to name this HTM page. Remember that DHTML is an integration of HTML with an ActiveX DLL that contains the interactive code for the page. Therefore, the page needs the class ID of the DLL to find the DLL and subsequently the interactive functionality of the page. The class ID is automatically added to the HTML within the Web page as you compile your project.

After you complete your Web page, you can make it available to other users on the Web in the following ways:

Search Engine URL
Yahoo http://www.yahoo.com
Infoseek http://www.infoseek.com
WebCrawler http://www.webcrawler.com
Apollo http://www.apollo.com
Lycos http://www.lycos.com
World Wide Web Yellow Pages http://www.yellow.com


Previous chapterNext chapterContents

© Copyright, Macmillan Computer Publishing. All rights reserved.