100% found this document useful (7 votes)
46 views

Building Distributed Applications with Visual Basic NET Dan Fox All Chapters Instant Download

Fox

Uploaded by

pagelcloosyd
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
100% found this document useful (7 votes)
46 views

Building Distributed Applications with Visual Basic NET Dan Fox All Chapters Instant Download

Fox

Uploaded by

pagelcloosyd
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
You are on page 1/ 47

Download the full version of the ebook at

https://ebookfinal.com

Building Distributed Applications with Visual


Basic NET Dan Fox

https://ebookfinal.com/download/building-
distributed-applications-with-visual-basic-net-
dan-fox/

Explore and download more ebook at https://ebookfinal.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Developing Web applications with Visual Basic NET and ASP


NET 1st Edition John Alexander

https://ebookfinal.com/download/developing-web-applications-with-
visual-basic-net-and-asp-net-1st-edition-john-alexander/

ebookfinal.com

Essential ASP NET with Examples in Visual Basic NET 1st


Edition Fritz Onion

https://ebookfinal.com/download/essential-asp-net-with-examples-in-
visual-basic-net-1st-edition-fritz-onion/

ebookfinal.com

Practical Database Programming with Visual Basic NET 1st


Edition Ying Bai

https://ebookfinal.com/download/practical-database-programming-with-
visual-basic-net-1st-edition-ying-bai/

ebookfinal.com

Practical Database Programming with Visual Basic NET 2nd


Edition Ying Bai

https://ebookfinal.com/download/practical-database-programming-with-
visual-basic-net-2nd-edition-ying-bai/

ebookfinal.com
Mastering Visual Basic NET 1st Edition Petroutsos

https://ebookfinal.com/download/mastering-visual-basic-net-1st-
edition-petroutsos/

ebookfinal.com

Sams Teach Yourself ADO NET in 21 Days 1st Edition Dan Fox

https://ebookfinal.com/download/sams-teach-yourself-ado-net-
in-21-days-1st-edition-dan-fox/

ebookfinal.com

Visual Basic NET Bible 1st Edition Bill Evjen

https://ebookfinal.com/download/visual-basic-net-bible-1st-edition-
bill-evjen/

ebookfinal.com

Visual Basic and Visual Basic NET for Scientists and


Engineers 1st Edition Christopher Frenz (Auth.)

https://ebookfinal.com/download/visual-basic-and-visual-basic-net-for-
scientists-and-engineers-1st-edition-christopher-frenz-auth/

ebookfinal.com

Visual Basic NET From VB6 to VB NET 1st Edition Matt


Tagliaferri

https://ebookfinal.com/download/visual-basic-net-from-vb6-to-vb-
net-1st-edition-matt-tagliaferri/

ebookfinal.com
Building Distributed Applications with Visual Basic NET
Dan Fox Digital Instant Download
Author(s): Dan Fox
ISBN(s): 9780672321306, 0672321300
Edition: illustrated edition
File Details: PDF, 8.81 MB
Year: 2001
Language: english
Building Distributed Applications
with Visual Basic .NET
Dan Fox
Quilogy, Inc.

800 East 96th Street, Indianapolis, IN 46240 USA


ASSOCIATE PUBLISHER
Building Distributed Applications Linda Engelman
with Visual Basic .NET ACQUISITIONS EDITOR
Sondra Scott
Copyright © 2002 by Sams Publishing
All rights reserved. No part of this book shall be reproduced, stored in a DEVELOPMENT EDITOR
retrieval system, or transmitted by any means, electronic, mechanical, photo- Shannon Leuma
copying, recording, or otherwise, without written permission from the pub- MANAGING EDITOR
lisher. No patent liability is assumed with respect to the use of the information Charlotte Clapp
contained herein. Although every precaution has been taken in the preparation
of this book, the publisher and author assume no responsibility for errors or PROJECT EDITOR
omissions. Nor is any liability assumed for damages resulting from the use of Elizabeth Finney
the information contained herein.
COPY EDITORS
International Standard Book Number: 0-672-32130-0 Geneil Breeze
Michael Henry
Library of Congress Catalog Card Number: 00-111343
Printed in the United States of America INDEXER
Erika Millen
First Printing: November 2001
04 03 02 01 4 3 2 1
PROOFREADER
Plan-it Publishing

Trademarks TECHNICAL EDITORS


Phil Syme
All terms mentioned in this book that are known to be trademarks or service
Dan Suceava
marks have been appropriately capitalized. Sams Publishing cannot attest to
the accuracy of this information. Use of a term in this book should not be TEAM COORDINATOR
regarded as affecting the validity of any trademark or service mark. Chris Feathers

MEDIA DEVELOPER
Warning and Disclaimer Dan Scherf
Every effort has been made to make this book as complete and as accurate as
INTERIOR DESIGNER
possible, but no warranty or fitness is implied. The information provided is on
Anne Jones
an “as is” basis. The author(s) and the publisher shall have neither liability nor
responsibility to any person or entity with respect to any loss or damages aris- COVER DESIGNER
ing from the information contained in this book or from the use of programs Aren Howell
accompanying it.
Contents at a Glance
Foreword x
Introduction 1

Part I .NET Concepts


1 The Microsoft .NET Architecture 9
2 The Development Environment 49
3 VB .NET Language Features 79
4 Object-Oriented Features 119
5 Packaging, Deployment, and Security 165
6 Error Handling and Debugging 199

Part II Enterprise Techniques


7 Accessing Data with ADO.NET 225
8 Building Components 299
9 Accessing Component Services 345
10 Building Web Forms 401
11 Building Web Services 509

Part III Integration


12 Accessing System Services 549
13 Implementing Services 609
14 Integrating with the Enterprise 653
Index 705
Table of Contents
Introduction 1
The Book’s Focus ....................................................................................1
The Book’s Layout ..................................................................................2
Part I: .NET Concepts ........................................................................2
Part II: Enterprise Techniques ............................................................2
Part III: Integration ............................................................................3
The Book’s Illustrative Style, Sample Application, and Web Site ..........4
The Book’s Audience ..............................................................................5

PART I .NET Concepts


1 The Microsoft .NET Architecture 9
A New Platform ....................................................................................11
What .NET Is and Is Not..................................................................12
VB’s Place in .NET ..........................................................................14
Common Language Runtime Architecture ............................................16
Goals of the CLR..............................................................................17
Managed Versus Unmanaged Code..................................................20
Common Language Specification ....................................................21
CLR Internals ..................................................................................22
Run-time Components......................................................................37
Class Libraries ..................................................................................44
Summary ................................................................................................47

2 The Development Environment 49


A New IDE ............................................................................................50
Projects and Solutions ......................................................................51
IDE Windows ..................................................................................55
Supported File Types ........................................................................64
Setting Project References................................................................67
Macros and Add-Ins ........................................................................69
Using Attributes ....................................................................................73
Command-Line Compilation ................................................................76
Summary ................................................................................................77

3 VB .NET Language Features 79


Keyword Changes ..................................................................................80
Functional Changes................................................................................85
Declarations ......................................................................................85
Operators ..........................................................................................86
Data Types ........................................................................................88
Arrays ..............................................................................................90
Structures ..........................................................................................98
Conversion ......................................................................................100
Strings ............................................................................................101
Block Scope....................................................................................105
Procedures ......................................................................................106
Upgrading from VB 6.0 ......................................................................107
Using the Upgrade Wizard ............................................................109
Summary ..............................................................................................117

4 Object-Oriented Features 119


OO Terminology ..................................................................................120
Encapsulation..................................................................................120
Polymorphism ................................................................................121
Inheritance ......................................................................................121
More OO Terms..............................................................................122
Role of Namespaces ............................................................................123
Defining Classes ..................................................................................126
Creating Members................................................................................127
Creating Methods ..........................................................................127
Creating Properties ........................................................................128
Creating Fields................................................................................130
Creating Events and Delegates ......................................................131
Creating Named Constants ............................................................144
Using Inheritance ................................................................................145
Using Polymorphism ......................................................................149
Creating and Using Shared Members ............................................150
Using Interface Based Programming ..................................................152
Versioning ......................................................................................154
Using Constructors and Destructors ....................................................155
Parameterized Constructors............................................................156
Destructors......................................................................................157
Summary ..............................................................................................163

