0% found this document useful (0 votes)
1K views1,117 pages

Visual Basic 6 Web Programming

This document is a book about developing web applications using Visual Basic 6. It includes chapters written by different authors on topics like VB6 web programming, ASP, SQL Server, and other Microsoft web technologies. The book is intended to help programmers learn to create enterprise solutions for e-commerce, healthcare, education and other industries using VB6 and Internet architectures. It was published in 1999 by Wrox Press Ltd.

Uploaded by

hiuray
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views1,117 pages

Visual Basic 6 Web Programming

This document is a book about developing web applications using Visual Basic 6. It includes chapters written by different authors on topics like VB6 web programming, ASP, SQL Server, and other Microsoft web technologies. The book is intended to help programmers learn to create enterprise solutions for e-commerce, healthcare, education and other industries using VB6 and Internet architectures. It was published in 1999 by Wrox Press Ltd.

Uploaded by

hiuray
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

TM

PROGRAMMER TO PROGRAMMER

PROFESSIONAL

VB6 Web
Programming
[Link], [Link],[Link], [Link], [Link], [Link],
[Link], [Link] Thomas, [Link], [Link], [Link],
[Link],[Link].
Professional
Visual Basic 6 Web
Programming

Jerry Ablan
Tom Barnaby
Pierre Boutquin
Matt Brown
Charles Caison
Richard Harrison
Jeffrey Hasan
Matthew Reynolds
Dmitriy Slosberg
Michael Lane Thomas
Thearon Willis
Paul Wilton

Wrox Press Ltd. 


Professional Visual Basic 6
Web Programming

© 1999 Wrox Press

All rights reserved. No part of this book may be reproduced, stored in a retrieval system or transmitted in
any form or by any means, without the prior written permission of the publisher, except in the case of brief
quotations embodied in critical articles or reviews.

The author and publisher have made every effort in the preparation of this book to ensure the accuracy of
the information. However, the information contained in this book is sold without warranty, either express or
implied. Neither the authors, Wrox Press nor its dealers or distributors will be held liable for any damages
caused or alleged to be caused either directly or indirectly by this book.

Published by Wrox Press Ltd. Arden House,1102 Warwick Road,


Acocks Green, Birmingham, B27 6BH
Printed in USA
ISBN 1-861002-22-X
Trademark Acknowledgements
Wrox has endeavored to provide trademark information about all the companies and products mentioned in
this book by the appropriate use of capitals. However, Wrox cannot guarantee the accuracy of this
information.

Credits

Authors Technical Reviewers


Jerry Ablan Robert Chang
Tom Barnaby John Granade
Pierre Boutquin Joe Sutphin
Matt Brown
Charles Caison Managing Editor
Richard Harrison Chris Hindley
Jeffrey Hasan
Matthew Reynolds Editors
Dmitriy Slosberg Andrew Polshaw
Michael Lane Thomas Jeremy Beacock
Thearon Willis Soheb Siddiqi
Paul Wilton
Design/Layout
Development Editors Tom Bartlett
Dominic Lowe Mark Burdett
Greg Pearson David Boyce
William Fallon
Additional Material Jonathan Jones
Chris Ullman John McNulty
Tim Waters
Index
Cover Andrew Criddle
Chris Morris
About the Authors

Jerry Ablan
Jerry Ablan is a Web developer with several years experience

Tom Barnaby
Tom has been working with computers for over 13 years. He started in grade school working on the
venerable TI-99/4A and his education continued into college where he studied Computer Science. After
graduating, Tom embarked on a career which has run the gamut of the programming experience – from
system level programming with C and UNIX, to client/server systems with C++ and NT, and finally to Web
Development with Visual Basic. Along the way, Tom has designed and developed 4GL, ERP, and data
warehouse applications.

Tom's teaching career began in 1995 with an "Intro to UNIX" evening course at a local community college.
Since then, he has gradually moved into instructing full-time, developing and teaching courses in Visual
Basic, C++, OOA/D, and MFC.

Pierre Boutquin
To Sandra.

Pierre Boutquin is a Senior Analyst in the corporate treasury of a major Canadian bank, where he helps
develop leading-edge market risk management software. He has over a decade of experience implementing
PC-based computer systems with in-depth knowledge of object-oriented analysis and design, Visual Basic,
Visual C++, and SQL. He most recently co-authored "Visual Basic 6 SuperBible" and "Visual Basic 6
Interactive Course", published by The Waite Group. He has also contributed material on COM and SQL
for other books. Pierre's spare time is mainly owned by Koshka and Sasha, his two adorable Burmese cats.
While petting them, he often thinks how nice it would be to find more time and get back into chess or keep
up with news from Belgium, his native country. You can reach him at boutquin@[Link].

I would like to thank Greg Pearson and all the other Wrox associates for the opportunity to work with
them. Jeremy Beacock, Soheb Siddiqi and Andrew Polshaw are all appreciated for their help in making me
look like an accomplished writer. Most importantly, I must acknowledge the enthusiastic encouragement I
receive from my wife Sandra. Without her, I surely would have faltered in my writing efforts. Finally, I
must also thank my colleagues in Corporate Treasury for their support and friendship.

Matt Brown
Matt Brown is a technical consultant and trainer for DBBasics in Raleigh North Carolina. He lives with his
vivacious wife Karen and his children: Matthew, Erin, and Dominic. In his spare time he enjoys sleeping,
reading, eating large quantities of meat, long walks and sunsets. In his spare time he resents having to shave
and bathe, but does so on a regular basis. Among Matt's favorite authors are Robert Silverberg, Ayn Rand,
and Guy Gavriel Kay. Matt wishes to make mention of and thank: Gary Kohan, Tim Waters, and his father
Al Brown. You can send email to Matt at Mattbr@[Link].
Charles Caison
Charles Caison is an instructor with DBBasics Corporation ([Link] He has
been involved in Windows development since 1992. He is a contributing author to Visual Basic
Programmer's Journal, Windows NT magazine, Microsoft Interactive Developer and other industry
publications. He also speaks at Microsoft Developer Days and other industry events. You can reach him at
charlesc@[Link].

Richard Harrison
Richard is a Microsoft Certified Solution Developer and a senior consultant for a major global IT services
company. He has recently been specialising in Microsoft Internet architectures and helping organisations to
use these technologies to build mission critical Web solutions.

Jeffrey Hasan
Jeff is a Lead Software Engineer with the Rare Medium Group in Los Angeles, California, where he is
responsible for architecting and implementing leading-edge e-commerce sites for Fortune 100 companies
and .com startups. He is experienced with NT/IIS web application development using Active Server Pages,
Visual Basic and SQL Server. He a regular contributor to several magazines, writing articles on VB, ASP,
ADO, COM and any other acronym he can think of. Jeff's chronic travel bug has most recently taken him
from the rainforests of Costa Rica to the Karakoram mountains of Northern Pakistan.

Matthew Reynolds
Matthew Reynolds is a developer, architect and evangelist of Web-based applications running on Microsoft
Internet technologies. He is also Senior Editor for [Link]. He lives in Phoenix, Arizona and
London, England on no fixed schedule.

Dmitriy Slosberg
Dmitriy Shlosberg has many years of experience in the field. He worked as a contractor for the past 3 years
developing enterprise solutions for the HealthCare, financial, educational, and security industry and is
currently a CEO of Impera Software Corp, where he is currently working on a new enterprise e-commerce
solution.

Michael Lane Thomas


Michael Lane Thomas has just got a job with Microsoft, and is too busy to write a proper bio!

Thearon Willis
A senior consultant with 19 years of IT experience, Thearon is currently a consultant for an International
Insurance company providing Web programming services. His Web development tools of choice are ASP,
Dynamic HTML, Visual Basic and SQL Server. Thearon lives in Charlotte, North Carolina with his wife
and daughter.

To my wife Margie for her patience and understanding while I write yet another book, I love you very
much.
Paul Wilton
Being a History and Politics graduate and Law post graduate the obvious career move was to programming.
However a misspent youth in and out of computer book stores and programming in BBC Basic and Z80
assembler gave some head start.

After an initial start as a Visual Basic applications programmer he found himself pulled into the net and has
spent the last 18 months helping create internet and intranet solutions.

Currently he is developing web based systems primarily using Visual Basic 6 and SQL Server 7 along with
other numerous technologies.

Lots of love to my fiancée Catherine who ensures my sanity chip remains plugged in.
Table of Contents

Introduction 1
What Does this Book Cover? 1
Introducing Internet Application development 1
Programming the client 2
Server side programming 2
Datahandling on the Web 3
Case Studies 3
Who is this Book For? 3
Technology Requirements 3
Conventions 4
Tell Us What You Think 5
Customer Support 5

Chapter 1: Web Fundamentals 7


Why Web Technology? 8
IT Strategy for the Millennium 9
Processing Islands in the Enterprise 9
Integrating the Enterprise 10
Extending the Enterprise 11
The Evolution of IT System Architectures 12
The Early Days – Centralized Computing 12
PC Networking: Moving Towards Decentralization 13
Client/Server Computing 13
Two Tier Client/Server 14
Three Tier Client/Server 16
Multi Tier Client/Server 16
Web Technologies: Centralized Computing but with a Twist 18
Web Technology Fundamentals 20
Table of Contents

TCP/IP Networking 21
TCP/IP Protocol Stack 21
Network Addresses 21
Port Numbers 23
Uniform Resource Locator 23
The World Wide Web 24
Hyper Text Transfer Protocol (HTTP) 24
HyperText Markup Language (HTML) 25
27
First Generation Web Applications 27
Next Generation Web Applications 28
Client-side: Dynamic HTML/Scripting/Components 28
Summary 31

Chapter 2: Windows DNA - a framework for

building applications 35
The Windows DNA Server Platform 36
Windows DNA Application Services 37
Software Components 39
Component Object Model 39
ActiveX 41
Software Component Characteristics 41
Universal Data Access 42
OLEDB & Active Data Objects 43
Transactions 44
Microsoft Transaction Server 45
Performance and Scalability 46
Distributed Transaction Coordinator 46
Message Queuing 48
Security 48
Internet Security 49
Internet Information Server Access Controls 49
Secure Channels 50
Digital certificates 50
Authenticode 51
Summary 52
ii
Table of Contents

Chapter 3: An Overview of Building Windows


DNA

Applications with Visual Basic 55


ActiveX Scripting – Visual Basic Script 56
ActiveX Controls 61
WebClasses 66
Dynamic HTML Applications 70
ActiveX Server Components 75
ActiveX Documents 78
Traditional Windows Clients 81
Summary 86

Chapter 4: Client-Side Programming


with Visual
Basic 89
The Intranet Revolution 90
ActiveX Scripting 92
Client-Side Scripting Using VBScript 92
What can I use VBScript for? 93
VBScript or JScript: Which one do I use? 93
Overview of VBScript 93
New Features in VBScript 5.0 97
Classes 97
Regular Expressions 100
Function Pointers 104
With Statement 105
Script Encoding 105
Handling Different Versions of VBScript 106
Using the Microsoft Script Debugger 107
Introducing XML and Scriptlets 109
The Bare Essentials of XML 109
Scriptlets: Components for the Web 111
How To Write a Scriptlet 111
iii
Table of Contents

Using the Scriptlet 113


Using ActiveX Controls on the Client 114

iv
Table of Contents

ActiveX Out of the Box 114


Hosting ActiveX Controls on a Web Page 115
The Internet Download Service 116
Using the ActiveX Control Pad 117
Summary 122

Chapter 5: Building Client-Side ActiveX


Controls 125
Understanding What ActiveX Is 126
Understanding ActiveX Controls 126
The UserControl Object 127
The ActiveX Control Interface 128
ActiveX Control Creation Using Visual Basic 130
The ActiveX Control Project Type 131
Building the Sales Analyzer ActiveX Control 131
Defining the Sales Analyzer Control's Purpose 132
Step 1: Starting the Project 133
Step 2: Adding the Constituent Controls 136
Step 3: Creating the ActiveX Control Interface 137
The ActiveX Control Interface Wizard 138
Step 4: Working from the Auto-Generated Code 143
Step 5: Coding the Business Logic 145
Coding the Data Loading Procedures 145
Coding the Charting Procedure 148
Step 6: Coding the Public Events 149
Step 7: Testing the Sales Analyzer Control on a Form 149
Step 8: Adding Property Pages 152
Step 9: Testing the Sales Analyzer Control on a Web Page 157
ActiveX Packaging and Deployment 160
Packaging your ActiveX Control 160
Deploying your ActiveX Control 162
Licensing ActiveX Controls 164
Digital Signing and Authenticode 166
Summary 169

v
Table of Contents

Chapter 6: Dynamic HTML Applications 171


What is a Dynamic HTML Application? 171
The General Idea 171
The Document Object Model 171
A 30,000-foot view of the Document Object Model 173
Introducing DHTML Applications 174
The DHTML Designer 175
What is VB doing? 176
A Practical Example 177
Getting Started 178
Dynamically Changing Text 180
Building up the Report 182
Saving the Report on the Server 186
Deploying DHTML Applications 188
Packaging Our Application 189
Publishing our Application's Package 196
Publishing Directly to a Web Site. 197
Publishing to a Folder on your Network 198
Summary 199

Chapter 7: Integrating Web Browsing Using


the WebBrowser
Objects 201
The Heart and Soul of Internet Explorer 202
IE-based Browsing Objects 203
Properties 204
Methods 205
Events 206
The 60-Second Browser 206
The Recipe 207
Surfing the Web 209
Beyond Browsing 210
Browsing your system 210
Loading Office Documents 211

vi
Table of Contents

Additional Features 212


Control Properties, Methods and Events 215
Calling and Controlling Internet Explorer 216
Control Properties 218
General Properties 218
Height, Left, Top, and Width 218
Visible 219
Visual UI Elements 221
AddressBar 221
MenuBar, StatusBar, and ToolBar 223
FullScreen and TheaterMode 224
StatusText 226
Web Page Specific 227
LocationName and LocationURL Properties 227
Document Property 228
Navigation-Related 232
Busy 232
Silent 232
Offline 233
Miscellaneous Properties 233
Name, Path, and FullName 233
Parent 235
HWND 236
ReadyState 236
RegisterAsDropTarget 237
Resizable 237
Tag 238
ToolTipText 238
TopLevelContainer 238
Type 238
Standard Control Properties 238
Control Methods 239
Navigating HTML Pages 239
Navigate and Navigate2 239
Refresh and Refresh2 240
Additional Navigation Control Methods 242
GoBack and GoForward 242
GoHome 244
GoSearch 245
Stop 246
Miscellaneous Methods 246
ClientToWindow 246
GetProperty and PutProperty 248
vii
Table of Contents

ShowBrowserBar 248
Standard Control Methods 249
Drag 250
Quit 250
SetFocus 250
ZOrder 250
QueryStatusWB 251
ExecWB 251
OLE Commands 252
Open Dialog 253
Save Command 253
SaveAs Dialog 254
Print Dialog 254
Page Setup 254
Cut, Copy, and Paste Commands 255
Refresh Command 256
Stop Command 256
Progress Indicators Commands 257
Set Title Command 258
Control Events 258
Page Navigation 258
BeforeNavigate2 258
DownloadBegin 260
NavigateComplete2 260
DownloadComplete 261
DocumentComplete 261
NewWindows2 262
"On" Events 263
OnFullScreen 263
OnMenuBar 263
OnQuit 263
OnStatusBar 264
OnTheaterMode 264
OnToolBar 264
OnVisible 264
The "Change" Events 264
CommandStateChange 264
ProgressChange 266
PropertyChange 267
StatusTextChange 268
TitleChange 268
Standard Control Events 268
Summary 269

viii
Table of Contents

Chapter 8: Getting Started By Understanding


ASP 271
The Anatomy of the HTTP Protocol 272
Overview 272
The HTTP Server 272
Protocol Basics 273
The Connection 273
The Request 273
The Response 276
HTTP Headers 276
The Disconnect 276
Introducing Active Server Pages 277
How the Server recognizes ASPs 277
ASP Basics 278
The Tags of ASP 278
<SCRIPT> Blocks 278
The Default Scripting Language 278
Mixing HTML and ASP 279
Commenting Your ASP Code 280
The Active Server Pages Object Model 281
Collections 281
Iterating the Contents Collection 282
Removing an Item from the Contents Collection 283
The Request Object 283
The Request Object's Collections 283
Request Object Properties and Methods 287
The Response Object 288
The Response Object's Collections 288
The Response Object's Methods 289
The Response Object's Properties 290
The Application and Session Objects 292
Scope Springs Eternal 292
The [Link] File 292
The Application Object 293
Collections 293
Methods 293
Events 293
ix
Table of Contents

The Session Object 294


Collections 294
Properties 295
Methods 296
Events 296
The Server Object 296
Properties 296
Methods 296
The ObjectContext Object 298
SetAbort 298
SetComplete 298
Using Active Server Pages Effectively 298
Designing the Site 298
Creating the [Link] file 299
Creating our Main Page 300
Summary 306

Chapter 9: Building Server Components in


Visual Basic 309
Introduction to Building ActiveX DLL Components 310
Component Types 310
ASP Objects 311
ObjectContext 311
ScriptingContext 312
Application Object 312
Request Object 312
Response Object 312
Server Object 312
Session Object 313
Designing for IIS 3 versus IIS 4/5 313
The Authors Sample Web Provider Component 314
[Link] File 314
Data Source 314
RequestAuthors Page 317
DisplayAuthors ASP 318
Authors ActiveX DLL 318
Project Properties 320
References 323

x
Table of Contents

Object Browser 323


Variable Declarations 324
OnStartPage and OnEndPage 325
Database Connection and Disconnection 325
AllAuthors Procedure 326
Testing Our Component 329
Compiling the ActiveX DLL 329
File Properties Dialog 330
Packaging Our Component for Distribution 331
Package Directory 335
Interesting Observations 335
Examples to Try 335
Web Page Consumer Component 337
Points to Ponder 340
Key items to remember 341
Choosing Names 341
Auto Increment the Version Number 342
Version Compatibility 342
ActiveX DLL Base Addresses 342
Interfaces 343
Unattended Execution 343
NT Event Log 343
Component Registration 343
Key items to avoid 344
Interface Changes 344
Bulky Components 344
Dialogs 344
NT Event Log 344
Summary 344

Chapter 10: Advanced Visual Basic Server


Components 347
Components That Provide Business Rules 347
The Role of a Business Component 348
Typical Uses of Business Server Components 348
Types of Business Components 349
In-Process Threading 350
In-Process and Out-of-Process Components 351
Interfacing with Other Services 351

xi
Table of Contents

ActiveX Data Objects 352


ADO Programming Model 353
Common Techniques 353
Variable Declarations 354
Establishing a Connection 354
Using the Errors Collection 355
Using the Command Object 355
Using the Recordset Object 356
Read-Only, Forward-Only 356
Multiple Recordsets in One Recordset Object 357
Using Single Recordset Updates 358
Updating Using a Stored Procedure 358
Using the Fields Collection 359
ADO Summary 359
The AuthorData Business Component 359
Insert Business Rules 360
Update Business Rules 361
Delete Business Rules 361
Stored Procedures 361
AuthorData Project 364
Project Properties 366
References 367
Registry Class 367
Database Module 377
Authors Class 382
Browsing the Business Component 398
Calling the Business Component 399
Help Files 400
Summary 401

Chapter 11: Interfacing With Server Services


in
Visual Basic 403
Microsoft Transaction Server 404
Benefits of Using MTS 404
Adding MTS to a Visual Basic Server Component 407
Starting and Ending an MTS Transaction 409
Installing a Component in MTS 410
xii
Table of Contents

Microsoft Message Queuing 412


Benefits of Using MSMQ 413
Adding MSMQ to a Visual Basic Server Component 414
Sending Messages 414
Receiving Messages 415
Security Issues 417
Collaboration Data Objects 417
Benefits of Using Collaboration Data Objects 417
Adding CDO to a Visual Basic Server Component 418
Sending Mail Messages 418
Sending Meeting Appointments 420
Active Directory Service Interfaces 422
Benefits of Using ADSI 422
Adding ADSI to a Visual Basic Server Component 423
Schema Information 423
Enumerating User Groups 425
Creating and Adding Users 426
Practical Examples 427
Adding Transactions 428
Add Method 428
Delete Method 429
Update Method 430
Compiling the Component 431
Adding Message Queuing 431
Adding Mail 433
Adding New Users 436
Summary 439

Chapter 12: Introducing Webclasses and


IIS
Applications 441
A New Type of Web Application 442
IIS Application Basics 443
General Advantages 445
Cost of Deployment 445
Development Environment 445

xiii
Table of Contents

Object Model 446


Audience Scope 446
Reusability 446
Code Separation 446
State Management 447
Previous Visual Basic Options 447
Comparison to DHTML Applications 447
Differences 447
Object Model 448
Processing location 448
Browser dependency 448
Network profile 448
Degree of web-enabling 448
HTML events processed 449
Processing Scope 449
IIS Apps vs Visual Interdev 449
Project Differences 449
Application Developers 450
Separating Content From Presentation 450
Web Server Implementation 450
Chaining Visual Interdev and Visual Basic 451
Windows DNA Participation 451
IIS Application RoadMap 451
IIS Application Preparations 454
Web Server Required 454
Webclass Hosting Requirement 456
Active Server Page Host 456
Active Server Page Functionality 457
Active Server Page Syntax 459
Webitem 459
Event 460
URL Data 460
Controlling the Web Server from within Visual Basic 460
Summary 462

xiv
Table of Contents

Chapter 13: The Fundamentals of IIS


Applications 465
IIS Applications – The Basics 466
Events, Properties, and Methods 466
Webclass Events 467
Initialize Event 467
BeginRequest Event 468
Start Event 469
EndRequest Event 471
Terminate Event 472
In The Event of a Real Error.... 472
Life Cycle Dimensions 473
Webclass Methods 474
ReleaseInstance 474
Trace 475
URLFor 475
Webclass Properties 476
NameInURL 476
Public 477
StateManagement 477
NextItem 478
BrowserType 479
Unattended Execution 479
Webitems 479
Standard Events 480
Template Events 482
Custom Events 483
Connecting HTTP Requests to Events 484
Typical Event Candidates 484
Name Assignment 486
Multiple Attributes 486
Connecting Attributes 486
Connecting to WebItem 487
Connecting to Custom Event 488
Updating Changes in the Webclass Designer 489
Summary 492

xv
Table of Contents

Chapter 14: Advanced Webclass Techniques 495


Sending HTTP Responses 496
HTML Template files 496
Tools to use 496
Visual Interdev 497
FrontPage 497
Notepad 498
DHTML Designer 498
3rd Party 501
Manipulating HTML Template Files 501
Adding Template Files 501
Removing Template Files 502
Editing HTML Template Files 502
Changes Made to HTML Templates 505
Response Object 505
Write 505
BinaryWrite 506
Processing HTML Template Files 508
Active Server Pages – Dynamic, but Limited 509
Scripting Language Limitations 509
Code Security 510
Scripting Performance 510
Limited Transactional Participation 510
Webclass Tag Processing 511
Template Initialization 512
HTML Template Tag Indicators 513
Tag Processing 515
Tag Processing Arguments 516
Building an IIS Application 518
Basic IIS Application 519
Implementing Advanced Techniques 524
Adding Templates 525
Connecting WebItems 528
Processing a Template File 534
Advanced Tag Processing 535
Processing Form Submittals 538

xvi
Table of Contents

Using the URLFor Method 541


Using BinaryWrite 542
Summary 544

Chapter 15: Meet RDS 547


Using RDS – an Introduction 547
Why Use RDS? An Example 548
RDS Eases the Network Burden 549
Using HTTP 549
Data on the Client 550
Web Clients don't Need a Constant Data Connection 550
Data Can Be Accessed From Virtually Anywhere 550
RDS Improves the User's Experience 551
The Structure of RDS 551
RDS and n-tier Applications 552
N-tier Applications in General 552
The Place of RDS in n-tier Applications 553
RDS Architecture 554
The RDS Object Model 556
The [Link] Object 556
Business Object Proxies 557
The [Link] Method 559
The [Link] Property 560
The [Link] Object 560
The ConvertToString Method 560
The Query Method 561
The CreateRecordset Method 562
The [Link] Object 563
Using the [Link] object 564
Methods of the [Link] object 565
The SubmitChanges and CancelUpdate Methods 565
The Move Methods 566
The Refresh Method 566
The Reset Method 567
Properties of the [Link] object 567
The Connect Property 567
The ExecuteOptions Property 567

xvii
Table of Contents

The FetchOptions Property 568


The InternetTimeout Property 568
The ReadyState Property 568
The Recordset and SourceRecordset Properties 568
The Server Property 569
The SQL Property 569
Filtering and Sorting 569
Events of the [Link] Object 570
The onReadyStateChange Event Procedure 570
The onError Event Procedure 570
Putting the Pieces Together 571
Summary 573

Chapter 16: A Guide to XML 575


XML as a second language 575
Putting XML in perspective 579
Well-formed XML 580
DTDs and Valid XML 580
XML Companions 581
DOM: Manipulating XML Data 582
A Tree Grows in XML 582
What is XSL? 585
Transforming XML for Display Using XSL 585
Transforming XML for Display Using XSL: Step-by-Step 587
Client-side XML 590
Generating XML using Visual Basic 6 590
XML from a Recordset using the ADO 2.1 Save method 591
XML from a Recordset using custom code 594
XML from a Recordset using DOM 603
Server-Side XML 610
Generating HTML from XML on the server 610
Sending XML from the client to the Server 615
Putting it all together: Using the IE5 HTTPRequest Object to Send
an XML File to the server 615

xviii
Table of Contents

Receiving an XML File on the server 621


Receiving XML on the Server using an ASP script 621
Receiving XML on the Server using a Visual Basic IIS Application
622
Summary 624

Case Study 1 : Message Board Part 1 627


Why a message board? 627
Technologies Used 628
Design Objectives 628
Speed 629
Ease of use 629
Accessible to Widest Range of Users 629
A Look at the Finished Product 630
Architecture Overview 631
Logical View 631
Physical Diagram 632
Interaction between tiers 632
Building the Message Board 633
The Database 633
Creating the message board database 633
Creating the Message table 634
The MessageWrite Table 637
Creating the Stored Procedures and Transaction 637
Creating a new database login 642
Creating a new ODBC Data Source 644
Creating the Middleware Business Object 646
Creating the HTML for the Message Header List 649
Retrieving an existing message 656
Adding a new message 656
Creating the DLL file 659

xix
Table of Contents

Mid-Study Summary 659

Case Study 1 : Message Board Part 2 661


Creating the Presentation Layer 661
Displaying the Message Headers 662
Creating the HTMLTemplates 662
Incorporating the HTML Templates for GetMessages 665
Error Handling in a Webclass 668
Populating tmpMessages Template’s WebClass Tags 670
A Test Run 670
Displaying the Sub message Headers 672
Row Highlighting Using Mouse Rollover 674
Retrieving a Message Using Remote Scripting 675
Installing Remote Scripting on the Server 676
Creating the ASP Page To Be Accessed Remotely 677
Remote Access from the Client Side HTML 679
The Message Retrieving Script 681
Responding To a User's Request to View a Message 682
Another Test Run 685
Creating a New Message 686
Storing The Message 688
Informing the User Whether the Message Posted Successfully 689
Adding the Message Creation VBScript 690
Creating a New Message 690
Replying to an Existing Message 691
Emailing a Message Author 691
Displaying a Helpfile 691
Link Back to your Web Site 693
Internet Explorer Message Board Completed! 693
Deploying the Message Board 693
Deploying the Database 694
Generating SQL Scripts 694
Deploying the Business Object 696
Deploying the Webclass 699
Deploying Remote Scripting 700
Summary 700

xx
Table of Contents

Case Study 2 : Web Based Document Management703


HISTORY 703
Design 704
Implementation 710
Configuration 724
Real Life Examples 726
AppClient 733
Summary 747

Case Study 3: DHTML Applications 749


The Employee Data-Entry Application (EDA) 749
Case Study Road Map 749
EDA Requirements 749
EDA Design 750
Implementing EDA 750
Create a DHTML Application project 751
Importing the HTML file 753
Implementing the User Interface 754
Saving the Employee Data 758
Implementing EDA - Take 2 762
Adding an ActiveX Control to the Web Page 762
Using ActiveX Controls in VB 765
766
Persisting the Employee Data 766
Saving State Information 771
Where To Go From Here 774

xxi
Table of Contents

Case Study 4 : CGI Integration 777


CGI Overview 777
Advantages and Disadvantages 778
Visual Basic and CGI 779
CGI Fundamentals 780
Composing the Query String 781
POST vs. GET 782
CGI Environmental Variables 783
Generating the Response 783
Project Description 784
Building a CGI Application Using VB 784
Breaking the Standard I/O Barrier with CStdIO 784
CStdIO API Declarations 785
CStdIO Initialize and Terminate 786
CStdIO WriteOut Method 787
CStdIO ReadIn Method 787
Testing the CStdIO Class 788
Designing the CGI Application Framework (CAF) 789
The ICGIApp Interface 790
CAF Classes 790
Implementing the CGI Application Framework 792
Implementing the CGILibGlobal Class 792
Implementing the CCGI Class 796
Implementing the CEventLog Class 800
Implementing the CStdIO Class 803
Defining the ICGIApp Interface 803
Summary 804
Using CAF to Implement CGIEmpData 804
Implementing ICGIApp with the CCGIEmp Class 804
Implementing the CEmployee Class 810
Testing the CGIEmpData Program 811

xxii
Table of Contents

Building a CGI Client using VB 812


Preparing the Environment 812
The Employee Data Entry Application Client 812
The CQueryString Class 814
Implementing the Employee Data Entry Form 818
Running the Employee Data Client 820
Summary 821
Appendix A: Common HTML Tags by Category 823
Appendix B Tutorial in VBScript 831
Appendix C: VBScript Reference 869
Appendix D: JScript Tutorial 893
Appendix E: Active Server Pages Object Model919
Appendix F: Configuring IIS4 925
Appendix G: ADO Remote Data Service (RDS)
Reference 939
Appendix H: Microsoft ActiveX Data Objects 2.0

Library Reference 953


Appendix I: Collaboration Data Objects for
NT Server (CDONTS) Reference971
Appendix J: Microsoft Transaction Server Type

Library Reference 1007


Appendix K: Microsoft Message Queue
Object Library Reference1011

Appendix L: Support and Errata 1037


xxiii
Table of Contents

Index 1045

xxiv
Table of Contents

xxv
Table of Contents

xxvi
Introduction

What Does this Book Cover?


Over the past five years, the internet has gone from the preserve of academics to the cutting edge of
business. A large part of this has been driven by the growth of the Web, with its graphical browsers and
high media profile. Even so, there are considerable advantages to using the internet as a programming
medium, and Microsoft have worked hard at finding ways of applying Visual Basic skills gained in
traditional application development to the internet. In this book, we're going to explore these methods,
focusing on how you can use your Visual Basic skills to program the web.

In particular, we'll be looking at the following areas:

 Introducing Internet Application development


 Client side programming
 Server Side Programming
 Data handling on the Internet

Let's discuss each of these sections in a little more depth.

Introducing Internet Application development


In this introductory section, we'll examine the internet's history and discuss its infrastructure. We'll look at
the advantages and disadvantages of developing for the web, and introduce you to the tools and techniques
that are available to you as a Visual Basic programmer. Most importantly, we'll discuss the architecture and
design considerations you need to bear in mind when you start designing for the web.
Introduction

 Web Fundamentals
 Windows DNA Application Framework
 Building Windows DNA Applications

Programming the client


One of the limiting factors in the growth of the internet was, for a long time, the inflexibility of the early
browsers. Essentially, they were designed to display simple text files, marked up with HTML. While this
was fine for research and simple publishing, it was not suitable for the transfer or retrieval of business
information, or for providing interactive, intelligent applications that allow users to carry out useful tasks,
or simply have fun. Gradually, however, browser potential has increased as Microsoft and Netscape, loosely
(and occasionally ineffectually!) shepherded by the World Wide Web Consortium, have introduced various
technologies to take browsers beyond simple display. We've focused specifically on those techniques that
can be directly leveraged by a Visual Basic programmer:

 Client-Side Programming with Visual Basic


 Building Client-Side ActiveX Controls
 DHTML Applications
 Integrating Web Browsing Using the WebBrowser Objects

The final chapter in this section is not directly about programming the client; instead it covers how you can
add web browsing to your applications, to take advantage of the flexibility of the Internet while still
maintaining complete design control over the client.

Server side programming


As you'll discover, although client-side programming with Visual Basic is very powerful, it also has some
significant disadvantages. In this section, we'll move on to looking at techniques for dynamically generating
HTML on the server, sending it out to clients, and processing information that the clients return. We'll
begin by looking at Microsoft's Active Server Pages, which is the foundation of Microsoft server-side
development, and then go on to explore the techniques which use Active Server Pages as a delivery
mechanism for your Visual Basic skills.

 Understanding ASP
 Server Components
 Advanced Server Components
 Interfacing With Server Services
 Intro to Web Classes & IIS Apps
 Basics of Web Classes & IIS Apps
 Advanced Web Classes Techniques

2
Introduction

Datahandling on the Web


To finish off our introduction to web programming, we're going to glance briefly at data-handling on the
web. The first technique will be an introduction to the Remote Data Services (RDS) which offer a
powerful method of manipulating data on the client, using a combination of client-side and server-side
components. Then we'll take a look at the next wave of web technology, XML – the eXtensible Markup
Language

 Meet RDS
 A Guide to XML

Case Study
Finally, we've rounded out the book with four case studies that look at the different aspects of programming
for the web. All the case studies showcase several different techniques, and provide real world application
of the methods we've studied throughout the book.

Who is this Book For?


If you've already picked this book up, then you probably have the most important knowledge you'll need
already – a solid understanding of Visual Basic. We expect you to have some knowledge of Visual Basic's
related skills, and in particular a reasonable familiarity with ADO, and how to use it to access databases.

This book isn't intended to teach you how to write your first web page, so we're assuming you already know
HTML. In any case, if you can master Visual Basic, you should have no trouble picking up HTML, from
any one of the wide range of HTML tutorials around; Wrox's own HTML 4.0 Programmer's Reference
(ISBN 1-861001-56-8) gives a no-nonsense introduction.

Apart from that, all you need is a desire to learn how to add the internet to your programming repertoire!

Technology Requirements
We've assumed that you either use or have access to a machine with NT4.0 installed. You'll need Service
Pack 5 (the most current update at the time of printing) and Option Pack 4 installed as well. Option Pack 4
gives you Internet Information Server 4.0 and Active Server Pages 2.0, the standard set-up on which we've
based this book.

You can install Personal Web Server on a Windows 95 or 98 machine, or peer-to-peer Web
Services on NT workstation to get Active Server Pages 2.0. We haven't covered these
however, and, although you will be able to run the code, you should refer to Microsoft's
documentation or to Wrox's Beginning Active Server Pages for more details.

For the client, we're assuming Internet Explorer 5.0. Installing IE5.0 will automatically add the ADO 2.1
library, and IE5 is essential for the chapters which discuss XML. If you choose to use IE4.1, then you will
need to install ADO 2.1 separately. You can download it from the Microsoft Data webpage,
[Link]

3
Introduction

If you want to be able to run all the code, you should also have access to a SQL Server 7.0 database. It need
not necessarily be installed on your development machine, but you will need administrator privileges. You
will also need the sample databases supplied with SQL Server. The code we've supplied will run with SQL
Server 6.5, or even Access at a pinch, but you should be prepared to do some tweaking.

For programming itself, we naturally expect you to have Visual Basic 6.0 installed, along with the most up
to date Service Pack for Studio 6.0 (currently 3, and available from
[Link] You will also need a good HTML editor – Visual
Interdev 6.0 is the most obvious choice, since it integrates well with VB – but there are a range of other
packages with varying degrees of sophistication and ASP and VB support. Homestead4.0 and
Drumbeat2000 are popular choices. You'll also find a simple text editor – Notepad is fine – useful for quick
checks and fixes.

To summarise, the optimal set up is:

 NT 4.0, with Service Pack 5 and Option Pack 4


 Internet Explorer 5.0
 ADO 2.1
 SQL Server 7.0 (SP2)
 Visual Basic 6.0 (SP3)
 Visual Interdev 6.0 (SP3)
 Notepad

Conventions
We have used a number of different styles of text and layout in the book to help differentiate between the
different kinds of information. Here are examples of the styles we use and an explanation of what they
mean:

Advice, hints, and background information comes indented and italicized, like this.

Important information comes in boxes like this.

Bullets are also indented, and appear with a little box marking each new bullet point, like this:

 Important Words are in a bold type font


 Words that appear on the screen in menus like the File or Window are in a similar font to the one that
you see on screen
 Keys that you press on the keyboard, like Ctrl and Enter, are in italics
 Code has several fonts. If it's a word that we're talking about in the text, for example when discussing
the For...Next loop, it's in a bold font. If it's a block of code that you can type in as a program and
run, then it's also in a gray box:

4
Introduction

Set oCars = CreateObject("[Link]")


Set recCars = [Link](RegistryRestore("Showroom", "Not Set"))

 Sometimes you'll see code in a mixture of styles, like this:

If IsMissing(ConnectionString) Then
varConn = RegistryRestore("Showroom", "Not Set")
Else
varConn = ConnectionString
End If

The code with a white background is code we've already looked at and that we don't wish to examine further.

These formats are designed to make sure that you know what it is you're looking at. We hope they make life
easier.

Tell Us What You Think


We've worked hard on this book to make it useful. We've tried to understand what you're willing to
exchange your hard-earned money for, and we've tried to make the book live up to your expectations.

Please let us know what you think about this book. Tell us what we did wrong, and what we did right. This
isn't just marketing flannel: we really do huddle around the email to find out what you think. If you don't
believe it, then send us a note. We'll answer, and we'll take whatever you say on board for future editions.
The easiest way is to use email:

feedback@[Link]

You can also find more details about Wrox Press on our web site. There, you'll find the code from our latest
books, sneak previews of forthcoming titles, and information about the authors and editors. You can order
Wrox titles directly from the site, or find out where your nearest local bookstore with Wrox titles is located.

Customer Support
If you find a mistake, please have a look at the errata page for this book on our web site first. If you can't
find an answer there, tell us about the problem and we'll do everything we can to answer promptly!
Appendix L outlines how can you can submit an errata in much greater detail. Just send us an email:

support@[Link]

or fill in the form on our web site:

[Link]

5
Introduction

6
Web Fundamentals

For a long time now, Microsoft has promoted their vision of "Information at Your Fingertips" so that a user
can operate more efficiently. It was during his keynote speech at COMDEX in 1990 that Bill Gates
introduced this concept and discussed his expectations of the future. He painted a picture of the
consequences that desktop computer technology would have in many areas of everyday life.

Four years later, Bill Gates gave another COMDEX speech updating his original theme. While he talked
about the effects of the recent rapid changes in the technology, there was still no reference to what no doubt
has caused the biggest revolution in the IT industry since the PC … the Internet.

Microsoft's D-Day awakening to the Internet wasn't until December 1995 when they publicly acknowledged
its significance and announced an overall Internet strategy. Later in March 1996 at their Professional
Developers Conference, Microsoft delivered a promise to use Internet standards to extend and embrace
existing IT infrastructures and to deliver a more effective computing environment. This would be achieved
by producing a comprehensive set of technologies, products, services and tools that would seamlessly
integrate desktops, LANs, legacy systems, GroupWare applications and the public Internet.

While Microsoft joined the Internet game relatively late, they rapidly gained momentum and have since
released an incredible range of innovative Internet products. These products have provided users with rich
Internet experiences, and organizations with the mechanisms to develop business critical Internet solutions
that are secure, robust, high performing and scaleable.

The most recent vision of Microsoft's strategy for delivering their "Information at Your Fingertips" goal
was unveiled at the Professional Developers Conference in September 1997. It was announced that
Microsoft's future strategy would be based on delivering an architectural framework for creating modern,
open, scaleable, multi-tier distributed Windows applications using both the Internet and client/server
technologies – this was to be known as the Windows Distributed interNet Applications Architecture or
Windows DNA.
Chapter 1

The roadmap for the delivery of Windows DNA meant that its introduction would be evolutionary and not
revolutionary. It would build on current investments in technologies, hardware, applications and skills.
Many of the services detailed in Windows DNA had been around for a number of years – however,
Windows DNA was the formalization of the framework and a blueprint for the future. Fundamental to
Windows DNA is Windows 2000 (previously known as Windows NT 5.0), which is not targeted for
delivery until late 1999. However, some of the key Windows DNA components are available now and
supplied in the Windows NT 4.0 Option Packs and Internet Explorer 5.

A crucial part of Microsoft's Windows DNA arsenal is their comprehensive portfolio of development
products. Most notable is Visual Studio (current version 6.0), which in its Enterprise edition includes all of
the Microsoft programming languages, development tools and documentation. The aim of the latest releases
of these development products is to address Windows DNA by reducing the differences between the
development of Internet applications and of more traditional client/server environments. Without doubt, the
most popular programming language is Visual Basic and, as we shall see throughout this book, the latest
version (Visual Basic 6.0) meets the DNA objectives in full.

In this chapter, we'll preview the key concepts of Web technologies in order to provide a foundation for
each of the topics discussed throughout the book. In particular we shall look at:

 Why the Web and Internet technologies are so popular and the reasons that many businesses are now
basing their IT strategies upon them
 The fundamentals of Web technologies, covering the key concepts that the remainder of the book will
assume the reader understands
 How various Microsoft technologies have overcome some of the problems of the early Web methods to
improve the user experience and enable business critical applications to be deployed over the Web

So let us start by discussing why Web technologies are so popular and understand fully why their wide
acceptance is not just due to media hype.

Why Web Technology?


Although the Internet has existed in various forms since the late 1960s, it is only over the last few years
that it has become widely known and utilized. In such a very short period of time, it has caused major
changes in information technology, business processes, communications and the way many people spend
their leisure time. It is probable that no other significant invention or technology has been embraced by so
many so quickly, or has had the potential to change our future lifestyle so dramatically. To compare its
growth, consider that the World Wide Web attained 50 millions users in four years – it took radio 38 years
and television 13 years to reach similar penetration.

To understand the main reasons for the rapid adoption of Web technologies, we need to comprehend the
effects of two important and independent issues that are driving future Information Technology directions –
one is business led and the other is technical. In the next couple of sections we shall discuss:

8
Web Fundamentals

 the critical issues facing organizations as they adjust to address the changing market forces and do
business in the 21st century
 the convergence of computing and communications, and discuss the evolution of IT system architectures

IT Strategy for the Millennium


As we approach the millennium, today's senior management is faced with the unique problems of ensuring
that their organizations can meet the challenges caused by the rapidly changing market place.

To survive, it is vital that their organizations have an effective IT strategy to enable competitive advantage
by providing productivity improvements, increased customer satisfaction, mechanisms for new and
enhanced revenue streams and timely access to key data for effective business decisions. In addition, the IT
infrastructure must provide flexibility and allow the business to react quickly to change and when potential
opportunities are recognized.

Another term recently coined by Microsoft is the Digital Nervous System and this provides a great
analogy. In a human, it is the web of nerves and synapses that enables the body to have the information that
it needs, when it needs it, to unconsciously perform its various complex tasks. Similarly, any competitive
company must have a healthy IT infrastructure (i.e. 'digital' nervous system) that provides good information
flow, allows it to perform its tasks in an efficient manner and that allows the business to respond quickly to
the frequently changing market dynamics.

Processing Islands in the Enterprise


For many years, organizations have accomplished their business goals by exploiting their technology base
in the following three dimensions:

 Data Processing – these are the core IT systems that control the fundamental business processes in an
organization; examples can include Accounting, Stock Control, Order Processing, Job Tracking, etc.
Many types of technologies, from large mainframes to client/server architectures have been applied to
these business critical systems and most of these still have a part to play in today's IT infrastructures.

 Personal Productivity – the huge popularity of the PC and the Integrated Office suites has forever
changed the way individual employees work with information and has often changed business practices
and strategies. These tools have dramatically increased productivity, streamlined operations and made IT
more cost effective.

 Collaboration – the use of communications and GroupWare software has enabled both organizations
and individuals to work in partnership and teams. Such systems can scale to thousands of users across
the enterprise enabling businesses to redefine their operations for further advantage and reduced costs.

However, many of these benefits do not come without high cost. Each of these dimensions typically has
their own infrastructures and businesses have been faced with the complex problem of building 'information
bridges' between the different systems and applications – building systems that span all dimensions has
been historically difficult. Furthermore, having multiple technology infrastructures always results in
additional costs for software, hardware, support and training.

9
Chapter 1

Integrating the Enterprise


Over the years, software vendors have offered various architectures in an attempt to integrate the various
distributed environments within an organization. Unfortunately such solutions have never provided the
complete seamless integration and flexibility that a business demands. At long last, there now seems to be
light at the end of the tunnel as it appears that using distributed computing frameworks based on Web
technologies provide the key to fulfilling these requirements. The rapid adoption of Internet standards by
every significant IT vendor has provided for the complete integration of the various distributed
environments and different infrastructures within an organization.

10
Web Fundamentals

The first serious use of Web technology within business was for the implementation of Intranets. Intranets
take full advantage of the open industry standards and the familiar Web browser/server software, originally
devised for the Internet, to provide employees with access to corporate information and processes.
However, whereas the Internet is open to all, an Intranet is closed and has strict user access controls
enforced.

Many companies are now taking advantage of Intranets to make it more efficient for their staff to locate and
process information, and to collaborate with each other. The Web browser approach enables a consistent
user interface and provides a single view of all company information irrespective of its native file format or
the type of data source. For most organizations their business information is key and many have huge
amounts of investment in existing data systems and electronic documents – mechanisms enabling the
leverage of such valuable knowledge in the organization can have considerable impact on business
performance.

Extending the Enterprise


A digital nervous system is not just about moving information around inside a company but also out to
customers, partners and suppliers. The recent advances in networking means that both private and public
networks (and in particular the Internet) can be exploited to extend the Enterprise to include external
parties. Many businesses are now finding that their infrastructures are becoming intelligently intertwined
with each other to form Extranets that are large 'Virtual Enterprises', and which frequently comprise many
different organizations.

As an example, consider the manufacturing supply chain; before the goods reach the end customer,
numerous organizations are involved along the chain from handling the raw materials, through the
manufacturing process, and on to distribution and retail. Each of these organizations can achieve faster
delivery times and reduce their inventory costs if they handle their business processes electronically.

11
Chapter 1

Business partners and customers work together to form a single, distributed, 'Virtual Enterprise'.

Let us now take a look at some of the technical aspects of this change.

The Evolution of IT System Architectures


Over the next few sections we shall be looking at the evolution of IT architectures and see how the pursuit
of an optimal solution has led us to using an infrastructure based on Web technologies. Hopefully by the
end of this discussion, you shall start to agree that the compulsion to move to using Web architectures is
irresistible.

So we shall start with a short history lesson…

The Early Days – Centralized Computing


In the 1960s and 70s, the computers adopted by businesses were expensive mainframes that used simple
monochrome terminals with keyboards to access the applications and the databases. These resources were
located centrally on the mainframe and processing times was shared or 'time-sliced' between the various
users.

Such terminals are now often referred to as 'dumb terminals' since they could not perform any of the
processing logic – they were text based and only capable of displaying screen forms comprising of
information received from the central system or entered by the user. The keyboards had a designated button
for 'submission' in which all of the information entered into the screen form would be sent to the central
system for subsequent processing such as validation and database access.

As time passed on, the hardware technology evolved and many small businesses migrated towards the use
of cheaper minicomputers and UNIX super-microcomputers. These systems relied on a new generation of
dumb terminals but they were typically no smarter than their predecessors. Such systems would intercept
every user key-press and then instantaneously generate the appropriate screen interaction.

This early model of computing was centralized –the business processing, data management and screen
presentation was all controlled by the central systems with just the user interaction handled by the terminal
devices.

12
Web Fundamentals

PC Networking: Moving Towards Decentralization


Over time, further advances in hardware, software and networking enabled the computer systems to move
from a centralized shared logic based architecture to a network of workstations and servers.

The first personal computers and local area networks appeared in the early 1980s. Applications that
exploited this new model were based on file sharing and various XBase products such as dBase, FoxPro and
Clipper popularized this approach. In such systems, all the data is downloaded from a central file server and
operated upon by application logic that is totally resident on the workstation. File sharing systems worked
well for small amounts of data and small populations of users. However, as the momentum for PC
networking grew, the capacity of such applications became strained and an alternative approach was
required – the solution came from using an application architecture known as client/server computing.

Client/Server Computing
Client/server involves breaking up the system functionality into distinct manageable layers that can be
independently developed, deployed across multiple machines and that use a communication mechanism to
allow the different layers to co-operate.

This approach is regarded as an enabling technology that can implement systems across an organization in a
modular and flexible manner. It allows for the distribution of applications away from single machines
located in isolated departments to an implementation across the enterprise. For example, it is now possible
for one person in customer services to access all corporate systems (subject to any security restrictions that
may have been imposed)– gone are the old days of annoying transfers between the different representatives
in each department.

13
Chapter 1

It is common to find that most client/server solutions involve the following independent layers:

 Presentation logic – this handles how the user interacts with the application; usually implemented by
providing an easy to use graphical user interface (GUI)
 Business logic – this handles the mechanics (or business rules) of the application, the processes that
reflect the everyday functions of the business
 Data access logic – this handles the storage and retrieval of data

The development of these separate layers needs careful design and an accurate definition of the distinct
boundaries to ensure that functionality within the different layers is not intertwined. Interfaces between the
layers must be carefully defined and strictly followed. Encapsulating the logic in this fashion ensures that
future changes can be implemented without impacting the other layers and this enables both reusability and
reliability.

There are many variations to client/server implementation; we shall now look at the three principle
architectures that are put into operation.

Two Tier Client/Server


The first generation of client/server systems was an evolution of the file sharing applications mentioned
above. With these applications, the central file server is replaced with a specialized relational database
management system (RDBMS). Such databases can offer high transaction rates at a fraction of the costs
associated with mainframes. When the client (a workstation application typically using a screen-based form
or GUI) needs to act upon data, it makes a request via the network to the database server – the database then
processes the request and returns just the data appropriate to the client's needs.

When compared to the file sharing application (which returned the complete file), this client/server
architecture dramatically reduces network traffic. In addition, today's databases provide many features that
enable the development of advanced multi-user applications – for example, allowing multiple users to
access and update the same set of data.

Because the processing is split between distinct layers – the workstation and the database server – such
architectures are referred to as being two-tier client/server architecture.

14
Web Fundamentals

This approach became very popular as it was found that sophisticated systems could be implemented
quickly (and thus cheaply) using development tools like Visual Basic and rapid application development
(RAD) techniques.

However, as expectations increased it was found that this architecture had certain limitations and problems,
including the following:

 the database requests can generate large result sets; the performance of two-tier architectures is found to
rapidly deteriorate as networking bottlenecks occur when an optimum number of users is exceeded
 the architecture imposes substantial processing on the client, since both the business and the presentation
logic are implemented here; this means workstations with powerful CPUs and large amounts of disk and
memory may be required
 each workstation session requires a separate database connection; this can drain resources on the
database server – for example, Microsoft SQL Server requires 37K of memory for each user connection
(and this is much lower than many other vendor's RDBMSs)
 deploying the business rules on the client can lead to high costs of deployment and support; if the logic
changes, the effort in updating software on numerous workstations can be excessive

So whilst two-tier client/server is justifiable for small workgroup applications, it is now generally agreed
that this approach offers a poor solution since it does not provide the flexibility or scalability for large-scale
applications deployed across the corporate enterprise.

15
Chapter 1

Three Tier Client/Server


Drawing on the lessons learnt from the two-tier systems, an increase in application performance and a
notable reduction in network traffic can be be achieved by inserting an additional tier in the middle,
between the workstation and the database server, to create three tiers. Because the programmer can then
make changes to the internal structure of the database, the way the client presents information, and most
importantly to the middle tier, without affecting the other two layers, the architecture is far more modular
and thus far easier to adapt to business's ever changing needs.

This approach is known as a three-tier client/server architecture. The middle layer is called the
application server and is used to handle the business logic of the system. The workstation is now only
responsible for handling the presentation logic. As before, the database server handles the data access logic.

It is possible for the application server and database server to physically reside on the same machine – and
in many cases this can provide an optimum solution. However, for it to be recognized as three-tier, distinct
logical boundaries or interfaces must exist between the two layers to ensure the advantages of the
architecture are achieved.

Multi Tier Client/Server


A further extension to three-tier solutions is the multi-tier, also called n-tier, architecture. These solutions
are the most flexible and scaleable and build on all the advantages of the three-tier architecture.

16
Web Fundamentals

In a multi-tier client/server solution, the business logic is partitioned and distributed over several machines.
As requirements change during a system's lifetime, this partitioning and deployment can be reviewed and
amended with minimal impact. Furthermore, additional tiers are included to support multiple databases and
other services such as message queues, legacy systems, data warehouses, communication middleware and
so on.

By enabling the distribution of the workload over many CPUs (using either symmetric multiprocessing or
massively parallel processing cluster technology), it is obvious how scalable solutions can be delivered.
Sometimes the distribution of the logic over separate geographical regions can be considered to achieve
optimum performance; for example, to locate processes at the sites where it limits the amount of slow
network communications performed.

symmetric multiprocessing (SMP) is an architecture allowing processing to be


undertaken by multiple CPUs that share a common operating system and memory

massively parallel processing (MPP) is an architecture that coordinates the overall


processing of a complex task by breaking it up and allowing each part to be undertaken
by a separate system (single CPU or SMP) using its own operating system and memory.

Unfortunately, three-tier and multi-tier client/server solutions are not trivial to implement. There are more
tasks to undertake and more complex issues to address than when building two-tier systems. A strong
understanding of the multi-tier client/server development techniques and an appreciation of the potential
pitfalls are vital. Once this experience has been acquired and the problems mastered, the rewards are
solutions that are more flexible, provide greater scalability and are easier to support.

17
Chapter 1

Web Technologies: Centralized Computing but with a


Twist
Just as we were beginning to get used to the issues of developing multi-tier architectures, the new paradigm
of Web Technologies arrived to direct interest from the traditional client/server architectures.

The Web architecture is a flexible and scaleable implementation of multi-tier computing and uses a Web
browser (client) to retrieve information from a Web server. The Web server can interface with application
servers which in turn interfaces with databases, enabling our Web applications to determine
programmatically the information that is returned to the user.

18
Web Fundamentals

In the simplest scenario, the three processing layers may reside on the same machine, as shown below.

Many people confuse the terms Internet and Web or consider the two as equivalent but in fact, the two are
very distinct. It is important to recognize that the Web is not a network but an application that operates over
networks using a communications protocol called HTTP (Hyper Text Transfer Protocol).

Most documents retrieved over the Web contain HTML (Hyper Text Markup Language), which is a page
description language that defines both the data content of the document and information on how the
information should be displayed (or rendered) by the Web browser. Modern Web browsers support the
display of multimedia within the retrieved HTML documents – including text, graphics, sound, video – and
hyperlinks in which items on the document are linked to other Web resources. By clicking on a hyperlink,
the Web browser automatically navigates to the target document.

19
Chapter 1

We can now see how the Web based data access model has traveled a full 360 degrees back to an apparently
centralized computing model. The twist however, is in this model, instead of accessing a single mainframe,
the client is now accessing geographically distributed applications resident on multiple servers
interconnected by networking technologies.

The great thing about this Web architecture is that it solves the several problems with traditional
client/server. By restricting the client processing logic to HTML it is possible to develop a single universal
application that can be deployed across different types of platforms, whether Windows, Mac, one of the
Unix flavors, or something else entirely.

In addition, all client logic is centrally administered and dynamically deployed – this means that any bug
fixes or enhancements will automatically be applied the next time the user accesses the application. This
avoids the process of having to manually deploy software on every desktop, which can be very costly on a
large population of users.

So recapping on what we have seen so far, there are two main messages to take with us as we proceed.
Firstly, the next hugely successful companies will be those that quickly enable the next generation of
business systems that exploit the convergence of computers and networking for business advantage.
Secondly, it will be the Web technologies that will be the key enabler in their search for prosperity.

In the next section we shall introduce some of the basics concepts about Web technologies that are
prerequisite knowledge in order to understanding the topics discussed in this book.

Web Technology Fundamentals


The recent rapid expansion of the Internet has led many people to think that the Internet is a new
innovation. Most people are surprised to learn that it has actually been around a number of years after
starting life off in the late 1960's as a research project called ARPANET (Advanced Research Projects
Agency Network). At the time of the Cold War, the US Department of Defense was concerned that their
communications infrastructure could be wiped out by a single nuclear strike on their central military
computer systems.

The objective of the ARPANET project was to investigate the development of a decentralized computer
network such that each node is of equal importance and an unexpected malfunction or deletion of a node
does not affect the resilience of the network. Should a network node be taken out of service (for any
reason), the network dynamically adjusts its routing configuration to use alternative paths to ensure that the
information is successfully delivered to its intended destination.

The ARPANET network later opened up to education establishments and commercial organizations. It has
since adopted a suite of protocols called the Internet Protocol Suite or as more commonly known TCP/IP.

The network then became known as the Internet and this took its name from being a collection of
interconnected networks. Now, the Internet has grown to encompass a huge number of autonomous
networks. Recent estimates have suggested that there will be over 100,000,000 computers on the Internet
very early into the new millennium.

20
Web Fundamentals

TCP/IP Networking
The Internet Protocol Suite includes a number of standard communications protocols; however, the two
most common protocols are:

 Internet Protocol (IP) – this is used to route a packet of data from node to node across the network
 Transmission Control Protocol (TCP) – this is used to create a point-to-point communication channel
and ensures that the information is delivered error free and in the correct order that it was originally
transmitted
It is these two main protocols that give the suite its more common name, TCP/IP.

TCP/IP Protocol Stack


The following diagram shows how TCP/IP exists in a stack of networking protocols that provides the
communications functionality.

There are a number of application protocols that can operate above the TCP/IP layers and applications that
use these can operate simultaneously. Common examples include Web (HTTP), Electronic Mail (SMTP),
Chat (IRC), File Transfer (FTP), Newsgroup Bulletin Boards (NNTP) and Terminal Emulation for
accessing traditional mainframes (Telnet).

Network Addresses
Every computer that is connected to an IP network is uniquely identified by a value, known as its IP
address. An IP address is written and spoken as a sequence of four 8-bit decimal numbers, separated by the
dot character, for example:

[Link]

21
Chapter 1

An IP network may be a single network of just a few computers, such as an Intranet, or it could be a
complex interconnected set of independent networks – an example of the latter case is the Internet. The IP
address must uniquely identify both the network, and the computer within the network. There are four
different ways in which this 32-bit block can be broken down into the network address and the host
address – these four decompositions are defined by the class types A, B, C and D; these are shown in the
table below:

The rapid growth of the Internet has led to a shortage of IP addresses – no one could have anticipated the
Internet when the protocol was first devised. The next version of the Internet Protocol (IPv6) will provide
relief to this problem by lengthening the IP address from 32 bits to 128 bits. This version is also frequently
referred to as IPng (IP Next Generation).

With certain Internet applications, it is possible to identify a computer on an IP network by using a logical
name, for example:

[Link]

When this happens, the Internet application must first resolve this logical name (i.e. [Link]) to
its corresponding IP address by communicating with another predefined server called a DNS (Domain
Name System). This server returns the associated IP address by means of a lookup database, that maps
logical domain names to IP addresses, or by communicating onwards with other DNS servers for the IP
address to be resolved.

22
Web Fundamentals

Don't worry about the leading http:// prefix in the above example – we shall be discussing this shortly.

Port Numbers
There is another important number that must be considered when communicating over an IP network; this is
called the port number. A port number is used to distinguish between the individual networking
applications that are running simultaneously above the TCP/IP protocol stack.

Port numbers for standard TCP/IP services are often referred to as well-known port numbers; here are some
examples:

 21 – File Transfer Protocol (FTP) … File Transfer


 23 – Telnet … Terminal Emulation
 25 – Simple Mail Transfer Protocol (SMTP) … Electronic Mail (E-Mail)
 80 – Hypertext Transfer Protocol (HTTP) … Web / WWW
 119 – Network News Transfer Protocol (NNTP) … Newsgroups / Forums
 194 – Internet Relay Chat (IRC) … Conferencing

Server processes are associated with a fixed port and the client must know the port in order to connect with
the network [Link] example, a Web server will normally be listening for connections on port 80 (the
http well-known port number) — a Web browser will use this port number by default when attempting to
connect to the remote computer.

Uniform Resource Locator


All information that can be accessed over the Internet must be uniquely identified using a reference that is
called a URL (Uniform Resource Locator). The naming scheme involves three concatenated items as
follows:

<protocol> :// <machine id> / <local name>

where:

Item Description
<protocol> identifies the application protocol used to retrieved the resource
<machine id> identifies the server on which the resource is located – this is either an IP
address (a unique sequence of four 8 bit numbers e.g. [Link])
or a domain name (e.g. [Link])
<local name> identifies the resource on the server and can include a directory structure
which the server must interpret. Can point to a default resource if one not
specified.

As an example, consider:

23
Chapter 1

[Link]

This will use the http protocol to retrieve a file from the machine [Link] (which is
resolved to an IP address of [Link]). The Web server maps the identifier
sitebuilder/[Link] onto a local filename that is then returned to the originator of the
request.

The World Wide Web


Along with e-mail, the most popular and commonly used Internet service is the Web. Recapping from what
we discussed earlier, the Web architecture is based on a client/server model and uses a client-side Web
browser to retrieve data files (documents, graphics, etc.) from a Web server. This server may be located on
our own local network or half way around the world on the Internet's World Wide Web (WWW).

Important! Many people confuse the terms WWW and Internet or consider the two as
equivalent, but in fact they are very distinct. It is important to recognize that the Web is
not a network but an application that operates over networks using TCP/IP protocols.

In our earlier discussions we mentioned HTTP and HTML – we shall now investigate these further.

Hyper Text Transfer Protocol (HTTP)


To retrieve a Web resource, the user either specifies a URL in the Web browser's address field or clicks on
a hyperlink in a document that has a URL associated with it. As we have already seen, the URL determines
how to access the Web resource by specifying a protocol, server address and the local name.

The Web browser specifies the details of the required document in an HTTP Request message. The Web
server receives this request and after processing it completes the operation by either returning the document
or an error in the HTTP Response message. If the operation is successful, the Web browser will determine
if there are any other embedded resources within the document, such as images, and if so fires off further
requests for the additional information required for completing the page rendering.

24
Web Fundamentals

HyperText Markup Language (HTML)


HyperText Markup Language (HTML) is a page description language for defining the content of hypertext
documents that are displayed in a format established by the Web browsers rendering scheme. HTML files
are typically suffixed with either .htm or .html.

An HTML document contains a series of tags and text that define the structure and content of the
document. A tag is a reserved keyword that is delimited by the < and > characters. Some tags (but not all)
can appear in both start and end formats with the latter proceeded by a forward slash e.g. <I> and </I> to
start and end italic formatting.

Some tags also include attributes that further qualify the meaning – for example:

<font face = "Times New Roman">

is used to specify the typeface of the subsequent text.

Several elements should always be included in HTML documents and this is illustrated in the following
basic HTML document skeleton:

<HTML>
<HEAD>
<TITLE>
Document Title
</TITLE>
</HEAD>
<BODY>
Document content
</BODY>
</HTML>

When the Web was first established the HTML documents that traveled the Internet originated from
research and academic circles. Such documents were typically textual and could be nicely formatted using a
minimal number of tags. Then graphic designers got involved and they cared more about visual effects,
compelling images and fancy fonts than document content.

25
Chapter 1

This led to the evolution of aesthetic tags and one company, Netscape, led the way with a number of their
own tags. Unfortunately, this proprietary approach meant that the original concept of platform
independence for HTML across all browsers was lost. The life of a Web Designer became much more
complex as they now had to think about the impact of using such tags. This meant considering the
commercial risks of potentially restricting their user base, or the designers could generate more complex
pages which contain simpler formatting instructions should a browser not support a particular tag.

These screen dumps show a


more comprehensive
example of some HTML.
They demonstrate an HTML
Editor from a Web
management and authoring
system called Microsoft
FrontPage. The tabs at the
base of the screen allow the
page author to switch
between editing the page
and previewing what it
would look like when
rendered by a Web browser.

26
Web Fundamentals

First Generation Web Applications


The first generation Web browsers were only capable of handling text and simple multimedia such as
images and sound. Information from a user could be captured by means of simple HTML forms and
transmitted to the Web server. These early Web pages are now often called static pages since they lack the
facilities for user interaction that we are accustomed to from typical PC software.

27
Chapter 1

The problem with static pages is that their contents is fixed, and so can not be adjusted depending on the
identity of the user or from information stored in backend databases and applications. The solution to this
was to extend the functionality of Web servers by means of the Common Gateway Interface (CGI). This
enabled the contents of a page to be generated dynamically by a program typically written in the C
programming language or a scripting language such as Perl.

With CGI, the Web page contents could be dynamically generated and personalized for the user and
constructed from information stored centrally. But unfortunately, CGI applications are a poor solution for
this activity – this is because each CGI HTTP request will cause a new process to be spawned, and after the
request has been handled, the process is killed. In a heavily hit site, the repetition of process creations and
database openings imposes an excessive overhead on system resources.

Another disadvantage of CGI is that HTML tags have to be hard coded into C printf statements and it is
usually difficult to visualize the Web page until the CGI process is actually invoked and the results are
displayed in a browser. This does not provide an optimum development process and compares poorly with
some of the latest tools that do provide a WYSIWYG Web development environment.

Next Generation Web Applications


The next generation of Web applications addressed these limitations by providing facilities for active pages
that enabled user interaction and an architecture designed for high performance, secure, robust and
scaleable distributed computing solutions.

Client-side: Dynamic HTML/Scripting/Components


The latest generation of Web browsers – such as Microsoft Internet Explorer 4.0 / 5.0 – have provided a
great improvement over their early counterparts through their support for downloaded software
components, scripting languages and advanced HTML capabilities.

Software components embedded within Web pages can be written using high level languages such as Visual
Basic, Visual C++ and Java. This enables sophisticated functionality unavailable with the relatively
primitive HTML. Furthermore, such components can establish direct TCP/IP connections with other
distributed components (i.e. the business logic tier) and avoid using the Web server – thus enabling a true
distributed computing environment.

28
Web Fundamentals

Scripting languages can be included within a Web page, and act as the software glue to allow the different
entities within a Web page to interact. Such items include the HTML intrinsic controls (such as edit boxes
and lists), the objects exposed by the Web browser and any embedded software components.

The use of script logic in our pages allows the client to become event-driven. As an example, script code
can be used to detect an event being fired by one control (a button click) and this can then invoke a method
on another control (such as starting the playback of a video control). The most commonly used scripting
languages for the Web are VBScript (a subset of Visual Basic) and JavaScript.

Previously, once an HTML page had been rendered on the screen its contents could only be changed if a
request was made to the Web server for a page refresh. This process could take at best a few seconds and so
severely impairing the users interactivity. The latest Web browsers now support a new generation of HTML
called Dynamic HTML (DHTML) that allows all of the HTML elements on a Web page to be manipulated
using script logic. Now changes to a Web page can be made, on the fly, without any need for time and
network consuming HTTP communication.

At the time of writing, Internet Explorer is the only browser that supports VBScript
and embedded software components written in Visual Basic and Visual C++. Thus
these technologies are only suitable for Intranets and Extranets where you can
impose restrictions over the type of browser that may access your Web pages. If you
need to reach the maximum audience possible on the Internet, then you must avoid
any scripting and software components in your Web pages. A frequent compromise
is to restrict access to just Internet Explorer (3.0 or later) or Netscape Navigator
(3.0 or later) as the vast majority of Internet users employ these browsers.
JavaScript and Java is the common denominator across all of these browsers.

Alternative mechanisms for developing server extensions were created which addressed the performance
pitfalls of using the traditional CGI processes. For example, several Web servers – including Microsoft
Internet Information Server (IIS) – support the Internet Server Application Programming Interface
(ISAPI). This enables the programmable logic to be compiled into Dynamic Link libraries and reside within
the Web server's process space – such logic can be loaded, once and for all, on first demand. ISAPI is much
more efficient than CGI because client requests do not spawn new processes.

29
Chapter 1

ISAPI programs are typically written using Visual C++. Fortunately for many, there is an easier method to
extend Web applications but still gain from the benefits that ISAPI offers – this simplicity comes from
Microsoft Active Server Pages (ASP). To use ASP, however, you must run these pages on Microsoft
Internet Information Server, or its scaled down Windows 98 implementation, Personal Web Server.

ASP builds on top of the ISAPI infrastructure to provide a server-side application framework.

An Active Server Page is a file with a .ASP suffix that contains both HTML syntax and server-side script
logic. When the Web server receives an HTTP request for the ASP document, an output HTML file is
generated for the response using a combination of both the HTML static information plus any HTML that is
generated dynamically by the server-side script logic. Several scripting languages are available for use in
ASP applications but the one most commonly used (including throughout this book) is VBScript.

The real power of ASP comes from its ability to very easily interact with other objects (such as the built-in
utility ASP objects, multi-tier client/server business objects, middleware to access databases and legacy
systems, Microsoft BackOffice components, etc.).

30
Web Fundamentals

It is crucial that you do not get confused between Dynamic HTML (DHTML) and
dynamically generated Web pages. DHTML is the feature that enables every HTML
element in a web page to be programmatically controlled using client-side script
logic.

Dynamically generated web pages are those that are programmatically created, on
the fly, at the Web server (typically by means of ASP / ISAPI / CGI and by using
information about the user and/or interfacing with server-side components,
databases, etc.)

Summary
That concludes our discussion on Web fundamentals and the subsequent topics will assume that you are
now familiar with the following basic concepts:

 Web technologies are built on a standard communications protocol called TCP/IP.


 The WWW (an application) and Internet (a network) are not interchangeable terms.
 HTTP is an application protocol that operates above the TCP/IP stack and is used to retrieve Web
resources.
 An Intranet is an implementation of Web technologies operating over a TCP/IP network that is restricted
to employees only. An Extranet is where a corporate TCP/IP network has been opened up to allow
access by business partners to specific areas of an internal Web site.
 Every computer on the TCP/IP network is uniquely identified by an IP address.
 Network server applications are assigned to operate on a specific well-known port number.
 Every Web resource is uniquely identified by its URL.
 HTML is a page description language for defining the content of hypertext documents.

31
Chapter 1

 Microsoft's Web browser is Internet Explorer and it provides support for downloaded software
components, scripting languages and advanced HTML capabilities.
 VB software components and VBScript are only suitable for use in Internet Explorer
 Microsoft's Web server is Internet Information Server and this can support sophisticated multi-tier Web
applications that are built using Active Server Pages.

Now that we can appreciate why the Web paradigm is increasingly important, we shall start to look at how
the Microsoft Windows DNA infrastructure can deliver the flexible digital nervous system that business
now demands.

32
Web Fundamentals

33
Chapter 1

34
Windows DNA - a framework for
building applications
During the opening discussion to this chapter, we introduced Microsoft's architectural framework called the
Windows Distributed interNet Applications Architecture (Windows DNA). One of the main objectives of
Windows DNA is to synthesize the differences between developing software for the Windows platform and
for the Internet, and to provide a development model that capitalizes on the best features from each
approach to provide a unified solution.

Some of the key features to this new development model are:

 Windows DNA integrates these two different worlds by enabling computers to interoperate and co-
operate equally well across both private and public networks using protocols that conform to open
industry standards.
 Windows DNA applications are designed around a loosely coupled distributed architecture. This
involves breaking the solution into the following distinct layers: presentation logic, business logic and
data access logic. These layers are then deployed in an optimum manner across multiple tiers.
 Windows DNA provides a set of standard services to handle components, communications, scripting,
user interface (DHTML), transactions, message queuing, security, directory services, data access,
systems management and high availability. By providing these core features 'out of the box', developers
can concentrate on their application rather than basic infrastructure and so can bring innovative solutions
to market quicker and at a lower cost.
 Windows DNA applications can take advantage of an efficient just-in-time software delivery model;
this allows central management to reduce the overall cost of ownership and ensures that the users are
always running the latest version of the software. For example, Office 2000 can be set up centrally so
that it will install itself on a desktop by deploying only the appropriate components for the profile of the
user. If another person (with a different profile) then uses the same desktop, Office will then
automatically deploy (if necessary) any additional components that they are entitled to. Also, if a
component gets updated or accidentally deleted, this will be automatically detected and will re-deploy
that component.
Chapter 2

 Windows DNA fully embraces an open approach to Internet computing, and supports numerous
standards approved by bodies such as the World Wide Web Consortium (W3C) and the Internet
Engineering Task Force (IETF).
 Windows DNA provides for mobile computing; when such applications are operating disconnected from
the network and central systems, they should still provide as much functionality as possible but degrade
gracefully where this is not possible.
 Windows DNA will continue to evolve and take advantage of many new technologies, however it will
always ensure that existing investments in skills, systems and information will be preserved.

It is the intention of Microsoft to deliver the different parts of Windows DNA over a number of years with
many of the key features being supplied as part of Windows 2000 (previously NT5.0). However, as we shall
see throughout this book, many of the features of Windows DNA are available today on Windows NT 4.0
when enhanced with the Windows NT 4.0 Option Pack and the Visual Studio 6.0 development environment.

In this chapter we shall investigate the key components and development methodologies provided by the
Windows DNA superstructure. In particular we shall look at:

 the Windows DNA Server Platform provided by the Windows NT/2000 operating system plus a number
of application services
 the advantages of using software components and why this approach is fundamental when building
solutions with Microsoft products
 the Microsoft initiatives to provide easy access to data irrespective of its format or the location where it
resides
 how to ensure the integrity of our data by means of transactions
 how to protect our systems by employing security measures

So let's start by putting Windows NT under the microscope.

The Windows DNA Server Platform


Bill Gates first conceived Windows NT in 1988 when he announced that Microsoft would develop an
operating system that was portable, secure, scalable, extensible, open, and internationalizable. These goals
meant that Windows NT could be converted to run on a number of different hardware platforms and operate
in a number of languages and character sets, all with minimal changes to the core code. In addition, it could
provide support for symmetric multiprocessing (SMP), that is run on machines with multiple CPUs.

To design Windows NT, Microsoft hired the much-regarded David Cutler who had worked on a number of
operating systems, including the PDP-11 and VAX, at Digital Equipment Corporation. The ideal operating
system initially dreamt by Bill Gates and David Cutler was code-named Cairo. The full objectives have
proven to be very difficult and tormenting to achieve and the ideas of Cairo have recently changed from
being an actual product release to just a philosophy.

36
Windows DNA - a framework for building applications

After five years of development, Windows NT was released; it was delivered in two versions NT 3.1 and
NT Advanced Server 3.1. The 3.1 tag indicates that the roots of its user interface were from Windows 3.1;
but that is where the similarities stopped.

In late 1994, Microsoft clarified the roles of the two versions by changing their names to give a clear
indication of their purpose. Windows NT became Windows NT Workstation 3.51 and Windows NT Server
3.51. Whilst being based on the same core code, the internal scheduling of tasks was optimized so that one
functions best as a desktop operating system and the other as a robust enterprise level multi-purpose
network operating system.

In 1996, NT version 4.0 (Workstation and Server) was released and included many new features; in
addition, it adopted the user interface from Windows 95.

Windows 2000 will be Microsoft's next step towards Cairo and will bring many advantages in the areas of
system management, application infrastructure, networking and communications, and information sharing
and publishing. Windows 2000 will be available in the following versions:

 Windows 2000 Professional will be the mainstream operating system for the business desktop
 Windows 2000 Server will to be the mainstream network operating system designed for small to
medium enterprise application deployments, it will support up to two-way symmetric multi-processing.
 Windows 2000 Advanced Server will be a more powerful application server designed for database-
intensive work and will include integrated clustering and load balancing services, it will support up to
four-way symmetric multi-processing and large physical memories.
 Windows 2000 Datacenter Server will be the most powerful server operating system optimized for
large scale data warehouses, online transaction processing and complex simulations, it will support up to
16-way symmetric multi-processing and up to 64GB of physical memory.

Windows DNA Application Services


Microsoft has made available a number of products and components that work together with Windows NT
to form a single coherent infrastructure that delivers a comprehensive business solution. Furthermore, the
familiar and consistent approach found throughout these products considerably reduces training and support
costs.

The products include:


 Internet Information Server (IIS) – provides Internet services including Web (HTTP), File Transfer
(FTP), News Groups (NNTP) and Email (SMTP). It is designed for ease of use, scalability, portability,
security, and extensibility, and it provides a powerful environment for the next generation of line-of-
business applications.
 Active Server Pages (ASP) – provides a server side scripting mechanism to implement extensions to the
IIS Web services.
 Transaction Server (MTS) – provides the infrastructure needed for multi-tier client server solutions. It
includes facilities to share resources, manage transactions and administrate component deployment.
 Message Queue Server (MSMQ) – provides store and forward asynchronous communications to
achieve reliable message delivery. It handles network outages and heterogeneous networking
architectures.

37
Chapter 2

 Index Server – provides search engine facilities to identify documents that contain specific text.
 Exchange Server - provides an integrated system for email, personal and group scheduling, electronic
forms, and groupware applications.
 SQL Server - provides a large-scale relational database management system designed specifically for
distributed client-server computing. There is also a 'light' version known as MSDE (Microsoft Data
Engine) that is suitable for a maximum of 5 simultaneous connections.
 Systems Management Server (SMS) - provides a centralized management tool for software
distribution, hardware/software inventory and diagnostic facilities.
 SNA Server - provides facilities for interfacing with legacy IBM and other host systems using SNA
communication protocols.
 Proxy Server - provides Internet access to the corporate desktop in a secure manner. It also enables the
caching of popular Web pages to improve performance
 Commercial Internet System - Provides facilities for Internet communities. It includes servers for
membership, personalization, billing, white pages, chat, mail, newsgroups, user locator, content
replication, and information retrieval.
 Site Server - provides a Web site environment for the deployment, implementation and analysis of
Intranets and business critical Web sites. There is also a Commerce Edition suitable for electronic
commerce sites.
 NetShow Server - provides streaming media services for Video and Audio broadcasting (called
netcasting).
 Cluster Server - provides clustering facilities allowing multiple NT nodes to combine to provide high
availability and scalability.
 Terminal Server - provides Windows applications to diverse desktop hardware through terminal
emulation.
 Certificate Server - provides facilities for the generation and distribution of digital certificates (which
we shall meet later in this chapter when we discuss security).

At the heart of Windows NT and the above products is the Microsoft Component Object Model (COM),
which is the glue that binds together the different parts of Windows DNA. COM is the most widely used
component software model in the computer industry and is used on over 150 million computer systems
throughout the world. The use of COM makes the development of complex applications and systems
integration tasks much simpler than any other alternative approach.

We shall now discuss why component software provides the most cost effective development approach and
investigate the COM technologies in a bit more depth.

38
Windows DNA - a framework for building applications

Software Components
Reaffirming our earlier discussions, exploiting information technology for business advantage has become
critical for companies to lower the cost of doing business and obtaining competitive advantage. However,
the software industry in its early years had become renowned for failing to deliver many projects on time or
to budget. Furthermore, organizations were finding this new generation of advanced software costly to
support and difficult to enhance. Such code was often poorly designed and written in an unstructured
fashion with different bits of logic intertwined. This made it difficult to understand and very risky to
change; even what might appear to be a minor amendment could easily and unknowingly cause severe
repercussions throughout the system.

IT managers recognized that new software techniques were required to overcome the problems of
complexity, increase the production rate of robust software, and re-use existing proven code. One powerful
technique that delivers this goal is component based software and this is fundamental when building
solutions with Microsoft products.

Component based software is a development process that emulates the construction processes used by many
more established industries. For example, the majority of today's car manufacturers build vehicles from
hundreds of components parts supplied from a large number of external companies. Each individual part
would have been designed, manufactured and passed through quality checks as a separate isolated process
undertaken by the part supplier. By delegating responsibility for many of these low level complexities, a car
manufacturer can concentrate on their core business – that is designing and building cars that are more
reliable and brought to market quickly due to a short development cycle … the exact goal that every
software company wants to achieve.

The software industry can now build systems in a similar manner by selecting a number of best of breed
software components. These components can then be glued together, using a software technology like
COM, to allow them to co-operate together to form a single integrated solution. The system designers and
integration team must have confidence that the functionality of the component behaves as published but
they do not need to worry about the complexities of the internal processing logic.

For many items of functionality, we can purchase 'off-the-shelf' software components from one the
numerous software vendors that specialize in the market of reusable components. Alternatively, if our
requirements are unique, then we can develop our own components using a suitable development tool such
as Visual Basic. In fact, this will be one of the major themes throughout this book.

Component Object Model


The Component Object Model (COM) is software technology that allows applications to be built from
binary software components. It provides a comprehensive framework that allows software components to be
plugged together to co-operate even if they have been written by different vendors, at different times using
different tools / languages and, if the objects are located in the same process, same machine or distributed
over multiple machines. Put simply, COM provides the 'software plumbing' between software objects and
insulates the component developer from such complexities

39
Chapter 2

The original specification of COM always allowed for co-operating objects to be located on different
machines but this was not implemented until Windows NT 4.0 and was then called Distributed COM
(DCOM). Because of this, in reality DCOM and COM are now the same animals. DCOM is layered on top
of the DCE (Distributed Computing Environment) RPC (Remote Procedure Call) specifications.

The following diagram shows how objects use COM/DCOM to co-operate even across process and machine
boundaries.

Whilst COM was not originally a committee-driven standard, it has since become an open market-driven
technology that is now fully published from the lowest level communications protocols to the highest-level
API functions. In addition, Microsoft has donated ownership of the technology's specifications to an open
industry association working under the auspices of The Open Group – to promote the common adoption of
these core technologies.

COM is now ubiquitous and available on a number of platforms including the following:

IBM MVS, IBM OS/400, IBM AIX, Siemens Nixdorf, HP/UX, Linux 2.0 (Intel), Sun Solaris, SCO
UnixWare, Compaq / Digital Unix, Compaq Digital Open VMS,

For more information, check out:

Solaris –
[Link]

Compaq/Digital –
[Link]
[Link]

Software AG -
[Link]

40
Windows DNA - a framework for building applications

ActiveX
When Microsoft released their first set of Internet tools in March 1996, they announced ActiveX
technology – which in all truth was just a catchy new name devised by the Microsoft marketing machine for
specific parts of their existing COM technology. ActiveX has to be one of the most misunderstood and
naively used expressions in the Internet technology arena. Many people get confused about ActiveX
because it does not mean just one thing. More precisely, ActiveX encompasses an ever-growing series of
technologies, each of which defines the interfaces between the software components to implement some
particular functionality. For the Internet and Windows DNA, examples include:

 ActiveX Scripting – enables script logic to be included in the downloaded Web page or used on the
server to generate the page content
 ActiveX Controls – enable client components to be incorporated within a web page and dynamically
downloaded as needed
 ActiveX Documents– enable the browser to support non HTML documents (such as Microsoft Office
documents)
 ActiveX Data Objects – enable an easy and flexible mechanism to get at data that can be located in a
number of different types of data stores
 ActiveX Server Components – enable the IIS Web Server to interface to other server software
components

To most Internet users, the ActiveX technologies work seamlessly and transparently, and they just
experience the effects of these rich technologies; it is irrelevant to them whether it is ActiveX or "voodoo
magic" that is operating under the covers. However, to the Web application developer ActiveX provides an
unrivalled set of tools for creating dynamic Web solutions that releases the full potential of Microsoft's
powerful Web platform.

Important! Currently, the only Web browser to natively support ActiveX


technologies is Internet Explorer (v3.0 onwards). If you use these technologies on
the Web then you may be severely restricting the number of visitors to your site. In
Intranet and Extranet solutions – where you can impose restrictions on the Web
browser – this is not such a problem. Using ActiveX technologies on the server is
perfectly acceptable in all cases because ASP can send standard platform
independent HTML to the client.

Software Component Characteristics


A software component can be defined as a combination of data and code that may act on that data, which
together can be considered as a single unit. An object, of which there may be many, is a created instance of
a software component.

41
Chapter 2

The data and code associated to the component defines everything that the component represents (state) and
what it can do (behavior). These characteristics are specified by the software component's definition; this
can comprise of:

 Properties – these are the attributes of the object that are available for access, update or both from an
external client that is using the object
 Methods – these are functions that can be invoked from an external client that is using the object,
sometimes methods will take arguments
 Events – these are signals which are fired when a specific action or interesting state occurs; these signals
are detected and acted upon by the external client

A software component may expose many properties and methods. Properties and methods that operate
together to perform a specific task are often grouped together and referred to as an object's ingoing
interface. Events that occur are grouped in an object's outgoing interface. A software component will
frequently support more than one interface and each interface is given a name, which by convention will
normally begin with a 'I' character; for example, IUnknown.

To help clarify this, lets look at a 'real world' example of a component that controls a Car.

Cars are very complex machines and so different interfaces are likely to be implemented to handle each of
the different parts … lets consider just one of its possible interfaces. The interface to handle the car's fuel
might be called IFuelTank.

IFuelTank would have a series of methods, properties and events; examples might include:

Properties: FuelLevel Amount of fuel in fuel tank

Method: FillTank Add fuel until tank is full

Events: TankFull Fired when the FuelLevel is at a maximum


TankLow Fired when FuelLevel reaches below 10% of maximum.
TankEmpty Fired when FuelLevel reaches zero

Some interfaces are standard and are published by software vendors; for example, Microsoft's ActiveX
specifications define many standard interfaces. Published interfaces cannot be changed. If software
developers write their software to conform to standard interfaces, then their software can communicate and
cooperate with other software conforming to such interfaces if required.

Universal Data Access


Reiterating again the message from our earlier discussions, a principal aim from Microsoft's early days has
been to put "Information at Your Fingertips" and enable businesses to exploit their data in order to gain
maximum business advantage. As a result, demands were put on the Microsoft designers and developers to
provide Windows DNA with a leading set of data access technologies and we shall now discuss how they
have reacted to this challenge with a strategy known as Universal Data Access (UDA). This is a Windows
DNA initiative to deliver both standards and software technologies for data access.

42
Windows DNA - a framework for building applications

In the past, data access mechanisms (such as ODBC - Microsoft's first open data access technology) have
assumed that the data is stored in structured relational databases. However, businesses today also store their
information in a number of other different data stores including office suite documents (Word, Excel, etc.),
text files, multimedia files (video, audio, graphics), email systems, directory services, project management
tools and so on. We can now start to see why the word 'Universal' in UDA was chosen.

Some major database vendors now supply "universal databases" that provide some support for data in non-
traditional formats such as those listed above. However this approach forces the data to be migrated into
their database engine and, as a result, can be expensive and not practical when the data is normally
distributed in a complex fashion across a large corporate enterprise.

The alternative strategy used by Microsoft UDA is to provide simple, consistent and highly efficient
mechanisms for accessing data irrespective of its format or the location where it resides, and without any
need for the data to be transformed or duplicated.

OLEDB & Active Data Objects


As part of the UDA solution, Microsoft has provided two software layers referred to as OLEDB and Active
Data Objects (ADO). Naturally, both of these layers expose COM interfaces and so they can easily be
plugged into our own applications as shown below.

From this diagram we can see that we can access data using either OLEDB or ADO.

OLEDB is designed to be the COM compliant successor to ODBC but in addition also addresses the need to
support data stored in non-relational data stores. However, also notice that OLEDB can sit above ODBC
and so may seamlessly be used with all of the numerous databases that are already ODBC compliant. With
time, most database vendors will support OLEDB natively as the direct approach will be more efficient.

43
Chapter 2

ADO works at a higher level than OLEDB and avoids many of the complexities that a programmer working
at the OLEDB needs to consider. In particular, it provides support for ActiveX clients, like the ActiveX
Scripting engine, making it ideal for use in ASP. ADO provides a simpler object model and enables data
access code to be developed with minimal effort. It is designed to be the only interface that most
programmers will need to understand to access data.

The database examples in this book will be using the simple ADO rather than OLEDB.

Some readers may be familiar with the older RDO and DAO data access
mechanisms, and indeed these do have similarities with ADO. However, it is
Microsoft's intention that ADO will eventually replace both RDO and DAO.

ADO also provides some useful features when working with Web architectures in which there may be no
permanent or error free connection between the client and the server. It includes support for a facility called
the Remote Data Service (RDS) in which the data may be disconnected and stored or manipulated on the
client; any changes to the data can then be reapplied to the server at a later time.

OLEDB, ADO, RDS and ODBC are collectively known as the Microsoft Data Access Components
(MDAC) and at the time of writing, the current version was MDAC v2.1. The latest version for download
and its associated information can be obtained from: [Link]

For business critical systems, an organization must be able to rely on its data and protect it from operating
failures. Data integrity relies on software services that prevent files and data stores from being left in a
corrupted state should system, network or application failures occur. We shall now discuss how Windows
DNA addresses this by means of transactions.

Transactions
A transaction is a group of independent actions that when considered as a whole, form a 'single item of
work'. When working with databases, it is important that a transaction has the following properties:

 Atomicity – all updates to a database under a transaction must be either committed or get rolled back to
their previous state
 Consistency – ensures that the database is updated in the correct manner
 Isolation – uncommitted transactional results are not seen by other pending transactions
 Durability – once a transaction is committed, it will persist even if failures occur

These properties are often referred to by the acronym ACID.

The use of transactions with older two-tier client / server architectures is simple to implement. Database
updates that are processed within a transaction must be bound by calls to functions with the database engine
– typically these are called Begin Transaction and Commit Transaction. If a failure of any sort is
programmatically detected, the database can be reverted to its original state by another called – typically
Rollback Transaction or Abort Transaction. If a system crash occurs, pending transactions can be
identified and the integrity of the database recovered, when the system restarts.

44
Windows DNA - a framework for building applications

With the demands of Internet and distributed computing, life gets more complex as we need to be able to
co-ordinate transactions over multi-tier architectures with multiple data sources (including relational
databases, legacy systems and message queuing systems). The implementation of a distributed transactional
system can be very complicated without some assistance.

A generic solution to this problem is software known as a transaction processing monitor (TPM). With
such systems, the client's request for business logic processing is sent to the TPM, which is then responsible
for routing the request to the appropriate service and ensuring the correct fulfillment of the operation, in
other words, ensuring the transaction's ACID. Additional features provided by such solutions include load
balancing / dynamic configuration, central resource monitoring and security.

As we might expect, Windows DNA provides exactly this kind of service, and, by means of Microsoft
Transaction Server,provides us with the infrastructure needed to address these requirements.

Microsoft Transaction Server


Microsoft Transaction Server (MTS) is a transaction processing environment that is designed for the
management of distributed component based applications. It provides an easy to use programming model
that extends COM and simplifies the development of secure, robust, scaleable, and high performance
solutions.

The functionality within MTS addresses many of the complex issues that previously developers had to
consider themselves when building multi-tier computing architectures. It manages automatically all
threading issues, object pooling, the sharing of resources, security access controls and the handling of
transaction context across objects. This all means that developers can concentrate totally on their own
business logic as the underlying plumbing and infrastructure is handled for them.

45
Chapter 2

Performance and Scalability


With standard COM, a created object will exist until either the client deletes the object or the client
processing it is terminated. This can obviously result in a heavily used server-centric application needing a
large number of components to be created, putting an excessive drain on precious systems resources.

To improve performance and scalability, MTS provides what is known as 'just in time' activation and 'as
soon as possible' deactivation. This feature enables clients to hold on to references to objects but the
objects become 'deactivated' for the period of time when their services are not required. When a client
needs the services of an object, MTS will try to assign one from its pool of deactivated objects (if available)
before resorting to the instantiation of a new object (if none available). This increases performance and
scalability because:

 Only a few objects need to be instantiated since they can be shared over many clients thus reducing the
demand on system resources.
 Objects can be initialized and waiting on standby, enabling them to react immediately to any client
request.

It is well known that establishing database connections is a notoriously expensive operation and in large
systems can result in unacceptable performance levels. Another advantage of MTS is that it provides
resource dispensers to recycle valuable system resources in a similar fashion to the way it recycles objects.

For example, an ODBC resource dispenser is available which recycles database connections. When an
ODBC database connection is no longer required, MTS just deactivates the connection rather than closing
it. When a component requires an ODBC database connection, MTS will first try to assign a connection that
it has in its pool of deactivated connections. A new ODBC database connection is only established if the
pool of available connections is empty.

Distributed Transaction Coordinator


When MTS is installed, another service called the Distributed Transaction Co-ordinator (DTC) is also
installed and configured to start up when the system is booted. DTC is responsible for managing the
transactions across networks and works by co-operating with the database's resource manager –the part of
the database that is responsible for ensuring the integrity of the database.

DTC monitors any MTS Components that are configured to support transactions. If any such component
reports a failure to MTS, then the DTC will automatically handle the database rollback. With a single
component operating on a single database this would be a simple task for us to program. However, MTS
and DTC really come into their own when a transaction involves multiple components operating in a multi-
tier distributed environment and spanning multiple databases.

46
Windows DNA - a framework for building applications

Consider the following example where a 'transfer' transaction consists of crediting one account and debiting
another. We must ensure that either both database transactions occur, or no database transactions occur –
otherwise money will have been created or lost.

47
Chapter 2

Message Queuing
One of the downsides of building business critical distributed systems that operate over the Internet or
WANs is that these networks are notoriously unreliable. For many applications, it is often sufficient for
messages to be sent asynchronously –an acknowledgement is not required in real time. Windows DNA
offers a facility called Microsoft Message Queue Server (MSMQ) to enable an efficient and reliable store
and forward asynchronous communications mechanism.

It is not surprising to learn that MSMQ is tightly integrated with MTS. Any call to MSMQ can be part of
any active transaction.

If within a transaction, a message is transmitted via MSMQ, it will first be safely stored in queue. If the
transaction completes successfully, the message will be sent. However, if the transaction is aborted, then
the rollback will remove the message from the queue – a receiver will never get a message that is sent
within an aborted transaction.

If within a transaction, a message is received via MSMQ, it will be removed from the queue. If the
transaction is aborted, then the rollback will ensure that the message still remains in the queue and so is not
lost.

For more information on MTS and MSMQ, check out Professional MTS/MSMQ, ISBN 1-
861001-46-0, from Wrox Press. Details of the objects, methods, and properties relating to
these technologies are available in the appendices at the end of this book.

Security
Security is an important concern with Windows DNA applications, and in particular those that involve the
public Internet. Scare stories of break-ins at high profile Internet sites, attacks on vital Internet services,
impersonation of important organizations, invasion of personal privacy and tales of electronic commerce
fraud makes attractive headlines and so frequently appear the computer industry press. From this it is not
surprising that one of the biggest concerns that businesses have about using the latest networking
technologies is for the security of their systems.

48
Windows DNA - a framework for building applications

Good security is achieved by the creation of sound policies, the employment of appropriate security
technologies, the consistent monitoring of all practices and a general awareness of trends in the security
arena. Fortunately most of the scare stories could have been avoided if the organizations involved had
understood fully the security practices and software technology that is available

When Microsoft developed their vision of Windows NT for the enterprise, their intention was that security
should be treated as paramount – so security features were designed into the foundations of the operating
system. This enables any organization to layer its security options in an appropriate combination, which is
specifically suited to combat the perceived risk of that organization. All Microsoft products and operating
system extensions that form part of the Windows DNA vision (such as COM, MTS, IIS, BackOffice, and so
on), are tightly integrated with Windows NT security and share the same security features and
administration tools.

Strong levels of security were built into the core of Windows NT in order to meet and exceed a certifiable
security standard, the C2 security guidelines required by the U.S. Department of Defense's security
evaluation criteria. Compliance with the C2 security standard was originally only required for government
organizations, but many commercial organizations have demanding corporate security needs and recognize
the value of the enhanced security that such systems offer.

Internet Security
The Internet Security Framework (ISF) is a white paper that was published by Microsoft towards the end
of 1996 and it explained their strategy to support a set of security technologies designed for online
communications and electronic business. Since this document was released, Microsoft has delivered
extensive security architecture for the Windows DNA based on industry standards. It includes certificate
services, secure communication channels, payment protocols and cryptographic support.

Internet Information Server Access Controls


The IIS Web service facilities are built upon the Windows NT security model. This means that all files and
directories that may be accessed over the Web are protected by Windows NT file permissions. All users
accessing the Web service are either given guest access or are authenticated against the Windows NT
security database, and then given appropriate access to the various objects.

When IIS is installed, it creates an anonymous user account called IUSR_sysname where sysname is the
computer name of the Windows NT system. Normally a user will access a Web site anonymously, and in
this case will operate under the security context of the IUSR_sysname account. This means that access is
restricted to those Web resources with the file permissions allocated to the IUSR_sysname account.

If the user requests a resource for which the IUSR_sysname user account does not have the appropriate
permissions, then IIS will deny the request and inform the originator what authentication methods it
supports. The server can then request the user's credentials – logon name and password – and then submit
this information in another request for the Web resource. The user information is then authenticated against
the Windows NT security database and provided that the user has been granted suitable permissions to
access the resource, the resource will be returned; otherwise the request is again denied.

49
Chapter 2

IIS supports two authentication methods; these are the Basic Authentication and the Windows NT
Challenge/Response mechanism. The main difference between Basic Authentication and Windows NT
Challenge/Response is that the latter does not send the password information across the network.
Currently Internet Explorer is the only Web browser to support Windows NT Challenge/Response.

Another possible use for Internet Explorer's Windows NT Challenge/Response capabilities is within an
Intranet environment and where a user has already logged on to a Windows domain.

When IIS denies an anonymous request and Windows NT Challenge/Response authentication is


enabled, IE will first attempt to use the user's domain credentials in the authentication process. Only if this
fails will the user be prompted for their credentials. This will happen automatically and transparently to the
user thus improving their user experience and providing seamless integration with the existing
infrastructure.

Secure Channels
The IIS Web service supports a security technology called secure channels, which provides a point to point
network connection that enables the following features:

 Authentication – one end point of an established communications session can request information to
identify the other end point.
 Non-repudiation – a message sender cannot falsely claim that they did not send the message.
 Privacy – messages in transit are encrypted; so the contents cannot be inspected if intercepted
 Integrity – messages in transit cannot be tampered with; otherwise protocol violation will occur

The secure channels technology encompasses a number of industry standard security protocols; the one that
is most commonly supported by most Web browsers is Secure Socket Layer (SSL 2.0 / SSL 3.0).

Digital certificates
Secure channels rely on another security technology that is called digital certificates. A digital certificate
contains the details of an individual or an organization in a format that is defined by a standard called
X.509 version 3. Digital certificates may be exchanged when a secured channel is established and this
allows each party to determine the identity of the other.

But what is there to stop anybody from creating a false certificate, and pretending that they are someone
else? The solution to this problem is Certificate Authorities (CAs), who are responsible for the issuing of
digital certificates. A CA is a commonly known trusted third party, responsible for verifying both the
contents and ownership of a certificate. Examples of Certificate Authorities include VeriSign, Thawte, GTE
and Entrust.

With Microsoft Certificate Server we can become the Certificate Authority and manage the generation and
distribution of digital certificates for our own communities of users, such as our customer base (Internet),
business partners (Extranets) and employees (Intranets).

50
Windows DNA - a framework for building applications

Authenticode
Now that the Web has become 'Active', executable logic can be automatically delivered to our desktop in a
variety of different forms such as browser scripts, ActiveX controls, Java applets, batch files, macros
attached to documents from office suite products and normal .EXE executables. Because this logic can
originate from an unknown source, there is obviously the scope for something really malicious to be
downloaded and cause irrevocable damage.

When we purchase software in the high street – such as the Microsoft Flight Simulator – we have
confidence that the product is safe to install on our machines for two reasons. Firstly it has been developed
by a software vendor that we trust and secondly, it is shrink-wrapped and so we believe that it has not been
tampered with since leaving Microsoft's manufacturing site. Similarly, for the downloadable Web
executable logic we need similar protection using. accountability and electronic shrink-wrapping.

The solution from Microsoft is Authenticode, which enables users and software publishers to create a trust
relationship between themselves. By using Authenticode, a software publisher use a digital certificate to
sign their code when they make it available for downloaded.

When Internet Explorer downloads executable logic, it checks that the software has not been tampered with
and uses the digital signature to ascertain the originator of the code, which it then notifies to the user. The
user is then given the option of either accepting the code or canceling the operation. If the user does not
trust the origin of the code, then they should, without hesitation, reject the code.

51
Chapter 2

Summary
In this chapter we have investigated Windows DNA – the name that Microsoft is calling their framework
that addresses the convergence of personal computers and the Web / networking technologies. We have
seen how it provides complete support for the ActiveX and Internet standards that enables developers to
integrate HTML, scripting, components, and transactions to build powerful, scaleable and highly available
applications that can run over the Internet and across the corporate enterprise.

The key points to this chapter are:

 Windows DNA is Microsoft's architectural framework for developing software for the Windows
platform and for the Internet. It provides a development model that capitalizes on the best features from
each technology to provide a unified solution. It provides a set of core services that frees the developers
from the complexity of programming infrastructure and allows them to concentrate on delivering
business solutions.
 Developing component-based software overcomes many problems of today's complex systems; it
increases the production rate of robust software and enables the re-use existing proven code.
 The Microsoft Component Object Model (COM) is the most widely used component software model in
the computer industry and is fundamental in building Windows DNA solutions. ActiveX is a name given
to many technologies based on COM.
 The key building blocks to Windows DNA are:
− The core server platform – Windows NT 4 / 2000, plus various extensions such as
Windows NT 4.0 Option pack, BackOffice and so on
− Component based software using COM technologies to simplify systems integration and
aid software reuse
− Universal Data Access to enable information to flow by providing reliable and high
performance access to data irrespective of the type of data source
− The use of transactions to provide data integrity
− The application of security measures to ensure that a system can be trusted.

The final message from this chapter is that many people are claiming that the "Internet will change
everything", … well that's wrong, it already has! So let's not get left behind. We shall now move swiftly on
and see how we can exploit Visual Basic and the Web to their full extent, starting in the next chapter with a
look at how we can use Visual Basic as the 'enabler' to deliver our Windows DNA solutions.

52
Windows DNA - a framework for building applications

53
Chapter 2

54
An Overview of Building
Windows DNA Applications with
Visual Basic
Since the main focus of this book is on Visual Basic Web programming, it's time now to investigate how we
can use Visual Basic technologies to enable the integration of HTML, scripting, components, and
transactions to build powerful, scaleable and highly available applications that run across the Internet and
corporate enterprise. The latest release – Visual Basic 6.0 – fully addresses the new Web paradigm and
provides the most productive tools for building Windows DNA applications.

The nature of the Windows DNA platform means that there are a number of different techniques and
locations for deploying our Visual Basic developed logic. The different types of executable logic that we
shall be considering in this book are shown below:

 ActiveX Scripting – Visual Basic Script


 ActiveX Controls
 WebClasses
 Dynamic HTML Applications
 ActiveX Server Components
 ActiveX Documents
 Traditional Windows Clients

The locations for each of these technologies are shown in the diagram below, showing how some of the
items operate in the client-side, others operate on the server-side and one, VBScript, operates on both.
Chapter 3

In this chapter we shall consider each one of these topics in turn and discuss the role that Visual Basic has
to play. For each, we shall briefly consider a simple example that, although not particularly challenging,
will set the scene and give a flavor of what is possible.

ActiveX Scripting – Visual Basic Script


Earlier, when we discussed 'Next Generation Web applications' we saw that scripting languages can be used
on both the client-side (IE handling Web pages) and the server-side (IIS invoking Active Server Pages). In
both cases, scripting is used to act as the software glue that integrates software components and controls the
actions required when events firing are detected. Script logic is interpreted and there is no concept of
compiling the scripts.

Rather than develop specific script processing logic for both IE and ASP, Microsoft has used ActiveX
technologies to provide a generic and flexible framework for adding any scripting language to any
application. The ActiveX Scripting architecture allows script hosts (such as IE, ASP or our own
application) to invoke scripting services within script engines (such as VBScript, JavaScript or our own
scripting language). The ActiveX Scripting specifications define the COM interfaces that a script host and
script engine must support; thus the hosts and engines can be supplied from different software vendors that
conform to the specification.

56
An Overview of Building Windows DNA Applications with
Visual Basic

Visual Basic Script (VBScript) is a popular script language and will be used throughout this book.
VBScript is a subset of Visual Basic for Applications (VBA, as used by the Microsoft Office Products),
which in turn is a subset of the popular Visual Basic. Most readers familiar with VB should be able to
quickly grasp this lightweight scripting version of the language. Note that the normal Visual Basic
development tool is not suitable for editing VBScript logic – instead, the most productive tool is the Visual
InterDev development environment.

57
Chapter 3

A VBScript reference guide is available in Appendix D, and Microsoft's online


documentation is available at [Link]

Web developers frequently complain that their clever client-side script logic can easily be viewed and
copied once downloaded. The most recent version of the VBScript engine (version 5.0) enables a BASE64
simple encoding algorithm to be applied to the VBScript code. This means that when a Web page source
code is viewed, the script logic appears scrambled which makes it awkward (though not impossible) for
anyone to inspect and re-use.

We shall now look at two examples of VBScript, one that is client-side executed in Internet Explorer and
the other server-side executed by the ASP host.

Remember that Internet Explorer (v3.0 onwards) is currently the only browser to support
VBScript and so its use on the Web is likely to restrict the number of visitors to your site.
However, VBScript is more frequently used with Intranets and Extranets where you can
usually impose restrictions of the Web browser that may be used. If you require script logic
to be used in a Web solution then you should consider using JavaScript (and don't encode
it!). There's a short JavaScript tutorial in Appendix D, and O'Reilly's JavaScript: The
Definitive Guide is just that.

Example – IE Client-side VBScript

Our client-side scripting example illustrates


how we can detect the user interacting with
the Web page and then execute a routine.
The Web page contains a button that when
clicked fires a routine to display Hello
World.

The onclick attribute within the <INPUT> tag defines the actions that are invoked when the user clicks
on the button; in our example we call a routine named clicked().

<INPUT id=butClickMe type=button value="Click me"


onclick="call clicked()">

58
An Overview of Building Windows DNA Applications with
Visual Basic

Note: The code in the onclick attribute is actually JavaScript because this is the
default and no language attribute was specified to override this. This illustrates
that it is possible to combine more than one scripting language in the same page.

The routine clicked()is defined with the <SCRIPT> and </SCRIPT> tags – which specifies that the
scripting language is VBScript.

<SCRIPT LANGUAGE=VBSCRIPT>
<!--
sub clicked
msgbox "Hello world"
end sub
//-->
</SCRIPT>

The HTML code in its entirety is as follows:

<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<TITLE>Wrox's Web Programming with VB6</TITLE>

<STYLE>
BODY {FONT-FAMILY: Arial; BACKGROUND-COLOR: pink; }
</STYLE>

<SCRIPT LANGUAGE=VBSCRIPT>
<!--
sub clicked
msgbox "Hello world"
end sub
//-->
</SCRIPT>
</HEAD>

<BODY>
<H1>Client-side VBScript ... in action</H1>
<P><INPUT id=butClickMe type=button value="Click me"
onclick="call clicked()"></P>
</BODY>
</HTML>

Example – ASP Server-side VBScript


In Chapter 1 we introduced Active Server Pages and saw that they are files with a .ASP suffix that contain
both HTML syntax and server-side script logic. When the Web server receives an HTTP request for the
ASP document, an output HTML file is generated for the response using a combination of both the HTML
static information plus any HTML that is generated dynamically by the server-side script logic.

59
Chapter 3

In our next scripting example, we shall demonstrate how we can use an ASP server-side script to
dynamically generate Web content. Our script logic will interface with a Microsoft product called
Membership & Personalization (M&P) Server to identify a Web user and to retrieve their name. The
response that is sent to the client is then able to give a personalized greeting.

The script logic in an ASP file that is to be executed server-side is identified by being within either:
 <% and %> marks, or
 <SCRIPT RUNAT=Server> and </SCRIPT> tags (note – if the RUNAT attribute is omitted then the
script is executed client side)

Whilst it is not important to worry about the actual details of the M&P processing, notice that a software
component is created using [Link] and then ASP invokes various methods on the
object to perform the required actions.

Set User = [Link]("[Link]")


[Link] "", gMemUserScriptID, gMemUserPassword

This is typical of ASP processing where the main functionality is performed by other components and ASP
is simply used as the software glue to integrate the different components and pass the results back to the
Web browser.

The ASP code in its entirety is as follows:

<%@ Language=VBScript %>


<HTML>

<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<TITLE>Wrox's Web Programming with VB6</TITLE>

60
An Overview of Building Windows DNA Applications with
Visual Basic

<STYLE>
BODY {FONT-FAMILY: Arial;BACKGROUND-COLOR: wheat; }
</STYLE>

<%
gMemUserPassword = "password"
gMemUserScriptID = "cn=administrator,ou=members,o=HarrisonMembership"
Set User = [Link]("[Link]")
[Link] "", gMemUserScriptID, gMemUserPassword
vFirstName = [Link]
vSurname = [Link]
%>

<SCRIPT LANGUAGE=VBSCRIPT>
<!--
sub clicked
msgbox "Hello " & "<% = vFirstName %>" & " " & "<% = vSurname %>"
end sub
//-->
</SCRIPT>

</HEAD>

<BODY>
<H1>Server-side & Client-side VBScript ... in action</H1>
<P><INPUT id=butClickMe type=button value="Click me"
onclick="call clicked()"></P>
</BODY>

</HTML>

We shall study VB Script on the client in detail in Chapters 4 and 5 and ASP and VBScript in Chapter X
(on the server).

ActiveX Controls
ActiveX Controls are software components that can 'package' a specific item of functionality and be hosted
within a parent application (known as an ActiveX Control Container) such as Internet Explorer (version 3.0
and later). This enables our Web pages to include advanced functionality that cannot be accommodated with
standard HTML and scripting. Examples of ActiveX controls include video/audio (Windows Media Player)
and animation (e.g. Macromedia Shockwave), which are installed with the Full version of Internet Explorer.

ActiveX controls are the next generation of OLE Custom eXtension/controls (OCXs
32 bit applications) and Visual Basic eXtension controls (VBXs) (16 bit
applications).

ActiveX controls can expose properties and methods, and fire events; these may be combined with some
script logic in our Web page to provide interactivity between the user and the control.

61
Chapter 3

For example, our Web page could have a video control and a button; the script logic could detect the button
click and then invoke the control's Play methods:

One great feature of ActiveX controls is that they can be referenced in the Web page so that the Web
browser will automatically download and install them if needed; such as when either the client does not
have the control or the installed control is an earlier version. This approach contrasts greatly with
Netscape's plug-ins, which is the alternative approach for embedding complex functionality into an area
within the Web browser. The installation of a plug-in is not automatic and involves invoking an application
setup utility followed by restarting the browser.

Using the Authenticode security technologies that we discussed in Chapter 2, the user can have confidence
of the software publisher of the control and that it has not been tampered with since it was released.

ActiveX controls can be written in any of the COM compliant programming languages, including Visual
C++, Visual J++ (Java) and, of course, Visual Basic. They must be compiled in the native machine code of
the client's target platform, which means that if we are to support multiple platforms, then we must produce
a separate version for each.

Remember again, that Internet Explorer is currently the only Web browser that
supports ActiveX technologies. Using them on the Internet will restrict the number
of users that can use your Web pages.

62
An Overview of Building Windows DNA Applications with
Visual Basic

Example – ActiveX Control


Our next example shows an ActiveX control that takes over an area of the Web page and displays a smiley
face. When the user clicks the Click Here text, it responds with a Hello World speech balloon.

We start in the VB development environment by specifying that we want to create an ActiveX Control
project.

63
Chapter 3

The Form for the project contains the following two images:

Image1

Image2

When the control is initialized, the event UserControl_Initialize is called. This event will make
Image1 appear:

[Link] = True
[Link] = False

The control has a public function called SayHello, which is exposed by COM. The function must be
declared as public so that it can be invoked from outside the object. When called, it first makes Image2
appear:

[Link] = False
[Link] = True

A delay of 3 seconds is then established:

PauseTime = 3
start = Timer
Do While Timer < start + PauseTime
DoEvents
Loop

And finally the normal face is restored

[Link] = False
[Link] = True

64
An Overview of Building Windows DNA Applications with
Visual Basic

The ActiveX control is embedded into our Web page using the <OBJECT> tag. This specifies the required
version of the control and the name of the cabinet file that contains the files required to install the control.
A wizard called the Package and Deployment Wizard, which we discuss in Chapter 6 is used to package
and compress the control plus the information required to install the control, into a .CAB file.

<OBJECT id=HelloCtrl classid=CLSID:FBDC6779-E4A0-11D2-943D-00104B4F37A4


codeBase=[Link]#version=1,0,0,0 height=124 width=264>
</OBJECT>

The Web page also includes a text item with an onclick attribute. If the user clicks on the text, the
SayHello method on our ActiveX control is invoked and the user will see the Hello World speech
balloon appear.

<H3 id=txtClickHere onclick="[Link]()">


Click Here</H3>

The VB ActiveX control code in its entirety is as follows:

Private Sub UserControl_Initialize()


[Link] = True
[Link] = False
End Sub
Public Function SayHello() As Variant

[Link] = False
[Link] = True

PauseTime = 3
start = Timer
Do While Timer < start + PauseTime
DoEvents
Loop

[Link] = True
[Link] = False

End Function

and the HTML page that displays the results looks like this:

<HTML>

<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<TITLE> Wrox's Web Programming with VB6</TITLE>

<STYLE>
BODY {FONT-FAMILY: Arial;BACKGROUND-COLOR: silver; }
</STYLE>

</HEAD>

<BODY>
<H1>ActiveX Controls ... in action</h1>

65
Chapter 3

<TABLE>
<TR>
<TD>
<H3 id=txtClickHere onclick="[Link]()">
Click Here</H3>
</TD>

<TD>
<OBJECT id=HelloCtrl classid=CLSID:FBDC6779-E4A0-11D2-943D-00104B4F37A4
codeBase=[Link]#version=1,0,0,0
height=124 width=264>
</OBJECT>
</TD>
</TR>
</TABLE>

</BODY>

</HTML>

We shall study ActiveX Controls in detail in Chapter 5.

WebClasses
Visual Basic 6.0 introduces a new type of VB project called a WebClass, which provides another
alternative for dynamically generating web pages. A Visual Basic WebClass is a server-side software
component that is responsible for handling HTTP Requests from a Web browser and generating the HTML
that is then returned in the HTTP Response. For each WebClass, VB generates one ASP file. This ASP file
contains just a few lines of script that is used to call the WebClass; this is shown in the diagram below.

66
An Overview of Building Windows DNA Applications with
Visual Basic

A WebClass is invoked from the Web browser by specifying a URL that references its corresponding ASP
file. The ASP is just a few lines of code that passes control onto the WebClass

A WebClass includes a number of modules called WebItems, which are responsible for generating the text
(normally HTML) to be returned. There are two types of WebItems:

 HTML Templates WebItems – these return chunks of HTML taken from files that can be created using
HTML editors such as Microsoft FrontPage. Non-standard HTML tags can be included in the templates
that will fire the ProcessTag event enabling the WebItem to apply some business rules and replace
the tag with meaningful data.
 Custom WebItems – these return chunks of HTML using a series of programmatic statements.

WebItems may expose routines that act as event handlers and can be made to fire in response to actions
occurring on the Web browser; for example, the user clicking on an image or an item of text. When this
happens, the Web page logic requests a URL that specifies the ASP file for the WebClass and has some
parameters tacked onto the end of the URL to identify the WebItem and the event handler.

Visual Basic 6.0 includes a WebClass visual designer to help manipulate HTML Templates and map Web
browser events to WebItem event handlers.

Example – WebClasses
The following WebClass example demonstrates the replacement processing and the mapping of a client-side
event to a server-side event handler.

The first screen will display a welcome message that is appropriate for the time of day. When the user
clicks on a hyperlink in the page, the server-side WebClass is called to generate the next Web page.

67
Chapter 3

We start by specifying that we want an IIS Application project.

When a WebClass is first invoked, the first function that is always called is WebClass_Start. In our
example, we specify that the WebItem to process the HTTP request is called Greeting.

Set NextItem = Greeting

This causes the Greeting_Respond routine to be called, which dumps out the HTML in the template
file that was assigned to the Greeting WebItem.

[Link]

But notice that the template includes a bit of nonstandard HTML, as below:

<WC@GREETING>Greeting</WC@GREETING>

The WC@ prefix in the tag means that this section of the HTML content is to be replaced. To handle this, the
Greeting_ProcessTag event is automatically called and the replacement tag is passed as a parameter.
For the WC@GREETING tag, the section of HTML is replaced (using the TagContents parameter) with a
greeting that is appropriate for the time of day.

If TagName = "WC@GREETING" Then


TheHour = Hour(Time())
If TheHour < 12 Then
TagContents = "Good Morning"
ElseIf TheHour > 18 Then
TagContents = "Good Evening"
Else
TagContents = "Good Day"
End If
End If

Using the Visual Basic WebClass visual designer we


can connect the event of a user clicking on the Enter
text to the WebItem event handler called
EnterSite_Respond.

68
An Overview of Building Windows DNA Applications with
Visual Basic

This 'Connect to WebItem' operation sets the HTML anchor to reference the required WebItem in the
URL.

<A HREF="[Link]?WCI=EnterSite&WCU"><H4>Enter</H4></A>

When the user clicks on the Enter text, the ASP file [Link] is called and this in turn routes the
HTTP request on to the EnterSite_Respond event handler.

Whereas Greeting_Respond delivered an HTML template, the EnterSite_Respond routine takes


an alternative approach. Instead, this WebItem generates the HTML in the HTTP Response using a series of
[Link] statements.

[Link] "<HTML><HEAD>"
[Link] "<STYLE>"
[Link] " BODY {FONT-FAMILY: Arial; & _
BACKGROUND-COLOR: lightyellow; }"
[Link] "</STYLE>"
[Link] "</HEAD><BODY>"
[Link] "<H1>WebClasses ... in action</H1>"
[Link] "Welcome to our site ... the time is " & _
Format(Now, "hh:mm AM/PM")
[Link] "</BODY></HTML>"

The VB WebClass code in its entirety is as follows:

Option Explicit
Option Compare Text
Private Sub Greeting_ProcessTag(ByVal TagName As String, TagContents As String,
SendTags As Boolean)
Dim TheHour
If TagName = "WC@GREETING" Then
TheHour = Hour(Time())
If TheHour < 12 Then
TagContents = "Good Morning"
ElseIf TheHour > 18 Then
TagContents = "Good Evening"
Else
TagContents = "Good Day"
End If
End If
End Sub
Private Sub Greeting_Respond()
[Link]
End Sub
Private Sub EnterSite_Respond()
[Link] "<HTML><HEAD>"
[Link] "<STYLE>"
[Link] " BODY {FONT-FAMILY: Arial;" & _
"BACKGROUND-COLOR: lightyellow; }"
[Link] "</STYLE>"
[Link] "</HEAD><BODY>"
[Link] "<H1>WebClasses ... in action</H1>"
[Link] "Welcome to our site ... the time is " & _
Format(Now, "hh:mm AM/PM")
[Link] "</BODY></HTML>"
End Sub
Private Sub WebClass_Start()
Set NextItem = Greeting
End Sub

69
Chapter 3

and the HTML template for the Greeting WebItem is:

<HTML>

<HEAD>
<META NAME="GENERATOR" Content="Microsoft FrontPage 3.0">
<TITLE>Wrox's Web programming With VB6</TITLE>

<STYLE>
BODY {FONT-FAMILY: Arial; BACKGROUND-COLOR: lightyellow; }
</STYLE>

</HEAD>

<BODY>

<H1>WebClasses ... in action</H1>

<P><WC@GREETING>Greeting</WC@GREETING>
<A><H4>Enter</H4></A>
</BODY>

</HTML>

We shall study WebClasses in detail in Chapters 12 to 14.

Dynamic HTML Applications


As we know from our earlier discussions, the early generation of Web browsers could only render static
documents. To change the display, time and network intensive communication with the Web server was
required in order to get a page refresh.

As from version 4.0 of Internet Explorer, all of the HTML elements on a Web page can be manipulated 'on
the fly' by means of a technology known as Dynamic HTML (DHTML). This browser provides a
comprehensive Document Object Model (DOM) that allows all tags and attributes in a Web page to be
programmatically accessed and amended using a scripting language such as VBScript. Thanks to DHTML
we can enable dynamic user interaction and reduce the load on the Web server.

Visual Basic 6.0 has introduced a new type of VB project called a DHTML Application that offers us an
alternative approach to using the scripting language to develop logic to manipulate the IE DOM and handle
user interactions.

Important! As with ActiveX technologies, when we use this technology we are


restricting ourselves to the latest versions of Internet Explorer and so limiting the
number of Internet users that can view our pages. The W3C have published a DOM
specification which hopefully one day all browser vendors will support in its
entirety … until then, we can only live in expectation of the glorious world of
browser compatibility.

70
An Overview of Building Windows DNA Applications with
Visual Basic

A Visual Basic DHTML Application produces two separate items:

 a client-side software component (an ActiveX Control without any user interface)
 a collection of HTML pages

The control is embedded within the Web pages and has full programmatic access to the document object
model. The two items operate together to perform the presentation layer functionality.

The advantages of using the DHTML Application approach as opposed to including script logic in the
HTML page include:

 the software component is compiled and so runs faster


 the deployed logic is in a binary format and so cannot easily be examined and ripped off
 the application can be developed using our familiar and powerful VB development environment

Visual Basic 6.0 includes a DHTML Application page designer to create the HTML Web pages and to
identify the tags that can be manipulated by the code.

Example – Dynamic HTML


In this next DHTML Application example we shall display a HELLO sign and then rotate it in three
dimensions.

There are also two buttons that allow the speed of the rotation to be altered.

We start by specifying that we want a DHTML Application project.

71
Chapter 3

The HELLO sign is displayed by using a Microsoft ActiveX control called the Structure Graphics Control
that is supplied as part of Internet Explorer. This uses vector graphics that are commands and a coordinate
system to reproduce an image; typical commands being Draw a Line, Draw a Shape, Fill With a Color,
Display Text, and so on. By using these methods it is often possible to generate graphical effects that are
much more lightweight than using equivalent JPG or GIF graphics files.

To get our sign, we specify the vector commands as parameters to the control.

<OBJECT classid=CLSID:369303C2-D7AC-11D0-89D5-00A0C90833E6
height=100 id=sgHelloSign width=100 VIEWASTEXT>
<PARAM NAME="SourceURL" VALUE="">
<PARAM NAME="CoordinateSystem" VALUE="0">
<PARAM NAME="MouseEventsEnabled" VALUE="-1">
<PARAM NAME="HighQuality" VALUE="0">
<PARAM NAME="PreserveAspectRatio" VALUE="-1">
<PARAM NAME="Line0001" VALUE="SetLineColor(255,255,255)">
<PARAM NAME="Line0002" VALUE="SetFillColor(255,0,0,0,0,255)">
<PARAM NAME="Line0003" VALUE="SetFillStyle(1)">
<PARAM NAME="Line0004" VALUE="SetLineStyle(1,0)">
<PARAM NAME="Line0005" VALUE="Polygon(
8,-45,15,-15,45,15,45,45,15,45,-15,15,-45,-15,-45,-45,-15)">
<PARAM NAME="Line0006" VALUE="SetFont('Arial',24,500,0,0,0)">
<PARAM NAME="Line0007" VALUE="SetLineColor(255,255,255)">
<PARAM NAME="Line0008" VALUE="SetFillColor(255,255,255,255,0,0)">
<PARAM NAME="Line0009" VALUE="Text('HELLO',-35,5)">
</OBJECT>

In addition, the HTML references another object – this is our DHTML Application object. The ClassID for
the object is inserted automatically by the Visual Basic development environment.

<!--METADATA TYPE="MsHtmlPageDesigner" startspan-->


<object id="DHTMLPage1"
classid="clsid:A97E9A15-E601-11D2-943F-00104B4F37A4"
width=0 height=0>
</object>
<!--METADATA TYPE="MsHtmlPageDesigner" endspan-->

The DHTML Application has access to all of the items in the Web page and the Web browser's window
object.

72
An Overview of Building Windows DNA Applications with
Visual Basic

When the Web page has been loaded, the BaseWindow_onload event is called. First a variable called
vTimer that is used to store the delay between each frame of the rotation, is initialized and then displayed
on the Web page.

vTimer = 50
[Link] = vTimer

Then a timer is kicked off. We specify that when the timer expires, the VBScript routine named DoRotate
in our DHTML Application object should be called.

Call [Link]("call [Link]()", vTimer, "VBScript")

So let's look at DoRotate(). First, the next frame in the rotation of the sign is done by calling the
Structure Graphics Control's Rotate() method.

Call [Link](3, 2, 1)

Then, the same timer as before is restarted, and this whole process is continually repeated.

The speed of the rotation is handled by amending the value of vTimer when either the Faster or Slower
buttons are clicked; these user actions are picked up by the butFaster_onclick and
butSlower_onclick event handlers.

The DHTML Application code in its entirety is as follows:

Dim vTimer

Private Sub BaseWindow_onload()


vTimer = 50
[Link] = vTimer
Call [Link]("call [Link]()", vTimer, "VBScript")
End Sub

Public Function DoRotate() As Variant


Call [Link](3, 2, 1)
Call [Link]("call [Link]()", vTimer, "VBScript")
End Function

Private Function butFaster_onclick() As Boolean


If vTimer > 2 Then
vTimer = vTimer - 2
End If
[Link] = vTimer
End Function

Private Function butSlower_onclick() As Boolean


If vTimer < 200 Then
vTimer = vTimer + 2
End If
[Link] = vTimer
End Function

73
Chapter 3

The HTML page looks like this:

<HTML>

<HEAD>
<TITLE>Hello World</TITLE>

<STYLE>
BODY {FONT-FAMILY: Arial;BACKGROUND-COLOR: lightblue; }
.SPEED {CURSOR: Hand; BACKGROUND-COLOR: blue; COLOR: white}
</STYLE>

</HEAD>

<BODY>

<!--METADATA TYPE="MsHtmlPageDesigner" startspan-->


<object id="DHTMLPage1"
classid="clsid:A97E9A15-E601-11D2-943F-00104B4F37A4"
width=0 height=0>
</object>
<!--METADATA TYPE="MsHtmlPageDesigner" endspan-->

<H1>Dynamic HTML ... in action</H1>


<TABLE>

<TR><TD align=middle>
<OBJECT classid=CLSID:369303C2-D7AC-11D0-89D5-00A0C90833E6
height=100 id=sgHelloSign width=100 VIEWASTEXT>
<PARAM NAME="SourceURL" VALUE="">
<PARAM NAME="CoordinateSystem" VALUE="0">
<PARAM NAME="MouseEventsEnabled" VALUE="-1">
<PARAM NAME="HighQuality" VALUE="0">
<PARAM NAME="PreserveAspectRatio" VALUE="-1">
<PARAM NAME="Line0001" VALUE="SetLineColor(255,255,255)">
<PARAM NAME="Line0002" VALUE="SetFillColor(255,0,0,0,0,255)">
<PARAM NAME="Line0003" VALUE="SetFillStyle(1)">
<PARAM NAME="Line0004" VALUE="SetLineStyle(1,0)">
<PARAM NAME="Line0005" VALUE="Polygon(
8,-45,15,-15,45,15,45,45,15,45,-15,15,-45,-15,-45,-45,-15)">
<PARAM NAME="Line0006" VALUE="SetFont('Arial',24,500,0,0,0)">
<PARAM NAME="Line0007" VALUE="SetLineColor(255,255,255)">
<PARAM NAME="Line0008" VALUE="SetFillColor(255,255,255,255,0,0)">
<PARAM NAME="Line0009" VALUE="Text('HELLO',-35,5)">
</OBJECT>
</TD>

<TD align=middle width=150>


<INPUT type="button" value="Faster" id=butFaster>
<INPUT type="button" value="Slower" id=butSlower>
<BR><BR>
Timer = <SPAN id=txtTimer>value</SPAN>
</TD></TR>

</TABLE>

</BODY>

</HTML>

We shall study Dynamic HTML Applications in detail in Chapter 6.

74
An Overview of Building Windows DNA Applications with
Visual Basic

ActiveX Server Components


An ActiveX Server Component is a non-visual COM compliant software component that is executed on the
server and used to perform specific business rules.

When we are developing complex ASP applications we must remember that the server-side script logic is
interpreted VBScript or JavaScript. When we start to develop really complex Web applications, Web server
performance starts to slow as it interprets the script logic. Furthermore, the scripting languages have
limited-functionality when compared to the capabilities of Visual Basic 6.0.

The recommended solution for ASP Web applications is to minimize the amount of script and to develop or
reuse existing ActiveX Server Components for the business logic. The ASP logic is then restricted to
generating the presentation layer (i.e. the HTML tags) and synchronizing the information flow between the
components. Alternatively, using WebClasses (called from ASP) to handle the presentation layer and to call
on the ActiveX Server Components for the business logic can optimize Web applications further.

ActiveX Server Components may be configured to run within the MTS environment. We discussed earlier
how this simplifies the development of transaction-based applications and can improve on the performance
and scalability of our systems.

Example – ActiveX Server Components


Our next example uses an ActiveX Server Component to generate the welcome text for a Web page. The
component reads the text from a database and uses a passed 'language' parameter as a key to the database
retrieval query.

The example uses ADO, which is the standard data access mechanism provided by Windows
DNA. ADO is a large topic and outside the scope of a DNA/VB overview chapter. In fact
whole books can be written on the subject such as Wrox's ADO 2.0 Programmers Reference
Guide and the Wrox book Professional ADO / RDS Programming.

75
Chapter 3

We start by specifying that we want an ActiveX DLL project.

Using the Visual Basic Properties window, we set the name of the project to HelloAxCtrl and the name
if the class to XHello.

The function that may be called to perform the action is called GetWelcome. Since this must be exposed
to callers from outside the component, we must specify that it is Public.

Public Function GetWelcome(ByVal vLanguage As Variant) As Variant

First, the SQL statement to get the text from the database is set up using the passed language parameter.

Let vSQL = "Select Message FROM WelcomeMsg " & _


"WHERE LanguageId = '" & vLanguage & "';"

Next an ADO Recordset object is instantiated. An ADO Recordset is probably the most used object with the
ADO object model and is used to examine and manipulate data from a data store.

Set oRs = CreateObject("[Link]")

We then invoke the query by calling the open method on the ADO Recordset object

[Link] = 1
[Link] vSQL, vDbConn, , , adCmdText

Then the welcome can be retrieved from the ADO Resultset returned from query.

vWelcome = [Link]("Message")

Finally, we tell MTS that everything was successful and then return the Welcome text as the result of the
function call.

[Link]
GetWelcome = vWelcome

The ASP logic determines the required language from a URL parameter

vLanguage = [Link]("Language")

76
An Overview of Building Windows DNA Applications with
Visual Basic

It then instantiates the component by using a ProgId based on the component's project and class names, i.e.
[Link]

Set obj = [Link]("[Link]")

Next the GetWelcome method can be invoked to obtain the Welcome text.

vHello = [Link](vLanguage)

Finally, the result is returned back in the HTTP response.

<H4><% = vHello %><H4>

The MTS Component code in its entirety is as follows:

Implements ObjectControl
Private Const vDbConn As Variant = "DSN=Welcome;"
Private oRs As [Link]
Private objMTSContext As ObjectContext
Private Function ObjectControl_CanBePooled() As Boolean
ObjectControl_CanBePooled = True
End Function
Private Sub ObjectControl_Deactivate()
Set objMTSContext = Nothing
Set oRs = Nothing
End Sub
Private Sub ObjectControl_Activate()
On Error GoTo ActivateErr
Set objMTSContext = GetObjectContext()
Exit Sub
ActivateErr:
End Sub
Public Function GetWelcome(ByVal vLanguage As Variant) As Variant
On Error GoTo GetWelcomeErr

Dim vSQL As Variant


Dim vWelcome As Variant

Let vSQL = "Select Message FROM WelcomeMsg " & _


"WHERE LanguageId = '" & vLanguage & "';"

Set oRs = CreateObject("[Link]")


[Link] = 1
[Link] vSQL, vDbConn, , , adCmdText

vWelcome = [Link]("Message")

[Link]
GetWelcome = vWelcome
Exit Function

GetWelcomeErr:
Trace ([Link])
[Link]
GetWelcome = "?" & [Link]

End Function

77
Chapter 3

The ASP code is this:

<HTML>

<HEAD>
<TITLE>Hello World</TITLE>

<STYLE>
BODY {FONT-FAMILY: Arial;BACKGROUND-COLOR: peachpuff; }
</STYLE>

</HEAD>

<BODY>
<H1>ActiveX Server Components ... in action<h1>
<%
Dim vLanguage,vHello,obj
vLanguage = [Link]("Language")
Set obj = [Link]("[Link]")
vHello = [Link](vLanguage)
%>
<H4><% = vHello %><H4>
</BODY>

</HTML>

We shall study ActiveX Server Components in detail in Chapter 9 and MTS is covered in Chapter 11.

ActiveX Documents
An ActiveX Document is a file that contains some data and a reference to a server application that can
allow the user to see and interact with the data. An ActiveX document can only be viewed in applications
that can act as ActiveX Document Containers, example of which are Internet Explorer and the Microsoft
Office Binder.

An example of an ActiveX Document is an MS Word document – this stores the content of the document
and has a reference to the MS Word executable. To illustrate this, remove the file association mapping of
.DOC files to MS Word (this is done via the Folder Options menu option from within Windows Explorer.
If you double click on a .DOC file, a dialog will appear asking what file to use as there is no longer any
application associated with this file type. However, try dragging and dropping the .DOC file into Internet
Explorer … you will see that the browser then takes on the MS Word personality and opens the file. Clever
stuff!

If you do delete the .DOC file association mapping, then first make a note of the
settings so that you can return your system back to the same state. Alternatively,
you will have to reinstall MS Word.

78
An Overview of Building Windows DNA Applications with
Visual Basic

This is shown in the screen shot below, where the container is Internet Explorer but it has incorporated the
MS Word menus and toolbars.

From version 5.0, Visual Basic has been able to support the development of ActiveX documents and so
enables us to deploy applications and associated data over the Web.

79
Chapter 3

Example – ActiveX Documents


Our ActiveX Document example takes over the Internet Explorer menu bars and allows the control over the
language that the Hello World greeting is displayed in. You can see from the screen dumps below that IE
now includes a menu option called Language that allows the user to select the required language.

We start by specifying that we want an ActiveX Document DLL project.

In a similar manner to developing a standard Visual Basic application, we use the VB development
environment to define the application menus and create a form that contains two labels. The second label is
dynamically changed to display the greeting when the user selects the language.

Clicking on an entry in the Language menu causes the mnuLang_Click event to be fired and the
greeting label is amended to the appropriate message for the required language.

80
An Overview of Building Windows DNA Applications with
Visual Basic

The ActiveX Document code in its entirety is as follows:

Option Explicit

Private Sub mnuLang_Click(Index As Integer)


Select Case Index
Case 1:
[Link] = "Hello World"
Case 2:
[Link] = "Bon Jour"
Case 3:
[Link] = "Hallo Welt"
Case 4:
[Link] = "Ciao Mondo"
Case 5:
[Link] = "Hello Mundo"
Case 6:
[Link] = "Hola Mundo"
Case Else:
[Link] = "?"
End Select
End Sub
Private Sub UserDocument_Initialize()
[Link] = "Hello World"
End Sub

Traditional Windows Clients


When discussing the latest Visual Basic features such as WebClasses and DHTML Applications, it's easy to
forget that standard Window applications can be developed to fully exploit the Web and networking
technologies. We shall see that it is easy to develop such applications that can render Hypertext Markup
Language (HTML) documents and use the TCP/IP protocols to retrieve and share information.

Visual Basic client applications can now operate in the multi-tier computing environments and invoke
business logic stored in server-side software components. This can be done either directly using DCOM or
by means of using HTTP to interface through a Web server with ASP logic. The latter is achieved through
the use of the Microsoft Internet Transfer Control that allows Visual Basic applications to connect to and
retrieve files from any Internet site that supports either the Hypertext Transfer Protocol (HTTP) or the File
Transfer Protocol (FTP).

The Microsoft Web Browser Control is an ActiveX control that may be used on a Visual Basic form to
retrieve data located on the Internet and to display Web content. It provides the same capabilities as
Internet Explorer including support for DHTML, ActiveX controls, ActiveX scripting, Java applets and
multimedia content (video and audio). In fact, Internet Explorer actually uses this control to render its
pages and so the reason it provides the same capabilities is no coincidence.

81
Chapter 3

Example DCOM
In this example, we communicate using DCOM directly to the server-side [Link]
component that we created earlier for deployment in MTS. The user chooses the language that is passed in
the DCOM call by means of a Language menu.

The code to instantiate the MTS component and invoke the GetWelcome method is similar to the logic
that we saw earlier when the task was done from an ASP script.

Set objHello = CreateObject("[Link]")


[Link] = [Link](vLanguage)

However, the main difference this time is that the target object is created on a different machine and the
method call to GetWelcome is made across the network. The information needed by DCOM to know about
the location of the component is stored in the Windows registry on the client machine. This registry
configuration is done for us by running a client installation program that is created by invoking an MTS
export facility.

The [Link] Application code in its entirety is as follows:

Option Explicit

Private Sub mnuLang_Click(Index As Integer)


Dim vLanguage
Dim objHello As Object
On Error GoTo errorhandler

Select Case Index


Case 1:
vLanguage = "EN"
Case 2:
vLanguage = "FR"
Case 3:
vLanguage = "DE"
Case 4:
vLanguage = "IT"

82
An Overview of Building Windows DNA Applications with
Visual Basic

Case 5:
vLanguage = "PO"
Case 6:
vLanguage = "ES"
Case Else:
vLanguage = "??"
End Select

Set objHello = CreateObject("[Link]")


[Link] = [Link](vLanguage)
Set objHello = Nothing

Exit Sub

errorhandler:
MsgBox "Error: " & [Link]

End Sub

Example – Internet Transfer Control


Our next example uses the Internet Transfer Control to initiate an HTTP Request then displays the HTML
data that is received in the HTTP Response. We shall request the Web page that we used earlier to
demonstrate ActiveX Server Components. As before, the user may choose the required language by means
of a Language menu. What should be shown is the HTML specific for the language selected.

When the user has chosen their language, then, provided that there is no outstanding request, we invoke the
HTTP request using the Internet Transfer Control's Execute method. This specifies the URL of the
required Web resource.

If Not [Link] Then


[Link] _
"[Link] & vLanguage, "GET"
End If

83
Chapter 3

Any change of status on the Internet Transfer Control causes the ctrlInternet_StateChanged event
to be called. The parameter that is passed gives us more information about the type of change of status.
When the HTTP Response has been received, the event is called passing a state of
icResponseCompleted.

When we detect that the HTTP Response has been received, we then extract the information out of the
response using GetChunk and then amend a label on the form to display it to the user

vData = [Link](4096)
[Link] = vData

The Standard .EXE Application code in its entirety is as follows:

Option Explicit

Private Sub mnuLang_Click(Index As Integer)


Dim vLanguage
On Error GoTo errorhandler

Select Case Index


Case 1:
vLanguage = "EN"
Case 2:
vLanguage = "FR"
Case 3:
vLanguage = "DE"
Case 4:
vLanguage = "IT"
Case 5:
vLanguage = "PO"
Case 6:
vLanguage = "ES"
Case Else:
vLanguage = "??"
End Select

If Not [Link] Then


[Link] _
"[Link] & vLanguage, "GET"
End If

Exit Sub

errorhandler:
MsgBox "Error: " & [Link]

End Sub
Private Sub ctrlInternet_StateChanged(ByVal State As Integer)
Dim vHeader As Variant
Dim vData As Variant
On Error GoTo errorhandler

84
An Overview of Building Windows DNA Applications with
Visual Basic

Select Case State


Case icResponseCompleted
vHeader = [Link]()
vData = [Link](4096)
[Link]
Rem MsgBox "Header: " & vHeader
Rem MsgBox "Data: " & vData
[Link] = vData

End Select

Exit Sub

errorhandler:
MsgBox "Error " & [Link]

End Sub

Example – Web Browser Control


Our final example works in a similar manner to the previous example but this time uses the Web Browser
Control to handle the HTTP Request / Response communications. In addition, this control has the ability to
display the HTML on the screen.

When the user has chosen their language, we invoke the HTTP Request using the Web Browser Control's
Navigate method, which specifies the URL of the required Web resource. The control displays the
HTML as soon as the HTTP Response is received.

[Link] _
"[Link] & vLanguage

85
Chapter 3

The Standard .EXE Application code in its entirety is as follows:

Option Explicit

Private Sub mnuLang_Click(Index As Integer)


Dim vLanguage
On Error GoTo errorhandler

Select Case Index


Case 1:
vLanguage = "EN"
Case 2:
vLanguage = "FR"
Case 3:
vLanguage = "DE"
Case 4:
vLanguage = "IT"
Case 5:
vLanguage = "PO"
Case 6:
vLanguage = "ES"
Case Else:
vLanguage = "??"
End Select

[Link] _
"[Link] & vLanguage

Exit Sub

errorhandler:
MsgBox "Error: " & [Link]

End Sub

We will discuss MTS/DCOM in Chapter 11 and the Web Browser Control in Chapter 6.

That concludes our quick tour of the different ways of using Visual Basic for implementing our Web
Applications in a Windows DNA environment.

Summary
In our lightning tour of using VB to create Windows DNA applications, we have seen that Visual Basic 6.0
and Visual Interdev 6.0 fully address the new Web paradigms and without doubt, they together provide the
most productive toolset for building Windows DNA applications.

86
An Overview of Building Windows DNA Applications with
Visual Basic

The key points to this chapter are:


 There are many facets to using VB with the Web and we have seen a variety of areas when VB logic
may be implemented; in particular we have considered VB deployed at:

The Web Client


− Web pages
− ActiveX Controls
− Dynamic HTML Applications
− ActiveX Documents
− Traditional Windows Clients

The Web Server


− Active Server Pages
− WebClasses
− ActiveX Server Components

 The use of ActiveX technologies will restrict your web pages to later versions of Internet Explorer and
so will restrict the number of Internet users that can use your pages.

We warned you at the top of this chapter that the pace would be fast and that we would only be considering
the code in the examples at a very high level in order to give a flavor of what is possible when using VB to
build Windows DNA applications. This easy life must now come to an end as it's time to drill down a lot
deeper and learn how to exploit these technologies to their full potential. We shall now consider each one of
these topics in much greater depth, starting in the next chapter with a look at the Web client.

87
Chapter 3

88
Client-Side Programming with
Visual Basic

In recent months, server-side technologies have received much of the attention in the wide world of Web
development. Technologies such as Active Server Pages and VB software components handle all processing
on the Web server and deliver formatted HTML–only pages to the client for display in the browser.
Traditionally, the Internet has been conceived as a world of fast, powerful Web servers and slow, weak
clients that can do little more than point a browser to the Web server and make simple requests. As a result,
the conventional wisdom has been to have the processing burden on the server, and to keep the client thin.
This approach does have its advantages. For one, server-side logic provides for a low cost of ownership,
because the files need only be updated in one location. Also, thin clients receive pure HTML, and so they
are not dependent on the platform that the server-side logic is deployed on.

Yet today, several factors are changing the conventional wisdom that thin clients are better, namely:

 Powerful client computers (home and office PCs) are equipped with high-speed chips and large stores of
RAM.
 Limitations on how much information can be exchanged over the Web are rapidly lifting because more
people now have high-speed Internet access via technologies like 56K modems, cable access, and ISDN.
 Improved compression technologies for audio and video files means that more dynamic content can be
delivered to clients in a reasonable amount of time.
 Intranets, which bring Internet technologies to local (LAN) and wide-area (WAN) networks, are an
increasingly popular corporate solution for information storage and exchange. Intranet solutions rely on
sharing the processing burden between server and clients.
Chapter 4

The need for capable and responsive client machines has grown as Web applications have become more
complex, and as the demand for dynamic, interactive content has increased. Significant delays, and even
timeouts, frequently result if the client has to make too many calls back to the Web server. Even a simple,
non-transactional page refresh can take quite a few seconds and so cause an undesirable user experience.
One or more of the following factors potentially delays client requests:

 Delays at the proxy server;


 Delays due to limited bandwidth on phone lines;
 Delays at the Web server, especially at high-traffic sites. The delay here could also be at database and
application servers that are behind the web server.
 Delays on one of the network nodes on route from one ISP to another.

Some client requests can only be handled by the Web server, such as resource-intensive database requests
in an e-commerce application. However, the client more efficiently handles other kinds of requests. These
include validating user input, formatting database requests (to the server), and handling user-interface
details. This division of labor is integral to the concept of n-tier application architecture, which specifies
that presentation services should be kept distinct from business and data access services.

In this chapter we'll introduce some of the exciting technologies that are pushing client-side Web
development to the next level. These include:

 ActiveX Scripting (e.g. VBScript)


 Client-side ActiveX controls
 XML, for delivering structured data to the Web
 COM-enabled Scriptlets (XML and ActiveX Scripting)

The Intranet Revolution


Intranets are designed to allow organizations to share information and provide services to its employees.
Intranet applications are developed using Internet technologies, but they are deployed on local- (LAN) or
wide-area (WAN) networks instead of the World Wide Web. Intranets are developed using a browser/server
architecture that shares the processing burden between the server and the client. Data services and business
services are run on Web servers (sometimes tied to dedicated database servers). Presentation-services are
managed on the client-side, and a browser is used to communicate between the client machine and the Web
server application.

Intranets are a popular solution for large companies, and offer the following advantages:

 TCP/IP network protocol and HTTP server/browser protocol for fast, reliable communication.
 HTML for publishing information to the Corporate Enterprise. HTML requires a short learning curve
and easily integrates with server-side technologies such as ASP and CGI, and other client-side
technologies such as ActiveX Scripting.

90
Client-Side Programming with Visual Basic

 Browser-based application front-ends can be rapidly developed using HTML, ActiveX Scripting and
ActiveX controls. (Chapter 5 shows you how to create custom ActiveX controls, in case you need to
extend or supplant a commercial ActiveX control).
 Intranets centralize and organize information in a manner best suited to the organization. They enable a
company's key information (often distributed all over the enterprise in a number of geographical areas)
to be easily and quickly located and retrieved – thus avoiding the waste of this information not being
exploited or having to be reinvented.
 Because the browser interface is a familiar environment for most users, they often find Intranet
applications easy to learn. By fronting many different applications with a web browser, a user gets a
consistent view of all corporate applications and data sources even though behind the scenes there may
be many different technologies and interfaces in use.
 Well-designed Intranets offer a secure environment where users can trust the content they receive.

Developing applications for Intranets mirrors developing for the Web, but with more advantages. Intranet
applications are developed for a restricted environment. Developers know in advance the processing
capabilities of the server and client machines, and can optimize the application for the environment. This
luxury is usually not afforded when developing for the Web, especially when catering to the mass market,
where multiple browsers and versions must be supported. The exception is where you are providing a great
service that lots of people want, such as a home banking application. In this case you can afford to restrict
the supported browser to Internet Explorer 4, for example, and shut out those users who don't want to go
along with the restriction.

The advantages of Intranets for developers are:

 Intranets usually use one standard browser, so developers need not worry about how their scripts will be
interpreted by different browsers. Of course, it is possible to have two versions of the same vendor's
browser in a large enterprise where users are gradually migrating from one version of a browser to
another.
 A standard browser lets developers exploit the latest client features to the full they know what the
browser can support. On the Web, where numerous browsers are used, developers have to support the
lowest common denominator of capabilities. This often means restricting the site to using old or outdated
technologies.
 Developers know in advance how much of the processing burden can be shared between server and
clients, based on machine capabilities.
 Web development technologies such as HTML and ActiveX allow for rapid client-side development.
Technologies like ASP and CGI provide for development on the server-side.

Client-side technologies are very important to Intranet development because Intranet client machines can
typically handle a higher processing burden than Internet client machines. Client-side technologies greatly
extend server-based applications by enabling the client to provide user services, such as a graphical
interface and input validation. Client-side technologies also transfer some of the processing burden from the
server to the client. In this chapter we'll discuss the technologies that are available for client-side
development and get you well on your way to becoming an effective Web and Intranet developer.

91
Chapter 4

ActiveX Scripting
ActiveX Scripting integrates a scripting language such as VBScript or JScript into a Web browser. ActiveX
Scripting depends on a scripting host and a scripting engine. The scripting engine is an in-process ActiveX
component that executes the script code. The scripting engine for VBScript, for example, is the component
[Link]. The Internet Explorer browser is referred to as the
ActiveX scripting host, which is a platform for running
the ActiveX scripting engine. When the browser
encounters a <SCRIPT> section it checks the
LANGUAGE attribute and looks for an appropriate
registered engine on the client. The browser calls the
engine, which executes the script and returns the result.

With ActiveX scripting, you can use any scripting language for which an engine is available and registered
on the client. Visual Basic Scripting Edition (VBScript) is just one of several scripting languages, but it's
the one we'll be covering in this chapter. VBScript is not an isolated technology, but a player in a larger
framework.

Client-Side Scripting Using VBScript


Since its introduction almost three years ago, VBScript grew from a simple, lightweight interpreter with a
basic collection of functions to a key player in advanced new client-side technologies like COM-enabled
scriptlets and DHTML (both reviewed later in this chapter). VBScript is a subset of the Visual Basic for
Applications (VBA) language, which finds wide use as a development language in products like Microsoft
Word, Excel and Access. VBScript is designed to be lightweight, portable and secure. You won't find any
File I/O functions in VBScript, nor can you use it to interact with the client machine's registry. You can't
even make calls to API functions registered on the client, because all of these activities leave the client
susceptible to file corruption, viruses and a host of other potential problems that we in the business
generally classify as bad news. Be warned, however, that VBScript can invoke dangerous COM components
that may have unwittingly been installed on the system.

92
Client-Side Programming with Visual Basic

What can I use VBScript for?


VBScript works alone, or in combination with other technologies to bring powerful functionality to the
Web. The key uses for VBScript are:

 Validation of user input


 Scripting ActiveX Controls on a Web page
 With XML for creating COM-enabled scriptlets
 Scripting Active Server Pages (server-side only)
 In the Windows Script Host, to write macros that automate common tasks
 Scripting events in Microsoft Exchange

VBScript or JScript: Which one do I use?


This question can't be answered by touting one scripting language as being superior to the other. Your
choice of scripting language really depends on your background, your personal preference, and your
intended audience. As a Visual Basic programmer, you will presumably want to leverage your existing
knowledge of VB into learning VBScript, which you can pick up in as little as a day. JScript, which is
closer in syntax to C++, is Microsoft's implementation of the so-called ECMA scripting language standard
that is set by a European standards association. JavaScript is Netscape's implementation of the ECMA
standard. In short, JScript and JavaScript are two languages based on the same standard, but marketed by
different companies.

If you want your Web pages to display properly in both the Internet Explorer and Netscape browsers, you
should probably choose JavaScript for scripting, although VBScript is supported in Netscape via a third
party plug-in, which you can download from [Link] This chapter focuses
on using VBScript with Internet Explorer. Keep in mind that some of the technologies covered here, such as
scriptlets and DHTML, will currently only work in Internet Explorer and many of the technologies
specifically require version 5.0 of the browser; this is available for free download from Microsoft at
[Link]

Overview of VBScript
It is customary for a discussion of VBScript to commence with what VBA elements are missing in
VBScript. In keeping with this tradition I give you the following table, which highlights important
differences between VBA and VBScript. However, I prefer not to focus on the missing elements, because it
leaves the reader with the impression that VBScript is a weak, watered-down language. In actuality,
VBScript is a slim, lightweight language that is tailored to its special environment: the browser.

93
Chapter 4

Category VBA VBScript


Arrays Flexible array bounds. Lower Array index only starts at zero.
Option Base keyword.
Data Types All data types available, No strict data types. Variants only.
including user-defined
types.
Strings Range of string functions. VBScript has a superior range of string
functions!
File I/O Several File I/O functions. No File I/O functions. Use Microsoft
Scripting Library on the server-side for
File I/O.
Collections Flexible collection object. Cannot use Add, Count, Item and
Remove methods, but VBScript can
iterate through collections of HTML
and XML elements.
Objects Flexible object creation. Object creation is late-bound. Can
define Classes as of VBScript 5.0.
Supports CreateObject and GetObject
for Automation.
System Screen, Printer, Err object. Err object only.
Objects
Error Flexible error handling. In-line error handling only with On
Handling Error Resume Next.

VBScript is embedded directly on a Web page using the <SCRIPT> tag, which for our purposes has a
single LANGUAGE attribute that should be set to VBScript in order for the scripting host to reference the
VBScript scripting engine. The general syntax for VBScript on a Web page is shown below, using a
schematic example:

<HTML>
<HEAD>
<SCRIPT LANGUAGE="VBScript">
<!--
Dim MyGlobal
Sub MyPublicScript()
' Code goes here
End Sub
-->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="VBScript">
<!—
Sub window_onLoad()
Call MyPrivateScript
End Sub
Sub MyPrivateScript()
Call MyPublicScript
End Sub

94
Client-Side Programming with Visual Basic

MsgBox “This code is worth $” & MyGlobal


-->
</SCRIPT>
</BODY>
<HTML>

VBScript code can be contained in procedures, as in MyPrivateScript, or it can be outside of any


procedure, as the MsgBox function above illustrates. Procedures and variables that are included between
<HEAD> tags take on a public scope and can be referenced by procedures between the <BODY> tags. Note
that all variables in VBScript use the variant data type. No user-defined data types are allowed. This also
applies to the interface of any DLL that you call from a script.

If you want to port your DLLs to VBScript, then ideally the interface should contain only variant
arguments. You can bend the rules somewhat by using a small handful of strict data types as arguments,
including String and Integer, but then you must apply the appropriate conversion function to any script
variable that gets passed to the DLL. For example, consider the following function, taken from the
Arithmetic class of MathDLL:

Public Function Multiply(ByVal intNum1 As Integer, ByVal varNum2 As Variant) As _


Variant
' Calculate and return a result
End Function

This function gets called from a script as follows:

Dim objMath, Num1, Num2, Result


Num1 = 2
Num2 = 4

Set objMath = CreateObject(“[Link]”)

Result = [Link](CInt(Num1),Num2)

Finally, you can use VBScript to script event procedures for HTML elements such as the onLoad event of
a window element. In fact, Internet Explorer exposes an entire object model that can be manipulated
programmatically using script (See Chapter 7). Later in this chapter we'll discuss how to use Scripting
Wizard in the ActiveX Control Pad to script HTML elements. In Chapter 4 we discuss how to use DHTML
to code against the Document Object Model that the browser also exposes.

VBScript does have some advantages over its full-featured cousin, VBA, most notably in the area of string
manipulation. Some VBScript functions, such as Filter and Join, work directly with arrays. Whereas
VBA requires you to loop through an array if you want to manipulate its elements, these VBScript functions
accept the array directly, and handle the iterations for you behind the scenes.

For example, here is the Filter function:

Dim X
Dim Result(3)
X = Array(“Wrox”,”Press”,”Books”)
Result = Filter(X,”o”) 'Result(0)=”Wrox”, Result(1)=”Books”

95
Chapter 4

The next table summarizes the useful string manipulation functions that were, until recently, only available
in VBScript, and have been since version 2.0. However, if you have VBA 2000, then you now have access
to all of these functions too. Seeing as not everyone will have the latest version, it still makes sense to
include this table. Functions that accept or return arrays only deal in one-dimensional arrays. The table
includes a "Nearest VBA Equivalent" column that gives you an idea of how much extra work is involved to
duplicate these VBScript functions in VBA.

VBScript Purpose Nearest VBA Equivalent


Function
Filter Searches an array for all occurrences Loop through each element
of a specified string. Returns an array. of an array and apply
InStr.
Join Concatenates all elements of an array. Loop through the array and
Returns a string. concatenate each element in
turn.
InStrRev Works like InStr, except it will use Use InStr to locate the
the end of the string as the starting search string, then subtract
position for searches. It can also the position from the length
behave like InStr. Returns a of the string.
position.
StrRever Reverse the order of characters in a Reassemble the string while
se string. Returns a string. looping through it
backwards.
Replace Substitute a section of a string with Use Mid, Left and Right
another string. You can either functions to dissect the
explicitly specify the section to be string, then concatenate
replaced, or you can specify a starting preserved sections with the
position and a character count. new section.
Returns a string.
Split Transform a single string with A reverse of the Array
embedded delimiters into a one- function. Lots of work to
dimensional array. Returns an array. duplicate!

Although string manipulation functions are the most significant distinction between VBScript and older
versions of VBA, there are others. VBScript now supports Regular Expressions, which take string matching
to another level, as I will outline later in the chapter. For advanced file manipulation VBScript 5.0 also adds
the Scripting Runtime Library, which has long been available with Active Server Pages. (I won't be
discussing the Scripting Runtime Library here since it is only used for server-side scripting). Finally,
VBScript has specialized formatting functions for currency and date/time (among others) to return
formatted values that are localized to the server's regional system settings.

96
Client-Side Programming with Visual Basic

There are several excellent introductory references available for VBScript; there is also a VBScript
Reference and a Tutorial in the appendices at the back of this book. You can also visit Microsoft's Scripting
site for the most up-to-date VBScript language reference. With VBScript 5.0, the differences between VBA
and VBScript have lessened. VBScript offers increased functionality and enhanced features, which I'll
discuss next.

Microsoft's Scripting site is located at:


[Link]

New Features in VBScript 5.0


VBScript 5.0, which ships with Internet Explorer 5.0, takes a big leap ahead from its predecessors, bringing
it up to par with JScript. VBScript 5.0 supports the following new features. The appendices at the back
cover the core VBScript programming language but do not include the features below:

 Classes
 Regular Expressions
 Function-pointers
 With...End With statement execution
 Script Encoding

Classes
The new Class statement brings object-oriented capability to VBScript. Object-oriented design simplifies
development by breaking complex code into simpler, smaller code components that encapsulate their logic
behind a robust interface. Classes define both the interface and the implementation of the object. In Visual
Basic, class definitions are contained in separate .CLS modules, but VBScript embeds the class definition
directly on the Web page between opening and closing Class statements. Within these statements, you can
define properties and methods as usual, using Public and Private statements, to distinguish public interface
members from private ones. Properties can be defined using property procedures or public variables, while
methods can be defined using regular procedures and functions.

There are some key differences between classes in Visual Basic versus VBScript. In Visual Basic, the
interface details can be kept separate from the implementation by defining the interface in one class
module, and then implementing this interface in another class module. This is not an option in VBScript.
Also, Visual Basic classes can raise events, but VBScript classes cannot. VBScript classes can, however,
raise errors using the Error object, which is useful for alerting the client to invalid input. Finally,
VBScript does not support the Friends statement for interface members.

So what can you use classes for in VBScript? The most meaningful use is to create business objects that
encapsulate business logic and validate user input. For example, you could create a business object that
accepts input from an HTML form, validates it, and then performs some calculations. The form's submit
button would invoke a method on a business object that assigns the input to properties and validates it in
the process. If the input is valid, the object can proceed with the calculations; otherwise, the object can
raise an error to the client that can be handled using an error trap.

97
Chapter 4

Let's look at an example of a class called SalaryCalculator that calculates an adjusted salary using
the inflation rate and a multiplier, which is simply a multiplication factor that is applied to the inflation
rate. So if your employer really likes you, they could use this calculator to adjust your salary by 2 times
inflation, where 2 is the multiplier:

<HTML>
<HEAD>
<SCRIPT LANGUAGE="VBScript">
<!--
Class SalaryCalculator
Public IRate, IMultiplier
Private varSalary

Property Get Salary


Salary = varSalary
End Property

Property Let Salary (varValue)


If varValue >0 Then
varSalary = varValue
Else
[Link] 6000, "salary", "Salary must be >$0."
End If
End Property

Function NewSalary()
NewSalary = varSalary*((1+(IRate*IMultiplier/100)))
End Function
End Class
-->
</SCRIPT>
</HEAD>

The object interface has three properties and a single method. The properties are Salary, IRate and
IMultiplier. The Salary property is implemented as a property procedure, while the other properties,
for illustration purposes, are implemented as public variables. You should always use property procedures
so that you can validate input and raise errors if necessary. Finally, the interface method is NewSalary,
implemented as a public function, which is provided to calculate an adjusted salary.

The class definition is included in the <HEAD> section of the Web page to make it available to the entire
Web page before the <BODY> section is interpreted. In the <BODY> section we create a
SalaryCalculator object by setting an object variable reference to the class. Object references in
VBScript are always late-bound, and you cannot use the As New syntax to create an object. The
following code listing illustrates how to create and use the SalaryCalculator object using VBScript:

<BODY>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub window_OnLoad()
On Error Resume Next
Dim y
Set y = New SalaryCalculator

98
Client-Side Programming with Visual Basic

[Link] = 30000
'Fixed values here, but you can retrieve them from an online form
[Link] = 4.0
[Link] = 1.5
If [Link] <> 0 Then
[Link] "Error " & [Link] & ": " & [Link] & "<br>"
Else
[Link] "Your current salary is " & FormatCurrency([Link]) & "<br>"
[Link] "The inflation rate is " & [Link] & _
"% and the multiplier is " & [Link] & "<br>"
[Link] "Your new salary is " & FormatCurrency([Link])
End If
End Sub
-->
</SCRIPT>
</BODY>
</HTML>

The output to the Web page from this code listing is:

Your current salary is $30,000.00


The inflation rate is 4.0% and the multiplier is 1.5
Your new salary is $31,800.00

Error Handling in VBScript


Let's take a quick moment to discuss error handling in VBScript. As in Visual Basic, VBScript errors are
exposed using the Err object, which is global in scope and does not need to be explicitly instanced.
VBScript only provides in-line error handling, which means that you need to use On Error Resume
Next to skip past the offending line. If you don't include this statement then a runtime error will halt
execution of the script.

VBScript has no On Error Goto statement, so the error handling statements must be included with the
regular code statements. As the example above illustrates, you should test the Number property of the Err
object prior to running any calculations. If its value is anything other than zero, then you have an error and
should take appropriate action. In this example, only the Salary property is validated. If an invalid value
is assigned, then the property procedure raises an error, which changes the property values of the Error
object, including the Number, Description and Source properties. Unlike with Visual Basic, this does not
cause the interpreter to jump directly to an error handler, because technically, there is none.

Issues to Consider when Using Classes in VBScript


While classes are an exciting new addition to VBScript, you shouldn't use them without first considering
whether it is wise to expose your class definitions to the outside world. If the class contains proprietary
business logic then you should encapsulate the logic in a binary ActiveX component instead, and insert the
component in the Web page. There are other advantages to using binary components. For one, they are
created using languages like Visual Basic, which offer more functions to the developer than VBScript.
Binary components are compiled and therefore more efficient for complex processing. Finally, you can add
licensing and security certificates to a binary component, which is not an option for VBScript objects.

99
Chapter 4

Regular Expressions
The new RegExp object brings the power of regular expressions to VBScript. Regular expression patterns
are used to match an input string against a set of regular expression characters, which describe how the
valid input string should look. If you've ever worked with input masks, then you've used regular expression
patterns. For example, the pattern for an e-mail address like president@[Link], is:

[Link] = “\w+\@\w+\.\w+”

The \w mask matches any word, character or digit, including an underscore. Notice that placeholder text,
such as the @ in an email address, is shown literally. The pattern for a phone number with area code, such
as (610) 555-1212 is:

[Link] = “\(\d{3}\)\s\d{3}\-\d{4}”

This example uses the \d mask for digits, and the \s mask for a space. Regular expressions help validate
complex strings. You can see a full listing of special characters for patterns in the table below, which is
adapted from the VBScript documentation.

Character Description
\ Marks the next character as either a special character or a literal. For example,
"n" matches the character "n". "\n" matches a newline character. The sequence
"\\" matches "\" and "\(" matches "(".
^ Matches the first character of input.
$ Matches the last character of input.
* Matches the preceding character zero or more times. For example, "zo*"
matches either "z" or "zoo".
+ Matches the preceding character one or more times. For example, "zo+"
matches "zoo" but not "z".
? Matches the preceding character zero or one time. For example, "a?ve?"
matches the "ve" in "never".
. Matches any single character except a newline character.
(pattern) Matches pattern and remembers the match. The matched substring can be
retrieved from the resulting Matches collection, using Item [0]...[n].
x|y Matches either x or y. For example, "z|food" matches "z" or "food".
"(z|f)ood" matches "zoo" or "food".

100
Client-Side Programming with Visual Basic

Character Description
{n} Matches exactly n times, where n is a nonnegative integer. For example,
"p{1}" matches "pet" but not "happy".
{n,} Matches at least n times, where n is a nonnegative integer. For example,
"p{2,}" matches "happy" but not "pet".
{n,m} Matches a character between n and m times, where m>n and m and n are
nonnegative integers. For example, "C{2,3}" matches "ICCA" or "ICCCA" but
not "ICA".
[xyz] A character set. Matches any one of the enclosed characters. For example,
"[abc]" matches the "a" in "plain".
[^xyz] A negative character set. Matches any character not enclosed. For example,
"[^abc]" matches the "p" in "plain".
[a-z] A range of characters. Matches any character in the specified range. For
example, "[a-z]" matches any lowercase alphabetic character in the range "a"
through "z".
[^m-z] A negative range of characters. Matches any character not in the specified
range. For example, "[^m-z]" matches any character not in the range "m"
through "z".
\b Matches a word boundary, or, the position between a word and a space. For
example, "er\b" matches the "er" in "never" but not the "er" in "verb".
\B Matches a nonword boundary. "ea*r\B" matches the "ear" in "never early".
\d Matches a digit character. Equivalent to [0-9].
\D Matches a nondigit character. Equivalent to [^0-9].
\f Matches a form-feed character.
\n Matches a newline character.
\r Matches a carriage return character.
\s Matches any white space including space, tab, form-feed, etc.
\S Matches any nonwhite space character.
\t Matches a tab character.
\v Matches a vertical tab character.
\w Matches any word character or digit, including underscore.
\W Matches any nonword character. Equivalent to "[^A-Za-z0-9_]".
\num Matches num, where num is a positive integer. A reference back to remembered
matches. For example, "(.)\1" matches two consecutive identical characters.

101
Chapter 4

Here is an example of the RegExp object using its Test method:

<SCRIPT LANGUAGE="VBScript">
<!--
Sub window_onLoad()
Dim email, phone
email="president@[Link]"
phone="(610) 555-1212"
Call Validate(email,"\w+\@\w+\.\w+")
Call Validate(phone,"\(\d{3}\)\s\d{3}\-\d{4}")
End Sub

Sub Validate(Input,Patrn)
Dim TestExp
Set TestExp = New RegExp
[Link] = Patrn
[Link] = True
If [Link](Input) Then
MsgBox Input & " is VALID"
Else
MsgBox Input & " is INVALID"
End If
End Sub
-->
</SCRIPT>

Pattern matches are executed using one of three methods of the RegExp object, which are:

 Test
 Replace
 Execute

The Test method uses the search string as an argument and returns True or False, depending if a valid
match is found. The Replace method accepts two arguments, the search string and a replacement string. If
a valid match is found, then the method returns the modified string; otherwise, it returns the original search
string. Note that VBScript provides its own Replace function for substituting one string into another. This
function is relatively inflexible, in that only a specific substring can be replaced, such as "blue" for "red".
On the other hand, the method that is provided by the RegExp object allows you to substitute directly into
a regular expression pattern match. For example, all e-mail matches in a sentence can be located by their
regular expression pattern, and then substituted.

The properties of the RegExp object are:

 Pattern
 IgnoreCase
 Global

102
Client-Side Programming with Visual Basic

The three properties define the settings for how a regular expression search gets conducted. The Pattern
property sets the regular expression pattern, as shown in the examples above. The Global property is a
Boolean that sets whether the regular expression matches multiple occurrences of the expression (True), or
just the first occurrence (False). By default, the Global property is True. Finally, the IgnoreCase
property is another Boolean that sets whether the match is case-sensitive (True) or case-insensitive
(False).

The Match Object and the Matches Collection


The Execute method of the RegExp object returns a special object called a Match object, which holds
read-only properties that describe the results of the match. The properties of the Match object are:

 FirstIndex
 Length
 Value

The FirstIndex property holds the starting character of the match in the string. The Length property holds
the matched string length in characters, and the Value property holds the actual matched string. The
Execute method also creates a Matches collection object, which holds all of the Match objects that
result from a single search. You need to set the Global property of the RegExp object to True in order
to get more than one match in a search string.

Here is an example of the Match object and Matches collection object:

<SCRIPT LANGUAGE="VBScript">
<!--
Sub Match()
Dim TestExp, Match, Matches, Result, I
I=0
Set TestExp = New RegExp
[Link] = "\w+\@\w+\.\w+"
[Link] = True
[Link] = True
Set Matches = [Link]("Write to: jeff@[Link] or jeff@[Link]")
For Each Match in Matches
I=I+1
Result = Result & "Match " & I & " (Position "
Result = Result & [Link] & ") = "
Result = Result & [Link] & "<br>"
Next
[Link] Result
End Sub
-->
</SCRIPT>

The code listing begins by declaring a new RegExp object called TestExp then defining its properties.
The regular expression pattern is set for an e-mail address. Once these properties are set, the Execute
method gets called with a string argument that contains two e-mail addresses. Recall that the Execute
method returns a Matches collection, which in this example will contain two items, one for each e-mail
address in the string.

103
Chapter 4

The code returns this output:

Match 1 (Position 10) = jeff@[Link]


Match 2 (Position 27) = jeff@[Link]

Function Pointers
In keeping with the dynamic, event-driven nature of the Web, VBScript introduces function pointers, which
are designed to work with the event handlers of DHTML objects in the Internet Explorer object model, such
as the window and form objects. Using the GetRef function, you can assign a procedure directly to the
event handler of a DHTML object. The alternative is that you would have to create a procedure for each
event handler, which takes a minimum of three lines of code, with implementation. However, a function
pointer sets the reference in a single line.

The following code sample illustrates no less than three function pointers for a Web page with a single
command button. The pointers operate on the window load and unload events, and on the button Click
event:

<HTML>
<HEAD>
<TITLE>GetRef Example</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub LoadPointer()
MsgBox "Loading " & [Link], 64, "Loading Web Page"
End Sub
Sub UnloadPointer()
MsgBox "Unloading " & [Link], 64, "Unloading Web Page"
End Sub
Sub ClickPointer()
MsgBox "Current Form: " & [Link](0).name & Chr(13) & _
"Current Button: " & [Link](0).elements(0).name, 64, _
"Web Page Info"
End Sub
set [Link] = GetRef("LoadPointer")
set [Link] = GetRef("UnloadPointer")
-->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="InputForm">
<INPUT NAME="cmdSubmit" TYPE="submit" VALUE="Submit Request">
<SCRIPT LANGUAGE="VBScript">
<!--
set [Link] = GetRef("ClickPointer")
-->
</SCRIPT>

</FORM>
</BODY>
</HTML>

104
Client-Side Programming with Visual Basic

With Statement
The With statement allows you to set a reference to an object once, and then make subsequent calls to its
interface without continually specifying the object name. This gives script performance a boost by reducing
the number of times the scripting engine has to make calls to reference the object's type library. Here is an
example, using the Err object:

<SCRIPT LANGUAGE="VBScript">
<!--
With Err
If .Number <> 0 Then
[Link] "Error " & .Number & ": " & .Description & "<br>"
End If
End With
-->
</SCRIPT>

Script Encoding

Many of us learned about scripting languages and some clever techniques by viewing the source code of
Web pages we find exceptionally interesting. However, many Web developers prefer not to share the fruits
of their labor so easily with the outside world. The stakes are higher with scriptlets, which are components
that are implemented using script. Component architectures are often proprietary in nature and need to be
protected.

Script encoding transforms scriptlets, HTML, and ASP scripts into an unreadable hash that includes a
calculated check sum, to ensure the integrity of the script. If anyone tries to alter the encoded script, then
the check sum will not match the script, and it will fail to load in the browser. Internet Explorer 5.0 can
interpret encoded scripts directly, although earlier versions of the browser cannot. Script is marked for
encoding by setting the LANGUAGE attribute of the script in the HTML page to <SCRIPT LANGUAGE =
[Link]>.

For encoding, Microsoft provides a command-line utility called Windows Script Encoder (Version 1.0)
that is available for download from Microsoft's Windows Script Technologies site, at
[Link] After downloading the executable, [Link],
double-click on its icon to un-bundle the documentation and to add the utility to C:\Program
Files\Windows Script Encoder\[Link].

To encode a script:

Move the script into the same directory as the utility (unless you add the directory to the PATH variable in
[Link]). Let's assume that the script is embedded along with regular HTML in a page called
[Link].

 Open an MS-DOS command prompt, navigate to the directory, and type the following at the command
line: screnc [Link] [Link] or
screnc /f [Link]

105
Chapter 4

The first syntax will create a separate file for the encoded script, while the second syntax will overwrite the
original file. The script encoder will encode scripting code only, and plain text will be left untouched.
Microsoft recommends that you add a plain-text copyright message to the top of your scripts to further deter
would-be pirates.

As a final note of caution, bear in mind that encoding is not the same as encrypting. Encoding makes life a
little bit awkward for the casual viewer but it won't stop those that really want to view the scripting from
finding a way to do so. Source encoding is not as reliable as the binary protection provided by ActiveX
controls. If the security of your script is of major concern, you might want to consider an alternative
approach, such as using server-side scripts, or encapsulating the script's business logic inside a binary
ActiveX control.

Handling Different Versions of VBScript


The new features available in VBScript 5.0 may be exciting, but only Internet Explorer 5.0 users (and later)
are guaranteed to be running the latest scripting engine. Unfortunately, it takes time for everyone to install
the latest version of a new browser. Older versions of Internet Explorer are also compatible with VBScript
5.0 as long as the client has installed the latest version of the scripting engine. Otherwise, VBScript
compilation errors (pop-up message boxes) will occur if an older browser attempts to load a page with
newer script features, such as an embedded Class definition. At best, the rest of the page will load smoothly
after the initial error. At worst, critical business logic will fail to load, and the user will be left with a
completely non-working page.

If there is any doubt about which browser version your user has, which is everywhere except in a controlled
Intranet setting, then you should refrain from using statements that may fail in earlier browsers. This makes
life less interesting, because the new VBScript features extend the scripting language in powerful ways.
You could put some code in the onLoad() event of the script window that detects what scripting engine
the user has installed. If the VBScript version is older than 5.0, you could display a message alerting the
user, and then perform a redirection or otherwise. Here is an example code listing:

<SCRIPT LANGUAGE="VBScript">
<!--
Sub window_onLoad()
If ScriptEngineMajorVersion < 5 Then
MsgBox "You are using an old version of VBScript." & _
vbCrLf & "Please download the new version before proceeding.", _
vbExclamation
[Link]("[Link]
Else
MsgBox "You are using: " & ScriptEngineVersion, vbInformation
End If
End Sub

Function ScriptEngineVersion()
Dim s
s = "" ' Build string with necessary info.
s = ScriptEngine & " Version "
s = s & ScriptEngineMajorVersion & "."
s = s & ScriptEngineMinorVersion & "."
ScriptEngineVersion = s 'Return the version.

106
Client-Side Programming with Visual Basic

End Function
-->
</SCRIPT>

Using the Microsoft Script Debugger


As Visual Basic developers, we are accustomed to an integrated development environment (IDE) that
provides responsive, informative tools for debugging. These tools include:

 Breakpoints
 Watch Expressions
 Step-wise compilation

The Microsoft Script Debugger is a plug-in for Internet Explorer that provides the same set of familiar
debugging tools for your scripting languages, and works with both VBScript and JScript. The Script
Debugger not only helps you find bugs, but it's a great learning tool, because you can step through scripts a
line at a time and can examine the script behavior at an easy pace.

The Script Debugger is available for download from Microsoft's Windows Script Technologies site. When
you install the Script Debugger, it becomes integrated with Internet Explorer. There are two ways to launch
the Script Debugger from Internet Explorer:

 Click on View | Script Debugger | Open


 Click on View | Script Debugger | Break at Next Statement

Alternatively, you can insert a Stop statement in the VBScript code, which launches the Debugger and
breaks execution of the script. If your script generates an error during execution, Internet Explorer will
prompt you with a dialog box that reports the error and asks if you want to debug the script. If you agree,
the Script Debugger will launch into debug mode. Refreshing the script page prompts the debugger to ask
you if you want to reload the page into the Debugger. If you want to continue debugging, then respond with
"Yes" (you will lose any prior debugging information).

The figures below show what happens when you try and execute
the last script example for handling different versions of
VBScript. Before re-running the script, I edited the If function
so that it now reads Iff. On loading the script, the following
dialog box pops up:

107
Chapter 4

On clicking "Yes", the Microsoft Script Debugger launches, as shown below:

The Debugger provides menus and toolbars for accessing its debugging functions. A "Running
Documents" pane shows all of the Internet Explorer windows currently open, and also shows what scripts
are running. The actual script code is displayed in its own code pane. The Immediate window, or
Command Window as it is called here when shown, is also available for you to query variables and
execute code, just like you're used to doing in Visual Basic's IDE. Finally, (though not shown), the Call
stack window lists both pending and previously called procedures in descending order in the window.

The Debug menu provides the following options:

 Continue
 Break at Next Statement
 Step Into
 Step Over
 Step Out

108
Client-Side Programming with Visual Basic

 Toggle Breakpoint
 Clear All Breakpoints
 Show Next Statement

The file in the Script Debugger is read-only, so once you have detected your error and are ready to fix it,
open your script in an editing environment and make the change. If the Debugger is still open, it will
prompt you to refresh the script. Alternatively, you can close the Debugger before editing your script, and
just hope that you've caught all the errors.

If you have Visual InterDev installed, then you don't need to install the Script Debugger, because Visual
InterDev will serve the same function as the Debugger. Visual InterDev is an all-around superior and much
more versatile product. However, the Script Debugger is free and easy to install, which makes it a welcome
addition for your Web development environment.

Introducing XML and Scriptlets


Extensible Markup Language (XML) is a new standard for describing and delivering structured data to the
Web. XML is a subset of Standardized General Markup Language (SGML), which means that it uses a tag-
based syntax. Whereas HTML uses tags to display data, XML uses tags to describe data. Also, while HTML
uses fixed tags only, XML uses tags that are entirely custom-defined. Hence, the XML language is referred
to as extensible. The important features of XML are:

 XML data is self-describing


 XML is extensible
 XML separates data structure from display
 XML allows granular updates

If you are looking for a detailed introduction to XML, this chapter will disappoint you, because our interest
in XML is limited to the role it plays in constructing scriptlets, which are COM-enabled components for
the Web created with XML and an ActiveX Scripting language. For detailed information on XML, see
chapter 16 or visit Microsoft's Web site at [Link]

The Bare Essentials of XML


Let's look at a simple example of an XML script called [Link], which describes the structure of the
Visual Basic Error object:

109
Chapter 4

<XML ID=”ObjectModel” TYPE=”text/xml”>


<object-browser>
<object>
<name>ErrObject</name>
<properties>
<property>Description </property>
<property>Number</property>
<property>Source</property>
<property>HelpContext</property>
<property>HelpFile</property>
</properties>
<methods>
<method>Raise</method>
<method>Clear</method>
</methods>
</object>
</object-browser>
</XML>

The simplicity of the script is striking, and you will notice how clearly the hierarchical nature of the Error
object model comes through. The unique tag names make it very easy to understand what each data element
is, and how it relates to others in the hierarchy. An XML script like this one can be embedded directly in a
web page, where it is referred to as a data island.

The XML model allows developers to create an unlimited number of custom tags to describe their data.
Because XML does not dictate how the data should be displayed, the client has complete control over what
data gets viewed and in what format. XML is an excellent means of delivering data from a server to a
client. Once the data is on the client desktop, client-side scripts can dynamically display the data in
different views without having to make repeated calls to the server.

There are several options for displaying XML data in the browser. Style sheets can be used to assign a
custom style to each element in the XML object model. Here is an example of a style sheet called
[Link]:

object {display:block;
font-size:18pt;
font-family:Arial;
color:blue;
text-align:left
}
properties {
font-size:14pt;
font-family:Arial;
color:black;
text-align:left;
}
methods {
font-size:14pt;
font-family:Arial;
color:green;
text-align:left;
}

The style sheet is linked to the XML file by adding a style definition at the top of the XML file, as in:

<?xml:stylesheet href="[Link]" type="text/css" ?>


<XML ID="ObjectModel" TYPE=”text/xml”>
<object-browser>

110
Client-Side Programming with Visual Basic

Internet Explorer 5.0 is able to natively parse and display XML, so you can point this browser directly to an
XML file to display it. In the case of [Link], using the style sheet, the browser should display the
following text:

ErrObject Description Number Source HelpFile HelpContext Raise Clear


This will probably not win any creative awards, even with the color differences you'd see on your browser,
but it does illustrate the distinction between XML definition versus display. If no style sheet is specified,
then the browser will display a collapsible tree-view of the XML definition that looks just like the
[Link] code listing.

Another option for displaying XML is with Internet Explorer's Document Object Model. XML data islands
are included in the document object model of the Web page, so you can use DHTML to traverse through a
data island with script in the same way that you would iterate through other document elements. In the
future we can expect to see new tools that will facilitate publishing XML to the Web.

This concludes our brief introduction to XML. Although you won't yet be an XML expert, you've seen
enough to understand the role that XML plays in constructing scriptlets.

Scriptlets: Components for the Web


Scriptlets are COM-enabled, custom components designed for the Web. They are intended to bring to
the Web the advantages of component-based development. As COM objects, scriptlets can provide the same
services that other COM objects provide, such as Automation. There are actually two kinds of scriptlets,
and it's important for you to understand the distinction between them:

 DHTML Scriptlets are user-interface components written in DHTML. With the release of Internet
Explorer 5.0, Microsoft now recommends that you use DHTML behaviors in place of scriptlets. For
more on DHTML behaviors please see Chapter 6.
 Scriptlets are general-purpose components for the Web, written in XML and ActiveX script. This
is the type of scriptlet we will be discussing here.

How To Write a Scriptlet


Scriptlets are analogous to class modules in Visual Basic, which serve as blueprints for creating objects.
Class modules contain:

 A definition of the object's interface


 Code implementation of the interface members.

We've seen how useful XML is for defining data structures. XML is used in a scriptlet to define the
interface, while ActiveX scripting is used to code the interface implementation and business logic.

111
Chapter 4

Scriptlets usually contain four XML elements:

 The <scriptlet> element, which encloses the scriptlet definition (i.e., the following three elements
in this list).
 The <registration> element, which contains information for registering your scriptlet, such as the
ProgID.
 The <implements> element, which specifies the COM interfaces that the scriptlet implements. For
example, if the scriptlet needs to provide Automation services, then it implements the Automation
handler. The interface definition is contained within the <implements> tags.
 The <script> element encloses ActiveX scripting code that implements the scriptlet's interface and
the business logic.

By now we're familiar with the SalaryCalculator example from earlier in the chapter. We first
introduced this example using plain vanilla VBScript. Later, we coded SalaryCalculator as a
VBScript class. Now we will create a third incarnation by coding SalaryCalculator as a scriptlet.

The code listing is:

<SCRIPTLET>

<REGISTRATION PROGID="[Link]">
</REGISTRATION>

<IMPLEMENTS ID=AUTOMATION TYPE=AUTOMATION>


<PROPERTY NAME=SALARY INTERNALNAME=VARSALARY>
<GET/>
<PUT/>
</PROPERTY>
<METHOD NAME=NEWSALARY>
<PARAMETER NAME=IRate/>
<PARAMETER NAME=IMultiplier/>
</METHOD>
</IMPLEMENTS>

<SCRIPT LANGUAGE="VBSCRIPT">

Private varSalary

function get_Salary()
Salary=varSalary
end function

function put_Salary(varValue)
If varValue >0 Then
varSalary = varValue
Else
[Link] 6000, "salary", "Salary must be >$0."
End If
end function

function NewSalary(IRate,IMultiplier)
NewSalary = varSalary*((1+(IRate*IMultiplier/100)))
end function

112
Client-Side Programming with Visual Basic

</SCRIPT>
</SCRIPTLET>

The code listing for the scriptlet should look quite familiar to you except for some syntax differences. The
first section of the code defines the component's interface, with <PUT> and <GET> tags used in place of
Property Let and Property Get statements. The second section of the code contains VBScript to
implement the interface. In the next section we look at how to download and use scriptlets in web pages.

Using the Scriptlet


The scriptlet is available to be called from a Web page once it has been downloaded. Scriptlets are subject
to the same security restrictions that ActiveX controls are subject to. For example, a Medium security
setting in Internet Explorer will ensure that the user is prompted before the scriptlet is downloaded. Here is
a simple Web page that uses the SalaryCalculator scriptlet:

<HTML>
<HEAD>
<TITLE> SalaryCalculator Scriptlet </TITLE>
</HEAD>

<OBJECT ID="SalaryCalculator" TYPE="text/x-scriptlet" WIDTH=300 HEIGHT=200>


<PARAM NAME="url" VALUE="[Link]

<BODY>

<SCRIPT LANGUAGE="VBScript">
<!--
Sub window_OnLoad()

On Error Resume Next

Dim MyInflation, MyMultiplier

[Link] = 30000
MyInflation=5.0
MyMultiplier=1.5

If [Link] <> 0 Then


[Link] "Error " & [Link] & ": " & [Link] & "<br>"
Else
[Link] "Your current salary is " &
FormatCurrency([Link]) & _ "<br>"
[Link] "The inflation rate is " & MyInflation & "% and the multiplier
is " & _
MyMultiplier & "<br>"
[Link] "Your new salary is " & _
FormatCurrency([Link](MyInflation, _
MyMultiplier))
End If

End Sub

113
Chapter 4

-->
</SCRIPT>

</BODY>
</HTML>

It can get tedious to type a scriptlet, so you may want to download the Microsoft Scriptlet Wizard, which
lets you add interface members and their parameters. The Wizard will generate the scriptlet interface
definition for you, but you will have to add the ActiveX scripting yourself. This wraps up our discussion of
scriptlets. Go forth and create components!

Using ActiveX Controls on the Client


For serious added functionality to your Web page, you will want to use ActiveX controls. Although HTML
and VBScript together can accomplish plenty, they do not match the sophistication of an ActiveX control,
nor do they provide the same robustness. Client-side scripts have no access to the client's system files,
whereas a registered ActiveX control potentially does. From a security perspective this may not be a good
thing, but from a functionality perspective it is. Clients can take precautions to protect themselves from
potentially damaging ActiveX controls. Chapter 5 covers ActiveX controls in detail, and reviews digital
signing, which is a way of certifying that a control is from a trusted source and is safe to use.

Scripts do not protect their proprietary business logic as well as ActiveX controls. (Although even binary
components can be reverse engineered by determined hackers to display their business logic). Script
encoding in Internet Explorer 5.0 goes some way toward solving this problem, but it is not the most secure
way to protect your source code. With ActiveX controls, you have many more options for protecting your
intellectual property, including licensing. In addition, ActiveX controls are compiled, binary components,
so the source code is not available for viewing.

In this section we will discuss how ActiveX Controls are included in a Web page. We will focus on using
the ActiveX Control Pad for adding controls to a Web page. Like the Script Debugger, this tool is available
for free, and works with controls in a similar fashion to its more sophisticated cousin, Visual InterDev. The
Control Pad also provides a Script Wizard that makes it easy to add script to client-side ActiveX controls.
This section introduces tools and concepts that will be explored further in Chapter 5.

ActiveX Out of the Box


As Visual Basic developers, we work with ActiveX controls all the time, and many of us regularly create
custom controls to develop an application. ActiveX controls are reusable software components that expose a
custom interface that can be manipulated programmatically. The Visual Basic Toolbox contains several
intrinsic ActiveX controls that are included in Visual Basic's runtime library. The Label, PictureBox
and CommandButton controls are all examples of intrinsic controls.

114
Client-Side Programming with Visual Basic

Visual Basic also ships with additional ActiveX controls, which are packaged in separate binary files with
.OCX extensions. Many more controls ship with Visual Basic, and can be accessed from the Project |
Components menu, including the Calendar Control and the Microsoft Chart Control. Some .OCX files
actually contain a package of controls, such as Microsoft Windows Common Controls 5.0
([Link]), which contains eight ActiveX controls, including the TabStrip, ToolBar,
StatusBar, ProgressBar, TreeView, ListView, ImageList and Slider controls.

There are many excellent ActiveX components available for use on the desktop and the Web. You can find
a good selection of components in the ActiveX Gallery at
[Link] If this selection of controls does not meet your
development needs, you can find many third-party ActiveX controls available on the market. These controls
are usually reasonably priced and can save you hours of development time. You also can develop your own
ActiveX control. Chapter 5 outlines how to write your own ActiveX components using Visual Basic.

Hosting ActiveX Controls on a Web Page


ActiveX controls enrich static Web pages with dynamic content and improve the quality and ease-of-use of
the interface that the clients see in their browser. ActiveX controls are not designed to function as stand-
alone components. Instead, they must function inside a host container, which is any environment that
implements COM and can support ActiveX controls. Examples of containers include forms in Visual Basic
projects, and the Internet Explorer browser. So it should come as no surprise that many ActiveX controls
function equally well on the desktop and on the Web. Each environment simply represents a different kind
of host container for the control.

ActiveX components may be integrated into a Web page in one of two ways:

Directly into an HTML page using the <OBJECT> tag, for example:

<OBJECT CLASSID=”3HGSD-000X-C10000A”
ID=”MyCalendar”
CODEBASE=”[Link]
</OBJECT>

Or using a scripting language such as VBScript's CreateObject method:

CreateObject(“[Link]”)

115
Chapter 4

The HTML <OBJECT> tag's many attributes provide detailed specifications for how the Web page hosts
the ActiveX control. There are attributes for everything from the control's registry GUID to coordinates that
specify where the control is placed on the page. The attributes of the <OBJECT> tag are summarized in the
table below:

Attribute Description
ID Equivalent to the Name property of the
ActiveX control. It is the name that will be
used to script the object and set/call its
properties and methods.
CLASSID The global unique identifer (GUID) that
identifies a registered ActiveX control. The
GUID is used to instance an ActiveX class.
CODEBASE The URL location from where the browser can
download the component, if it does not already
exist on the client machine. The CODEBASE
optionally contains a version number for the
control.
DATA Specifies a file that is used by the ActiveX
control. For example, a Multimedia control
uses .avi (video) and .wav (audio) files.
NAME This attribute identifies the control if it exists
inside a <FORM> and is submitted in the HTTP
method.
STANDBY Text that identifies the ActiveX control while it
is downloading or instancing.
ALIGN Specifies the placement of the ActiveX control
on the Web page. Align Values include:
Baseline, Center, Left, Middle, Right,
TextBottom, TextMiddle and TextTop.
HEIGHT, WIDTH Height and Width parameters in pixels.
BORDER, HSPACE, VSPACE Border width and padding parameters.

The Internet Download Service


The Internet Download Service (IDS) is the process by which ActiveX controls are downloaded to a client
machine and registered. When the browser opens a Web page and encounters an <OBJECT> tag, it uses the
value of the CLASSID attribute to determine whether the component is already registered on the client
machine, and if the version is up to date. If the ActiveX control is not found, or if it is out of date, then a
new version of the control needs to be downloaded to the client machine.

116
Client-Side Programming with Visual Basic

The specific steps of the IDS are as follows:

 The browser encounters an <OBJECT> tag.


 The browser reads the CLASSID attribute (GUID) and checks the Windows Registry to determine if the
control is already registered on the client machine, and if it is the correct version. To enable version
checking, the CODEBASE attribute should contain the version information appended to the URL, as in:

<OBJECT
CODEBASE=[Link]/[Link]#version=1,0,0,2

/OBJECT>

 If the control is not already registered, or if the version must be updated, then the browser makes a call
to the Windows API function called GoGetClassObjectFromURL. The control's CODEBASE
information is passed in the function call. The function will asynchronously download the control and
register it to the client machine. (Here is a trick: You can set #version equal to –1,-1,-1,-1 to
ensure that the ActiveX control is downloaded and re-registered every time the <OBJECT> tag is
encountered by the browser. This ensures that you are always using the most current version of the
control).

You will face potential security risks when downloading ActiveX controls from the Web, because the
controls must be registered to a client machine. The IDS does not check whether the downloaded control is
certified as safe. By "safe" we mean that the control comes from a trusted source and that it will not corrupt
the client machine in any way. Safety screening is provided by the browser, which uses security certificates
and digital certificates to screen for potentially damaging controls. This technology is discussed in further
detail in Chapter 5.

Using the ActiveX Control Pad


ActiveX Controls are usually not useful until activated by setting properties and calling methods on the
control. You can manipulate ActiveX Controls both at design-time (using property pages, for example) and
at run-time (using script). The ActiveX Control Pad makes it easy for you to work with ActiveX controls,
and allows you to:

 Insert ActiveX controls on a Web page


 Set properties at design–time
 Add script to manipulate the control at run-time.

The ActiveX Control Pad is available for download at:


[Link]

 To illustrate the ActiveX Control Pad, we will create a simple front-end to the SalaryCalculator
class listed earlier. You will design the front-end using Microsoft Forms 2.0 ActiveX controls, which
ship with Internet Explorer, and are a group of familiar user interface controls, such as textboxes and
command buttons. We will use the Script Wizard to implement code in the event procedures raised by
the controls.

117
Chapter 4

Install the ActiveX Control Pad and run it from the Programs menu. The Control Pad opens to a new HTML
page.

Select Edit | Insert ActiveX Control. You will see a dialog box with a list of available ActiveX controls:

Insert a CommandButton control, and you will see the following entry in the HTML pane:

<OBJECT ID="cmdOK" CLASSID="CLSID:D7053240-CE69-11CD-A777-00DD01143C57"


STYLE="TOP:94pt;LEFT:94pt;WIDTH:78pt;HEIGHT:16pt;TABINDEX:5;ZINDEX:5;">
<PARAM NAME="Caption" VALUE="Calculate">
<PARAM NAME="Size" VALUE="2752;564">
<PARAM NAME="FontCharSet" VALUE="0">
<PARAM NAME="FontPitchAndFamily" VALUE="2">
<PARAM NAME="ParagraphAlign" VALUE="3">
<PARAM NAME="FontWeight" VALUE="0">
</OBJECT>

Next, you should see a blue cube in the left margin of the code pane next to this code listing. If you click on
this cube it will bring up the control in design-time view with its property sheet. You can set the properties
here, just like in Visual Basic.

Insert two textboxes, a command button and


descriptive labels, so that the layout resembles
this screenshot:

118
Client-Side Programming with Visual Basic

The final HTML code listing for the remaining controls (excluding the CommandButton control) appears
below. You can read the property settings for each control directly from this listing. If we were writing this
code in straight HTML, we would need to use tables to align the controls. But by using ActiveX controls,
we can specify the dimensions directly in the <OBJECT> tag.

<BODY>
<OBJECT ID="Label1"
CLASSID="CLSID:978C9E23-D4B0-11CE-BF2D-00AA003F40D0"
STYLE="TOP:8pt;LEFT:8pt;WIDTH:94pt;HEIGHT:16pt;ZINDEX:0;">
<PARAM NAME="Caption" VALUE="Salary Calculator">
<PARAM NAME="Size" VALUE="3316;564">
<PARAM NAME="FontEffects" VALUE="1073741825">
<PARAM NAME="FontHeight" VALUE="200">
<PARAM NAME="FontCharSet" VALUE="0">
<PARAM NAME="FontPitchAndFamily" VALUE="2">
<PARAM NAME="FontWeight" VALUE="700">
</OBJECT>
<OBJECT ID="Label2"
CLASSID="CLSID:978C9E23-D4B0-11CE-BF2D-00AA003F40D0"
STYLE="TOP:39pt;LEFT:8pt;WIDTH:70pt;HEIGHT:16pt;ZINDEX:1;">
<PARAM NAME="Caption" VALUE="Enter your salary:">
<PARAM NAME="Size" VALUE="2469;564">
<PARAM NAME="FontCharSet" VALUE="0">
<PARAM NAME="FontPitchAndFamily" VALUE="2">
<PARAM NAME="FontWeight" VALUE="0">
</OBJECT>
<OBJECT ID="Label3"
CLASSID="CLSID:978C9E23-D4B0-11CE-BF2D-00AA003F40D0"
STYLE="TOP:62pt;LEFT:8pt;WIDTH:70pt;HEIGHT:16pt;ZINDEX:2;">
<PARAM NAME="Caption" VALUE="Enter inflation rate:">
<PARAM NAME="Size" VALUE="2469;564">
<PARAM NAME="FontCharSet" VALUE="0">
<PARAM NAME="FontPitchAndFamily" VALUE="2">
<PARAM NAME="FontWeight" VALUE="0">
</OBJECT>
<OBJECT ID="TxtSalary"
CLASSID="CLSID:8BD21D10-EC42-11CE-9E0D-00AA006002F3"
STYLE="TOP:39pt;LEFT:78pt;WIDTH:109pt;HEIGHT:16pt;TABINDEX:3;ZINDEX:3;">
<PARAM NAME="VariousPropertyBits" VALUE="746604571">
<PARAM NAME="Size" VALUE="3845;564">
<PARAM NAME="FontCharSet" VALUE="0">
<PARAM NAME="FontPitchAndFamily" VALUE="2">
<PARAM NAME="FontWeight" VALUE="0">
</OBJECT>
<OBJECT ID="TxtIRate"
CLASSID="CLSID:8BD21D10-EC42-11CE-9E0D-00AA006002F3"
STYLE="TOP:62pt;LEFT:78pt;WIDTH:109pt;HEIGHT:16pt;TABINDEX:4;ZINDEX:4;">
<PARAM NAME="VariousPropertyBits" VALUE="746604571">
<PARAM NAME="Size" VALUE="3845;564">
<PARAM NAME="FontCharSet" VALUE="0">
<PARAM NAME="FontPitchAndFamily" VALUE="2">
<PARAM NAME="FontWeight" VALUE="0">
</OBJECT>
</BODY>

119
Chapter 4

Now it's time to implement the SalaryCalculator code. Select Tools | Script Wizard to open the
Script Wizard. On the left you see an event pane, which shows the constituent controls. Locate "cmdOK"
(the CommandButton control), and click on the sign to view all of the event procedures for this control.
Select the "Click" event, and toggle the "Code View" option button on. (Code View allows you to write
customized VBScript or JavaScript, while List View does not). Your screen should appear like this:

Add the following code listing to the cmdOK_Click() event procedure in the code pane:

On Error Resume Next

Dim y
Set y = New SalaryCalculator
[Link] = [Link]
[Link] = [Link]
[Link] = 1.5

If [Link] <> 0 Then


If [Link]=13 Then MsgBox "Error 13: Empty input is invalid" & Chr(13) & _
"Please enter valid input", 16, "Invalid Input"
If [Link]<>13 Then MsgBox "Error " & [Link] & ": " & _
[Link] & Chr(13) & _
"Please enter a valid " & [Link], 16, "Invalid Input"
Else
MsgBox "Your new salary is " & FormatCurrency([Link]) & _
", based on an IRate of " & _
[Link] & "%" & Chr(13) & "and a multiplier of 1.5", 64, "New Salary"
End If

120
Client-Side Programming with Visual Basic

Close out of the Script Wizard and add the class definition to the <HEAD> section:

<SCRIPT LANGUAGE="VBScript">
<!--
Class SalaryCalculator
Public IRate, IMultiplier
Private varSalary

Property Get Salary


Salary = varSalary
End Property

Property Let Salary (varValue)


If varValue >0 Then
varSalary = varValue
Else
[Link] 6000, "salary", "Salary must be >$0."
End If
End Property

Function NewSalary()
NewSalary = varSalary*((1+(IRate*IMultiplier/100)))
End Function
End Class
-->
</SCRIPT>

Save the HTML file as [Link], then


open it up in Internet Explorer. You should see
the following:

Pressing the calculate button results in:

121
Chapter 4

As this example shows, using the ActiveX Control Pad is more than a convenience. You will want to avoid
manually inserting ActiveX controls for two good reasons:

 It is easy to mistype the CLASSID, not to mention it's tedious, and


 The Control Pad's graphical interface provides a versatile view of all the controls on a Web page, and
enables you to quickly scan available control properties and methods, set property values, and implement
code behind event procedures.

Keep in mind that this example is for illustrative purposes only, since you could accomplish the same thing
using straight HTML. We will be revisiting the ActiveX Control Pad in Chapter 5, when we use it to add a
custom control to a Web page with script.

Summary
This chapter demonstrated the many aspects to client-side programming, especially with the release of
Internet Explorer 5.0, which supports several client-side technologies, including ActiveX Scripting, XML,
and Scriptlets. DHTML, another important client-side technology, is covered in full in Chapter 6. These
technologies are changing the traditional client-server relationship on the Web. By bringing a higher level
of sophistication to the client-side, these technologies are reducing client dependence on the server. Today,
Web applications do more and perform better. ActiveX is a key player in Microsoft's vision for the future
direction of Web development technology. In the next chapter you'll see a start-to-finish approach for
deploying ActiveX components on the Web.

So to sum it up, in this chapter you should have learned:

 What ActiveX Scripting is and how you can implement it


 The new features in VBScript 5.0 and how to implement them
 The basics for implementing XML
 How to use and write Scriptlets
 How to implement ActiveX controls from within your Web page, using scripting
 How to use the ActiveX Control Pad to place ActiveX controls into your Web page

122
Client-Side Programming with Visual Basic

123
Chapter 4

124
Building Client-Side ActiveX
Controls

ActiveX controls are software components that are used as building blocks for applications. We introduced
component based software in Chapter 1, and discussed the advantages that this approach provides.
ActiveX controls encapsulate their functionality and logic behind a programmable public interface.
Developers can access the control's functionality by manipulating the interface. Many controls also expose
a visual interface, such as the Calendar control, while others, such as the Timer control, do not.

ActiveX controls always operate within a Container, which could include a Visual Basic form or a Web
browser. In fact, many controls function equally well both on the desktop and on the Web. The control itself
will look and behave the same regardless of what container it is sited in. However, each container type has
its own way of interacting with the control. A Web browser, for example, would use HTML and a scripting
language to manipulate a control. On the desktop, the same control could be added to a Visual Basic form
and manipulated with code.

Developers use controls to build their applications more quickly and efficiently, because controls save them
from having to code all the functionality themselves. A good ActiveX control can contribute to an
application in two ways. First, it provides out-of-the-box functionality, and a rich, programmable interface
for accessing the control. Second, if the control provides a visual interface, then it contributes directly to
the look and feel of the application. As with cars and electronics, the quality of an application is a direct
reflection of the quality of the controls that were used to build it.
Chapter 5

ActiveX is a key technology in the world of object-oriented programming, which has become popular
among Visual Basic developers in response to a growing need to make sophisticated applications easier to
develop, debug and maintain, especially by multi-person development teams. Component-based application
development allows complex applications to be broken out into self-contained units of code that can be
independently developed and inserted into the application framework. ActiveX components are also called
server components, because their purpose is to respond to, and service, client requests.

A further advantage of ActiveX is that it is a language-independent technology, and components may be


written and deployed in several development environments, including Visual Basic, Visual C++ and Visual
J++. As we saw in Chapter 4, ActiveX COM components can also be written directly for the Web using
Scriptlets (XML and VBScript together).

Understanding What ActiveX Is


It might be more appropriate to ask what ActiveX isn't, because these days, ActiveX appears everywhere.
ActiveX is a catchall term for any reusable, binary COM component. ActiveX components are COM
objects, which means that they implement standard interfaces, encapsulate their business logic and support
automation requests. These components include:

 ActiveX Controls (*.ocx)


 ActiveX DLLs (*.dll)
 ActiveX EXEs (*.exe)
 ActiveX Documents (*.vbd)

ActiveX Controls are components that always operate in a container, and usually expose a visual interface.
ActiveX DLLs are in-process components that provide classes and functions, but usually do not expose a
visual interface. ActiveX DLLs are useful for when you want to encapsulate business logic, but don't need
the overhead of a visual interface. ActiveX EXEs are out-of-process components and serve a similar
function to ActiveX DLLs, except that they function as stand-alone applications. Finally, ActiveX
Documents are complete applications that are designed to run in a browser. Visual Basic provides a wizard
to migrate existing Standard EXE projects to ActiveX Document projects. ActiveX Documents allow you to
quickly and easily migrate existing desktop applications to the Web.

Understanding ActiveX Controls


From this point forward, we will focus on ActiveX controls, as opposed to the family of components that
fall under the ActiveX umbrella. ActiveX controls fall under one of three types:

 Aggregate controls
 Sub-classed controls
 User controls

126
Building Client–Side ActiveX Controls

The aggregate control is the most common kind of control. Two or more existing controls combine into
one control, which aggregates, or combines, the interfaces of each constituent control. The sub-classed
control takes an existing control and extends its behavior in some way. For example, it may take a standard
textbox control and add a couple of custom properties. A user control describes any control that does not
rely on constituent or sub-classed controls. This kind of control is not common, because the development
environment of Visual Basic is very control-oriented, and it's difficult to code without them.

ActiveX controls are written for developers to use in building their own applications. A compiled control is
activated as soon as it is placed in a Container, such as a form or a browser. The ActiveX control is
activated whether the Container is in design-time or run-time mode, but the control does not always make
all of its properties equally available to write to in both modes. This might occur, for example, if the control
has certain property settings that affect its performance, and which should only be manipulated by the
developer at design-time. For the purposes of this discussion, we define the user of a control to be a
developer who has added your compiled control to their project, and is accessing it both at design-time and
at run-time, when they compile their own project.

The UserControl Object


When you open a new ActiveX Control project, a blank UserControl Designer loads to the screen. The
UserControl contributes to an ActiveX control project at two levels. On the one hand, you use it to
assemble the control's visual interface by adding constituent controls, just as you would add to a Visual
Basic form. (Note that non-visual ActiveX controls, such as the Timer control simply have nothing added to
the UserControl Designer). In addition, the UserControl is a special object whose interface is
incorporated into the public interface of the new ActiveX control. The UserControl object contributes
events that are raised at different stages throughout the control's lifetime. It also provides access to the
control's Container by way of the Extender object, which allows the control to adopt property values that
are set by the Container. The UserControl object's key interface members are:

Interface Member Description


Initialize Event This event fires each time an instance of the control is created.
Controls are instanced in design-time, when they are added to a
container (e.g., a form) and at run-time, when they are loaded.
InitProperties/ The very first time a control is instanced, the
ReadProperties Events InitProperties event fires. Usually, the initial properties
are written to the PropertyBag object. The
ReadProperties event fires at all subsequent times.
Usually, this event contains code that retrieves initial
properties from the PropertyBag object.
WriteProperties Event This event occurs at design-time when a control instance is
destroyed, prior to the Terminate event firing. This event
will only fire if a property setting has changed during design-
time.
Table Continued on Following Page

127
Chapter 5

Interface Member Description


Terminate Event This event occurs when the control instance is destroyed. When
a project is compiled, the design-time instance of the control is
destroyed, and is replaced by a new, run-time instance of the
control. Thus, the Terminate event fires when a project in
design mode is compiled, and an Initialize event immediately
follows.
AmbientChanged Event The UserControl object provides an Ambient object,
which contains properties that the Container object passes
on to the control, such as BackColor. This event fires if an
ambient property changes.
AsyncReadComplete Event The UserControl object supports asynchronous
downloading of data. This event fires when a download is
complete.
Extender Object This object is provided to allow the control to adopt selected
Container properties.
Hyperlink Property This property returns a Hyperlink object that provides
navigation services.

In summary, the UserControl object allows an ActiveX control to respond to its environment, to interact
with its Container and to manage its state. This list only touches on the detailed interface of the
UserControl object.

The ActiveX Control Interface


The ActiveX Control Interface is a complex mix of aggregated and custom members derived from three
sources:

 Aggregated interfaces of the constituent controls


 The UserControl Interface
 Custom Interface members that are coded into the control

128
Building Client–Side ActiveX Controls

ActiveX controls expose a public interface that can be manipulated by the control's user. They also have a
private interface that can be manipulated internally, but which is not available for outside manipulation.
However, a control may expose any private member as public, by mapping the private member to a public
one. For example, consider a control with a command button that raises a private Click event. When the
user of the control clicks on this button, the Click event is raised internally to the control, which then
executes any implemented code. The user will not see the Click event unless the control raises a public
event in response to the private event being raised.

For every private interface member that you choose to map as public, there are several more that you
shouldn't map. Clearly, you have to make choices to avoid cluttering the public interface. As we'll see, the
ActiveX Control Interface Wizard is a useful tool for selectively mapping private members as public.

An ActiveX control inherits the interfaces of its constituent controls. These contribute to the ActiveX
control's private interface, and also make up its visual interface, which gives the user something to interact
with. Some controls, such as the Timer control, do not provide a visual interface. Frequently, the control's
visual interface members are mapped to public interface members, because users like to have many
programming options with ActiveX controls. This requires extra work while creating the control, because
each constituent control has to be mapped individually.

Most of the UserControl interface members contribute directly to the ActiveX control's public interface.
The Initialize and ReadProperties events, for example, are important members of the public
interface. Finally, a control can have custom interface members, such as property procedures, custom
events, and functions. There is no rule as to whether custom members contribute to the ActiveX control's
public or private interface. This is your choice to make, as the control's developer.

129
Chapter 5

The term abstract interface refers to the collective set of properties, methods and events, both public and
private, that describe what the object is and does. All of the members we've discussed so far contribute to
the control's abstract interface. From the user's perspective, the ActiveX control presents a unified public
interface. From the developer's perspective, an ActiveX control provides an abstract interface of both public
and private members, which combine to provide the control's complete interface.

ActiveX controls are complicated components to create because of their peculiar, event-intensive interface,
which must be implemented so that the control can function effectively in both design-time and run-time
modes. But the good news is that developing controls for desktop applications does not differ much from
developing for Web applications. The biggest difference is that each environment provides a different type
of container, and so the options for interacting with the control are different. On the Web, for example,
ActiveX controls are manipulated using a scripting language, such as VBScript. In an Excel container,
Visual Basic for Applications is the available "scripting" language. This is of little importance because
wherever the COM standard is supported, ActiveX controls can be used. A well-designed ActiveX control
offers the user with a rich, programmable interface, but does not restrict the user to any one programming
method.

ActiveX Control Creation Using Visual


Basic
The software marketplace is brimming with hundreds of commercial ActiveX controls that provide many
different kinds of functionality. Examples include stock ticker controls and controls that provide Internet
capabilities. Most of these controls are reasonably priced and include unlimited, royalty-free run-time
licenses, so you can include the control in your applications and distribute it to as many users as buy your
software. Despite the choices, there are still times when you may need to develop your own custom
controls.

Visual Basic provides an excellent development environment for ActiveX controls, especially Version 6.0,
which we will focus on here, although I will attempt to accommodate Version 5.0 users as well. Visual
Basic allows multiple projects to be added to a group and opened simultaneously. This feature is invaluable
for debugging ActiveX controls, which only function inside a container. Visual Basic 6 extends your
options for debugging controls by allowing you to specify how the component will be launched, whether in
a browser or in another project. The Enterprise Edition of VB6 also provides a utility (not covered here)
called the ActiveX Control Test Container, which lets you test individual interface members with ease.

130
Building Client–Side ActiveX Controls

The ActiveX Control Project Type


ActiveX controls are created in their own project type, which provides a UserControl instead of a form.
The UserControl object is the base for the ActiveX control. It hosts constituent controls and contributes
its interface to the public interface of the ActiveX control.

Building the Sales Analyzer ActiveX


Control
Now that we've covered the theory behind ActiveX controls, it's time to create one of our own controls. The
best way to understand the complicated life of an ActiveX control is to jump in and build one. As with other
kinds of projects, you should not start coding until you have established the purpose of the control, and
have planned out its interface. In this chapter, we'll be building a "Sales Analyzer" ActiveX control, which
charts sales data. The steps involved in building the control are:

 Define the purpose of the control


 Define the control's abstract interface
 Define the control's visual interface
 Implement code behind the interface
 Debug and test the control.

131
Chapter 5

Defining the Sales Analyzer Control's


Purpose
To understand the purpose of the Sales Analyzer control, let's consider the following business scenario: A
large food distribution company uses an AS/400 mainframe application to manage its transactions and to
run nightly batch processes. Every night the system generates a summary of the previous day's sales by
customer account, and exports the data as a comma-delimited text file to the company's Windows NT Web
server. The next business day, employees can log on to the corporate intranet and use their browser to
display the sales data. Instead of displaying hard sales numbers, the Web page contains a Sales Analyzer
control to chart the data by selected customer account. Furthermore, the user is able to click on any chart
point to display a summary of the sales data.

The figure shows a sample Web page containing the Sales Analyzer control, with sales data already loaded
into the control. The Sales Analyzer control works as follows:

1. The control loads on the Web page, but is not yet populated with data.
2. The control exposes an ExtractFile property for the path to the file containing the sales data.
This property should be set on the Web page using a <PARAM> tag.

3. The user clicks the "Run Extract" button.

132
Building Client–Side ActiveX Controls

4. If the extract file is valid, then the control runs private procedures that open the extract file, and
loads the sales data. If the extract file is not found, then the control prompts the user to enter a valid
filename.

5. Once the sales data is loaded, the user can select any customer from the drop-down combo box. The
customer's sales data will automatically be charted.

6. The user can point and click on any chart point to see a summary of the sales data, including the
sales order ID, the amount of the sale, and the date the merchandise was shipped.

This description of how the control works is not exactly accurate in describing how the control sends
notifications the user. While it is possible for an ActiveX control embedded on a Web page to raise a
message box or input box, it is not very good style. A good programming rule of thumb is to have the
Container be responsible for all direct interactions with the user, which includes raising message boxes. So
instead of raising message boxes, the ActiveX control should be designed to raise custom events, which can
be trapped by scripting language procedures in the Web page. These procedures, in turn, determine the best
way to send a notification to the user.

Step 1: Starting the Project


Developing ActiveX controls directly for the Web is not an intuitive exercise for most people, so initially
we'll develop the Sales Analyzer control for the desktop. Once the control is debugged and compiled, we'll
insert it on a Web page for display in a browser.

To start developing the Sales Analyzer control, we need to set up the project files as follows:

1. Open Visual Basic and choose File | New Project. Double-click the ActiveX Control icon to
display the UserControl Designer.

2. Open Project | Project1 Properties and change the settings to match the screenshot below. The
control's threading model must be set to single-threaded to support the Microsoft Chart Control (one
of the constituent controls).

133
Chapter 5

A discussion of threading is beyond the scope of this chapter, so a simple description will be adequate. The
threading model determines how many threads per process are used to service requests to the ActiveX
control. Apartment-threaded controls employ several threads per process, and are well-suited to Internet
Explorer, which is itself multi-threaded. Single-threaded controls, however, provide only one thread per
process, and so may suffer lower performance because all calls have to be handled in sequence. The general
rule for VB components is to use apartment threading where possible, then all the rest is taken care of for
you behind the scenes.

3. Open Project | Components and set references to the Microsoft Chart Control and to the
Microsoft Common Dialog Control.

134
Building Client–Side ActiveX Controls

Rename UserControl1 to Sales, and rename the project file to [Link].

4. Use File | Add Project to add a Standard EXE project to the Project Explorer window. This will
serve as the test environment for our control before we migrate it to a web environment. Rename
Project1 to Test, and save the project files in a new directory called Analyzer, using the default
Group1 group project name. Make sure that you right click on Test and select the option "Set As
Startup" from the pop-up menu. The Project Explorer window should now look like:

135
Chapter 5

Step 2: Adding the Constituent Controls


Controls are added to the UserControl Designer in the same way as they are added to the Form Designer:
you simply drag-and-drop the controls onto the designer, and resize them as needed. The Sales Analyzer
control uses an MS Chart control, a Label control, a ComboBox control, and a CommandButton control.
Add these controls to the UserControl Designer, using the property settings shown in the table below.

Control (Name) Property Value


UserControl (Sales) Width, Height 6540, 5130

Label (lblTitle) Width, Height 6255, 255


Top, Left 120, 120
Caption Orders by Sales Amount ($)
Font MS Sans Serif, 8 pt, Bold
Alignment Center
MSChart (MSChart1) Width, Height 6255, 4095
Top, Left 480, 120
ComboBox (cboCustomers) Width, Height 3855, 315
Top, Left 4680, 840
CommandButton Width, Height 1095, 315
(cmdExtract)
Top, Left 4680, 4800
Caption &Run Extract

136
Building Client–Side ActiveX Controls

The UserControl designer should now look like this:

Step 3: Creating the ActiveX Control


Interface
The visual interface of the Sales Analyzer control is now in place, so the next steps are:

1. Decide which interface members to implement from constituent controls


2. Code additional interface members, such as property procedures, and
3. Add property pages.

Recall that the interfaces of each of the constituent controls are aggregated into the overall ActiveX control
interface. The Sales Analyzer control traps events from each of its constituent controls, so that it recognizes
when the user is taking an action. We can implement code behind the event procedures of any constituent
control, such as the Click event of the cmdExtract button. These interface members are private, so only
the ActiveX control can respond to them, and they do not contribute to the control's public interface. If we
want these private events to map to the public interface then we can do so by raising custom public events
from the private event procedures. Interfaces are useful because they limit the number of ways in which a
user can make requests of the ActiveX control. It is up to you, the developer, to decide which private
interface members to map as public.

137
Chapter 5

The public interface of the Sales Analyzer control will consist of two custom properties and two custom
events:

Interface attributes Description


ExtractFile property Sets the filename and path to the extract file that contains the
sales data.
ChartType property Sets the chart type to a 2D-bar chart or a 3D-bar chart.

FileStatus event Raised from the cmdExtract_Click event, which fires when
the user clicks the "Run Extract" button. The event argument is a
status code that indicates whether ExtractFile references a
valid extract file.
PointSelected event Raised directly from the MSChart1_PointSelected event,
which fires when the user clicks a data point on the chart. The
event arguments contain sales data specific to the selected data
point.

Notice that the control's public FileStatus event is raised from within the private Click event of the
cmdExtract constituent control. Similarly, the control's public PointSelected event is raised from
within the private PointSelected event of the MSChart1 constituent control. This is how private
interface members are mapped to the public interface.

The ActiveX Control Interface Wizard


The ActiveX Control Interface Wizard is a timesaving tool for creating a public interface from an often
complex, aggregated private interface. The wizard allows you to create custom members and to map private
interface members of constituent controls to the public interface of the ActiveX control. The wizard's job is
to auto-generate code based on your specifications. The wizard may be run any number of times, but you
should always run it as soon as you have added all the constituent controls and prior to implementing any
code. I have not noticed any ill effects from running the wizard against a "mature" control with lots of
implemented code.

The wizard has a number of dialog boxes to work through, but it will save you lots of coding time. You can
only run the wizard right after you have added the constituent controls (the visual interface) and you are
ready to create the control's public interface. The wizard helps you understand the process of creating an
ActiveX control interface, and how the private interface maps to the public interface. In short, the wizard is
a time-saver and a great learning tool. The steps for using the wizard for our control are as follows:

138
Building Client–Side ActiveX Controls

4. In Visual Basic 6, select Add-Ins | Add-In Manager and select the wizard as shown below:

5. Next, run the wizard from Add-Ins | ActiveX Control Interface Wizard. The first dialog after the
introduction in the wizard prompts you to select interface members of constituent controls that you
want to add to the main control's public interface. Remove all of the members, since we want to
custom create our own interface.

139
Chapter 5

6. The "Create Custom Members" dialog allows you to create custom public interface from scratch.
Click the New… button to add new properties, methods and events, as shown:

We need to add the two properties and two events that were mentioned above: the ExtractFile and
ChartType properties, and the FileStatus and PointSelected events. The dialog box should look
like the screenshot below when you are complete:

140
Building Client–Side ActiveX Controls

7. The next dialog box called "Set Mapping" allows you to map public interface members to the private
interface members of constituent controls. We'll map the public PointSelected event to the
private PointSelected event of MSChart1, and the public FileStatus event to the private
Click event of cmdExtract:

141
Chapter 5

8. The "Set Attributes" dialog box lets us set the attributes of the remaining unmapped public members.
If a public member is already mapped to a private member from a previous dialog, then it will not be
available now. Here we are also able to set whether an attribute may be set at runtime, design-time,
both, or even neither. Design-time only properties are intended solely for the developer, while
runtime properties are intended for both developer and user. In our case, we will set the
ChartType property to be available in design time only, for read and write operations. The
ExtractFile property will be available for read and write operations in design-time, but only for
read operations at runtime.

142
Building Client–Side ActiveX Controls

9. At the final dialog of the wizard, simply hit the Finish button to start generating code.

Step 4: Working from the Auto-Generated Code


As you might expect, the auto-generated code needs to be changed and enhanced. Sometimes you will need
to modify the arguments that are passed to methods and functions and you will almost always need to
implement custom business logic. The wizard does a good job of creating useful code without requiring
many cleanups. In order to create a customized public interface we have to add some features that the
wizard is not capable of generating, for example, enumerated constants and custom event arguments. The
additions and changes that we need to for [Link] are as follows:

 Add a UserControl_Initialize event


 Chang the arguments of the custom events, FileStatus and PointSelected
 Add enumerated constants for the ChartType property
 Add enumerated constants for the StatusCode argument of the FileStatus event
 Modify the InitProperties, ReadProperties and WriteProperties events, so that they
no longer use default values or constants.
 Delete default property settings generated by the wizard.

143
Chapter 5

Here is what the code listing looks like so far:

Option Explicit

'Property Variables:
Dim m_ExtractFile As String
Dim m_ChartType As ChartFormat

'Enumerations:
Public Enum Status
FileOK
FileEmpty
FileNotFound
End Enum

Public Enum ChartFormat


Bar3D
Bar2D
End Enum

'Event Declarations:
Event FileStatus(ByVal StatusCode As Status)
Event PointSelected(evtCompanyName As Variant, evtOrderID As Variant, _
evtSalesAmount As Variant, evtShippedDate As Variant)

Private Sub UserControl_Initialize()


'This event fires first at both design-time and runtime
With MSChart1
.ColumnCount = 1
.RowCount = 1
.RowLabel = ""
.Data = 0
End With
[Link] = False
End Sub

'Initialize Properties for User Control


Private Sub UserControl_InitProperties()
m_ExtractFile = ""
m_ChartType = Bar2D
End Sub

'Load property values from storage


Private Sub UserControl_ReadProperties(PropBag As PropertyBag)
m_ExtractFile = [Link]("ExtractFile", "")
m_ChartType = [Link]("ChartType", "")
End Sub

'Write property values to storage


Private Sub UserControl_WriteProperties(PropBag As PropertyBag)
Call [Link]("ExtractFile", m_ExtractFile, "")
Call [Link]("ChartType", m_ChartType, "")
End Sub

'Properties:
Public Property Get ChartType() As ChartFormat
If [Link] Then [Link] 393
ChartType = m_ChartType
End Property

144
Building Client–Side ActiveX Controls

Public Property Let ChartType(ByVal New_ChartType As ChartFormat)


If [Link] Then [Link] 382
m_ChartType = New_ChartType
PropertyChanged "ChartType"
End Property

Public Property Get ExtractFile() As String


ExtractFile = m_ExtractFile
End Property

Public Property Let ExtractFile(ByVal New_ExtractFile As String)


m_ExtractFile = New_ExtractFile
PropertyChanged "ExtractFile"
End Property

'Events (not coded yet):


Private Sub cmdExtract_Click()
'RaiseEvent FileStatus() 'Not coded yet
End Sub

Private Sub MSChart1_PointSelected(Series As Integer, DataPoint As Integer,


MouseFlags As Integer, Cancel As Integer)
'RaiseEvent PointSelected() 'Not coded yet
End Sub

The highlighted code shows the changes we've made from the original code produced by the wizard.

Step 5: Coding the Business Logic


Now that the public interface is in place we can move on to implementing business logic. The interface
definition is just a framework of methods, properties and events, and so far there is very little that these
interface members are actually doing. Business logic must be implemented behind each interface member in
order to process the requests that the members are expected to handle. For example, when the user wishes to
view sales data, she selects a customer from the combo box then clicks the control's single command button
labeled Run Extract. When the user clicks this button, the control must gather sales data for the selected
customer from the database. The Click event of the command button in turn calls a private procedure
called GetData, which actually performs the database operation.

Coding the Data Loading Procedures


The sample data set for the Sales Analyzer control comes from the "Order Details" query of the Northwinds
database. The query provides customer orders by sales amount, and is ordered by shipping date, not
customer, so that repeat customers are scattered throughout the data file. I created a comma-delimited
extract file by exporting the query results to a text file called [Link]. The file contains four fields:
OrderID, SaleAmount, CompanyName and ShippedDate. Here are the first few records of the file:

145
Chapter 5

SaleAmount,OrderID,CompanyName,ShippedDate
"$7,390.20",10360,Blondel père et fils,34701
"$9,210.90",10372,Queen Cozinha,34708
"$2,900.00",10382,Ernst Handel,34715

The ActiveX control assumes that the data will only be in this format, and is not currently equipped to
handle exceptions. Switch over to [Link] in code view, and start a new code listing by dimensioning
3 variant arrays in the Declarations section of the form. These will hold data that has been retrieved from
the text file:

Private vSales() As Variant


Private vCustomers() As Variant
Private vBookmarks() As Variant

When the user clicks Run Extract, which, to our code, is the cmdExtract button, the control checks if
the ExtractFile property of the ActiveX control was set, and whether the file exists. This property may
be set directly at run time by direct assignment, or it may be set at design time using a property page which
we will be developing later in the chapter. Regardless of the outcome, the public FileStatus event is
always raised to communicate back to the user at runtime, using the enumerated type Status as an
argument. As you may recall:

Public Enum Status


FileOK
FileEmpty
FileNotFound
End Enum

Event FileStatus(ByVal StatusCode As Status)

This listing should look familiar because we added it immediately after running the wizard. There is no
need to add it to your code pane again.

The code behind the cmdExtract_Click event should now read:

Private Sub cmdExtract_Click()


'Purpose: Load the extract file

Dim nI As Integer

'Test the Extract File


If m_ExtractFile = "" Then
RaiseEvent FileStatus([Link]) 'ExtractFile property is empty
Exit Sub
ElseIf Dir(m_ExtractFile) = "" Then
RaiseEvent FileStatus([Link]) 'Extract File was not found
Exit Sub
Else
RaiseEvent FileStatus([Link]) 'Extract File OK
End If

Call GetData

146
Building Client–Side ActiveX Controls

'Populate combo
For nI = 1 To UBound(vCustomers)
Call [Link](vCustomers(nI))
Next nI

[Link] = 0
Call cboCustomers_Click

End Sub

If the Extract file is valid, then the cmdExtract_Click procedure calls the private GetData procedure,
shown below. GetData opens the sales data file and reads it into a private variant array called vSales.
This array is ordered by column then row, to accommodate the MSChart control, which expects data in
this order. Next, the GetData procedure examines vSales for unique customer names, and populates
them into the vCustomers array:

Private Sub GetData()


'Purpose:
'1. Read contents of '[Link]' into vSales()
'2. Add the customers to vCustomers()
'Note: Header row is assigned index of zero

Dim nI As Integer
Dim nJ As Integer
Dim blnFound As Boolean
Dim nCustomers As Integer

'Read the extract file into vSales()


nI = 0
Open m_ExtractFile For Input As #1
Do While Not EOF(1)
ReDim Preserve vSales(4, nI) As Variant
Input #1, vSales(0, nI), vSales(1, nI), _
vSales(2, nI), vSales(3, nI)
nI = nI + 1
Loop
Close #1

'Initialize
nCustomers = 1
ReDim vCustomers(nCustomers) As Variant
vCustomers(nCustomers) = vSales(2, 1)

'Assemble array of customers


For nI = 1 To UBound(vSales, 2)
For nJ = 1 To UBound(vCustomers)
If vCustomers(nJ) = vSales(2, nI) Then
blnFound = True
Exit For
End If
Next nJ
If Not blnFound Then
nCustomers = nCustomers + 1
ReDim Preserve vCustomers(nCustomers)
vCustomers(UBound(vCustomers)) = vSales(2, nI)
Else

147
Chapter 5

blnFound = False
End If
Next nI
End Sub

Coding the Charting Procedure


Once vCustomers has been filled, it can populate the control's drop-down combo box, cboCustomers.
If you refer back to the cmdExtract_Click event, you will see where this is done immediately
following the call to GetData. Once the combo box is populated, the user can click around in it to select
different customers. The cboCustomers_Click event implements code to automatically chart the
selected customer's sales data. Specifically, when the user clicks on a customer, code executes to retrieve
the customer's sales data from vSales, and to add it to the chart.

Because the customer sales data is scattered throughout the vSales array, the procedure must search
through the entire array to locate all the order entries for the selected customer. When the procedure locates
a relevant record, it checks the row number of the entry in vSales, and adds this row number to the
vBookmarks array. So the vBookmarks array simply points to the customer's sales data in vSales:

Private Sub cboCustomers_Click()


'Chart selected Customer
'Note: vSales() must have (column, row) order to work with MSChart control

Dim nI As Integer
Dim nJ As Integer

Erase vBookmarks

With MSChart1
nJ = 1
.ColumnCount = nJ 'Update
.Column = 1

For nI = 1 To UBound(vSales, 2)

If vSales(2, nI) = [Link] Then


'Store position in vBookmarks()
ReDim Preserve vBookmarks(nJ) As Variant
vBookmarks(nJ) = nI
'Add to chart
.RowCount = nJ
.Row = nJ
.RowLabel = vSales(1, nI)
.Data = vSales(0, nI)
nJ = nJ + 1
End If

Next nI

148
Building Client–Side ActiveX Controls

End With

[Link] = True

End Sub

Step 6: Coding the Public Events


Once the chart displays, the user can select a point and display summary sales information. The
PointSelected event of the MSChart control maps to the custom PointSelected event of the Sales
Analyzer control. The custom event's arguments are elements of the sales data records. Recall:

Event PointSelected(evtCompanyName As Variant, evtOrderID As Variant, _


evtSalesAmount As Variant, evtShippedDate As Variant)

The event is called from:

Private Sub MSChart1_PointSelected(Series As Integer, DataPoint As Integer, _


MouseFlags As Integer, Cancel As Integer)

'Raise an event with summary information on the selected data point


nK = vBookmarks(DataPoint) 'Get current position in vSales()
RaiseEvent PointSelected(vSales(2, nK), vSales(1, nK), vSales(0, nK), vSales(3,
nK))

End Sub

The control needs property pages before it is completely ready for shipping, but we'll pause for a moment to
deploy our control on a form and see what a splash it makes.

Step 7: Testing the Sales Analyzer Control


on a Form
Testing our new Sales Analyzer control is a simple process:

1. Close the Sales UserControl Designer by clicking on the X button in the Control-menu box. This
enables the UserControl icon in the ToolBox, essentially putting it into runtime mode, although the
Test project remains in design time mode.

2. Switch to the Test project and add the Sales Analyzer control to Form1. If the UserControl icon is
still grayed out, then you need to close the UserControl Designer again. Form1 should now look like
this:

149
Chapter 5

3. Right-click on the embedded control to open its property page, and set the ExtractFile and
ChartType properties using the browse button and option buttons, respectively. The property page
is the only way that you can set these (Test project) design time properties.

4. Implement code behind the control's public events. Try adding the following simple code listing
behind Form1:

Private Sub Sales1_FileStatus(ByVal StatusCode As [Link])


'Purpose: Trap event that shows Extract File status

Select Case StatusCode


Case [Link]
'File is valid: no action
Case Else
[Link] = InputBox("The ExtractFile property was not set or" & _
"is invalid." & vbCrLf & "Please enter a valid path, then click the " & _
"extract button:", "Extract File Invalid")
End Select

End Sub

150
Building Client–Side ActiveX Controls

Private Sub Sales1_PointSelected(evtCompanyName As Variant, _


evtOrderID As Variant, _
evtSalesAmount As Variant, _
evtShippedDate As Variant)

MsgBox "Order #" & evtOrderID & " for " & Format(evtSalesAmount, "Currency") & _
vbCrLf & "Shipped on " & Format(CDate(evtShippedDate), "mm/dd/yyyy"), _
vbInformation, evtCompanyName

End Sub

5. Start the Test project, and click the Run Extract button. The control should populate with data. If
the filename property happens to be invalid, you will be prompted with an input box to provide a
valid file.

151
Chapter 5

6. Click on any data point to see a summary of the sales data.


7. When you are satisfied that the control works, select File | Make [Link] to compile the
control and register it to your system.

Step 8: Adding Property Pages


Property pages provide a user-friendly way to set control properties at design-time. They allow a developer
to set a control's properties through dialog sheets instead of through the Properties window in Visual
Basic's Integrated Development Environment (IDE). Property pages are opened by right-clicking on a
control and selecting "Properties" from the pop-up menu. If the control does not support property pages,
then in design-time this action will activate the standard Properties window that we're used to seeing in the
Visual Basic Integrated Development Environment (IDE).

The next figure shows the property pages for the MSChart control as they appear at design-time. These
pages are shown for illustration purposes only, and it is important to point out that you will only see these
pages if you open the MSChart control independently. As soon as you aggregate the MSChart control into a
User control, its property pages are no longer available, since its role now is to contribute to the User
control, not to act as an independent control. Property pages in a User control are entirely the responsibility
of the developer to create.

152
Building Client–Side ActiveX Controls

Property pages completely customize how properties can be set, in contrast to the standard Properties
window, which has limited display options. Property pages provide a code pane for Visual Basic code,
which allows you to validate user input and make the experience more interactive than the standard
Properties window.

As an exercise we will create a property page for the Sales Analyzer control, focusing on the ChartType
and ExtractFile properties, both of which can be set at design-time. The property page limits the
ChartType property to one of two types, and lets the developer select the ExtractFile using a browse
button. The final view of the compiled property page is shown below

153
Chapter 5

Create a property page for the Sales Analyzer control as follows:

1. Open a new property page in [Link] using Project | Add Property Page. You should see a
new folder called Property Pages open within the Analyzer project window, and a property page icon
appear.

2. Change the (Name) property of the page to AnalyzerProps.


3. Add the controls as shown in the above figure, and as shown in the table below. You will notice that
the compiled view has 3 additional buttons at the bottom of the page (OK, Cancel and Apply) as
well as a Tab control with 'AnalyzerProps' as the caption. These are added automatically, but will
not appear in design view.

Control (Name) Property Value

Label (LblExtractFile) Width, Height 2700, 240


Top, Left 240, 240
Caption Extract File:
TextBox Width, Height 3780, 330
(TxtExtractFile)
Top, Left 600, 240

154
Building Client–Side ActiveX Controls

Control (Name) Property Value


Frame (Frame1) Width, Height 3855, 1335
Top, Left 1200, 240
Caption Chart Type
OptionButton (OptChart) Width, Height 1815, 375
Top, Left 360, 240
Caption 3D Bar Chart
OptionButton (OptChart) Width, Height 1815, 375
Top, Left 1920, 480
Caption 2D Bar Chart
CommandButton Width, Height 1095, 375
(cmdBrowse)
Top, Left 600, 4200
Caption &Browse
CommonDialog Top, Left 1680, 4560
(CommonDialog1)

4. Add the following code listing to the property page, in order to associate the Sales Analyzer control
attributes with the textbox and option button controls on the property page:

Private Sub txtExtractFile_Change()


Changed = True
End Sub
Private Sub optChart_Click(Index As Integer)
Changed = True
End Sub
Private Sub PropertyPage_ApplyChanges()
SelectedControls(0).ExtractFile = [Link]
If optChart(0).Value = True Then
SelectedControls(0).ChartType = 0
Else
SelectedControls(0).ChartType = 1
End If
End Sub
Private Sub PropertyPage_SelectionChanged()
[Link] = SelectedControls(0).ExtractFile
If SelectedControls(0).ChartType = 0 Then
optChart(0).Value = True
Else
optChart(1).Value = True
End If
End Sub

155
Chapter 5

Private Sub cmdBrowse_Click()


'Purpose: Browse for sales data text files

Dim CancelError As Boolean

On Error GoTo ErrHandler


CancelError = True ' Set filters.
[Link] = "Text Files (*.txt)|*.txt" ' Specify default filter.
[Link] = 2 ' Display the Open dialog box.
[Link] ' Call the open file procedure.

'Open new Extract File


[Link] = [Link]

Exit Sub
ErrHandler:
'User pressed Cancel button.
Exit Sub
End Sub

The simple code listing manages the association between Sales control properties and the property page
controls. When the user first opens the property page, the SelectionChanged event fires, which assigns
the current Sales property settings to the property page controls. When the user types in the textbox, or
clicks one of the option buttons, the Changed property of the Property Page object is set to True. Once
the Apply button is clicked, the ApplyChanges event fires, and the property page controls are used to set
the Sales control properties. If the user clicks the OK button to close the property page, then the
ApplyChanges event only fires if the Changed property equals True.

This wraps up our discussion of property pages and almost wraps up our development tasks for the Sales
Analyzer control. As a finishing touch we should add descriptions of each public interface member using
the dialog box in Tools | Procedure Attributes. These descriptions will show up in Visual Basic's Object
Browser. For example, for the ChartType property:

This is a good time to compile the control again, to incorporate the property pages into the OCX file. If
you've been following the steps outlined here, then you already compiled the control once, at the end of
Step 7. Before recompiling you should confirm that Binary Compatibility is set, in order to maintain a
single Global Unique Identifier (GUID), which uniquely identifies the component in the client computer's
registry. It is especially important to maintain a consistent GUID if the ActiveX control will be deployed on
a web page (see Step 9).

156
Building Client–Side ActiveX Controls

To set Binary Compatibility:

 Copy the current OCX file to a new directory called \Compatibility. I usually place this directory as a
subfolder of the directory where the VB source files reside.
 Open Project | Properties and switch to the Component tab.
 Select the radio button for Binary Compatibility
 Type or browse to the location of the compatibility OCX file.
 Hit Apply or OK to commit the new settings.
 Finally, select File | Make [Link] to compile the control and register it to your system.

Step 9: Testing the Sales Analyzer Control


on a Web Page
We can easily add the Sales Analyzer Control to a Web page using the ActiveX Control Pad, which was
introduced in Chapter 4. Using the Script Wizard we can quickly add VBScript code to the FileStatus
and PointSelected events. Use the following steps:

157
Chapter 5

1. Open the ActiveX Control Pad and select Edit | Insert ActiveX Control.
2. Select [Link] from the list of available, registered ActiveX controls. If it does not show
up, browse to the location of the [Link] file, and select it there.

3. The control will appear in design mode. Right-click on the control to open the property page and set
the ExtractFile and ChartType properties. You can also set these properties in the floating
Properties window. Click the close button on the designer when you are finished.

4. Next, open the Script Wizard from Tools | Script Wizard. You will see the interface members of
the Sales1 control displayed in an Explorer-type view. Select the FileStatus event in Code
View, and add the code as shown below:

5. Select the PointSelected event in Code View, and add the code as shown here:

158
Building Client–Side ActiveX Controls

Click OK, and you should see the following listing in the code pane (except for the CODEBASE attribute,
which I added):

<HTML>

<HEAD>
<TITLE>Sales Analyzer</TITLE>
</HEAD>

<BODY>
<H2>Sales Analysis </H2>
<H4>View the latest sales data using the Sales Analyzer Control</H4>

<OBJECT ID="Sales1" WIDTH=436 HEIGHT=343


CLASSID="CLSID:9C352639-DA4C-11D2-BB19-000000000000"
CODEBASE="[Link]#version=1,2,0,0">
<PARAM NAME="_ExtentX" VALUE="11536">
<PARAM NAME="_ExtentY" VALUE="9049">
<PARAM NAME="ExtractFile" VALUE="c:\projects\wrox\analyzer\[Link]">
<PARAM NAME="ChartType" VALUE="1">
</OBJECT>

<SCRIPT LANGUAGE="VBScript">
<!--

Sub Sales1_FileStatus(StatusCode)
Select Case StatusCode
Case 0
'File is valid: no action
Case Else
[Link] = InputBox("The ExtractFile property was " & _
"not set or is invalid." & vbCrLf & "Please enter a valid " & _
"path, then click the extract button:", "Extract File Invalid")
End Select
end sub

159
Chapter 5

Sub Sales1_PointSelected(evtCompanyName, evtOrderID, evtSalesAmount,_


evtShippedDate)
MsgBox "Order #" & evtOrderID & " for " & FormatCurrency(evtSalesAmount) & _
vbCrLf & "Shipped on " & FormatDateTime(evtShippedDate, 2), _
vbInformation, evtCompanyName
end sub

-->
</SCRIPT>
</BODY>

</HTML>

6. Finally, save the Web page as [Link], and open it in Internet Explorer. The control functions
the same in a browser container as it does in a form container.

ActiveX Packaging and Deployment


Distributing your control to users involves a two-step process of first packaging your component, then
deploying it. Visual Basic provides different options for packaging components. Visual Basic 6 provides a
wizard for packaging your control into a compressed cabinet file (.cab) that users can download directly
from the Web. You can include all of the support files in the cabinet file, or you can specify that some or all
of the support files be downloaded from another URL. For example, an ActiveX control always requires the
Visual Basic runtime DLL, which is well over 1 MB in size. You can specify that the runtime file should be
downloaded from Microsoft's Web site, thereby dramatically decreasing the size of the cabinet file.

You have different options for deploying your control. You can make it available on your Web page for
download. Alternatively, you could go commercial, and sell your control in a shrink-wrapped box. Either
way, you need to consider adding a license key, to ensure that only registered developers use your control.
Visual Basic makes it very easy to add a license key.

As a professional developer, you are responsible for distributing software that does not contain any
potentially harmful content that could disrupt a user's Registry or interfere with their system files. Code
signing or Digital Signing, is a technology that certifies to the control's user that you are a trusted software
provider. Although digital signing does not guarantee per se that your content is safe to run, it does identify
you as a known, trusted developer who is registered with a Certificate Authority. Many developers poorly
understand Digital signing, but its popularity is on the rise in response to the proliferation of ActiveX
content on the Internet.

Packaging your ActiveX Control


Visual Basic 6 provides a Packaging and Deployment Wizard for creating a cabinet file for your ActiveX
control that bundles the OCX and all support files into a single compressed file. Run the Wizard as follows:

160
Building Client–Side ActiveX Controls

1. In Visual Basic 6, select Add-Ins | Add-In Manager and load the Package and Deployment Wizard.
2. Open the ActiveX control project then run the wizard from Add-Ins | Package and Deployment
Wizard.

3. Click the Package button to create a new cabinet file.


4. Select "Internet Package" as the Package Type.
5. Choose a location for the package files.
6. Include all of the check-marked files in the package.
7. Mark the component as safe for initialization and scripting from the drop-down items. "Safe for
scripting" means that the component can be safely accessed using an ActiveX scripting language,
such as VBScript. "Safe for initialization" means that the component can be instanced with no
potential harm to the user's system. You should only mark the component as "Safe for
initialization" if it does not interact with the user's file system.

161
Chapter 5

8. Finally, give the package a name, such as "Analyzer CAB", and click Finish.

Deploying your ActiveX Control


Once you have packaged your control, you'll want to make it available for others to install and use. The
deployment wizard in Visual Basic 6 simplifies the process of uploading your production-ready control files
to a storage location on a Web server. If you are using Visual Basic 5 you will need to upload your files
manually. The deployment wizard lets you specify a storage location on a remote server and an upload
method, including FTP and HTTP Post. If you created a server-side install package, then you can request
that the deployment wizard unpack and install the files after they have been uploaded to the Web server.

The steps for deploying an ActiveX control package to a Web server are:

1. Open the ActiveX control project then run the wizard from Add-Ins | Package and Deployment
Wizard.

2. Click the Deploy button.

3. Select a Package to deploy.

162
Building Client–Side ActiveX Controls

4. Select Web Publishing as the Deployment Method.

163
Chapter 5

5. Select the Items to Deploy. Note that the Package wizard automatically created a basic HTML page
to host your control. The page inserts your control using an <OBJECT> tag.

6. Choose a destination URL and a Web publishing protocol.

7. Click the Finish button to save a script for future Web server deployments.

Licensing ActiveX Controls


Licensing helps you protect the investment of time, money and research that you have put into developing
your ActiveX control. Licensing prevents another developer from using your control in their project without
your permission. To add a license key, simply put a check against Require License Key in the Project |
Project Properties dialog box. When you compile the project, the wizard will generate a license key with
an LPK filename extension. The LPK file is separate from the OCX file; however, the LPK file must be
registered on the same machine as the OCX file in order for someone to use your control.

If someone simply copies a licensed OCX file over to their machine without the LPK file then they will not
be able to use the OCX file, either in design-time or run-time modes

164
Building Client–Side ActiveX Controls

Container applications such as Visual Basic and Microsoft InterDev will not load a licensed control in
design time unless they can match a local, registered license key with the control. If you wish to provide
design-time licensing rights to a developer, then you should provide them with a setup program for your
control that includes the license file. Keep in mind that the Packaging and Deployment wizard will not
automatically add license files to a setup program or cabinet file, so you must add these yourself in the
Included Files wizard dialog

Licensed ActiveX controls that are deployed on a Web page have a further requirement. Microsoft's Internet
Explorer requires that all components on a single Web page be covered under a license package that
contains runtime-licensing information on all the components. You can think of it as an array of CLSID and
license key pairs. To create a license package, you need to use the utility LPK_TOOL.exe, which can be
found in the Tools directory on the Visual Basic CD. Once you've created this file, place it in the same
directory where the HTML page resides. You also need to include a reference in the HTML page to the
Internet Explorer Licensing Manager ActiveX object. The following code listing shows a sample Web page
that uses the Sales Analyzer control:

<! Reference to the IE Licensing Manager !>


<OBJECT CLASSID="clsid:5220cb21-c88d-11cf-b347-00aa00a28331">
<PARAM NAME="LPKPath" VALUE="[Link]">
</OBJECT>

<! Reference to the Sales Analyzer Control !>


<OBJECT CLASSID="CLSID:9C352639-DA4C-11D2-BB19-000000000000" WIDTH=100 HEIGHT=25>
CODEBASE="[Link]#version=1,2,0,0">
<PARAM NAME="_ExtentX" VALUE="11536">
<PARAM NAME="_ExtentY" VALUE="9049">
<PARAM NAME="ExtractFile" VALUE="c:\projects\wrox\analyzer\[Link]">
<PARAM NAME="ChartType" VALUE="1">
</OBJECT>

If your licensed control is deployed on a web site in this manner then there is nothing stopping an
unauthorized user from downloading the control, using it, and even redistributing it. If you need to prevent
an unauthorized user from downloading your control then you will need to implement security to restrict
access to the web page where the control resides. Another alternative is to distribute just the control over
the web site, and to distribute the licensing package independently, either from a secure web site, or else
directly to the user. So while anyone can download the control binary source code, Internet Explorer will
not create an instance of control unless it can match the license key.

Other developers who use your licensed control in developing their own need to make special distribution
arrangements to accommodate licensing restrictions. The options are:

 Require that all users of the new control have a licensed version of your control on their machine.
 Distribute your license key with the new control, with your permission and a shared revenue agreement.
 None of the above if you give the developer unlimited run-time distribution rights.

165
Chapter 5

Digital Signing and Authenticode


Digital Signing is a confusing topic for many developers, but with the proliferation of ActiveX controls on
the Internet, it's a critical one to understand. This section provides you with an overview of the technology
and an introduction to the buzzwords. However, since information changes rapidly, I will also include
online references that you should consult for the most up-to-date information on Digital signing.

What is Certification?
As we will discuss in Chapter 6, before using a control, you need to ensure that the control is authentic and
has integrity. Enter the Certificate Authority (CA), which is an organization that issues Digital
Certificates to developers who have gone through an application process and are now certified as trusted
sources. There are several CAs to choose from, but Microsoft currently recommends VeriSign:
[Link]

There are two types of certification you can receive. Each is valid for one year before it must be renewed:

1. Class 2 Certification is for "Individual Developers", and costs $20 per year. The application process
is relatively simple and it takes about 5 business days to receive your certificate.

2. Class 3 Certification is for commercial developers and costs $400 per year. The lengthy application
process requires the developer to:

 Prove their employment status


 Make "The Pledge" that their software is not potentially harmful
 Submit a Dun & Bradstreet Rating that certifies that their company is solvent.

Once you have been approved for certification, the CA will provide you with two files:

 The Software Publisher Certificate (SPC), which identifies the software publisher and provides their
public key. The SPC provides an X.509 certificate that is distributed with the published software.
 The private encryption key that the publisher uses to generate a digital signature for their software.

How Does Digital Signing Work?


As we discussed in Chapter 2, when a developer is ready to publish their software to the Web, they use the
Authenticode utilities (available from
[Link] and currently in
version 2.0) their private encryption key and their SPC to digitally sign their software. You aren't limited to
just signing ActiveX controls. In addition to OCX files, you can sign EXE, DLL and CAB files. The signing
process works as follows:

166
Building Client–Side ActiveX Controls

1. Compile the software component.


2. Locate your private key and SPC files. (Microsoft recommends that you store the files on a
removable medium, such as a floppy disk, in a secure location).

3. Open an MS-DOS Window and navigate to the directory where the SignCode utility is located.
4. The SignCode utility uses the following syntax, which you type at the command line:

signcode –spc SPC –v PVK –n ControlName –i URL -$ commercial –t


[Link] –x ControlName

SPC is the SPC filename, PVK is the private key filename, ControlName is the name of the software
component, and URL is the home page of your company. The –t switch adds a timestamp to the
component. This feature ensures that once your component has been signed, it will continue to be stamped
as secure, even if you let your certificate expire after one year. The –x switch indicates that the component
has already been signed once, and that you are re-signing it in order to add a timestamp. A component must
also be resigned if it is recompiled. Here's a more specific example of using the SignCode utility:

signcode –spc a:\[Link] –v [Link] –n "Sales1" –i [Link] -$


commercial –t [Link] –x
"[Link]"

Authenticode provides utilities that generate test certificates, including a test SPC. So before you rush out
to get a real certificate from a CA, be sure to take advantage of test certificates to learn more about how the
signing process works.

Reading a Digital Signature


To get the full protection of digital signing, you need to set the security level in Internet Explorer to at least
medium. This level ensures that Internet Explorer will follow up the information provided by the digital
signature to verify that the software is from a trusted source and has not been altered. In fact, the medium
security setting, by default, will not allow you to download unsigned components (but the low setting will).
The high setting will not allow you to download an untrusted component at all.

When a user downloads a component that has been digitally signed, they receive a Security Warning prompt
that contains the following information:

 The name of the Certificate Authority


 The identity of the publisher
 A prompt asking if they want to continue downloading the software component.

167
Chapter 5

If the security setting is at least medium, Internet Explorer uses the digital signature to confirm the identity
of the publisher, and uses the public key to verify that the software has not been altered. If any problems
are found, or if the component is not signed, Internet Explorer will not permit the component to be
downloaded.

Clicking the More Info button on the Security Warning prompt gives you access to all the certificate
information.

Remember, no control is guaranteed to be safe, even one that comes from a trusted source, so use your
judgement about whether to deploy it. If there is any doubt, just say no, then research the control. On the
brighter side, if you find a publisher whom you are comfortable with, then you can add them to your list of
trusted publishers, and Internet Explorer will not prompt you for that publisher again, unless it finds that
the software was tampered with. Remember, if you have any doubt at all about the authenticity or integrity
of a software component then always avoid downloading it. You should also never use less than a medium
security level in Internet Explorer.

Code Signing Resources


Your best source for information on Authenticode and Digital signing is Microsoft's Web site. For an
excellent introduction to code signing see the article:
[Link]

Another good resource on these security topics is ASP/MTS/ADSI Web Security by [Link], ISBN:
0130844659

The Site Builder Network section on Security and Cryptography is a must-visit, at:
[Link]
[Link]#/workshop/security/[Link]

168
Building Client–Side ActiveX Controls

For a high-level Authenticode FAQ, visit VeriSign at:


[Link]

Summary
This chapter provided you with a hands-on look at how to create ActiveX controls and how to package and
deploy them for the Web. The example Sales Analyzer control illustrates how ActiveX controls can provide
a level of functionality that would be difficult to provide on the Web with other technologies. It is relatively
easy to leverage your existing understanding of desktop development in Visual Basic to the Web because
the coding methodology does not change for different containers (e.g., the browser versus a Visual Basic
form). However, you should not get lulled into a false sense of complacency, because distribution over the
Web has more complications than distribution for the desktop.

Topics such as licensing and digital signing are complicated and always changing, so your best source of
information will be the Internet. This chapter attempted to provide you with an overview of these complex
technologies, and hopefully a starting point from which to learn more. Whether you are a small, home-
grown development firm or a major software development company, every developer needs to think through
Web deployment issues and how to roll your components out in a way that protects the security of your
customers and the legal rights of developers like yourself.

In summary, this chapter introduced you to the following topics:

 ActiveX Control Creation using Visual Basic


 Distributing Controls to the Web
 Utilities that help you create, test and deploy your Control, including the ActiveX Control Pad and
the Package and Deployment Wizard
 Licensing and Digital Signing Issues

Component development is a changing topic, and I encourage you to keep up to date by visiting the
Component Development section of the Site Builder Network at:
[Link]
[Link]#/workshop/components/[Link]

In the next chapter, we're going to explore the advantages of the new Visual Basic DHTML Application,
which offers you a whole new range of flexible and powerful programming tools to take your applications
on to the web.

169
Chapter 5

170
Dynamic HTML Applications

What is a Dynamic HTML Application?


A Dynamic HTML (DHTML) Application is a type of Visual Basic 6 project that you can use to build
"smart" Web pages. It works in a similar way to the traditional Visual Basic [Link] project, but in
DHTML Applications you distribute the applications by giving users access to a Web page, rather than
giving them an executable file.

The General Idea


When you start a DHTML Application project in Visual Basic, you're presented with a form that you can
use to build up your page. This works in a similar way to Microsoft FrontPage or your favorite HTML
editing tool. All you do is enter the text into the page and when you want something special like a form or a
picture, you grab the appropriate tool from a palette and draw it directly on to a page.

In fact, this is exactly how DHTML Applications are created, but the word 'dynamic' should be tipping you
off that there's something special going on. Simply, what VB lets you do is add some intelligence to your
page, and that intelligence is able to change the content on your page dynamically. Consequently, a web
page will interact with the user as if it was an application, rather than simply being passive like the pages of
a book.

The Document Object Model


Internet Explorer's Document Object Model (DOM) is a set of objects that lets you control all of the
elements on your HTML page.
Chapter 6

Before Internet Explorer 3, Internet Explorer did have an object model, but no one outside of Redmond
knew about it. All the Microsoft developers wanted to do was get a page from a Web site and display it on
the screen. To do this, they had to build a whole number of internal structures and gizmos that'd let them
take the HTML and interpret (or 'parse') it into a format they could use to draw it on the screen.

But, when Netscape decided that Java was the way to go and brought out Navigator 3, Netscape had to
make their counterpart object model available to page designers. Both Java and JavaScript needed to be
able to interact with elements on the page. The object model makes it possible to identify any of the
elements on a page and change their properties - for example, to alter the source of an image.

When Internet Explorer 3 was released, Microsoft's browser now had support for Java, JavaScript and their
own cut down version of Visual Basic called VBScript. They also turned their own object model inside out
so that developers could see it, just like Netscape did. They modeled their object model so it was mostly
compatible with Netscape's.

The only way script code can communicate with what's already on the page and add new things to the page
is by manipulating the DOM programmatically. Although the DOM has been around for a while now,
DHTML has only been around since Internet Explorer 4. The impact that IE4 has on the DOM is that it is
now extremely feature rich.

172
Dynamic HTML Applications

What does all this have to do with us today? Well, Microsoft have long touted the significance of ActiveX
technology and, along with it, their Component Object Model (COM) technology. Simply, these
technologies let applications and components cooperate by sharing functionality and data. Much of what
you read in this book is only possible because of ActiveX. In fact, as we shall see in Chapter 7, Internet
Explorer itself is just a window frame and an ActiveX control that functions as a Web browser! ActiveX
controls allow us to do one important thing – they let us access Internet Explorer's Document Object Model
from any application we like. And what this chapter is all about is how we can manipulate the DOM using a
Visual Basic component hosted inside a Web page.

A 30,000-foot view of the Document Object Model


As you can see from the figure on the previous page, the Document Object Model is laid out as a tree, much
like most object models that you're familiar with.

At the base of this tree is the Document object. This object provides programmatic access to the rest of the
tree, and is the object we'll be using a lot of throughout this chapter. For example, you can ask the
Document object for the object that contains stuff inside the BODY tag of your HTML document (the
Body object, no less), or for the frames that make up the page. In fact, when you ask for a specific frame,
you can access that frame's Document object too so you can effectively walk through and around anything
that Internet Explorer can see.

What's important about the DOM is that it is not read-only. You can manipulate it by changing methods and
properties on the DOM objects just like you would with, say, the Form or Button objects inside Visual
Basic itself. This means that not only can you ask IE to load a document and then query the elements that
appear on that page, but you can either make a page completely from scratch (not entirely recommended,
but do-able), or you can locate and modify elements already on that page to get the desired effect.

One important point – in order to access an element on the page, it must have an ID attribute (also known as
an ID property). A neat thing that IE does that Netscape doesn't, is say you define a button as having an ID
of ClickMe, IE will define an object called ClickMe as part of the global scope of your script. This
means that you can refer to that object directly from code, like this:

MsgBox [Link]

An alternate way of accessing the same object is to use the "All" property of the Document object:

MsgBox [Link]("ClickMe").innerHTML

Those of you interested in performance should note that the latter example is less efficient, basically
because IE has to walk a list of objects to find the one you wanted.

To show you how to modify the document, later in this chapter we'll see how we can add rows and columns
to a table. We do this by finding the table we want to manipulate (and in our case, we give it an ID, like
MyTable) and then calling methods on it to modify it. Like this:

Set NewRow = [Link]

173
Chapter 6

We'll be laboring this point later, but pretty much everything you get back from the DOM is an object in its
own right, with its own set of methods and properties. In the insertRow example, we get back an
HTMLTableRow object. Once we have that, we can call the "insertCell" method and then we get back
another object, and so on.

One of the neat things about the DOM is that there's literally nothing you can't do with it. You can change
any part of any element on your pages.

Here's some examples:

 You can create new elements. For example, you can actually add OPTION elements to a SELECT
element after the page is loaded.
 You can remove elements. For example, removing sentences from a paragraph as the user changes other
elements on the page.
 You can hide elements, or control any part of an element's style. For example, hiding an INPUT
element when the user clicks off a check box, or changing the color of a table.
 You can dynamically build a table then take the HTML that's used to build up that table and save it to a
file. (That's the example we'll be working on next.)

The DOM is a pretty large object model, but it's thoughtfully and logically laid out. One of the good parts
about API's like this is once you get the hang of how a little bit works, you can usually take that same
paradigm and 'guestimate' how parts your not so familiar with works.

You can find a whole load of raw reference materials at [Link] in the Web
Workshop. (Look for DHTML References.) Naturally, Wrox publishes a number of books on the subject,
and you can find more information on those at [Link]

Introducing DHTML Applications


To start the DHTML Application project, open Visual Basic and choose DHTML Application from the
New Project dialog as shown in the screenshot.

174
Dynamic HTML Applications

When VB opens the new project, you need to kick start it into giving you something to work with, so using
the Project tree in the top right, expand Designers and double-click DHTMLPage1. You will end up
with something that looks like Figure 6.2.

An important thing to note here is that VB has automatically suggested we use the HTML control palette,
rather than the General control palette that we're used to using. It's suggesting that we use this because it's
better to use HTML specific controls on a Web page, rather than using the general purpose Visual Basic
ones, which may not be installed on the client machine.

The DHTML Designer


The DHTML Designer that VB presents us with is similar to the one you might find in Microsoft FrontPage
or another popular page editor. Simply, it lets you create an HTML file using a WYSIWYG editor. Try it
now and you'll see it's natural to use. Below is a simple example of what can be done. It's a fairly crude
editor, but you can input text and images in the right-hand pane of the window, and the elements you add
are mirrored on the left.

175
Chapter 6

If you press the Start toolbar button, or select Run|Start from the menu, Visual Basic will open Internet
Explorer and you'll be able to see your new page. (The very first time you do this, VB will come up with
the Project Properties dialog box with the Debugging tag selected. Select the Start Component radio
button and click OK.) When you return to VB you'll have to press the End toolbar button, or select Run-
End to get the DHTML Designer back.

Nothing special's happened so far, so let's try building a simple application. Using the HTML control
palette, select the Button control and draw a new button on your page. Once it's in place, double-click the
button and enter this code:

Private Function Button1_onclick() As Boolean


[Link] = "[Link]
End Function

Now try running your application again. When the button appears, click on it and you should be taken to
Wrox's home page.

What is VB doing?
What's happening here is very straightforward. We're using the DOM to control the Document object and
we're telling it to navigate to a new page. VB is taking over the job of understanding the technical part of
telling Internet Explorer that when the button is pressed it should go ahead and change the Location
property of the Document object to the new Web page.

With Internet Explorer open, go ahead and select View|Source from the menu. VB doesn't do a very good
job of formatting the original source code and for this example I've added some white space to aid reading.
Normally, the source will open in Notepad. What you get will look similar to this:

176
Dynamic HTML Applications

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">


<HTML>
<HEAD>
<META content="text/html; " http-equiv=Content-Type>
<META content="MSHTML 5.00.2314.1000" name=GENERATOR>
</HEAD>
<BODY class=(Normal)>
<!--METADATA TYPE="MsHtmlPageDesigner" startspan-->
<object id="DHTMLPage1" classid="clsid:D60D7F1C-0E4F-11D3-AFAE-00A0CC40290A"
width=0 height=0>
</object>
<!--METADATA TYPE="MsHtmlPageDesigner" endspan-->

<P>Hello World.
<INPUT id=Button1 name=Button1 style="HEIGHT: 45px; LEFT: 40px; POSITION:
absolute; TOP: 94px; WIDTH: 196px" type=button value=Button1>
</P>
</BODY>
</HTML>

The highlighted code tells Internet Explorer to load an ActiveX object. As part of the DHTML Application
project, Visual Basic is responsible for generating that ActiveX control.

The ActiveX component encapsulates all of the logic we build into the page. This is a different approach to
the majority of DHTML editing tools. Macromedia Dreamweaver, for example, generates JavaScript code
and inserts it directly into the page. That's not what's happening here, and the VB approach has two distinct
advantages and one disadvantage. Firstly, people viewing your page can't see your source code, which is
important if you want to protect your intellectual property, or stop people from playing with the code and
breaking it. Secondly, compiled Visual Basic code runs faster than interpreted JavaScript code. The
balancing disadvantage is that our pages can only be used on Windows machines that have Internet
Explorer 4 or later installed as the web client.

When our ActiveX component is initialized, it hooks itself into Internet Explorer and starts listening for any
events that occur. When it detects an OnClick event, it searches for the source element (the button) and
looks to see if there's anything it should do in response. By virtue of the fact that the component has been
linked into the Internet Explorer environment, the VB code you write now has the same access to the
Document Object Model as IE itself does. Therefore, you are able to find and control the Document object.

A Practical Example
Let's imagine that Barb is the manager of a sales team of three people: Edward, Amir and Stephanie. Each
week, she wants her salespeople to send her a report on how much they sold and to whom. Presently, each
member of the team has to enter the values into a Microsoft Word document and then send it to her over e-
mail.

177
Chapter 6

What she'd like is to give her people access to a Web page that they can use to fill in their figures. When
the form is complete, she'd like to have the report saved to a server so she can access it at her leisure the
following week.

We can make this happen for Barb by building her a DHTML Application. Just so you know where we're
headed, the screenshot above shows the page we're going to build.

Getting Started
Looking at the page we want to build, it's obvious what we need to do. The page is divided into two
sections: an area where the report data will appear and an area containing the form that the salesperson can
use to enter the data.

178
Dynamic HTML Applications

Let's start off by building the page in Visual Basic. I'll assume you're familiar with how to build up a VB
form, and creating a DHTML page is a similar process. So, start a new project, open the DHTML Designer
and try to duplicate what you can see in the screenshot above. (Don't enter the sample report data row, in
the top section, because we'll do this dynamically later).

By default, the text on the page works how you'd expect but the form elements float on top,
leading to a tricky situation where you're fighting the designer to keep the layout stable. The
answer is to check off the Absolute Position toolbar button immediately after you've
dropped on a new element. This'll stop the elements from floating around on top of the text
and the whole thing will behave more logically.

When you want to add values to the product list, you'll need to use the SELECT element's property sheet.
To do this, right-click on the element and choose Properties. The screenshot below shows an example of a
property sheet with two products.

OK, so we've gone through the process of using the DHTML Designer, let's look at making the page
responsive.

179
Chapter 6

Dynamically Changing Text


You should now have something that looks like the screenshot below. By default, VB does not show the
symbols showing the paragraph and line breaks. Click the "Show Details" toolbar button so you can see this
hidden stuff.

Look at the highlighted block of text. Barb doesn't want her salespeople having to fill out the date, so our
app will do it for them.

In order to do that, though, we need to be able to address that highlighted block. In DHTML, you can give
any element on your page an ID which you then use to address that element from your code. Once you
know what the ID is, you can run methods on and get and set properties for that element.

Firstly, we need to define that block of text as being addressable in its own right. As it stands, the text is
part of the whole paragraph which includes the 'Weekly Sales Report' text, so right now we can't just alter
the little bit concerning the date. With the date highlighted, press the Wrap Selection in
<SPAN>…</SPAN> toolbar button.

180
Dynamic HTML Applications

It's time to start looking at the DOM tree that takes up the left-hand side of the DHTML Designer:

The DOM is represented hierarchically, just like the way Windows Explorer represents the folders on your
computer's hard disk. In the Figure, we can see that Document is at the root of the tree. Body appears as
the only child of document, so we know that BODY is parented by Document and, by association,
Document contains BODY. The highlighted portion shows our new SPAN element which is parented by the
Paragraph element.

To make the current date appear in the top section of the page, the SPAN has to be programmable, and to
be programmable it has to have an ID. With the SPAN selected in the DOM Tree, go over to the Property
Palette and set the (Id) property to read: CurrentDate.

Although Visual Basic refers to this property as (Id), the parenthesis is just there so VB
will display it at the top of the property list. In the Document Object Model itself, the ID
property doesn't have parenthesis, it's simply called ID.

Double-clicking on CurrentDate in the DOM Tree will bring up the Code Editor. (Careful here,
because you can't just click on the selected text, you have do to it from the tree.) What we need to do now is
hook into the load event so as soon as the SPAN is loaded we can change the text. If, however, you look in
the Event drop down on the Code Editor, you'll notice there is no event that looks like it'll get called when
the page loads. This is by design. Our component has to hook into IE somehow, and it can't do that until it's
loaded and it may only load after the SPAN element does – which means it can't properly capture the event.
Instead, you have to drop down the Object list, select DHTMLPage and then select the Load event. The
screenshot below shows the correct object and event to choose.

Enter the code for DHTMLPage_Load as you see it here:

Private Sub DHTMLPage_Load()


[Link] = "w/e " & MonthName(Month(Now)) _
& " " & Day(Now) & " " & Year(Now)
End Sub

181
Chapter 6

You'll be glad to know that the full Visual Basic debugger works when you're building
DHTML Applications. You can set breakpoints, move the execution pointer and watch
variables as usual.
This is similar to the trick we saw before with navigating to a new page when a button was pressed. When
the page gets initialized, it fires its own Load event. That event requests that the innerHTML property of
a control called CurrentDate is changed to reflect a string we construct dynamically. In this case
CurrentDate points to our SPAN element. The innerHTML property is a DHTML property that the
majority of elements have. InnerHTML contains the HTML that the control is required to display. When
we change that value, Internet Explorer is prompted to re-render the part of the page that accommodates
that control and so our new text is seen!

Building up the Report


Our next job is a little more complicated. What we want is whenever one of our salespeople presses the
"Add to Report" button, we want to take the information in the form and add a new row to the table to
reflect the sales data.

Let's start by making sure the table that is going to contain the report data is addressable, so set the ID
value of the table, in the Property Window, to ReportTable. If you prefer, you can select elements
directly from the DHTML tree..

If you find it tricky to select elements on the WYSIWYG part of the DHTML Designer,
remember you can select elements directly from the DHTML Tree.

Now we need to make every element in the form addressable. Assign IDs to your elements like this:

 Sales person list – PersonList


 Date field – DateBox
 Company field – CompanyBox
 Product list – ProductList
 Amount field – AmountBox
 Add To Report Button – AddToReport
 Save Report Button – SaveReport

Now let's get down to business and start adding the data to the report. In this example, we're going to
simplify things by not worrying about validating the input.

So where do we start? Well, we know we need to create a row on the table, so let's start there. The
HTMLTable element has a method called insertRow. The method returns an HTMLTableRow object,
so let's do that first.

Bear in mind that the Document Object Model has the word "Object" in it because
every single part of a document is represented with an object. That may seem
obvious, but you'll get a clearer understanding of what's happening when you
remember the majority of properties and methods you will use will return objects.

Private Function AddToReport_onclick () As Boolean


Set NewRow = [Link]
End Function

182
Dynamic HTML Applications

You can try running the application, but not a great deal will happen. Next, we need to add some columns
to our new row:

Private Function AddToReport_onclick() As Boolean


Set NewRow = [Link]
Set DateCell = [Link]
[Link] = [Link]
End Function

Inserting a new cell into the row returns an object just like inserting a new row into the table did. (Just so
you know, the kind of object that represents individual cells is called HTMLTableCell and, in fact,
DateCell will contain one of these objects after the call to insertCell.) Once we've created the
cell, we can go ahead and set the HTML text for that cell to be equal to the value our user entered into the
date box.

After adding the code to create the other three columns, our code looks like this:

Private Function AddToReport_onclick() As Boolean

' Create a new row in the report...


Set NewRow = [Link]

' Insert a new cell to contain the date value


Set DateCell = [Link]
[Link] = [Link]

' Do the same with the company name


Set CompanyCell = [Link]
[Link] = [Link]

' Add a cell and set the product name (see notes)
Set ProductCell = [Link]
[Link] = [Link]([Link]).Text

' Add a cell and set the amount


Set amountcell = [Link]
[Link] = [Link]

End Function

The statement "[Link]([Link]).Text" is used


because by default when we ask a SELECT box for it's Value and there's no value set, it returns an empty
string. This can happen when you use the property sheet and specify Text values, but not a corresponding
Value entry.

You can get a better understanding of what I mean by going back and looking at the figure
showing the Property Pages for the ProductList select box. Notice how the Value
edit box is blank, where the Text one isn't.

The code that's been added returns the text value instead. It does this by getting the index of the selected
item and asking ProductList for its corresponding OPTION element. Once we have the OPTION
element, we ask it for its Text value and we then add this to the report.

183
Chapter 6

The screen shot below shows what we have so far.

We can improve the formatting by changing the code:

[Link] = [Link]([Link]).Text

' Add a cell and set the amount (nicely formatted)


Set amountcell = [Link]
[Link] = "right"
[Link] = "$" & FormatNumber([Link], 2)

End Function

The new line we've added there uses Cascading Style Sheets (CSS) to alter the formatting of the cell. CSS
was introduced along with DHTML. It has two functions. Firstly, it lets page designers lay out their pages
with far greater control than was previously possible. Secondly, it has mechanisms that reduce the need to
constantly repeat yourself when using styling tags in HTML. When you're sending data over a network of
any sort, you don't want to ever repeat yourself because it's a waste of bandwidth. One of the many things
CSS lets us do is generate a "class" which we can configure with the appropriate font settings. When we add
elements to our page, we can assign that class to those elements and eliminate the repetition. Here's an
example of what we can do:

184
Dynamic HTML Applications

<HTML>
<HEAD>
<STYLE>
.myclass { font-family:"arial,geneva"; font-size:10pt; }
</STYLE>
</HEAD>
<BODY>
<TABLE CLASS=myclass>
<TR>
<TD>Value</TD>
<TD>Another</TD>
<TD>Value 3</TD>
<TD>And so on</TD>
</TR>
</TABLE>
</BODY>
</HTML>

The STYLE tag is used to define a style-sheet. We've created a class inside this style-sheet called
myclass. We've then assigned that class to the TABLE element so now everything inside the table will be
nicely formatted. Since this is a small styling element for only one page, we've included it on the page
itself. That said, one of the biggest advantages of stylesheets is that you can include them as a separate
.css file, and then call it from your HTML page using @import

<style>
@import URL("[Link]
<style>

Obviously, this will allow you to use a single stylesheet across several pages – guaranteeing lower file sizes
(because you can skip the formatting in HTML) and a consistent style across your website (because all your
pages use the same styling information).

In our VB example the line [Link] = "right" is accessing the style


definition for the cell (through the Style property), and then altering that definitions TextAlign
property to right-align the cell. We could, if we wanted, assign a class to the cell with a line like:

[Link] = "myclass"

Although the adoption of CSS isn't as widespread as it could be because not every browser on the everyday
desktop implements it, CSS makes life much easier for Web designers. As a DHTML Application designer,
you can take as much advantage of it as you like because these applications are only supported by Internet
Explorer 4.0 onward- in other words, only those which support DHTML applications anyway!
CSS is an involved technology so we won't cover it in too much detail here, but you can find
a lot of information about CSS on any of the popular Web building sites, the MSDN Library
or Wrox's Professional Style Sheets for HTML and XML (ISBN 1861001657).

185
Chapter 6

Saving the Report on the Server


Recall that in the pre-DHTML Application scenario, our salespeople are e-mailing Barb with their reports
once a week. Ideally, Barb would like the reports put in the correct place on her departmental server so she
knows that they are getting filed and backed up properly.

The following code snippet will create the appropriate folder on the server and configure the name of a file
that we can use to store the report data in. To give this a context, we know the path of a shared folder on a
server where we want to store the reports and we'll create a subfolder inside that folder based on the current
date. Then, we'll create an HTML file based on the name of the salesperson.

Private Function SaveReport_onclick() As Boolean

' Create the FileSystemObject...


Set fso = CreateObject("[Link]")

' Where do we want to save all reports?


' (Change this path when you're debugging to make it save
' somewhere on your local computer!)
' The trailing slash is important!
basepath = "\Sales\Reports\Weekly\"

' Each week has it's own folder...


basepath = basepath & Month(Now) & "-" & Day(Now) & "-" & Year(Now)

' Now create the folder...


' BUT, as any of our salespeople can do this, the folder may
' already be in place. Ignore any errors that occur, and
' then reset the error handler back to normal operation.
On Error Resume Next
[Link] basepath
On Error GoTo 0
' Make up a filename based on the name of the salesperson...
FileName = basepath & "\" & [Link] _
([Link]).Text & ".htm"

' Create our new file...


Set file = [Link](FileName)

' ...and this is where we'll draw our report!


' Close the file
[Link]
Set file = Nothing

' Cleanup
Set fso = Nothing
End Function

That code should be self explanatory, but remember you will need to reference the Windows Scripting
Library from your project. Note that [Link] cannot be used, as the value could be empty.

In order to make that snippet useful we need to write some VB code that'll generate the HTML of the
report. Active Server Pages developers should already be familiar with the concept of writing VB code that
generates HTML pages.

186
Dynamic HTML Applications

We'll start by adding the framework of the document. The HTML to do that looks like this:

<HTML>
<HEAD>
<TITLE>Weekly Sales Report</TITLE>
</HEAD>
<BODY>
...report goes here...
</BODY>
</HTML>

And we can add this to the report with these lines:

' ...and this is where we'll draw our report!


[Link] "<HTML><HEAD><TITLE>Weekly Sales Report</TITLE><BODY>"
[Link] "</BODY></HTML>"

When we're building reports up by directly writing to a file, we want to keep the number of WriteLine
commands to a minimum. The File object will add a carriage-return/line-feed pair to the end of each line
written with WriteLine and frequent use of carriage-return/line-feeds can break the parsing code of
Internet Explorer leading to horrible looking results. As a rule of thumb, don't worry about nicely formatted
HTML on simple, dynamically generated pages– optimize for speed and size by not adding white-space
characters.

Adding the report information to the HTML file is possibly the easiest part of the whole procedure. We can
simply ask Internet Explorer for the actual HTML that was built up using our code:

' ...and this is where we'll draw our report!


[Link] "<HTML><HEAD><TITLE>Weekly Sales Report</TITLE><BODY>"
[Link] [Link]
[Link] "</BODY></HTML>"

Notice that we were using the innerHTML property of our elements and now we're using outerHTML.
We've had to take this approach because innerHTML returns the HTML that makes up the children inside
of the element. OuterHTML gives us the HTML of the actual element as well as the HTML of the children.
(To get a good understanding of this, try running the sample using innerHTML instead. You'll notice the
report data will be displayed in a single line because there won't be a table to frame the data.)

We can now finish our example by adding some code to add the salesperson's name to the report and place
the report in the center of the page:

' ...and this is where we'll draw our report!


[Link] "<HTML><HEAD><TITLE>Weekly Sales Report</TITLE><BODY>"
[Link] "<CENTER><FONT SIZE=5><B>" & [Link] & "</FONT>"
[Link] "<BR><FONT SIZE=3>Weekly Sales Report for " _
& MonthName(Month(Now)) & " " & Day(Now) & " " & Year(Now) & "</FONT>"
[Link] "<BR><BR>"
[Link] [Link]
[Link] "</CENTER></BODY></HTML>"

187
Chapter 6

When you run the code, clicking the Save Report button will add an HTML file to the folder created by
the code. This page should look like this:

In order to keep this example simple, I refrained from adding a "Total" line to the report. If you want to put
one in, you can and I would suggest two approaches. The simplest one is keep a global variable that you
increment each time you add a line to the report. Then, when you come to render the report to the file, tack
on another row, as shown below. (Don't forget, innerHTML won't give us the table framing that we need,
so we have to write the frame ourselves and then use innerHTML.)

[Link] "<TABLE BORDER=1>"


[Link] [Link]
[Link] "<TR><TD COLSPAN=3></TD><TD>TOTAL: " & total & "</TD></TR>"
[Link] "</TABLE>"

The more complex approach involves keeping the preview up-to-date as the report is being built. You could
either define a separate <SPAN> element on your document that you change as you add rows, or you could
add a permanent row to ReportTable and make sure that when you insert new rows, you always insert
above the permanent one. Either way, it's possible.

Deploying DHTML Applications


Now that you're going great guns building DHTML Applications for everyone who wants one, you need to
find an effective way to deploy them. This is where the trade-off between fast, secure code balances itself
out against deployment issues. Whereas a server-side application requires no specialized deployment code,
our DHTML Application has some client-side stuff and that has to be automatically installed when our
application is first used.

The principle behind what we're going to do is build a "cabinet" file containing all the stuff that the client
computer needs to have installed so that we can run our application.

188
Dynamic HTML Applications

Cabinet files (which have the extension ".CAB") are used a lot by Microsoft for installing their software. In
fact, cabinet files were developed specifically for Windows 95 Setup, and have since found their way into
all Microsoft Setup programs.

Microsoft have developed a utility called CabView which can be used to examine the
contents of cabinet files. You can find this on the Microsoft Web site by searching for
'CabView'. The popular shareware package WinZip 7.0 can also read .CAB files.

When you visit a page that uses an ActiveX control or component, Internet Explorer is informed of the
control through an OBJECT tag. (You may recall that we saw an OBJECT tag when we first viewed the
source code of our test HTML page.) Every single ActiveX object in existence is identified by a Globally
Unique Identifier (or GUID). This is in fact a huge, 128-bit number and is generated from a combination of
a unique number burned into the originator's network card and the current time on the originator's
computer. No two GUIDs are alike, so any developer can be certain that when he or she allocated a GUID
to a control, there will never be a conflict.

When IE finds an OBJECT tag, it uses the GUID to see if the appropriate object is installed on the local
computer. If it is then it just goes ahead and initializes the object. If it isn't, the OBJECT tag contains an
attribute called CODEBASE which directs IE to a URL where it can download the object. Usually this URL
points to a .CAB file.

As we discussed in Chapter 5, there is one more point about ActiveX controls that's important, and it bears
repeating. ActiveX controls have full access to the system they are running on. There is nothing stopping
any ActiveX control from harvesting all the Word documents off of your hard disk and e-mailing them to
everyone in your address book. ActiveX's counterpart, Java applets, have no such problem. Java applets run
in a conceptual device called the "sandbox", which is a collection of functions and operations that the Java
architects have deemed safe. It's not physically possible for a Java applet to start scanning your hard disk
for Word documents.

Because ActiveX is supposed to compete with Java applets, Microsoft decided to develop an authentication
scheme where you have to go to a third-party called a "certificate authority" and pay them to for a digital
signature which you then use to sign your code. (This technology is called Microsoft Authenticode.) By
signing their code, developers know that when you visit their Web sites, you're either warned about using
code that hasn't been marked as safe or prevented from doing so completely. We'll cover signing code and
security in the next section.

Packaging Our Application


Now that we've tested and debugged our example, compile it by selecting Make [Link] from VB's
File menu. You'll be asked to save the DLL (save it to the project folder), and you'll then be asked to save
the HTML file that we built using the DHTML Designer. Save this into the project folder as well, and call it
[Link].

189
Chapter 6

By default, the Package and Deployment Wizard is not loaded into Visual Basic. Select Add-In
Manager from the Add-ins menu. Select Package and Deployment Wizard, and check
Loaded/Unloaded. Confirm that the Load Behavior column says Loaded and click OK, resulting in a
screen that should look like the screenshot below.

Now, return to the Add-Ins menu and select Package and Deployment Wizard. When asked, say that you
do want to save the project.

The Package and Deployment Wizard, shown in the screenshot below, works by building scripts that
contain instructions on where to find the constituent parts of your project. This is an expansion on the
simpler form of deployment we covered in Chapter 5. These scripts stay with the project so you can reuse
them later. Microsoft designed it that way because some developers could have multiple scripts for the
same project that do slightly different jobs. For this example we're only going to create and use one script.

190
Dynamic HTML Applications

To start with, we need to package the code, so using the Package and Deployment Wizard, select
Package.

The Package Type dialog below lets us choose from three different packages. Standard Setup Package
is used when we want to wrap our project up in an executable file that we physically give to someone,
Internet Package is used to create a .CAB file (which is what we want to do) and Dependency File is
used to create a list of what other DLLs and packages the components in the project have access to in order
to work. Dependency files are particularly useful for debugging installations because you can use them to
quickly find what's missing.

Make sure Internet Package is selected and click Next.

The next dialog, Package Folder, simply wants to know where we want the put the files on our local
computer before we move them over to the Web server. Choose a folder and click Next.

191
Chapter 6

The screenshot above shows a dialog that appears when the dependency information for one of the DLLs
we're using cannot be found. For some reason, Microsoft chose not to put dependency information on
[Link] which is used in all DHTML Application projects. This file is a Type Library (hence the
extension .TLB) and contains support information for the controls that appear on the HTML control
palette. Make sure the checkbox is unchecked and click OK.

The screenshot below shows the "Included Files" dialog which is where we're told what files will be
included in the package by default. We are also given the opportunity to add files to the package. You may,
for example, wish to include other executable files or documentation in the package.

192
Dynamic HTML Applications

[Link] is, obviously, our project DLL. [Link] we covered above and
[Link] is the DHTML Designer run-time support file. VB6 Runtime and OLE Automation is
actually another package that's supplied with VB for deployment with your applications. It is used to make
sure the computer you're installing onto has all of the files VB needs to run your application properly on the
client machine.

Click Next to proceed.

The File Source dialog shown below lets us decide if we want all of the bits of our project included in our
package. If you select VB6 Runtime and OLE Automation you'll notice that rather than Include in this
cab being checked, Download from the Microsoft Web Site is instead. The theory behind this is that
because this package is pretty large, you may not want to include it in your package. If the package is
needed (because the VB runtimes aren't installed on the computer you're installing your application onto)
IE can go download it from the Microsoft website.

193
Chapter 6

In the list of four items in the package, only [Link] and the VB6 Runtime packages can be
downloaded from the Microsoft Web site. [Link] is our own DLL, and [Link] has
to be available for our DLL to load. Naturally, as it is our own DLL, it can't be downloaded from the
Microsoft site! Make sure than when you select [Link] and the VB6 Runtime that Download
from Microsoft Web site is selected.

If you're trying to deploy your applications in an environment where it's not


reasonable to have your applications downloading stuff from Microsoft's site, you
can choose to put these other DLLs and packages on another server in your
building. Use the Download from alternate Web site option to direct IE to the other
resources. Including the run-time components in your package will increase the size
by 1.1MB.

194
Dynamic HTML Applications

The screenshot above shows the Safety Settings dialog which prompts us to revisit the signing discussion
we started earlier

Because Microsoft respect the fact that not everyone is in a position to pay for certificates, VB can mark
your DLLs as safe for certain functions. This is dependent on the honor system – there is no mechanism for
guaranteeing the promise you're making here!

By setting "Safe for Scripting" to "Yes" you are saying that the code in your component will not create,
change or delete arbitrary files, including temporary files when the code is running. "Safe for Initialization"
means the component won't do anything like that when it's starting up.

Some of you have probably noticed that although we've checked these options, our
example project does create files. We're doing this for demonstration purposes, and
because you've seen all the code that goes into the application. Normally you should
always leave unsafe components marked as Unsafe, and leave the user or customer
to make the final decision- for a clean demonstration of what can go wrong with
ActiveX, check out [Link]

The Microsoft documentation has these words to say on this issue:

"By marking a component as safe for scripting or safe for initialization, you are guaranteeing that your
component can never corrupt or cause undesirable behavior on an end user's machine, even if used in a Web
page that you yourself did not author. Marking a component as either safe for scripting or safe for
initialization implies that you are accepting liability for this guarantee."

Set the security settings and click Next. When the Finish dialog appears, leave the package name as it is
and press Finish.

195
Chapter 6

If you open Explorer and navigate to the folder you specified in the "Package Folder" dialog you'll find the
.CAB file and an HTML file. Try opening the HTML file and running your application!

Publishing our Application's Package


Now we have to make the application available on a Web server. From the start page of the "Package and
Deployment Wizard" (as seen in Figure 6.12), select Deploy.

When the new Wizard starts, select the package you wish to deploy. You should only have one possible
option, and that'll be the name you set in the "Finish" dialog before.

There are three ways you can publish your application. You can either publish through HTTP Post or FTP
(denoted by "Web Publishing" above, or by supplying the path to a folder on your network.

Whichever method you chose, you'll be asked for the files you wish to deploy in the Items to Deploy
dialog. You should make sure both the CAB file and the HTML file are both checked on and press Next.

You'll then be prompted by the "Additional Items to Deploy" dialog to supply the names of other files or
folders you wish to deploy. You could here, for example, supply the names of documentation files you also
wanted to upload.

196
Dynamic HTML Applications

Publishing Directly to a Web Site.


The alternate Web publishing method is to use FTP, and this is the method illustrated in the screenshot
below

Whichever you choose, you'll need to supply the location of the server. When you've done this, click
"Next". If the site you've chosen has never been used before, the Wizard will ask you if you want to save
the configuration information on your computer for use in other projects.

The server you want to publish to will usually require some form of proof of identity before it'll allow you
to transfer the data. The commonest method is simply to use the inbuilt NT challenge/response dialog:

197
Chapter 6

Publishing to a Folder on your Network


If you're posting applications to a departmental server, you may well find that you have direct access to the
folders on that server. If you do, publishing becomes a little more straightforward. The next screenshot
shows the dialog you can use to select the network folder to save the package and Web pages to.

198
Dynamic HTML Applications

Summary
After reading this chapter you should be able to…

 Explain to your peers what a DHTML Application is.


 Create a new DTHML Application.
 Design DHTML pages using the DHTML Designer.
 Add code to elements on the pages that can react to events and manipulate the data on the page.
 Package your application so it can be deployed.
 Deploy your new application so people can use it.

Our example raises a number of questions. For one thing, we're not using ASP, which is the typical way of
providing dynamic applications to users on a network. In fact, our example does not even use a database,
which is pretty unusual in its own right. If you were to ASP-enable this application, the only advantage
you're going to get is that it can store the reports on the server in a more "purist" manner, and we could also
rig our application to e-mail the reports.

What the DHTML Application does give us is the ability to quickly build interactive Web pages that don't
have to keep calling back to the server. Just as ADO's Remote Data Service can retrieve queries directly
from a database server without having to re-execute an ASP page, DHTML Applications can modify the
page content without having to make repeated calls to a Web server. A big advantage for using VB's
DHTML Applications as opposed to manipulating the DOM using raw VBScript is that VB's editing and
debugging environment is much stronger. The disadvantage is the deployment and signing of your ActiveX
component.

199
Chapter 6

200
Integrating Web Browsing Using
the WebBrowser Objects

In this chapter, we will introduce the concept of the WebBrowser and InternetExplorer objects. We
will investigate the current architecture of the Internet Explorer application, and look into how Microsoft
has modified the design of the browser to allow developers, like yourself, to leverage this free,
encapsulated functionality. We will investigate all the major properties, methods, and events of the
controls. The abilities that these controls provide us open the door for incredible flexibility in application
development.

While many options exist for developing web solutions for your company's application needs, in many
cases, web-enabling existing applications may prove to be a more desirable option. Sometimes, it is not
feasible to completely rewrite an existing application into a web-based equivalent. In other scenarios,
developing a completely non-Win32 solution may also carry with it limitations that are unacceptable to the
development needs of the company.

In this chapter, we will cover:

 Creating a basic web browser


 The differences between the WebBrowser and InternetExplorer control
 Scenarios and uses of the controls
 Properties of the controls
 Methods of the controls
 Events of the controls

Let's start by investigating the heart and soul of Internet Explorer.


Chapter 7

The Heart and Soul of Internet Explorer


Starting with the introduction of Internet Explorer 3.x, Microsoft extracted the technology for accessing the
Internet and exposed it to the Windows desktop and any Win32-based application. In order to provide
improved access and documentation to the internet functionality exposed and supported by the core
elements of Internet Explorer, Microsoft supplied the Internet Client SDK. The Internet Client SDK
provides examples, demos, and valuable references for the full range of functionality available through the
Internet Explorer core files.

The Internet Client SDK can be downloaded from


[Link]

When they released Internet Explorer 4.x, Microsoft separated the core functions such as issuing HTTP
requests and rendering HTML into a separate dynamic-link library which registers as the Microsoft Internet
Controls on any system that has Internet Explorer 4.x or better installed.

The DLL encapsulating this functionality, [Link], not only provides all the necessary logic to
request and render HTML pages, but also exposes this functionality through a series of programmable
controls and OLE automation objects. Registering this DLL on your system, usually accomplished through
installation of Internet Explorer itself, will provide several newly registered controls whose ProgId will
begin with SHDocVwCtl.

You can obtain and register the [Link] file independently of a Microsoft IE
installation. Doing so may result in less functionality, as other, newer functions of
the browser such as scripting and DHTML support are not directly handled by this
DLL. Also, you should check with Microsoft accounting and licensing requirements
for using portions of Internet Explorer without a standard installation preceding
use.

The primary control on which we will be focusing is the WebBrowser object. This object exposes the key
functionality of Internet Explorer in a generic object arrangement. While the WebBrowser is provided as an
ActiveX control for use directly on a Visual Basic form, another important object, called
InternetExplorer, is available within the DLL.

202
Integrating Web Browsing Using the WebBrowser Objects

The InternetExplorer automation object allows Internet Explorer itself to be programmatically


controlled. This can be quite useful at times when you would prefer to make small changes to Internet
Explorer rather than building a browser-like application from the ground-level up.

SHDocVwCtl, is rumored to stand for Simple HTML Document Viewer Control. Whether or
not this is actually true, this is a good method for remembering the ProgID and DLL name.
Don't forget, though, that the DLL name is actually shortened to [Link] to conform
to the 8.3 naming conventions.

IE-based Browsing Objects


Internet Explorer exposes two objects that can be used for browsing the web. These objects, WebBrowser
and InternetExplorer, are encapsulated within the [Link]. Both objects share the same
programmatic COM interface, IWebBrowser2, although not all methods, events, and properties exposed
through this interface apply to both objects. From version 4, onward the WebBrowser control container
was modified so it could be hosted directly by the Windows shell, thereby exposing its use by other
Windows-based applications.

203
Chapter 7

Properties
InternetExplorer WebBrowser Control
AddressBar AddressBar
Application Application
Busy Busy
Container Container
Document Document
FullName Partially implemented
FullScreen FullScreen
Height Height
HWND
Left Left
LocationName LocationName
LocationURL LocationURL
MenuBar MenuBar
Name Name
Offline Offline
Parent Parent
Path Partially implemented
ReadyState ReadyState
RegisterAsBrowser RegisterAsBrowser
RegisterAsDropTarget RegisterAsDropTarget
Resizable Resizable
Silent Silent
StatusBar StatusBar
StatusText StatusText
Tag
TheaterMode TheaterMode
ToolBar ToolBar
ToolTipText
Top Top
TopLevelContainer TopLevelContainer
Type Type
Visible Visible
Width Width

204
Integrating Web Browsing Using the WebBrowser Objects

According to the MSDN documentation, the properties available to the WebBrowser object are a proper
subset of those available for the InternetExplorer object. As you can see from our table this isn't
strictly true, since the WebBrowser object has access to two properties from Visual Basic- Tag and
ToolTipText. The main difference in available properties, however, focuses mostly on added visual
elements available in Internet Explorer, such as ToolBar, StatusBar, and MenuBar, that go beyond
the core browsing window provide by the basic WebBrowser object. The two properties described as
partially implemented, FullName and Path are special cases; refer to the relevant sections for a fuller
description.

Methods
InternetExplorer WebBrowser Control
ClientToWindow
ExecWB ExecWB
GetProperty
GoBack GoBack
GoForward GoForward
GoHome GoHome
GoSearch GoSearch
Navigate Navigate
Navigate2 Navigate2
PutProperty
QueryStatusWB QueryStatusWB
Quit Quit
Refresh Refresh
Refresh2 Refresh2
ShowBrowserBar ShowBrowserBar
Stop Stop

The collection of methods for the WebBrowser object is actually a proper subset of those available to the
InternetExplorer object. The differences, though small, focus on additional cookie support and the
ability to query OLE command status.

205
Chapter 7

Events
InternetExplorer WebBrowser Control
BeforeNavigate2 BeforeNavigate2
CommandStateChange CommandStateChange
DocumentComplete DocumentComplete
DownloadBegin DownloadBegin
DownloadComplete DownloadComplete
NavigateComplete2 NavigateComplete2
NewWindow2 NewWindow2
OnFullScreen OnFullScreen
OnMenuBar OnMenuBar
OnQuit
OnStatusBar OnStatusBar
OnTheaterMode OnTheaterMode
OnToolBar OnToolBar
OnVisible OnVisible
ProgressChange ProgressChange
PropertyChange
StatusTextChange StatusTextChange
TitleChange TitleChange

The collection of events for the WebBrowser object is a proper subset of those available for the
InternetExplorer object.

The 60-Second Browser


We have a browsing object to work with now... so what, you may ask. This method of encapsulating and
exposing the ability to navigate to and render HTML-based pages opens the door to unique applications.
These options are far more flexible than we have ever had before. A few simple lines of code and a couple
of quickly placed objects are all that are needed to create hybrid applications that are exposed to the new
web-based functionality. The developer can look at it from two angles. You can either add web browsing
functionality to existing applications, which can include access to databases anywhere in the world using
Active Server Pages, Remote Data Services and the Internet, or you can add extended functionality to your
web browser without being limited by the customization options afforded to the developer through the
Internet Explorer Administration Kit.

206
Integrating Web Browsing Using the WebBrowser Objects

The flexibility which this type of application provides is absolutely tremendous. A fraction of these
opportunities includes:

 Kiosk-based applications which use a dial-up line to access the Internet


 Hyper-customized web browsers.
 POS systems using a centralized credit card processing system on the web server
 Web-based applications with Win32-based front-ends sold out of the box.
 Applications with world-wide database connectivity direct to the source
 Browser-based navigation filters which send the browse history back to a central database
 Applications comprised entirely of web pages, replacing Form objects with embedded ActiveX controls

One of the obvious places to start down this journey of merging web-browsing into existing applications is
to create a basic web browser. The ability to create a functional browser in 60 seconds should be a
testament to the flexibility the web truly provides. To start this process, let's take a look at the recipe for the
60-second browser.

The Recipe
The browser we will create will be extremely simple in nature. We will include the following items in the
user interface:

 Form object for the basic visual structure of the browser


 TextBox for the rudimentary method of URL input
 Command button to initiate browsing
 WebBrowser control for the rendering of the web page.

To begin the process, we


need to start Visual Basic
with a Standard Exe project.

207
Chapter 7

Once we have opened our Standard Exe project and resized the default Form object to be of a sufficient
size for a browser (400 pixels by 360 pixels should work) we must include a reference to the WebBrowser
component. Perform this by selecting Project | Components (or using Ctrl-T) and then select the checkbox
next to Microsoft Internet Controls.

At this point, your toolbox should now contain a couple of additional controls ready for placement. The
globe is the WebBrowser control.

Add the following controls to your form:

 WebBrowser
 Textbox
 CommandButton

208
Integrating Web Browsing Using the WebBrowser Objects

Position the WebBrowser component to take up most of the Form, but leave a vertical strip along the left-
hand side of the Form object. We will use this to add assorted buttons later in the chapter. Your browser
might now look a little like the following.

Of course, we've spiced up the browser a little. I could not perform this whole process in 60 seconds with
these visual enhancements, but the objects and code can be written in around 60 seconds.

Surfing the Web


Now that we have the visual elements in place, it's time to add a little functionality to the Form. Let's add
one line of code to the Click event of the CommandButton. Double-click on the CommandButton and
add the following lines of code:

Private Sub Command1_Click()


[Link] [Link]
End Sub

209
Chapter 7

Once this code has been added, clicking the command button will cause the WebBrowser control to issue an
HTTP request for the URL provided in the TextBox named Text1. Running this application, and
providing the URL of a prebuilt HTML page may result in something similar to the following:

At this point we now have a fully functionally web browser. What? You disagree! OK, I understand that
companies like Microsoft and Netscape have radically changed what web browsers are capable of
performing, hence raising the bar on the expectations of a fully-functional browser. Keep in mind though,
that simply requesting and rendering web pages alone, with support for hyperlinking, is a tremendous
functionality enhancement to provide with such little effort. An entirely new breed of applications can be
developed that leverage portions of UI being housed, maintained, and developed remotely on a web server.
Application enhancements can be obtained every time a web page is requested.

Beyond Browsing
Certainly, this newly found ability to request and render web pages is not enough. Not even close! If you
remember earlier when I described that starting with Internet Explorer 4.0, the WebBrowser object is now
hosted by the Windows shell. This simple fact allows not just HTML pages to be loaded and rendered, but
anything that can be loaded by Windows Explorer itself. This can be used to extend the functionality
provided by the use of the WebBrowser in multiple, unique ways.

Browsing your system


If we load up our little demo application, and attempt to navigate to C:\, we will find that our application
now appears to behave suspiciously similar to Windows Explorer.

This similarity is borne out by the screenshot below, which shows the right click context menu available in
Explorer. When browsing a folder through the WebBrowser object, this gives you access to the View
mode, Arrange mode, and other assorted options.

210
Integrating Web Browsing Using the WebBrowser Objects

Loading Office Documents


To go even beyond the simplistic local browsing functionality derived from the Windows shell, through the
WebBrowser object, additional technologies are supported. As we discussed in Chapter 3, Microsoft
created a member of the ActiveX technology family known as ActiveX Documents (formerly OLE
documents). The WebBrowser object is able to act as an ActiveX Document container, just as Internet
Explorer itself can, thus allowing Office documents to be loaded and edited directly from our demo
application.

211
Chapter 7

You'll notice that even Word's spell checking function is working! Of course, there are some limitations to
the functionality you can get:

 The appropriate Office application must be legally installed to support the document.
 The last used environment configuration (toolbars, etc) for the Office application will be used.
 The full path (UNC, local, or URL) must be provided. Prefixing with the "[Link] protocol indicator
is optional.
 Limitations exist as to the extent of the full Office application functionality (menu items, etc) that will be
exposed to the WebBrowser object.
 Editing the document is allowed. Keep in mind that when you use the original is edited, as opposed to a
temporary copy stored in storage.

These limitations notwithstanding, the WebBrowser object is an incredibly powerful control that allows
numerous functions from within a single control.

Additional Features
It stands to reason that some of the goodies would have to be reserved for Internet Explorer's use of the
underlying control. Sure enough, this is the case. Not all of Internet Explorers functions are available from
the WebBrowser, although some functionality can be obtained through a special method of the
WebBrowser control.

Covered in some detail later in the chapter, the ExecWB method opens up the door to several common
actions performed within Internet Explorer. We will take a brief look at three of the functions:

 Opening a file/URL
 Page Setup
 Printing

To provide this functionality from


our application, we will add a
ComboBox to provide a mechanism
for choosing these options. Not too
complicated, but just enough to get
the job done.

212
Integrating Web Browsing Using the WebBrowser Objects

Once this ComboBox has been added, we need to add a little code behind one of its events to initiate the
functionality when requested. We will be adding a Select Case statement to account for the three
options we included within our ComboBox list. The code is placed within the Click event of the
ComboBox and for our example looks like this:

Private Sub Combo1_Click()


If Len([Link]) > 0 Then
Select Case Combo1
Case "Print"
[Link] OLECMDID_PRINT, 0, Null, Null
Case "Page Setup"
[Link] OLECMDID_PAGESETUP, 0, Null, Null
Case "Open Location"
[Link] OLECMDID_OPEN, 0, Null, Null
End Select
End If
End Sub

Now that we have set things up with the UI and code, let's test each element to see what it looks like.

Opening a file/URL
The standard Internet Explorer Open dialog box for opening a folder or file according to its "Internet
address" or URL, is normally invoked from the File | Open drop-down menu, and
when choosing the "Open Location" item we have added to our ComboBox list, we are presented with the
following, familiar scene:

213
Chapter 7

The ability to navigate to a URL can be performed programmatically, without the


use of an input box, standard or custom, with other, more direct methods then
shown here. If the standard Internet Explorer Open dialog box is desired, this is the
best method.

Page Setup
The Page Setup dialog is a useful functionality of Internet Explorer. It provides the ability to modify the
orientation of the web pages, which affects printing, as well as other features such as dictating the header
and footer information to be included with every web page printed. This dialog is normally invoked from
the File | Page Setup… menu item on the Internet Explorer menus.

After choosing our Page Setup option from the ComboBox, the standard Internet Explorer setup dialog
will appear:

Printing
The standard Internet Explorer printing dialog box is a powerful tool. Printing a web page loaded into a
WebBrowser control on a form can certainly be performed in numerous ways, but the IE print dialog
provides a great deal of functionality and several choices that pertain directly to the printing of web pages.
The standard method within Internet Explorer for invoking the print dialog is to select File|Print… from the
drop-down menus.

214
Integrating Web Browsing Using the WebBrowser Objects

The dialog itself, when invoking through our ComboBox, would normally look very similar to the
following:

Control Properties, Methods and Events


Now we've set up a simple browser, and shown how you can add some basic functionality, we'll look at
extending our application. In order to fully embrace the functionality of the WebBrowser and
InternetExplorer objects, including their strengths and weaknesses, you should be aware of the
available properties, methods, and events that are exposed by these objects. We have already taken a look at
some of these object attributes in creating our 60-second browser. We are going to continue to expand and
enhance the WBDemoApp web browser to provide a strong foundation for you, the developer, to experience
the process of expanding the WebBrowser and InternetExplorer objects in many different ways. As
you read through the remainder of the chapter, you should be thinking about the unique and creative ways
in which you can leverage this packaged web accessibility to provide unique solutions to your application
development needs.

Keep in mind that the properties, events, and methods available with a given version
of [Link] may differ, at the discretion of Microsoft. Applications written
with a particular version of the WebBrowser may function differently with
another..

215
Chapter 7

For the attributes that apply to both the WebBrowser and InternetExplorer objects, we will focus on
implementing the attribute for the WebBrowser object. Many of the attributes only apply to the
InternetExplorer object. For those attributes, we'll be providing code examples to demonstrate the
functionality by controlling Internet Explorer. Consequently, we'll need to provide some foundational code
to support those examples.

Calling and Controlling Internet Explorer


With the InternetExplorer object automation server object exposed by [Link], an instance
of Internet Explorer can be easily called and controlled from within a Visual Basic application. To provide
this functionality to WBDemoApp, we need to modify the user interface a little.

You'll notice we've added a button with the Internet Explorer logo, and assigned it the name
cmdIELaunch_Click. We've also added a couple of radio buttons, which we'll be using later. Once
this UI change has been completed, we need to add some code to create an instance of
InternetExplorer. We will add the necessary code to load an instance of Internet Explorer and set an
object reference to it that may be used later. This code involves three steps:

1. Dim an object variable to hold the InternetExplorer reference


2. Create an instance of the InternetExplorer object in the Form_Load event
3. Set some of Internet Explorer's properties, before revealing it.

' Prepare Global Reference for loading IE


Dim IE As Object
Private Sub Form_Load()

' Start instance of IE


' Note: IE is not visible at this time

Set IE = CreateObject("[Link]")

End Sub
Private Sub cmdIELaunch_Click()

216
Integrating Web Browsing Using the WebBrowser Objects

' Navigate IE to location provided in TextBox


' Note: Setting the Visible property last will decrease perceived
' response time for the navigation.

With IE
.Navigate [Link]
.Width = 420
.Height = 360
.Visible = True
End With

End Sub

Note that we've added code to modify the height and width of Internet Explorer by setting the appropriate
properties of the InternetExplorer object reference. We've also used the Navigate property to set
Internet Explorer's target to the URL in the text box. Finally, we set the Visible property to true so that
the document can be seen.

When the application is run, clicking on the Go To... button and then the new IE button will result in
similar pages being loaded, side-by-side, rendered within the WebBrowser object and a programmatically
controlled instance of Internet Explorer. Note the width and height of Internet Explorer is appropriate for
the settings made.

217
Chapter 7

Control Properties
We will start our investigation of the WebBrowser control by looking at the available properties. Many of
the properties listed are standard for visual COM controls in general, therefore many of the properties will
be grouped into scenarios and used together to obtain the desired effect.

General Properties
The WebBrowser control provides some of the same basic properties as any other ActiveX control. Some
of these standard properties include the basic size properties, and the visible property.

Height, Left, Top, and Width


Imagine that you want to adjust our original WebBrowser object whenever the parent Form object is
resized. This can be accomplished, as expected, by using the Height, Left, Top, and Width properties
from within the form's Resize event. This brings up a good point about the benefits of the WebBrowser
control and the combination of application functionality plus user interface advantages that can be obtained
by using rendered web pages. As the page is resized, the visual elements on the web pages will generally
adjust to fit the modified browser window size, and scroll bars will appear as needed . This allows the user to
exercise the ability to adjust the application as necessary without losing any information being presented by
the web page.

Private Sub Form_Resize()

With WebBrowser1
.Width = [Link] – .Left – 225
.Height = [Link] – .Top – 525
End With

End Sub

If you notice, the width and height of the browsing window is


adjusted based on the form's Width and Height properties, plus
the necessary offset to account for the border and other controls
on the form. The resulting WBDemoApp, once resized, will
highlight the effect of the resize. Note the automatic appearance
of the scroll bars.

218
Integrating Web Browsing Using the WebBrowser Objects

Visible
Use of the Visible property for the WebBrowser control would generally be no different than for any
other ActiveX control. The nature of web browsing though, generally involves switching between multiple
pages, to reduce the effect of longer download times. This is especially so for power surfers performing
research. You, as developer, may prefer to hide windows when they're not in use. Using the Visible
property, combined with the radio buttons we added earlier, will allow you to do this.

To implement this scenario, let's modify the design of the Form object.

After modifying the Form appropriately, we need to add code for two different events. We need to alter the
behavior of the Go To... button to switch which WebBrowser object is set to navigate. We also need to
modify the Visible property of the first WebBrowser object to allow viewing of the second "browser",
which we add in the same way we added the first. We attach this procedure to the radio button array,
Option1 in our code.

Private Sub Command1_Click()


If [Link](0) Then
[Link] [Link]
Else
[Link] [Link]
End If
End Sub

219
Chapter 7

Private Sub Option1_Click(Index As Integer)


Select Case Index
Case 0
[Link] = True
Case 1
[Link] = False
End Select
End Sub

Notice that the code chooses which browser navigates to the requested page, based on which radio option is
selected.

To highlight the functionality we have just added, we will perform the following steps:

1. Run WBDemoApp.
2. Switch to browser number 2.
3. Navigate to a web page.
4. Switch back to browser number 1.
5. Resize WBDemoApp.

After performing these tasks, you should notice that a skinny band of WebBrowser2 is visible along the
bottom and right sides of the application. This is due to the fact that we did not enter the same resize code
for the newly added additional browser.

220
Integrating Web Browsing Using the WebBrowser Objects

Visual UI Elements
A number of properties are exposed by the InternetExplorer objects to allow manipulation of some of
the commonly recognized graphical UI elements. By modifying these properties, a running instance of
Internet Explorer can be controlled by your application. This opens the door to numerous avenues of
customization.
The WebBrowser control ignores any attempts to set these properties for it. Attempting to
set, for example, the StatusBar property of a WebBrowser control will not generate an
error, but will not produce any functional result.

AddressBar
In order to support the ability to programmatically reveal or hide the address bar, independent of Internet
Explorer, the AddressBar property will need to be modified. We can use the Menu Editor in VB,
accessible from the Tools drop-down menu, to provide a convenient method to toggle the value of the
AddressBar property.

221
Chapter 7

Once we have added the menu item as shown, we must add the necessary code to keep the menu's
Checked property in sync with the actual InternetExplorer AddressBar property.

Private Sub mnuIEAddressBar_Click()

[Link] = Not [Link]


[Link] = [Link]

End Sub

Private Sub cmdIELaunch_Click()

' Navigate IE to location provided in TextBox


' Note: Setting the Visible property last will decrease perceived
' response time for the navigation.

With IE
.Navigate [Link]
.Width = 420
.Height = 360
.Visible = True
.AddressBar = [Link]
End With

End Sub

Notice how the AddressBar property is merely kept in sync with the Checked property whenever the
instance of Internet Explorer is launched. If we attempt to run WBDemoApp at this point, we will see that
the instance of Internet Explorer referenced by the IE object variable is visually in sync with the menu item
Checked property.

222
Integrating Web Browsing Using the WebBrowser Objects

MenuBar, StatusBar, and ToolBar


The MenuBar, StatusBar, and ToolBar properties perform in much the same fashion as the
AddressBar we looked at earlier.

If we perform the same modifications through the Menu Editor, we can produce similar results for the other
"Bar" properties exposed by the InternetExplorer object. Of course we will have to add the
appropriate functions to the appropriate events for the newly created menu items, as well as modify the event
in which the Internet Explorer instance is launched, to ensure the properties are kept in synch.

Private Sub cmdIELaunch_Click()

' Navigate IE to location provided in TextBox


' Note: Setting the Visible property last will decrease perceived
' response time for the navigation.

With IE
.Navigate [Link]
.Width = 420
.Height = 360
.Visible = True
.AddressBar = [Link]
.MenuBar = [Link]
.StatusBar = [Link]
.ToolBar = [Link]
End With

End Sub

Private Sub mnuIEMenuBar_Click()


[Link] = Not [Link]
[Link] = [Link]
End Sub

Private Sub mnuIEStatusBar_Click()


[Link] = Not [Link]
IE. StatusBar = [Link]
End Sub

Private Sub mnuIEToolBar_Click()


[Link] = Not [Link]
IE. ToolBar = [Link]
End Sub

223
Chapter 7

Upon successfully modifying the code, running our WBDemoApp application will now allow all four Bar
attributes to be modified by our customized application.

FullScreen and TheaterMode


The FullScreen and TheaterMode properties of the InternetExplorer object are somewhat
confusing. Both properties effectively result in an Internet Explorer instance being enlarged to take over the
entire screen. In fact, you may have used that property in the FullScreen toolbar button that is available
on the Internet Explorer toolbar.

The strange thing is that the FullScreen button on the Internet Explorer toolbar actually toggles the
TheaterMode property and there is no method to actually set the FullScreen property in Internet
Explorer. The difference between these two properties is very simple. The FullScreen property causes
Internet Explorer to maximize to the full size of the desktop, without any "bars". The TheaterMode
causes Internet Explorer to maximize to the size of the desktop, also without borders, while providing the
following:

 Minimized version of the toolbar


 AddressBar
 MenuBar
 Integration of the bars on one line (no stacking bars)
 Modified Minimize, Maximized, and Close buttons in upper-right corner of Internet Explorer

224
Integrating Web Browsing Using the WebBrowser Objects

In other words, the FullScreen goes completely full screen, while TheaterMode maintains application
UI elements, as seen here:

Its important to note that mixing the settings for FullScreen and TheaterMode has been known to confuse
Internet Explorer and result in weird combinations, such as:

 FullScreen with no borders, but a title bar;


 TheaterMode with full-sized toolbars and stacked bars!

Because of the difference in these properties from the "Bar" properties, we've chosen to put a separator
between the two groups of menu items on our IE Config dropdown. We should also default the Checked
property of these two menu items to not selected.

We now need to add the code necessary to synch the menu items and Internet Explorer:

Private Sub cmdIELaunch_Click()


With IE
.Navigate [Link]
.Width = 420
.Height = 360
.Visible = True
.AddressBar = [Link]
.MenuBar = [Link]
.StatusBar = [Link]
.ToolBar = [Link]
.FullScreen = [Link]
.TheaterMode = [Link]
End With
End Sub

Private Sub mnuIEFullScreen_Click()


[Link] = Not [Link]
[Link] = [Link]
End Sub

Private Sub mnuIETheaterMode_Click()


[Link] = Not [Link]
[Link] = [Link]
End Sub

225
Chapter 7

Once this code is added, we can run the WBDemoApp application. If we choose the FullScreen menu item
and then resize and move WBDemoApp, we can obtain a unique functionality that is unobtainable with
Internet Explorer alone.

StatusText
The StatusText property provides a mechanism for assigning a text string to the lower left-hand section
of the StatusBar previously modified. This property performs the same action as commonly performed via
scripting within a web page. If the code

[Link] = "Launched by WBDemoApp"

is executed at some point, then the StatusText will be displayed as seen here.

This text will only remain until overwritten by page scripting, another property set, or a normal Internet
Explorer event.

226
Integrating Web Browsing Using the WebBrowser Objects

Web Page Specific


Several properties are exposed by the WebBrowser control that provide direct information about the
document or web page being loaded itself. Two of these properties, LocationName and LocationURL
are very simple. The third property, Document, is possibly the most powerful property exposed by the
control. It seems like an innocent, and obvious property to provide, but the ramifications on potential
functionality this exposes is incredible.
LocationName and LocationURL Properties
The LocationName and LocationURL properties are related to each other in the information that they
provide regarding the currently rendered document, file, or location. The value returned by these properties
varies based on whether the File or HTTP protocol is used to access the target.

Let's add the following code to the DocumentComplete event of WebBrowser1:

Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)

MsgBox [Link]
MsgBox [Link]

End Sub

The first line of code, upon navigating to a file local to the development system may result in the following:

The purpose of the LocationName property is to return the Title of the Web page which has been loaded
and rendered. Should the <TITLE> tag within the HTML page contain the value of "Demo Page", then
this value is returned by the LocationName property only if the file is loaded from the Web, or more
specifically, only if delivered via the HTTP protocol and served up by a web server. If the file is loaded
locally, using the File protocol, then LocationName property will returned the name of the file being
loaded, even if its an HTML with a <TITLE> tag.

227
Chapter 7

The LocationURL property performs the same no matter where the file is found, or what protocol is used
to load the file.

Note that the URL includes the protocol type used, even if the file path provided did not explicitly include
the protocol.

The behavior shown in the figure for the LocationName property differs from the
behavior dictated within Microsoft documentation in the MSDN Library. Testing should be
performed to confirm the behavior when using this property.

Document Property
The Document property is an incredibly powerful attribute to be exposed by the WebBrowser control.
The Document property is an object reference to the very Document Object Model generated for a web
page loaded by Internet Explorer. In other words, the entire collection of elements, or objects within a web
page are directly and immediately accessible to the Visual Basic code through the Document property –
exactly as for the DHTML application we saw in the previous chapter. Any HTML tag within a web page
can be accessed directly and its properties read or modified.

Let me repeat that! ANY element within a web page can be dynamically modified by the Visual Basic code.
Furthermore, this feature can be used to send commands to an application via the attributes of non-visual or
hidden HTML tags. Essentially, the full functionality of DHTML is completely and totally exposed to the
Visual Basic application through the Document property. The ramifications and uses of this feature could
fill an entire book completely by itself. Fortunately, I will give but a simple example.

228
Integrating Web Browsing Using the WebBrowser Objects

We are going to use the web page title, and the value of the background attribute of the web page's <BODY>
tag to change the caption of a label added just above the WebBrowser control, as shown here:

To modify the Caption property of the Label, we will use the DocumentComplete event of the
WebBrowser control (described in more detail later) to set the Caption. We will set the Caption to the
combination of the title of the Document and the background property of the <BODY> tag.

Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)

[Link] = [Link] _
& "( background image = " _
& [Link]("BodyID").background & " )"

End Sub

Note that the Title property and the background property of the BodyID item of the All collection
are used in the assignment of Label1's Caption property. The Document property is an object reference
to the top-level object in the Document Object Model for a web page. The value of the standard <TITLE>
tag in a web page is automatically assigned to the Title property of the Document object. The
"BodyID" member of the All collection is a little bit trickier. To explain, let's look at the starting HTML
in the [Link] web page being loaded.

<HTML>
<HEAD>
<META NAME="GENERATOR" CONTENT="Microsoft Visual Studio 6.0">
<TITLE> Demo Page Title </TITLE>
</HEAD>
<BODY id="BodyID" background="[Link]" leftmargin=10>

The <BODY> tag has been given an id of "BodyID". By providing an id attribute for an HTML tag within
the web page, an element (or tag) can be more easily accessed through the Document object property. The
All collection is a collection within the Document Object Model which contains all HTML tags within the
web page, therefore the HTML code listed above would create a "BodyID" member of the All collection
upon the page being rendered.

229
Chapter 7

If we go ahead and run the WBDemoApp application, we should get the following error:

If we choose debug, it should lead up right back to the line assigning the new Caption property of the
Label object.

What is wrong you ask? One little step was overlooked. Remember that the actual Document Object Model
and Document property are not provided by the [Link] file. The actual HTML Object Library is
provided by another Internet Explorer provided file, [Link]. Therefore, we need to provide a Visual
Basic project Reference to the Microsoft HTML Object Library.

230
Integrating Web Browsing Using the WebBrowser Objects

Some of you might not find this item in the Reference list. If this is the case, one of four things has
happened:

 Internet Explorer is not installed on the system.


 Internet Explorer is installed but [Link] is not registered properly.
 [Link] has been registered and referenced, but a bug in VB6 removes it from the list at that time.
In this option, just open your Visual Basic VBP file in Notepad and confirm the Reference line..
 [Link] is registered, but shows up as the Internet Explorer Scripting Object Model.

MSHTML is the true parsing and rendering engine behind Internet Explorer. It
provides the framework for creating the object model and the type library for the
HTML Object Model

231
Chapter 7

While the HTML Object Library is provided by the [Link] file, the registered name, depending on
the version of [Link] used, will probably be the Internet Explorer Scripting Object Model. Once
this reference is made, viewing the Visual Basic Project file (.vbp) will reveal the Microsoft HTML
Object Library reference

At this time, re-running WBDemoApp should result in no errors, and the label will now reflect the
appropriate value.

It is HIGHLY recommended that the Visual Basic developer become familiar with
DHTML and the Document Object Model. A strong understanding of the DOM,
DHTML, and the WebBrowser control can lead to incredibly powerful applications.

Navigation-Related
A number of properties exposed by both the WebBrowser and InternetExplorer objects deal with
the process of navigating, or modifying the process of navigating. These properties include Busy,
Offline, and Status

Busy
The Busy property is a Boolean value which indicates whether or not the control is currently in the middle
of browsing to a document or in the middle of a download operation. This property is often used in
conditional statements to determine whether or not code, which would be dependent upon the free state of
the control, can be safely executed.

Silent
The Silent property is used to modify the behavior of the WebBrowser control when faced with a
dialog box. Normally, the dialog boxes are presented to the user for confirmation or evaluation, such as
when a web site cannot be navigated. By setting the Silent property to TRUE, dialog boxes are
completely suppressed. Keep in mind that setting this property may cause vital information normally
conveyed through dialog boxes to be lost.

232
Integrating Web Browsing Using the WebBrowser Objects

To add this functionality to our WBDemoApp, we can add a menu item similar to the previous IE Config.

Offline
The Offline property is used to force either the InternetExplorer or WebBrowser control to read
the necessary data about the target file or URL from the local cache. Even if the information is available
over the network to be refreshed, the file will be loaded from the local data cache maintained for the web
browser. This property can be useful so that the application can degrade gracefully when a network
connection becomes temporarily unavailable.

Miscellaneous Properties
Of course, a very large number of properties remain to be discussed. We will endeavor to cover most of
those properties within this section. These properties can help to ascertain almost any information necessary
about the WebBrowser or InternetExplorer objects.

Name, Path, and FullName


The Name, Path, and FullName properties are closely related to each other. The order these properties
are listed above might seem somewhat out of the expected order, but the relationship between these values
is not completely intuitive.

A series of Msgbox commands will be used to emphasize the differences between these values. I will use
the WBDemoApp application as the example. To bring things into context, the copy of Visual Basic 6 used
to produce this demo was installed in the default location, and the WBDemoApp folder for the project file
was my local drive location of C:\Windows\Desktop\writing\demoapp\.

First of all, let's start with the WebBrowser control. As one might expect, using a Msgbox command with
the Name property for WebBrowser2 will give a value of WebBrowser2.

233
Chapter 7

This value was probably fairly predictable. Now the Path property value, on the other hand, is not very
intuitive in its returned value:

For those developers familiar with the default installation folder for Visual Studio, this is the folder where
Visual Basic 6 is installed by default. That would seem a little strange to some, since the Visual Basic
project is in another directory. The path to the application would seem to be more appropriately set to the
Visual Basic project directory. A little explanation is revealed if we produce a message box with the
FullName property value for WebBrowser2:

As you can see, the FullName and Path properties are referring to the location of Visual Basic 6. This
certainly seems a little strange and definitely not intuitive. The description of the FullName property, for
example, states that it "Returns a string that evaluates to the fully qualified path of the executable file that
contains the Internet Explorer application." But wait a minute! First of all, what about the executable file
that contains the WebBrowser control? Second, wouldn't the executable file be the WBDemoApp?

If you check out the Path and FullName properties in MSDN Library, you will see that those properties
only apply to InternetExplorer. In reality, these properties obviously apply to the WebBrowser
control. Furthermore, the executable file containing the WebBrowser control is actual Visual Basic when
in the Design environment; hence the returned values reference the appropriate information for [Link].
This should lead to the obvious question of what value is returned when WBDemoApp is compiled. If the
executable is compiled into the project directory, the value of Path changes, when [Link] is
run, from the Visual Basic installation directory to C::

234
Integrating Web Browsing Using the WebBrowser Objects

The value of the FullName, likewise, produces the expected full name and path of the container
executable, or C:\WINDOWS\DESKTOP\writing\demoapp\[Link].

If we explore the value of these properties for an instance of the InternetExplorer automation object,
we will find a similarly unintuitive result. The results of the properties are obtained by using a message box
command on the IE object reference that we have used thus far in our WBDemoApp demonstration
application. The Name property, as might be expected, is predictable, returning the value Internet
Explorer.

The Path and FullName properties of the InternetExplorer do not, as one might expect, return a value
that is equivalent to the location or full name of [Link]. The actual results returned point to a
different container executable, C:\WINDOWS\

The value of C:\WINDOWS\ might seem somewhat surprising, but keep in mind that starting with Internet
Explorer 4.x, the WebBrowser and InternetExplorer objects are now hosted by the Windows Shell,
which is [Link]. Therefore, the results of [Link] is much more sensible, giving
C:\Windows\[Link] This indicates that the "container" executable for the
InternetExplorer object is, in fact, [Link], otherwise known as the Windows Shell.

One last thing to keep in mind, is that these message box dialogs were returned either prior to the instance
of Internet Explorer being launched and assigned as an object reference to IE, or after launching, but
without the instance of Internet Explorer having been closed. Closing the launched instance of Internet
Explorer will result in an error dialog box indicating that the remote server component cannot be found,
thus halting the WBDemoApp application.

This error dialog will be the same for attempting to access numerous properties of the
InternetExplorer object whenever an instance has been launched and closed manually, as long as the
appropriate error handling code has not been provided.

Parent
The Parent property, as might be expected, returns an object reference to the Parent of the WebBrowser
or InternetExplorer objects. In order to obtain the following dialogs, the Name property of the
Parent property was used to return a functionality reference to the identity of the object returned. The
Parent property of the WebBrowser control returns Form1

235
Chapter 7

This result should seem very predictable, as we have yet to modify the name of the Form object on which
we had placed the WebBrowser control instance. The results of the Parent property on
InternetExplorer obj