5 Packaging, Deployment, and Security 165


Packaging and Deployment Concepts ................................................166
Assemblies Revisited......................................................................166
PreJITing Your Code ......................................................................176
Packaging and Deployment Options ..................................................177
Deployment Scenarios....................................................................177
Installing Server Resources ............................................................182
Securing Your Code ............................................................................187
Code Access Security ....................................................................187
Role-Based Security ......................................................................194
Summary ..............................................................................................198
vi
BUILDING DISTRIBUTED APPLICATIONS WITH VISUAL BASIC .NET

6 Error Handling and Debugging 199


Handling Exceptions............................................................................200
Using Unstructured Exception Handling ......................................202
Using Structured Exception Handling............................................205
Using the VS.NET Debugger ..............................................................209
Starting Debugging ........................................................................210
Attaching to a Running Process ....................................................213
Using Diagnostics ................................................................................214
Using the Debug Class ..................................................................215
Using Tracing ................................................................................217
Using Listeners ..............................................................................220
Summary ..............................................................................................222

PART I Enterprise Techniques


7 Accessing Data with ADO.NET 225
ADO.NET Defined ..............................................................................226
Relation to OLE DB and ADO ......................................................228
System.Data Architecture ....................................................................228
Managed Providers ........................................................................229
Connection Pooling ........................................................................242
Disconnected Data..........................................................................244
Application Scenario: The Quilogy Education System ......................256
Defining the Data Structure............................................................258
Handling Data Access ....................................................................286
Summary ..............................................................................................298

8 Building Components 299


Designing Components........................................................................300
Building Classes Versus Components ............................................301
Marshalling Objects........................................................................302
Building Reusable Components ....................................................310
Using .NET Remoting ........................................................................317
Hosting Components ......................................................................318
Activating Components ..................................................................325
Using Advanced Remoting ............................................................331
Calling Unmanaged DLLs ..................................................................333
Wrapping Unmanaged DLLs ........................................................335
Using Callbacks..............................................................................343
Summary ..............................................................................................344
vii
CONTENTS

9 Accessing Component Services 345


Migrating from MTS to COM+ ..........................................................347
Administrative Changes ................................................................347
Architectural Changes ....................................................................348
Implementing COM+ Services ......................................................354
Automatic Transactions ..................................................................358
Object Activation and Construction ..............................................363
Object Pooling ................................................................................366
Shared Properties............................................................................367
COM+ Events ................................................................................369
Queued Components ......................................................................374
COM+ Security ..............................................................................378
Registering Serviced Components ......................................................382
First-Use Registration ....................................................................382
Manual Registration ......................................................................384
Interoperating ......................................................................................384
Accessing COM Components from .NET ....................................385
Accessing .NET Components from Unmanaged Code..................391
Summary ..............................................................................................399

10 Building Web Forms 401


Understanding ASP.NET ....................................................................402
ASP.NET Architecture....................................................................403
Programming Models ....................................................................407
Differences from ASP ....................................................................408
Example Application............................................................................418
Web Forms Architecture ......................................................................419
Page Processing Flow ....................................................................419
Event Model ..................................................................................425
ASP.NET Features ..............................................................................430
Configuration Files ........................................................................430
Security ..........................................................................................433
State Management ..........................................................................449
Caching ..........................................................................................455
Tracing............................................................................................462
ASP.NET Server Controls ..................................................................464
HTML Server Controls ..................................................................465
Web Server Controls ......................................................................469
Web Forms User Controls ..............................................................505
Summary ..............................................................................................508
viii
BUILDING DISTRIBUTED APPLICATIONS WITH VISUAL BASIC .NET

11 Building Web Services 509


Web Service Architecture ....................................................................510
Uses for Web Services....................................................................512
Web Service Technology ................................................................514
Web Service Implementation ..............................................................523
Creating a Web Service Class ........................................................524
Web Service Design Issues ............................................................534
Customizing SOAP ........................................................................536
Consuming a Web Service ..................................................................539
Using the Client Proxy ..................................................................542
Summary ..............................................................................................545

PART III Integration


12 Accessing System Services 549
Understanding I/O Concepts................................................................550
Reading and Writing Files..............................................................552
Creating Multithreaded Applications ..................................................577
Using Threads ................................................................................579
Using Thread Pools ........................................................................587
Manipulating Windows Processes ......................................................594
Using Cryptography ............................................................................602
Summary ..............................................................................................608

13 Implementing Services 609


Creating Service Applications ............................................................610
Building a Service ..........................................................................611
Installing Services ..........................................................................616
Controlling Services ......................................................................622
Scheduling the Service ........................................................................625
Using a Simple Timer ....................................................................625
Using Event Logging ..........................................................................627
Writing to the Event Log................................................................628
Using a Custom Log ......................................................................630
Receiving Notification....................................................................633
Monitoring Performance......................................................................634
Installing Custom Performance Counters ......................................635
Using Performance Counters..........................................................636
Sampling Performance Counters....................................................639
Communicating over the .NET............................................................639
Using System.Net ..........................................................................640
Using FTP ......................................................................................646
Summary ..............................................................................................653
ix
CONTENTS

14 Integrating with the Enterprise 653


Using the XML Classes ......................................................................654
Streaming XML..............................................................................655
Accessing Data With the DOM......................................................667
Transforming a Document..............................................................672
Handling XML Schemas ................................................................675
Serializating to XML......................................................................680
Integrating Messaging..........................................................................686
Administering Queues ....................................................................687
Sending and Receiving Messages ..................................................692
Integrating Active Directory ................................................................699
Querying the Directory ..................................................................701
Summary ..............................................................................................704

Index 705
Foreword
The shift to .NET technologies is underway, bringing with it exciting opportunities that only
distributed computing makes possible. This I know to be true, having experienced the awesome
power of .NET technologies at work each day where our award-winning internal systems run
on the .NET platform.
As Chief Technology Officer at Quilogy, a provider of business solutions through digital con-
sulting, advanced hosting, and technical education, I have worked closely with Dan Fox over
the past several years learning, experimenting with, and applying new Microsoft technologies
to our own organization. For only by testing and building proven solutions for ourselves can
we be sure to provide our customers with the best, most effective solutions. Our work over the
past year to incorporate .NET strategies has been especially rewarding.
Dan’s demonstrated mastery of .NET technologies at Quilogy as well as his previous profes-
sional experiences building large-scale systems for a major oil company, extensive knowledge
of database and object-oriented systems, as well as numerous Microsoft certifications make
him uniquely qualified to write this book. Additionally, this year marks the 10th anniversary of
Visual Basic, which makes this book’s publication particularly meaningful. As we have found
for ourselves, the best way for professional VB developers to enter into the .NET sphere is
through Visual Basic .NET.
As the leading language used by corporate developers to build solutions, VB with its new .NET
qualities now can address even more of the needs and concerns of business developers, which
makes understanding it at this time so crucial. Part of the great news about .NET is that you
can move into it and still leverage your existing skills because of its multilanguage support. As
the book shows, there are some concepts and techniques you’ll need to learn, but they’ll build
on those you already have, so you can start to take advantage of all the new features and capa-
bilities that .NET has to offer.
Rather than restating Microsoft’s documentation, Dan explains the course of an application’s
development and offers wide-ranging insight as he delves into the whys, such as why VB .NET
is important, and the hows, such as how VB .NET fits into the general scheme. Additionally,
numerous code examples clearly illustrate key points and complement the book’s easy readabil-
ity. Dan is a sought-after instructor and speaker at such major events as TechEd and Developer
Days. He is also a regular contributor to several print and online magazines including Visual
Basic Programmers Journal, SQL Server Magazine, InformIT, and Advisor journals. His exem-
plary teaching methods, engaging speaking voice, and comprehensive knowledge shine through
in this book.
Currently as Technical Director, Dan is charged with helping me select technologies, set appli-
cation architecture, identify successful design patterns, and educate staff on emerging technolo-
gies. Since taking on this important position in the company, he has been instrumental in the
development of Quilogy’s breakthrough system for building portal solutions called Quilogy
Accelerator (QA). Using the code to Quilogy’s own intranet as a .NET accelerator, QA facili-
tates the process of creating portal and intranet solutions faster and less expensively than either
buying or building from scratch.
As we have found with QA and you will find as you apply .NET strategies to your own busi-
ness practices, .NET is changing the face of technological business solutions in extraordinarily
exciting new directions.
Alan Groh
CTO Quilogy
About the Author
Dan Fox is Technical Director for Quilogy in Overland Park, Kansas. Quilogy (www.quilogy.com)
is a leading Microsoft Gold Certified Partner and Solution Provider with more than 450 con-
sultants nationwide in 16 cities. Quilogy provides digital consulting and technical education
services to a wide range of clients and specializes in building solutions on the Microsoft plat-
form. As a Certified Technical Education Center, Quilogy teaches the range of Microsoft
Official Curriculum (MOC) courses and specializes in building solutions and teaching courses
using both .NET development and .NET Enterprise Servers.
Dan is a Microsoft Certified Solutions Developer, Systems Engineer, and Trainer who has been
a consultant, instructor, and managing consultant on a variety of projects. In his role as a
Technical Director, Dan provides technical guidance to Quilogy’s consultants and customers.
Before joining Quilogy in 1995, Dan worked for Chevron in Houston, Texas, and the National
Association of Insurance Commissioners in Kansas City, Missouri. Dan earned his B.S. in
Computer Science from Iowa State University in 1991.
Dan has been a frequent contributor to the Visual Basic Programmer’s Journal and has written
numerous articles for SQL Server magazine, Advisor journals, and InformIT.com. He authored
the book Pure Visual Basic from Sams and coauthored a book on the Visual Basic 6 Distributed
Exam (70-175) for Certification Insider Press. He has spoken at TechEd and several Developer
Days conferences and Microsoft events.
Dan lives in Shawnee, Kansas, with his lovely wife, Beth, and two young daughters, Laura and
Anna. Besides earning the nickname “Dan.NET” from his family, Dan spends his time reading,
enjoying movies, and as always, rooting for the Cubs.

About the Technical Reviewers


Dan Suceava is currently a Senior Programmer for Vitrix, Inc., a time-and-attendance software
company located in Tempe, Arizona. He has been developing desktop and n-tiered applications
in Visual Basic since 1996. He currently has completed working on an ASP solution that offers
time keeping over the Web to other businesses. He holds a Master’s Degree in Computer
Science from Arizona State University.
Phil Syme has been programming with C++ and Visual Basic since the release of Windows 3.1.
He helped create several enterprise-scale projects developed for Fortune 100 companies that
used Microsoft technologies. Phil has coauthored two articles published in IEEE symposiums.
Currently, Phil is writing two books with Peter Aitken, called Sams Teach Yourself Internet
Programming with C# in 21 Days and Sams Teach Yourself Internet Programming with VB .Net
in 21 Days.
Eric Wilson has been developing business applications for eCommerce, Internet, and LAN-
based solutions since 1994. Eric is certified in a variety of Microsoft solutions and has achieved
the following status with Microsoft: MCSE (Microsoft Certified Systems Engineer), MCSD
(Microsoft Certified Solutions Developer), MCT (Microsoft Certified Trainer), MCP (Microsoft
Certified Professional), and MCP + I (Microsoft Certified Professional + Internet). Currently,
Eric is the President and CEO of Web Basix, Inc., located in RTP (Research Triangle Park),
North Carolina, focusing on enterprise level application development and developer training.
Dedication
To my daughters, Laura and Anna, who are always a reminder of God’s blessings.

Acknowledgments
First, I’d to thank the Senior Acquisitions Editor on this project at Sams, Sondra Scott. From
our initial contact, she has been an encouragement and a great person to work with. She made
sure that each step in the process went smoothly and provided excellent feedback early in the
process in the form of reviews. In addition, I’d like to thank Shannon Leuma, the Development
Editor, who was ever vigilant to keep me on schedule, make sure that the content was well
organized, and made many suggestions that served to make this a better book.
Of course, the two key elements of any technical book such as this, the actual written word and
the code, were greatly improved by the copyediting skills of Mike Henry and Geneil Breeze,
and the technical reviews of Phil Syme, Dan Suceava, and Eric Wilson. The five of them made
sure that the book was readable and contained accurate information, something that was diffi-
cult given the fact that the reviewers had to work with multiple beta versions of the product for
most of the development cycle.
As you can tell from the cover and forward, this book was a team effort by Quilogy, the com-
pany for which I work. President and CEO Randy Schilling and Chief Technology Officer
Alan Groh’s encouragement and investment in the project was instrumental to making it a suc-
cess. Because the book was developed so early in the product life cycle, their willingness to
give me the resources to develop a book of this scope, including both the time and travel to
Redmond, contributed greatly to the quality of the final result. Throughout the process, Quilogy
consultants and instructors reviewed the content and provided helpful advice and suggestions.
To all these talented people, I’m certainly indebted, particularly, Tim Vanover, Dave Wanta,
Jason Wisener, Sue Van Gels, Adrian Anttila, and Cathey Barrett.
In addition, the scope and purpose of the book was shaped and honed through excellent reviews
by Ari Bixhorn, VB Product Manager at Microsoft; Steve Hoag, Senior Technical Writer for
VB User Education at Microsoft; Kyle Lutes, Assistant Professor at the Computer Technology
Department of Purdue University; Richard Nelson, Senior Software Architect at Intuitive
Manufacturing Systems; Lars Powers, Vice President/Solution Development at Acclarant, Inc.;
Mike Snell, Chief Software Architect at Acclarant, Inc.; and Larry Wall, Team Leader Microsoft
Group at Synapse Technology. Thanks to all of you for your help.
And so, as is true of any book, this one was truly a team effort. That being said, any errors are
only mine, so feel free to e-mail me at dfox@quilogy.com with corrections and suggestions.
Finally and most importantly, I couldn’t have embarked on this project without the loving sup-
port of my wife, Beth, and daughters, Laura and Anna. Beth’s continuous encouragement and
patience during this project made it much easier to accomplish, and my girls as always pro-
vided the balance that keeps my technological pursuits in perspective.
Tell Us What You Think!
As the reader of this book, you are our most important critic and commentator. We value your
opinion and want to know what we’re doing right, what we could do better, what areas you’d
like to see us publish in, and any other words of wisdom you’re willing to pass our way.
As an associate publisher for Sams Publishing, I welcome your comments. You can e-mail
or write me directly to let me know what you did or didn’t like about this book—as well as
what we can do to make our books stronger.
Please note that I cannot help you with technical problems related to the topic of this book,
and that due to the high volume of mail I receive, I might not be able to reply to every
message.
When you write, please be sure to include this book’s title and author as well as your name
and phone or fax number. I will carefully review your comments and share them with the
author and editors who worked on the book.

E-mail: feedback@samspublishing.com

Mail: Sams Publishing


800 East 96th Street
Indianapolis, IN 46240 USA
Introduction
Congratulations on stepping into the world of .NET! As you no doubt know by now, for many
developers, this is a big step. .NET in general and VB .NET in particular introduce new tech-
nology and new ways of performing familiar tasks that require attention to both conceptual and
practical issues when designing and developing software.
This introduction explains the focus, layout, illustrative style, sample application, Web site, and
intended audience of the book.

The Book’s Focus


Not all software is created equal. The architecture and techniques you use when designing and
building a forms-based application, for example, are not the same as for building a Web-based
application. Because many different types of applications require different approaches, and
thus will use VB .NET in different ways, this book focuses on building distributed applications.
By “building” distributed applications, I’m referring to the design and construction of the soft-
ware. To that end, this book focuses both on architectural issues and implementation by explain-
ing how a certain aspect of VB .NET fits into the bigger picture, and how it can or should be
used in a distributed application in addition to the details of the syntax. By distributed applica-
tions, I mean those applications that employ a Web architecture and typically are constructed in
logical services or tiers (presentation, business logic, data access). As a result, for example,
developing forms-based applications using the Windows Forms package is beyond the scope of
this book, whereas almost a quarter of the book is devoted to building presentation services
using both Web Forms and Web Services.
As mentioned, distributed applications also include building business logic and data access ser-
vices. Therefore, some of the largest chapters deal with integrating VB .NET with Component
Services and using ADO.NET and XML. Many readers might be familiar with this architecture
as Windows DNA although that marketing term refers to the previous generation of technology
including VB 6.0 and COM. Indeed, this book can be thought of as a collection of techniques
for building updated Windows DNA applications with VB .NET.
In addition, I’ve placed some emphasis on building server-based applications as well and have
included coverage on Windows service applications and employing the networking APIs in
.NET. I’ve included these topics because they often are employed as simply an additional inter-
face to a distributed application and are needed to create robust back ends for data exchange or
data loading.
2
Building Distributed Applications with Visual Basic .NET

The Book’s Layout


To walk you through the conceptual and practical issues, this book is comprised of three sec-
tions that will facilitate understanding of not only the how but also the why of building distrib-
uted applications.

Part I: .NET Concepts


Part I, “.NET Concepts,” provides an overview of the key concepts that developers need to be
aware of when undertaking projects using VB .NET. The section begins with Chapter 1, “The
Microsoft .NET Architecture,” which not only introduces the platform but also dives right into
the substrate of VB .NET, the common-language runtime (CLR) upon which everything in the
product is built. The CLR is indeed the revolutionary aspect of VB .NET, and, as you’ll see,
when put in proper context, VB .NET can simply be thought of as a tool used to build applica-
tions for the CLR, referred to as managed applications.
Although a good deal of technical information is found in Chapter 1, my intent is not to scare
off anyone. However, I think it is crucial to gain at least a surface level understanding of the
CLR because it helps make sense of many of the other concepts in VB .NET such as those dis-
cussed in Chapter 4, “Object-Oriented Features,” and Chapter 5, “Packaging, Deployment, and
Security.” In addition, Part I covers the changes and new features in both Visual Studio .NET in
Chapter 2, “The Development Environment,” and the VB language itself in Chapter 3, “VB .NET
Language Features.” Finally, the section closes with Chapter 6, “Error Handling and Debugging,”
which discusses how error handling and debugging have been improved in this version of the
product.

Part II: Enterprise Techniques


Part II, “Enterprise Techniques,” is the core of the book and is comprised of five chapters that
discuss each of the services layers (presentation, business, data access) in a distributed applica-
tion in reverse order. The section begins with Chapter 7, “Accessing Data with ADO.NET,”
which examines how the ADO.NET programming model enables you to more easily build
loosely coupled applications while taking advantage of XML.
This chapter, and the others in the section, provide examples from a sample application that
implements a simple student registration site for the company I work for, Quilogy. Quilogy
(www.quilogy.com) is a digital consulting firm that offers technical education at training cen-
ters around the country. To that end, students need to be able to query our course schedule,
register for class, review their transcript, and so on from our public Web site. The sample
application implements these features using VB .NET and is provided, along with the underly-
ing database schema, on the companion Web site (www.samspublishing.com). The application
3
INTRODUCTION

uses SQL Server 2000 on the back end, so although ADO.NET supports accessing other
providers, the examples in this section and throughout the book will focus on SQL Server.
Chapter 8, “Building Components,” discusses how components are built in VB .NET. The
chapter also looks at legacy DLLs to ensure that your existing code can be used in .NET.
Finally, a discussion on how components in VB .NET applications can be shared with .NET
Remoting is presented, which, like its precursor DCOM, often comes in handy when the sub-
systems in a distributed application need to communicate across process and machine bound-
aries. Chapter 9, “Accessing Component Services,” logically follows by discussing how
business and data access logic in VB .NET components can be integrated with Windows 2000
Component Services. This allows your VB .NET components to take advantage of the object
pooling, just-in-time activation, transactional control, and other features VB developers rou-
tinely implement in distributed applications. In addition, this chapter shows how components
built in VB .NET can interoperate with classic COM components.
Part II is rounded out with Chapter 10, “Building Web Forms” and Chapter 11, “Building Web
Services,” which cover the aspects of the presentation services layer necessary to build a Web-
based application. In large part, Chapter 10 covers the architecture and features of ASP.NET
and how they differ from ASP and then discusses in detail the Web Forms programming model
using the UI of the Quilogy sample application for illustration. Chapter 11 introduces a second
type of interface that VB .NET can produce by discussing Web Services. Because Web
Services are a new concept to many developers, this chapter provides a foundation by explor-
ing the underlying technologies involved and how they are implemented in VB .NET.

Part III: Integration


The last section of the book, Part III, “Integration,” is comprised of a collection of topics that
allow VB .NET developers to extend their code. Chapter 12, “Accessing System Services,”
covers I/O concepts, creating multithreaded applications, and a brief introduction to using
cryptography. Chapter 13, “Implementing Services,” walks through creating Windows Services
in VB .NET as well as using scheduling, the event log, performance counters, and network
communication. Finally, Chapter 14, “Integrating with the Enterprise,” examines three topics
that allow VB .NET developers to extend their reach to data sources other than relational data-
bases by using the XML classes, message queuing, and integrating with Active Directory.
As you might be aware, VB .NET largely gains its functionality from the class libraries that all
the Visual Studio .NET languages can take advantage of, which I’ll refer to as the Services
Framework. As such, you’ll notice that only Chapters 2, 3, and 4 actually discuss issues partic-
ular to VB .NET. Most of the rest of the book is simply an explication of how the classes of
the Services Framework can be used within the VB .NET language. This realization is key to
understanding VB .NET as a product and its role in Visual Studio .NET. In this way, VB .NET
4
Building Distributed Applications with Visual Basic .NET

can be thought of as a tool used to integrate the prebuilt components of the Services Framework
into a specific solution. Thinking of VB .NET this way should come as no surprise to existing
VB developers because the strength of previous versions of VB also was integrating prebuilt
and custom components.

The Book’s Illustrative Style, Sample Application,


and Web Site
Typically, each chapter or major section begins with an explanatory paragraph or two that
attempts to put the topic under discussion in the proper context. For example, when discussing
ADO.NET, the first question many developers have is how it interoperates with ADO 2.x and
how knowledge of ADO will be leveraged when programming data access in VB .NET. With
the context set, the discussion moves into explaining the relevant syntax and APIs that enable
you to take advantage of the feature. In many cases, the explanation of the syntax is illustrated
using code snippets as well as tables and figures that explicate the syntax, list the methods of a
particular class, for example, or show a hierarchy that illustrates how the class fits into the big-
ger picture. Finally, in most cases, a functional example is presented in one or more code list-
ings that illustrate techniques in context. This is used as a springboard to point out interesting
aspects of the feature and alternative techniques.
Along the way, the text is peppered with explanatory notes, cautions, and sidebars that point
out related issues or point you to places elsewhere in the book or external to it where addi-
tional information can be found. For example, several notes refer to background information
from my previous book, Pure Visual Basic. Because no single book can cover a topic as big as
VB .NET and the .NET Framework, notes are often used to delineate the boundaries of the
book by giving you hints as to how a particular technique could be extended or alternatively
implemented.
To be sure, this style requires some discipline on the part of the reader because many of the
details and alternatives are embedded in the explanatory paragraphs, and the reader must refer
back to the code listings frequently to follow the discussion. However, I’ve also tried to limit
the amount of information to that immediately relevant to building applications and so, for
example, not all the overloaded signatures of each method are explained along with the myriad
arguments supported. That kind of information is better presented and should be found in the
excellent online help that ships with the product.
The other key implication of the style I’ve employed is that it is definitely not a tutorial.
Readers attempting to type in the code exactly as presented in the book will have trouble
because in many cases the code shows only the relevant portion of a larger concept that will
not execute by itself. In addition, in many cases, the code is analogous to pseudo code and is
designed to show how a particular API can be used but does not implement all the details.
5
INTRODUCTION

The approach I recommend when reading the book is to read the entire section, tracking with
the code listings and snippets, and then perusing the online documentation or other sources for
any additional information before developing your own samples in your own problem domain
using the listings as a starting point. To help you in this endeavor, as mentioned earlier, the
code listings, along with the complete Quilogy sample application discussed in Chapters 7
through 11, can be found on the Sams Web site at www.samspublishing.com. To remind you of
this as you read, each chapter introduction includes the following note:

NOTE
All code listings and supplemental material for this chapter can be found on the
book’s Web site at www.samspublishing.com.

In addition, when using the listings, it should be noted that because in VB .NET the act of ref-
erencing external libraries usually entails placing an Imports statement at the beginning of
your code file, many of the code listings and examples contain shaded Imports statements at
the beginning. These are shaded because they wouldn’t appear in actual code in that location
but are required to produce the code found in the listing or example.
This book intentionally is heavy on code listings and short on figures. I believe that developers
can learn more quickly by viewing the code of others rather than through a tutorial or a simple
discussion. I tried to restrict the use of figures to those required to place a concept in context
or, for example, to give you an idea of where in the VS .NET UI to look for a particular fea-
ture. The screen shots should not be used as a tutorial, and as you work with VS .NET, the par-
ticulars of your solution will mean that the screens you see might differ.
I’ve also focused primarily on how you implement features using code rather than the graphi-
cal designers and wizards included in VS .NET. This too is intentional because I believe that to
develop a firm foundation you need to understand what’s happening at the code level and by
nature, graphical interactions and wizards don’t translate well to this medium.

The Book’s Audience


As you read the book, you might notice that I had a primary and a secondary audience in mind.
Existing corporate VB developers are the primary audience. As a result, the book is primarily
written from the perspective of a developer comfortable with the syntax of VB 6.0 who is
building Windows DNA applications today. In fact, the prototypical reader I pictured in my
mind is the typical student who attends one of Quilogy’s Microsoft Official Curriculum (MOC)
courses on VB. Typically, these developers have been using VB for some time and are building
6
Building Distributed Applications with Visual Basic .NET

COM components to house their data access and business logic and employing Microsoft
Transaction Server or Component Services. They are also versed in ADO and ASP develop-
ment and are just beginning to use XML. For these developers, the primary challenge when
moving to VB .NET is the object-oriented nature of the Services Framework and the additional
language syntax used to implement these features. As such, Chapters 3 and 4 will be especially
useful.
The secondary audience is the ASP developer who typically has less formal training and spe-
cializes in Web development. For these developers, the challenge is to move from building
two-tiered Web applications to a multitiered architecture, as described in Chapter 7. In addi-
tion, the richness of the VB .NET language, as opposed to VBScript or JScript, will require an
adjustment.
Finally, the many classes in the Services Framework that allow you to easily use system ser-
vices will open up a new world of possibilities. I’ve tried to highlight the portions of the
Services Framework (especially in Part III) that will be the most useful.
I wrote this book because I think that the underlying technology of the platform and the direc-
tion Microsoft has chosen with VB .NET make it ideally suited to developing distributed appli-
cations. However, the paradigm shift associated with the platform and the sheer size of the
product will make it difficult for some VB developers to get a handle on how to use VB .NET.
In the end, this book provides a bit of a roadmap and a survey of VB .NET and the Services
Framework and how it can be used to build distributed applications.
So what are you waiting for? Let’s get started by exploring the foundation of VB .NET: the
Microsoft .NET architecture.
Dan Fox
Shawnee, Kansas
August 2001
PART
.NET Concepts
I
IN THIS PART
1 The Microsoft .NET Architecture 9

2 The Development Environment 49

3 VB .NET Language Features 79

4 Object-Oriented Features 119

5 Packaging, Deployment, and Security 165

6 Error Handling and Debugging 199


The Microsoft .NET CHAPTER

1
Architecture

IN THIS CHAPTER
• A New Platform 11

• Common Language Runtime Architecture 16


.NET Concepts
10
PART I

As you are no doubt already aware, Visual Basic .NET (VB .NET) is far more than simply a
new release of Visual Basic. VB .NET is actually a piece in the larger puzzle of Microsoft’s
.NET architecture. This architecture encompasses not only a new release of Visual Studio
(Visual Studio .NET), which includes a suite of languages and a common platform on which
all the Visual Studio languages run referred to as the .NET Framework, but also new releases
of server products such as SQL Server 2000, BizTalk Server 2000, and Application Center
Server 2000, collectively referred to as .NET Enterprise Servers.

A Storm Coming?
In addition to the .NET development and server story, Microsoft has disclosed prelimi-
nary plans for building and hosting a set of Web-based services under the name .NET
My Services (formerly codenamed Hailstorm). Briefly, these services will be built using
technology in the .NET Framework and will allow users the ability to share and con-
sume personal information anywhere on any device. The core of the initiative is to
integrate disparate silos of information such as tasks, contacts, inbox, schedule, notifi-
cations, and favorites, among others, into a single secure Web-based information
store accessible via standard Internet protocols.
Currently, Passport, Microsoft’s authentication service, is the only publicly available
piece of this vision that is referred to both as Building Block Services and Foundation
Services. Passport integration in ASP.NET will be discussed in Chapter 10, “Building
Web Forms” while more information on .NET My Services can be found at
http://www.microsoft.com/myservices/default.asp.

Together, all these new tools are designed to help developers build modern, robust, distributed
applications. To help you understand how VB .NET fits into the architecture, this chapter will
discuss the platform and its implications for VB developers. Although this is a large chapter
with a lot of technical material, the differences in the fundamental architecture between previ-
ous versions of VB and VB .NET are significant. So significant, in fact, that you need to
immediately get a baseline for how these changes have been implemented and what they mean
to the larger picture of the .NET Framework and Visual Studio .NET.

NOTE
All code listings and supplemental material for this chapter can be found on the
book’s Web site at samspublishing.com.
The Microsoft .NET Architecture
11
CHAPTER 1

A New Platform 1

THE MICROSOFT
For corporate developers, application development has gone through several major shifts in the

ARCHITECTURE
last decade. As we started the 1990s, we were already immersed in the shift from developing

.NET
character-based monolithic mainframe applications to two-tier client/server applications on
PC-based hardware and operating systems utilizing ODBC-compliant relational databases and
graphical user interfaces (GUIs). At nearly the same time, we began to see the adoption of
object-oriented programming (OOP) concepts such as encapsulation, inheritance, polymor-
phism, and reusable components into development tools such as PowerBuilder and Visual
Basic. With a subsequent move to distributed computing relying on n-tier architectures and
component-based programming, by early 1997, many of these tools and technologies were rel-
atively mature, widely distributed, and entrenched in the corporate developer community.
From the perspective of a corporate developer utilizing Microsoft products, this produced an
architecture in which a Visual Studio client application written in VB or Microsoft Foundation
Classes (MFC) communicated with COM components running in Microsoft Transaction Server
(MTS) using the DCOM protocol. The components themselves accessed a relational database
such as SQL Server or Oracle using an ODBC driver or, later, an OLEDB provider. By utiliz-
ing the object context, MTS gave developers the ability to handle transactions across these het-
erogeneous databases using XA (a subset of services from the X/Open Distributed Transaction
Processing (DTP)) and centralized object destruction and creation.
Of course, the largest change had reached critical mass by 1997 with the widespread adoption
of the Internet, HTML, and now XML. Although Microsoft released a new development tool,
Visual InterDev (VID), and a programming model for Web development, Active Server Pages
(ASP), both of these were largely additions to the existing architecture that provided integra-
tion with existing components and relational databases, but did not alter the way development
was done in the core Visual Studio languages Visual Basic and Visual C++. In addition, the
programming model and visual design tools provided in VID and ASP were not nearly as
robust as those in the more mature products. Attempts to integrate Web programming into VB,
such as the inclusion of ActiveX documents, DHTML applications, and Web classes, only
illustrated the point that at their core, the flagship development tools were ill-suited for life in a
Web world. One of the main reasons for this is that the tools relied on technology—such as the
Win32 API, COM, and DCOM—that was developed in the early 1990s when desktop comput-
ing was central and when persistently connected clients in an insulated LAN environment were
the norm.
Developing applications for which the Internet is the platform requires a different mindset—a
mindset that moves from thinking of writing software for only internal consumption to one in
which all users of the Internet are your potential customers. And this requires different technol-
ogy that is up to the task of incorporating support for the loosely coupled nature of clients and
.NET Concepts
12
PART I

servers, a new security model, and the integration of industry standard HTTP and XML as
ubiquitous protocols. I don’t know about you, but if all this could be packaged within a modern
object-oriented framework that provides maximum reusability and developer productivity, it
sounds like a platform I’d like to use.
And so, at its core, the .NET Framework and Visual Studio .NET (which I’ll refer to together
as simply .NET) are tools designed to take advantage of the Internet as the major platform for
application development. At the highest level, the goals for the initial release were to produce a
development environment:
• Where the Internet and Internet standards are second nature
• Where distributed Web applications are easy to build
• That combines the power of object-oriented programming and relieves the burdens of
complicated versioning and deployment
In the remainder of this section and chapter, I’ll talk specifically about what .NET is and dis-
cover how Visual Basic .NET fits in.

What .NET Is and Is Not


In the months leading up to the release of Visual Studio .NET (VS .NET), there has been much
speculation and confusion about exactly what .NET is and what it is not. To set the stage for
the rest of this chapter—and indeed for the entire book—I want to cover a few points along
those lines.
First and foremost, the .NET Framework and VS .NET are not evolutionary upgrades to the
Visual Studio 6.0 (VS 6.0) product set. In almost all respects, they are revolutionary in that
they offer a fundamentally different programming model based on the Common Language
Runtime (CLR) that all the development tools share. The mere fact that I refer to the .NET
Framework apart from VS .NET indicates that these are two separate products, where VS .NET
is dependent on the .NET Framework. However the reverse is not true. This new model
requires new thinking on the part of developers because not only has syntax changed in their
chosen .NET language, but the fundamental structure and runtime behavior of programs might
be quite different in .NET.
Second, .NET is not a Microsoft version of Java. Although .NET borrows a little from the Java
playbook in terms of using ideas such as just-in-time compilation and garbage collection, its
strength will probably not lie in the fact that it can be platform independent. However, as you’ll
see, the architecture of .NET makes it possible to port the CLR to various platforms so that
your applications could, in the future, be compiled once and run anywhere. In fact, .NET’s
greatest strength is its language independence. As was the strength of classic COM, being able
to write code that interoperates well with code written in another language is typically more
The Microsoft .NET Architecture
13
CHAPTER 1

important than being able to run the same binary on various platforms. In addition, the amount 1
of integration possible in .NET far exceeds that provided by COM and extends all the way to

THE MICROSOFT
ARCHITECTURE
cross-language inheritance.

.NET
In any case, Microsoft’s vision for platform independence relies on industry standards such as
Simple Object Access Protocol (SOAP), an XML-based protocol, to make cross-platform calls
and interact with services exposed over the Web (also known as XML Web Services).
Companies throughout the industry from IBM to Sun are supporting the SOAP standard now
in the hands of the W3C (http://www.w3.org/TR/SOAP/), and so its inclusion in .NET moves
us forward to the time when applications built on differing platforms will be able to communi-
cate seamlessly.

NOTE
For a look at a variety of Web Services built on various platforms, see
www.xmethods.net.

On the other side of the fence, .NET is a new platform for developing distributed Web applica-
tions. .NET mainstreams the concept of Web Services as programmable application compo-
nents accessible via standard Web protocols. The .NET Framework includes hundreds of
prebuilt classes that encapsulate these Web standards and protocols to provide a great founda-
tion for building both interactive Web applications and Web Services, as I’ll discuss in
Chapters 10, “Building Web Forms,” and 11, “Building Web Services.”
.NET also provides a new model for building and sharing components. As you’re probably
aware, the reliance of classic COM components on registry entries, Globally Unique
Identifiers (GUIDs), v-tables, and IUnknown makes distributing and invoking those compo-
nents across the network using DCOM sometimes tricky. In .NET, all those concepts go away
and are replaced by a simpler mechanism that allows remoting of components across the net-
work, easy deployment, and side-by-side versioning of components on the same machine. You
will explore many of these concepts in Chapters 5, “Packaging, Deployment, and Security,”
and 8, “Building Components.”
Finally, .NET is a Rapid Application Development (RAD) tool for distributed applications.
The inclusion of the Server Explorer window in the VS. NET IDE (covered in Chapter 2, “The
Development Environment”), the .NET Framework classes for manipulating data through
ADO.NET (covered in Chapter 7, “Accessing Data with ADO.NET”), and integrating with
both low-level system services such as threading (covered in Chapter 12, “Accessing System
Services”) and high-level services such as messaging and Active Directory (covered in Chapter
14, “Integrating with the Enterprise”) make it a high-productivity environment.
.NET Concepts
14
PART I

VB’s Place in .NET


Visual Basic as a development tool has gone through several major revisions over the years.
Particularly, the releases of VB 3.0, 4.0, and 5.0 provided significant enhancements that
enabled VB to access databases, act as a COM client, and create ActiveX controls and COM
components. However, with the release of Visual Basic .NET (VB .NET), VB has undergone
its biggest change by far in its now ten-year history.
Perhaps the key point to remember with VB .NET is that it is now a first-class citizen within
VS .NET. What this means is that VB .NET has full access to the IDE, services, and features
within the .NET Framework and is not limited by a “glass ceiling.” Because of this fact, in
theory, almost all code written in other VS .NET languages such as Visual C# (VC#), JScript,
and Visual C++ (VC++) with managed extensions will be able to be translated to VB .NET
with identical performance.

NOTE
The phrase in theory in the previous paragraph refers to the fact that compilers, as
well as the .NET Framework, play a role in performance. Even if the VB .NET language
contains syntactical equivalents for all VC# constructs, the VB .NET compiler would
still have to produce intermediate language code (as discussed later) identical to that
produced by the VC# compiler in order for two applications to perform identically.
This is unlikely, and so in certain circumstances a language built on the .NET
Framework might outperform another language when executing similar operations.
However, these small differences will also tend to even out in the scope of an entire
application.
In the initial release of VS .NET, VC++ will be the only language through which you
can create code that does not use the CLR at all. VC# will allow you to write code
blocks that do not use the CLR and so in both cases, when using these features, all
bets on performance are off.

Entire books have been written on how to extend VB to implement specific features (and break
through the “glass ceiling”) of the Win32 API, such as threading, callbacks, and writing NT
services. (I know because I’ve written one of them.) However, with VB .NET, all these features
are transparent and accessible through a set of class libraries that ship with VS .NET, called the
.NET Framework classes or the Services Framework. Using the Services Framework in your
applications allows VB .NET to support the RAD model that VB developers have come to
expect.
The Microsoft .NET Architecture
15
CHAPTER 1

NOTE 1

THE MICROSOFT
ARCHITECTURE
Throughout this book I’ll use the term Services Framework to refer to the entire col-

.NET
lection of over a thousand classes that ship with Visual Studio .NET, both those that
implement support for the various programming models such as Web Forms and Web
Services, and the lower-level classes that implement network communication, IO,
threading, and so on. Some authors will refer to the entire collection as simply the
.NET Framework, .NET Frameworks, or Base Class Libraries (BCL). Although I seldom
use the term, I reserve BCL for the lower-level classes upon which the higher-level
programming models are built.

The second point to consider is that VB .NET not only encompasses the functionality of previ-
ous versions of VB to create form-based applications and components, it also can be used to
create Web applications using a robust event-driven programming model. In other words, the
functionality of the forms package and ASP have been abstracted into application program-
ming models and exposed to all the .NET programming languages through reusable framework
classes.

NOTE
As a result of the inclusion of the Web-based programming into the Services
Framework, developers who in the past used Visual InterDev as their primary tool will
likely be migrating to VB .NET. For developers, moving from a language such as
VBScript, which did not support types other than Variant and lacked support for
more sophisticated features like classes and events, to the robust .NET languages
might at first seem daunting. For those developers I say, bear with me. Much of the
information in this chapter is crucial for getting the big picture. That being said,
those developers will find more of the information for which they are looking, and
can move through the book using a faster track, by concentrating on Chapters 2, 3, 4,
7, 10, and 11.

In addition, many of the intrinsic functions and statements have been abstracted into the
Services Framework and the CLR, the result being that VB .NET actually contains fewer
keywords than previous versions. A picture of how these parts fit together can be seen in
Figure 1.1.
.NET Concepts
16
PART I

NOTE
VB .NET is a Common Language Specification (CLS)–compliant language and so it can
take advantage of the CLR. There is a more complete discussion of the CLS later in
this chapter.

Visual Studio .NET


Development Tools < CLS Compliant Languages
(VB .NET, C#, VC++, others)

ASP.NET Win Forms


Application Programming Models WebApplication
WebService

Services Framework
Microsoft .NET Framework <
Common Language Runtime

SOAP

HTTP
Internet Standards <
TCP/IP

FIGURE 1.1
The .NET architecture. Much of the functionality of previous versions of VB has been abstracted into the application
programming models and Services Framework.

Taken together, you can infer that VB .NET is different from previous versions of VB because
it is now only one of many languages that take advantage of the services provided by the .NET
Framework. This is great for VB developers because they can now access all the features .NET
provides without paying the price of increased complexity, kludgy workarounds, and degraded
performance.
In the remainder of this chapter, I’ll drill down on the foundation of Figure 1.1 and discuss the
key concepts behind the CLR and the Services Framework.

Common Language Runtime Architecture


At the core of .NET is certainly the CLR. Simply put, the CLR provides the environment in
which all code compiled in VB .NET (and other compliant languages) executes. Although my
goal in discussing the CLR is not to delve into the low-level details, which has been done in
other publications, the CLR is so important that all VB .NET developers should have at least a
rudimentary understanding of how it works and its key features.
The Microsoft .NET Architecture
17
CHAPTER 1

NOTE 1

THE MICROSOFT
ARCHITECTURE
See Jeffery Richter’s series of articles on the MSDN Web site (msdn.microsoft.com) for

.NET
more details on the CLR.

As was true with VB 6.0 and COM, developers creating distributed applications could get
by with developing their applications without any appreciation for the internals of COM.
However, extending that knowledge just a little bit allows you to create applications that take
full advantage of what the CLR provides.

Goals of the CLR


To create a new platform for distributed Web application development, Microsoft needed to
develop a common architecture on which to base this platform. As mentioned previously, the
current way most VB developers develop distributed applications is by integrating ASP, VB,
MTS, COM+, and Win32 API calls, all of which have different programming semantics and
their own idiosyncrasies in the ways they perform basic functions such as error handling, deal-
ing with return values, passing arguments, handling data types, and memory management. And
so it became apparent that if a new platform was going to be developed, it needed to unify
these programming models under a central architecture. This is what the CLR is and does.
At the highest level, then, the CLR was designed to implement the following four goals:
• Simplify application development
• Provide a robust and secure execution environment
• Support multiple programming languages
• Simplify deployment and management
To deliver on these goals, the designers of the CLR had to address the issue of application
interoperability. In the past, two pieces of software often communicated using COM, which
relied on a common binary standard that both pieces of software implemented so that they
could safely invoke methods on each other’s objects. Although this provided a level of integra-
tion, both pieces of software still needed to implement the plumbing (interfaces and AddRef
and Release code) and rely on the operating system’s COM Library (OLE32.DLL and
STDOLE.DLL among others) and registry for support. And even though VB hid these details
quite nicely from developers, these two pieces of software could not directly interact, for
example, to extend each other’s objects through implementation inheritance.
.NET Concepts
18
PART I

NOTE
COM does support the notion of interface inheritance so that one object can imple-
ment another’s interfaces (which defines the required method and property signa-
tures including the method names, arguments, and return values, if any). This allows
you to write polymorphic code and could also be done in VB 6.0 (see Chapter 15 of
my book, Pure Visual Basic, Sams Publishing, August 1999, for a more in-depth discus-
sion). However, this technique does not allow the actual code inside the object to be
reused. Implementation inheritance means that one object can be derived from
another and that when the derived object is executed, the code from the parent will
also run if desired. This leads to greater code reuse, although there are pitfalls as
well. We’ll look more closely at these features as they’ve been added to VB .NET in
Chapter 4, “Object-Oriented Features.”

The CLR provides the common substrate within which all the software runs so that objects can
directly interact, and so that all the plumbing code is eliminated from both the components
themselves and the operating system. For example, in the COM world, components were
responsible for the in-memory layout of their objects into v-table structures so that the appro-
priate methods could be located at runtime. Now, however, this responsibility has been relieved
from the components and is handled by the CLR.
Because all VB .NET code is run by the CLR, it can provide services like those listed here:
• Different compilation models—As I’ll discuss shortly, the abstraction of the CLR from
the development languages allows the runtime to determine when an application is com-
piled.
• Automatic lifetime management—Because all objects—and everything is ultimately an
object in .NET—are managed by the CLR, it can monitor when those objects are created
and used, and when they are no longer needed. As a result, it will use a garbage collec-
tion (GC) algorithm to free resources as necessary. This means that you can no longer
have stray pointers and that circular references will be resolved. In fact, you are no
longer responsible for freeing resources (setting an object to Nothing, for example) at all.
This is great news, but it changes the way you will design your code, for example,
because Terminate events are no longer supported. I’ll cover this topic in more detail
both in this chapter and in Chapter 3, “VB .NET Language Features.”
• Code correctness and type-safety—VB developers have always taken for granted that
in many cases they could assign a variable of one type to another and VB would auto-
matically convert it for them. By default, however, the CLR strictly enforces type safety
so that developers can’t make arbitrary references to memory locations and make unsafe
The Microsoft .NET Architecture
19
CHAPTER 1

casts—things that VB developers typically don’t care about, but that happen frequently 1
in VC++ and are exploited by hackers. What it means to VB .NET developers is that

THE MICROSOFT
ARCHITECTURE
there is a new default behavior and more levels of type safety that can be used. I’ll cover
this in detail in Chapter 3.

.NET
• Simplified deployment—Because the CLR eliminates the plumbing required for com-
ponents to communicate, it also reduces the installation and deployment burden for
developers. By eliminating registration (for the most part, as you’ll see in Chapter 5.)
and allowing features such as side-by-side execution both on the same machine and even
within the same process, some .NET applications can be deployed simply by copying
directories (referred to as XCOPY deployment).
• Evidence-based security—This new platform also requires a new security model. In the
past, security models typically relied on the credentials of the user running the code.
However, in distributed applications where code can be downloaded from the Internet
and executed, the code itself needs to be trusted. The .NET security model is not simply
a rehashing of the Microsoft Authenticode technology used for signing and encrypting
ActiveX controls; it is a new model based on evidence provided by both the code as well
as the user (through operating system accounts or roles) and is policy-based. In addition,
the security model can be accessed both declaratively and imperatively inside your code.
I will discuss this in more detail in Chapter 5.
• Common exception handling—As mentioned previously, the varying programming
models used by corporate developers all handle errors in different ways. COM uses
HRESULTs, the Win32 API uses function return values with a second call to retrieve the
error, ASP uses inline error handling, and VB uses error trapping within a module. The
CLR includes structured exception handling, which allows isolation of the error code and
works well across language boundaries. I’ll discuss how VB .NET implements this fea-
ture in Chapter 6, “Error Handling and Debugging.”
These features of the CLR allow languages to work together and leverage common tools such
as the debugger and profiler so that cross-language and even cross-machine debugging (cov-
ered in Chapter 6) are simplified. This results in a greater freedom to use the language of your
choice without sacrifice. This is, once again, good news for VB .NET developers.
And finally, as implied earlier and discussed in the following sections, the all-encompassing
nature of the CLR gives it the nature of a Hardware Abstraction Layer (HAL) and makes it
possible to write code that might not require recompilation as you move it to a new platform.
Initially, Microsoft is planning to port the CLR to its family of operating systems including
Windows 98, Windows Me, Windows NT 4.0, Windows 2000, Windows XP, 64-bit Windows,
and even Windows CE in a package called the .NET Compact Framework. In the future, other
non-Microsoft operating systems might also be included.
.NET Concepts
20
PART I

Managed Versus Unmanaged Code


All code that executes outside the CLR—meaning code written for previous versions of VB as
well as calls to the Win32 API, calls to classic COM and COM+ components, and calls to
third-party ActiveX controls—is referred to as unmanaged code. There is a sharp distinction
between unmanaged code and the managed code produced to run in the CLR. Managed code is
structured so that the CLR can augment it with its services. Requirements for managed code
include the ability for the CLR to
• Locate the metadata for a particular method given an address
• Walk the call stack
• Handle exceptions
• Store and retrieve security information
For example, to walk the call stack, the CLR uses a specific API to understand the layout of
stack frames produced by a particular compiler vendor. As a result, the compiler must provide
an implementation of this API either in the just-in-time compiler (discussed later) or in the
managed code itself.

NOTE
As mentioned previously, only VC++ can produce unmanaged code. The default mode
for VC++ is to create unmanaged code, and so the product is referred to as “Visual
C++ with managed extensions.” However, VC# will also allow you to write unman-
aged code within a method by using the unsafe modifier. As a result, a VC# devel-
oper can use pointers and override the GC algorithm in certain cases to keep it from
freeing resources using a technique called pinning. As implied by its name, the
unsafe modifier can allow developers to override the features of the CLR noted in
the “Automatic lifetime management” bullet point earlier and therefore create stray
pointers and unresolved circular references. Note, however, that this unmanaged
code will run only if the code is trusted by the CLR security model.

VB .NET produces only managed code and so must use the interoperability features of .NET
(referred to simply as “interop”) to access any form of unmanaged code. We’ll take a look at
how this is accomplished in Chapter 9, “Accessing Component Services.”
One of the ramifications of this for VB .NET developers is that upgrading VB 6.0 projects to
VB .NET (covered in Chapter 3) means that the interop services will be relied upon heavily,
which adds a layer of complexity and slows performance. For these and other reasons, VB
.NET developers will need to be very careful when deciding what and when to upgrade.
The Microsoft .NET Architecture
21
CHAPTER 1

Death of COM?
1

THE MICROSOFT
ARCHITECTURE
With all these changes, what does this mean for COM? Well, the good news is that
because VB hid many of the complexities of COM from developers, changing the

.NET
infrastructure should not inconvenience most developers. In addition, doing away
with the headaches of GUIDs and the registry, the single-version-per-machine scheme
that it implied, as well as dealing with compatibility settings, are all a good thing. Is
COM dead? Yes, in terms of its infrastructure.
However, many corporate VB developers have a good understanding of COM and
take advantage of interface-based programming in their designs. These developers
can still use the same techniques in their designs, while they can also augment them
with implementation inheritance. Is COM dead? No, in terms of the concept of shar-
ing and reusing code.
In any case, many of us will have to coexist in both worlds for some time to come. For
example, one of the most common scenarios will be that newly developed managed
code (perhaps a new ASP.NET UI or Web Service) will need to call previously deployed
COM+ components written in VB 6.0. For this to work, VB .NET developers will need
to be aware of both the old and new worlds and how they interoperate (as I’ll discuss
in Chapter 9). In fact, it might be argued that some new VB .NET developers will need
a short course on classic COM to implement scenarios like the one mentioned.

Common Language Specification


As mentioned previously, VB .NET is only one of several languages Microsoft is creating to
target the CLR. However, the CLR makes it possible for other language vendors to create com-
pilers that target it as well. To assist in this process, Microsoft has published the Common
Language Specification (CLS). Simply put, the CLS is published on msdn.microsoft.com and
defines a set of rules that the vendors must live by if they want their languages to work with
the CLR. Most of these rules have to do with how languages expose type information (includ-
ing primitive types such as integers, strings, and complex types such as arrays, enumerations,
and objects) and special features such as exception handling, attributes, and interfaces.

NOTE
Strictly speaking, the CLS binds vendors to rules only for types that are made public
and accessible outside a particular assembly. Assemblies will be covered in more detail
at the end of this chapter.
.NET Concepts
22
PART I

In fact, the CLS dictates a subset of what the CLR provides for languages to be compatible.
Individual vendors can then implement more of the functionality if they desire. The CLS
defines three levels for compatibility:
• consumers—Languages that use the CLR but do not extend it
• extenders—Languages that use the CLR and extend it by adding additional data types
• frameworks—Languages that implement libraries used by a wide range of programming
languages and tools
As of this time, many vendors have indicated their willingness to create compilers for lan-
guages such as Pascal, Smalltalk, LISP, FORTRAN, Perl, and over 20 others. In fact, Microsoft
has even produced a version of Java (J# .NET) that targets the CLR as a part of its JUMP (Java
User Migration Path) program.
To assist in this effort, Microsoft and Hewlett Packard jointly submitted the CLS, CLR
(referred to as the Common Language Infrastructure), and the C# language specification to the
international industry standards body ECMA. See msdn.microsoft.com/net/ecma and
www.ecma.ch for more details.

NOTE
Obviously, this book is geared towards existing VB and ASP developers, and as such, I
am definitely of the opinion that these developers will be much more productive
much sooner using VB .NET than VC# due to the syntax similarities. In addition, VB
.NET preserves much of what was good about BASIC to begin with, namely a more
readable and hence understandable syntax. VC# was designed with C++ and Java
developers in mind and so will be the natural path to .NET for those developers. That
being said, VC# is in many respects more like VB .NET than C++, and so many VB
developers will have no trouble reading and understanding the syntax.

CLR Internals
To help you get a feel for how the CLR works, I’ll use an inside-out approach by first dis-
cussing what happens on a binary level and then moving up to a single application level, cross-
application level, and finally to the cross-machine and deployment level. I’ll begin the
discussion by focusing on how code is compiled and executed for the CLR.

MSIL
As with any executable today, the code you write in VB .NET eventually must execute as
native CPU instructions for the processor on which the code will be run. However, although
unmanaged compilers create these native CPU instructions directly, and interpreters such as
The Microsoft .NET Architecture
23
CHAPTER 1

ASP create instructions on the fly that map to CPU instructions, the managed compilers written 1
for the CLR, which include VB .NET, create a higher level, machine-independent set of

THE MICROSOFT
ARCHITECTURE
instructions referred to as Microsoft Intermediate Language (MSIL). The MSIL instructions
are then stored in a portable executable (PE) file with a .DLL or .EXE extension based on the

.NET
Microsoft Portable Executable format, which itself extends the Common Object File Format
(COFF) commonly used for executable content. These files are referred to as modules in .NET
(not to be confused with VB modules as discussed in Chapter 2). MSIL is eventually loaded by
the CLR and compiled to native instructions and executed.
To view the MSIL created by the VB .NET compiler, you can use the IL Disassembler utility
(ILDasm.exe) that ships with .NET. This graphical utility lets you view each method in your
program, along with its associated MSIL, by double-clicking on the method. Figure 1.2 shows
ILDasm opened up on a method called AddOrder in a class called Orders.

FIGURE 1.2
The IL Disassembler. This graphical utility lets you view the MSIL created for your VB .NET code. Note that the
instructions begin with IL_0000 in the foreground window.

This basic architecture and its implications should be familiar to VB developers. First, it means
that VB. NET binaries are not native code but a form of intermediate code as was true for most
of VB’s history. The big difference is that MSIL is a much lower level set of instructions than
the interpreted code produced in previous versions of VB. Although you might be thinking that
Random documents with unrelated
content Scribd suggests to you:
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like