Visual Basic .NET and the .NET Platform: An Advanced Guide

ANDREWTROELSEN

APress Media, LLC Visual Basic .NET and the .NET Platform: An Advanced Guide Copyright ©2002 by Andrew'Ii'oelsen Originally published by Apress in 2002

All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.

ISBN 978-1-893115-26-2 ISBN 978-1-4302-0849-5 (eBook) DOI 10.1007/978-1-4302-0849-5 Trademarked names may appear in this book. Rather than use a trademark sym• bol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.

Editorial Directors: Dan Appleman, Gary Cornell, Jason Gilmore, Karen Watterson Technical Reviewers: Pamela Fanstill, Rob Macdonald, Dan Appleman, William Oellermann Managing Editor: Grace Wong Copy Editors: Anne Friedman, Nicole LeClerc Production Editors: Janet Vail with Kari Brooks and Anne Friedman Composition and Art Services: Impressions Book and Journal Services, Inc. Indexer: Carol Burbo Cover Designer: Tom Debolski Marketing Manager: Stephanie Rodriguez

Distributed to the book trade in the United States by Springer-Verlag New York, lnc.,175 Fifth Avenue, New York, NY, 10010 and outside the United States by Springer-Verlag GmbH & Co. KG, Tiergartenstr. 17, 69112 Heidelberg, Germany

In the United States, phone 1-800-SPRINGER, email orders@springer-ny. com, or visit http: I lwww. springer-ny. com. Outside the United States, fax +49 6221 345229, email orders@springer. de, or visit http: I lwww. springer. de.

For information on translations, please contact Apress directly at 901 Grayson Street, Suite 204, Berkeley, CA 94710. Phone 510-549-5930, fax: 510-549-5939, email [email protected], or visit http:llwww.apress.com.

The information in this book is distributed on an "as is" basis, without warranty. Although every precaution has been taken in the preparation of this work, nei• ther the author nor Apress shall have any liability to any person or entity with re• spect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work.

The for this book is available to readers at http: I lwww. a press. com in the Downloads section. You will need to answer questions pertaining to this book in order to successfully download the code. This book is dedicated to the memory ofthe thousands ofpeople who lost their lives during the tragic events that took place on September 11, 2001. Of exactly equal importance, this book is dedicated to each and every individual who worked around the clock, without limits, to bring some degree ofnormalcy back to New York, Pennsylvania, and Washington D. C. Thank you for your strength, inspiration, and relentless commitment. Thank you for engaging the unimaginable. Contents at a Glance

What You Need to Use This Book ...... xv Acknowledgments ...... xxii Introduction ...... xviii

Chapter 1 The Philosophy of • NET ...... 1 Chapter 2 Building Visual Basic • NET Applications ...... 41 Chapter 3 VB .NET Language Fundamentals ...... 77 Chapter 4 Object-Oriented Programming with VB .NET ...... 159 Chapter 5 Interfaces and Collections ...... 227 Chapter 6 Delegates, Events, and Callback Interfaces .....263 Chapter 1 Assemblies, Threads, and AppDomains ...... 297 Chapter 8 Type Reflection and Attribute-Based Programming ...... 385 Chapter 9 Building a Better Window (Introducing ) ...... 421 Chapter 10 A Better Painting Framework (GDI+) ...... 507 Chapter 11 Programming with Windows Form Controls ...... 589 Chapter 12 Input, Output, and Object Serialization ...... 677 Chapter 13 Interacting with Unmanaged Code ...... 733 Chapter 14 Data Access with ADO.NET ...... 791 Chapter 15 Web Development and ASP. NET ...... 877 Chapter 16 Building (and Understanding) Web Services .... .971

Index ...... 1019

iv Contents

What You Need to Use This Book ...... xv

Acknowledgments ...... xxii

Introduction ...... xviii

Chapter 1 The Philosophy of • NET ...... 1

Understanding the Current State of Affairs ...... 1 The •NET Solution ...... 5 Building Blocks of .NET (CLR, CTS, and CLS) ...... 6 .NET -Aware Programming Languages ...... 7 What VB • NET Brings to the Table ...... 9 An Overview of .NET Binaries (aka Assemblies) ...... 10 The Role of Intermediate Language ...... 12 The Role of Metadata ...... 15 Compiling IL to Platform-Specific Instructions ...... 16 • NET Types and • NET Names paces ...... 17 Understanding the ...... 17 Understanding the Common Type System ...... 20 Understanding the Common Language Specification ...... 24 Working with Namespaces ...... 26 A Tour of the • NET Name spaces ...... 27 Referencing External Assemblies ...... 30 Increasing Your Namespace Nomenclature ...... 31 Summary ...... 39

Chapter 2 Building Visual Basic .NET Applications ...... 41

Building VB .NET Applications Using the Command Line Compiler ...... 41 Building Your First VB .NET Application ...... 43

v Contents

Building VB .NET Applications Using the Visual Studio • NET IDE ...... 49 Building Your VS .NET Test Application ...... 53 Configuring a VB .NET Project ...... 55 The Properties Window ...... 59 Adding Some Code ...... 60 What Happened to the World of VB 6.0? ...... 68 Upgrading VB 6.0 Projects into VB .NET ...... 72 The Microsoft.VisualBasic.Compatability.VB6 Namespace ...... 75 Should You Upgrade? ...... 75 Summary ...... 76

Chapter 3 VB • NET Language Fundamentals ...... 77

The Role of the Module Type ...... 77 The Main Method ...... 80 Data Types and Variable Declarations ...... 81 Experimenting with the System Data Types ...... 85 Data Type Conversions ...... 88 Concatenation Operators ...... 89 Basic Input and Output with the Console Class ...... 90 Introducing VB • NET String Formatting ...... 91 Anatomy of a Simple VB . NET Class ...... 93 Creating Objects: Constructor Basics ...... 94 Default Values ...... 99 Defining Program Constants ...... 100 Understanding Value Types and Reference Types ...... 102 The Master Node: System.Object ...... 107 VB • NET Iteration Constructs ...... 113 VB .NET Control Flow Constructs ...... 117 Additional VB .NET Operators ...... 119 Defining Custom Class Methods ...... 121 Method Parameter Modifiers ·(ByRef and ByVal) ...... 127 Shared Methods ...... 132 Static (Not Shared) Data ...... 137 Array Manipulation in VB • NET ...... 139 String Manipulation in VB .NET ...... 143 VB .NET Enumerations ...... 146 Defining Structures in VB • NET ...... 151 Defining Custom Namespaces ...... 153 Summary ...... 158

vi Contents

Chapter 4 Object-Oriented Programming with VB . NET ...... 159

A Catalog of VB • NET 00-Centric Keywords ...... 159 Formal Definition of the VB .NET Class ...... 161 Member Overloading ...... 165 Defining the Default Public Interface ...... 166 Pillars of OOP ...... 168 The First Pillar: VB .NET's Encapsulation Services ...... 173 Pseudo-Encapsulation: Creating Read-Only Fields ...... 181 The Second Pillar: VB .NET's Inheritance Support ...... 182 Keeping Family Secrets: The "Protected" Keyword ...... 186 Nested Type Definitions ...... 192 The Third Pillar: VB • NET's Polymorphic Support ...... 193 Casting between Class Types {CType) ...... 202 Exception Handling ...... 204 Understanding Object Lifetime ...... 215 Finalizing an Object Reference ...... 216 Building an Ad Hoc Destruction Method ...... 218 Interacting with the Garbage Collector ...... 219 Summary ...... 225

Chapter 5 Interfaces and Collections ...... 227

Understanding Interface-Based Programming ...... 227 Building a Custom Enumerator {!Enumerable and !Enumerator) ...... 241 Building Cloneable Objects {ICloneable) ...... 245 Building Comparable Objects {!Comparable) ...... 251 Exploring the System.Collections Namespace ...... 257 Summary ...... 262

Chapter 6 Delegates, Events, and Callback Interfaces ...... 263

A Quick Recap of Events a la VB 6.0 ...... 263 Designing an Event Interface ...... 267 The VB . NET Delegate Keyword ...... 271 The Simplest Possible Example ...... 274 Building a More Elaborate Delegate Example ...... 277

vii Contents

Understanding (and Using) Events ...... 286 Summary ...... 296 Problems with Classic COM Binaries ...... 297 An Overview of • NET Assemblies ...... 300 Building a Single File Test Assembly ...... 308 A VB . NET Client Application ...... 312 A C# Client Application ...... 313 Cross-Language Inheritance ...... 315 Exploring the CarLibrary' s Manifest ...... 319 Exploring the CarLibrary' s Types ...... 323 Building Multi file Assemblies ...... 326 Understanding Private Assemblies ...... 331 Probing Basics ...... 333 Understanding Shared Assemblies ...... 338 Understanding Shared Names ...... 339 Using a Shared Assembly ...... 346 Understanding . NET Version Policies ...... 347 Recording Version Information ...... 348 Building SharedAssembly Version 2.0 ...... 351 Specifying Custom Version Policies ...... 352 Using the .NET Administrative Tool (mscorcfg.msc) ...... 354 The Ngen.exe Utility ...... 363 Review of Traditional Win32 Thread Programming ...... 364 Understanding System.AppDomain ...... 366 System. Threading Names pace ...... 369 Naming Threads ...... 373 Concurrency Revisited ...... 377 The VB .NET "Sync Lock" Keyword ...... 380 Using System. Threading. Interlocked ...... 382 Summary ...... 384

Chapter 8 Type Reflection and Attribute-Based Programming ...... 385

Understanding Reflection ...... 385 The System. Type Class ...... 386 Investigating the System. Reflection Names pace ...... 393 Dynamically Loading an Assembly ...... 393 Understanding Dynamic Invocation (Late Binding) ...... 398 Understanding (and Building) Dynamic Assemblies ...... 402 Understanding Attributed Programming ...... 410

viii Contents

Building Custom Attributes ...... 414 The VB .NET "Assemblyinfo.vb" File ...... 418 Discovering Attributes at Runtime ...... 419 Summary ...... 420

Chapter 9 Building a Better Window (Introducing Windows Forms) ...... 421

A Tale of Two GUI Names paces ...... 421 Overview of the Windows Forms Names pace ...... 422 Building a Windows Forms Application by Hand ...... 422 Building a Visual Studio .NET Windows Forms Project Workspace ...... 426 The System. Windows. Forms. Application Class ...... 432 The Anatomy of a Form ...... 437 Basic Form Functionality ...... 437 The System. ComponentModel. Component Class ...... 438 The Control Class ...... 439 Control Events ...... 444 Responding to Keyboard Events ...... 451 The Control Class Revisited ...... 452 The ScrollableControl Class ...... 456 ContainerControl Class ...... 457 The Form Class ...... 457 Building Menus with Windows Forms ...... 459 Building Your Menu System ...... 462 Building a Menu Using Visual Studio • NET ...... 470 Understanding Status Bars ...... 472 Building a Status Bar Using Visual Studio • NET ...... 479 Building a ToolBar ...... 481 Building ToolBars at Design Time ...... 486 A Minimal and Complete Windows Forms Application ...... 490 Interacting with the System Registry ...... 492 Interacting with the Event Viewer ...... 496 Building an MDI Application ...... 500 Summary ...... 506

ix Contents

Chapter 10 A Better Painting Framework (GDI+) .. .507

Remembering the World of VB 6.0 Graphics Programming ...... 507 Survey of the GDI+ Namespaces ...... 508 Overview of the System.Drawing Namespace ...... 509 Configuring a GDI+ Project Workspace ...... 511 Examining the System.Drawing Utility Types ...... 511 Understanding Paint Sessions ...... 516 Understanding the Graphics Class ...... 520 Default GDI+ Coordinate System ...... 522 Establishing an Active Color ...... 526 Manipulating Fonts ...... 530 Survey of the System. Drawing. Drawing2D Names pace ...... 542 Working with Pens ...... 545 Rendering Images ...... 560 Dragging, Hit Testing, and the PictureBox Control ...... 564 Understanding the • NET Resource Format ...... 574 System. Resources Names pace ...... 576 Working with ResourceWriters ...... 581 Working with ResourceManagers ...... 583 Automatic Resource Configuration ala Visual Studio .NET ....584 Summary ...... 587

Chapter 11 Programming with Windows Form Controls ...... 589

Understanding the Windows Forms Control Hierarchy ...... 589 Adding Controls to Forms (the Hard Way) ...... 590 Adding Controls to Forms {the Easy Way) ...... 594 The TextBox Control ...... 596 The Mighty Button Type (and the ButtonBase Parent Class) ....600 Working with CheckBoxes ...... 603 Working with RadioButtons and GroupBoxes ...... 605 ListBoxes and ComboBoxes ...... 610 Configuring the Tab Order ...... 615 The TrackBar Control ...... 617 The MonthCalendar Control ...... 620 More on the System.DateTime Type ...... 623 The Spin Controls: DomainUpDown and NumericUpDown ...... 625 Working with Panel Controls ...... 628 Assigning Tool Tips to Controls ...... 629

X Contents

Working with the ErrorProvider ...... 632 Configuring a Control's Anchoring Behavior ...... 634 Configuring a Control's Docking Behavior ...... 636 Building Custom Dialog Boxes ...... 638 Form Inheritance ...... 645 Understanding Custom Controls ...... 647 The Class, Control, UserControl, and Component Distinction .. 648 Building a Custom UserControl ...... 650 Creating the Images ...... 651 Building the Design Time GUI ...... 654 Establishing the Default Public Sector ...... 655 Defining the Custom Events ...... 657 Supporting Custom Properties ...... 657 Controlling the Animation ...... 659 Building a VB • NET Client Application ...... 660 Select Members of the System.ComponentModel Namespace ...... 663 Enhancing the Design Time Appearance of CarControl ...... 665 Building a .NET (Data) Component ...... 668 Connecting to the Cars Database ...... 669 Using Your Custom Component ...... 672 Summary ...... 675

Chapter 12 Input, Output, and Object Serialization ...... 677

Exploring the System. IO Namespace ...... 677 The Directory(Info) and File(Info) Types ...... 679 Enumerating Files with the Directoryinfo Type ...... 683 Creating Subdirectories with the Directoryinfo Type ...... 684 The Shared Members of the Directory Class ...... 686 The Fileinfo Class ...... 688 The Abstract Stream Class ...... 693 Working with StreamWri ters and StreamReaders ...... 697 Working with StringWri ters ...... 702 Working with StringReaders ...... 704 Working with Binary Data (BinaryReaders and BinaryWriters) .. 705 Object Persistence in the .NET Framework ...... 710 The Role of Object Graphs ...... 710 Configuring Objects for Serialization ...... 711 Serialization Using a Binary Formatter ...... 716 Serialization Using a SOAP Formatter ...... 719

xi Contents

Custom Serialization (and the ISerializable Interface) ...... 720 A Windows Forms Car Logger Application ...... 724 Summary ...... 732

Chapter 13 Interacting with Unmanaged Code ...... 733

Understanding Interoperability Issues ...... 733 A Painfully Simple Example: VB .NET Applications Communicating with VB 6.0 COM Types ...... 734 The System. Runtime. InteropServices Namespace ...... 737 Understanding .NET to COM Interoperability ...... 739 The Role of COM IDL ...... 742 Importing the Type Library ...... 747 Examining the Generated Assembly Manifest ...... 751 Building a More Interesting VB 6.0 COM Server ...... 753 Examining the Interop Assembly ...... 756 The Complete VB • NET Client ...... 761 Understanding COM to . NET Interoperability ...... 762 The Role of the CCW ...... 763 Understanding the ((Class Interface" ...... 764 Building Your • NET Type ...... 765 Generating the Type Library and Registering the .NET Types .. 767 Examining the Exported Type Information ...... 768 Viewing the Type Using the OLE/COM Object Viewer ...... 770 Examining the Registration Entries ...... 771 Building a Visual Basic 6.0 Test Client ...... 773 . NET to COM Mapping Issues ...... 775 Controlling the Generated IDL (or Influencing Tlbexp.exe) ... 779 Interacting with COM+ Component Services ...... 781 Building COM+-Aware Types ...... 784 Building a COM+-Aware VB • NET Type ...... 785 Examining the Component Services Explorer ...... 787 Summary ...... 789

Chapter 14 Data Access with ADO.NET ...... 791

The Need for ADO. NET ...... 791 Understanding the ADO.NET Namespaces ...... 794 The Types of System. Data ...... 795 Examining the DataColumn Type ...... 796

xii Contents

Examining the Data Row Type ...... 803 Details of the Data Table ...... 808 Building a Complete Data Table ...... 809 Understanding the DataView Type ...... 820 Understanding the Role of the DataSet ...... 822 Expressing Relations Using the Data Relation Type ...... 829 Reading and Writing XML-Based DataSets ...... 834 Building a Simple Test Database ...... 837 ADO.NET Managed Providers ...... 838 Working with the OleDb Managed Provider ...... 839 The Role of the OleDbDataAdapter Type ...... 848 Working with the SQL Managed Provider ...... 852 Autogenerated SQL Commands ...... 859 Filling a Multitabled DataSet (and Adding DataRelations) ....861 Bring in the Wizards! ...... 865 Summary ...... 874

Chapter 15 Web Development and ASP. NET ...... 877

Web Applications and Web Servers ...... 877 The Basic Structure of an HTML Document ...... 880 Basic HTML Text Formatting ...... 882 Visual Studio '.NET HTML Editors ...... 886 HTML Form Development ...... 888 The Role of Client-Side Scripting ...... 894 Submitting the Form Data (GET and POST) ...... 899 Building a Classic Active Server Page ...... 900 Building Your First Official ASP. NET Application ...... 905 Some Problems with Classic ASP ...... 906 Some Benefits of ASP. NET ...... 906 The ASP. NET Name spaces ...... 907 Creating a Simple VB • NET Web Application ...... 908 The Architecture of an ASP.NET Web Application ...... 915 Understanding the Application/Session Distinction ...... 922 The Globals.asax File and HttpApplication Type ...... 926 The Life Cycle of a Page-Derived Type ...... 929 Understanding ViewS tate ...... 932 Debugging and Tracing ASP .NET Applications ...... 934 Understanding the Benefits of Web Form Controls ...... 936 Working with Web Form Controls ...... 938 Categories of Web Form Controls ...... 942

xiii Contents

Understanding Server-Side Event Handling ...... 955 A Complete ASP oNET Example ...... 960 Summary ...... 969

Chapter 16 Building (and Understanding) Web Services ...... 971

Understanding the Role of Web Services ...... 971 The Anatomy of a Web Service ...... 972 An Overview of the Web Service Names paces ...... 973 Examining the System oWeb oServices Names pace ...... 974 Building a Simple Web Service ...... 975 The WebMethodAttribute Type ...... 982 Understanding the Web Service Description Language {WSDL) ... 988 Web Service Invocation Protocols ...... 991 WSDL into VB oNET Code (Generating a Proxy) ...... 997 Building the Assembly ...... 1001 Building a Client ...... 1002 Generating a Proxy with VSoNET ...... 1004 A More Interesting Web Service (and Web Client) ...... 1006 Serialization of Custom Types (Further Details) ...... 1011 Understanding the Discovery Service Protocol ...... 1014 Summary ...... 1016

Index ...... 1019

xiv What You Need to Use This Book

THE VERY FIRST THING you must do before you dig in is download the accompanying source code for this book from the Apress Web site (http: I /www.apress.com). As you read over each chapter, you find the following icon has been liberally scat• tered throughout the text:

This is your visual cue that the example under discussion may be loaded into Visual Studio .NET for examination. In addition to the source code, you need to have a copy of .NET Beta 2. In this text, I have chosen to focus primarily on using the Visual Studio .NET develop• ment environment. Although you are free to build and compile your code using nothing more than the VB .NET compiler (which is included with the .NET SDK) and Notepad.exe, you will find that VS .NET takes care of a number of low-level details on your behalf. Finally, understand that this is an advanced text geared toward the sea• soned software professional. The goals of this text are not to labor over each and every detail of the "For" loop, examine each and every menu selection of the Visual Studio .NET IDE, or describe all ten steps of a given VS .NET wizard. My assumption is that you are well equipped to explore the IDE and have no problem activating menu options. On the other hand, I assume no foreknowl• edge ofVB .NET or the .NET platform. In particular, this book is well suited for individuals possessing the following traits:

• You are an experienced software professional who has solid background in some modern-day programming language (Visual Basic, C++, Java, and so on).

• You are unafraid to consult online Help, build sample programs, and explore .NET on your own terms (and do so often without shame).

Even a book of this size cannot possibly cover each and every aspect of the .NET platform. The online Help that ships with the .NET SDK is incredibly

XV What You Need to Use This Book

readable, and it provides numerous code examples, white papers, and online tutorials. Once you have read (and understood) these sixteen chapters, you will be in a perfect position to build complete .NET solutions with the VB .NET lan• guage. At this point, online Help will become your faithful companion that extends and complements the material presented here. So, let's get on with the show! It is my sincere hope that this book will guide you safely through the .NET universe and serve as a solid reference during your life as an author of managed code usingVB .NET.

Andrew Troelsen Minneapolis, Minnesota

xvi Acknowledgments

FmsT, MANY THANKS to Gary Cornell and Dan Appleman, who encouraged me to translate my first Apress publication (C# and the .NET Platform) into the ver• nacular ofVisual Basic. A solid (and affectionate) thanks to Grace Wong and Stephanie Rodriguez, who again kept me honest and provided a fantastic working environment (see you at the PDC!). A special thanks to Carol Burbo for working with an incredibly tight deadline in order to index this material. A mammoth amount of gratitude to the editorial staff: Anne Friedman (glad to work with you again Anne! See you on book number three?), Nicole LeClerc, Christie Roden, Janet Vail, and Kari Brooks, who all did an outstanding job edit• ing, formatting, and massaging the knots out of my original manuscript. Thanks for your focus and clarity during the course of this project. I also must offer heartfelt thanks to my primary technical editor, Pam Fanstill. Thanks for laboring over each and every line of syntax and pointing out the lingering C# tokens that escaped my view. Your work was phenomenal (hon• est). Additional huge thanks are extended to Dan Appleman, Rob Macdonald, and William Oellermann for offering additional technical reviews (and numerous insights). Any remaining faux pas are my sole responsibility. Thanks to my fellow cohorts at Intertech-Inc.: Steve Close, Gina McGhee, Andrew "Gunner" Sondgeroth, and Tom Barnaby, who, while working on their own books, provided an encouraging, intense, and positive environment. As well, thanks to Tom Salonek for just being Tom (remember, always bring more beer). Finally, thanks and love to Mary and Wally Troelsen (aka Mom and Dad), and my wife, friend, and confidant, Amanda. I hope you all know how much your support means to me.

xvii Introduction

MicRosoFT's .NET PlATFORM represents an entirely new way to build distributed, desktop, and mobile applications. One thing to be painfully aware of from the outset is that the .NET platform has nothing at all to do with classic COM, VB 6.0, ATL, or any other pre-.NET frameworks. For example, as you read over this text, you will find that .NET types do not support !Unknown, are not cataloged in the system registry, and are not described using COM type libraries. Understand that these COM primitives have not simply been hidden away from view-they no longer exist. Given that .NET is such a radical departure from the current modus operandi ofWin32 development, Microsoft has developed a new language named C# (pro• nounced "see-sharp") specifically for this new platform. C#, like Java, has its syntactic roots in C++. However, C# has also been influenced by Visual Basic 6.0, specifically with regard to the use of class properties, "for each'' -like iteration, and the IDE itself. Nevertheless, given that C# still uses numerous C++-like tokens (semicolons, colons, and curly brackets), many die-hard VBers may find the syntax of C# a bit unpalatable. The good news is that in addition to the advent of C#, Microsoft has also shipped a brand-new update of the ever-popular Visual Basic programming lan• guage termed VB .NET, which is also specifically geared toward the development of .NET applications. As you move through this text, you will see that VB .NET is not simply an upgrade from VB 6.0. Rather, VB .NET can best be understood as a brand• new programming language that just happens to look suspiciously like earlier iterations of the language. Ifyou feel this last statement is a bit alarmist in nature, consider the following (partial) sampling of new constructs offered by VB .NET:

• Unlike VB 6.0, VB .NET supports class constructors, implementation inher• itance, classical polymorphism, and method overloading.

• VB .NET allows developers to natively build multithreaded applications (which could be achieved to some degree in VB 6.0, if youwere willing to drop down to the raw Win32 API).

• Unlike previous versions ofVisual Basic, VB .NET supports the develop• ment of extremely robust graphical-based (as opposed to GUI-based) applications using a facility termed GDI+.

• VB .NET supports new data types (System. Object), removes other data types (the Variant), and has reworked current language constructs (class xviii Introduction

properties, strings, arrays, enumerations, and class types) to bring Visual Basic up to snuff with the .NET architecture.

Despite these (and other) substantial changes, VB .NET still supports the key features that have established Microsoft Visual Basic as the most popular pro• gramming language to date. For those of you who have worked with earlier editions ofVB, you will notice many key similarities. On a related note, once you learn the syntax and semantics ofVB .NET, you find that the process oflearning additional .NET-aware languages (such as C#) is painfully simple. The truth of the matter is that .NET is an extremely language• agnostic platform. You can make use of any .NET-aware language (and possibly numerous .NET-aware languages) during the development of your next coding effort. In this vein, your greatest challenge is not necessarily learning the VB .NET language, but rather coming to terms with the numerous types defined in the .NET base class libraries. Once you understand how to leverage the existing code base, you find that the concept of "syntax" becomes a nonissue given that all.NET-aware languages make use of the same base class types. This is also a good thing, given that you should be able to move swiftly between various .NET languages with minimal fuss and bother. The goals of this text are to provide a solid foundation of the syntax and semantics ofVB .NET, as well as the architecture of the .NET platform. As you read through the (many) pages that follow, you are exposed to each major facet of the .NET base class libraries. Let's take a high-level overview of each chapter.

Chapter 1: The Philosophy of .NET

Chapter 1 functions as the backbone for this text. The first task of the chapter is to examine the world ofWmdows development as we know it today and review the shortcomings of the current state of affairs. However, the primary goal is to acquaint you with the meaning behind a number of .NET-centric building blocks, such as the Common Language Runtime (CLR), the Common Type System (CTS), the Common Language Specification (CLS), and the base class libraries. In addition, this chapter introduces you to a set of core tools ULDasm.exe, WmCV.exe, and so on) that allow you to explore the .NET class libraries at your leisure.

Chapter 2: Building VB .NET Applications

Chapter 2 begins with an examination of how to interact with the VB .NET com• piler (vbc.exe) in the raw. As you see later in the text, some advanced aspects of VB .NET (such as building multifile assemblies) are only accessible from the

xix Introduction

command-line compiler. Given this fact, spending the time to build some simple VB .NET applications by hand will serve you well. The later half of this chapter illustrates the core features of the Visual Studio .NET IDE. To wrap things up, you examine the pros and cons of converting existing VB 6.0 code into the .NET paradigm.

Chapter 3: VB .NET Language Fundamentals

The goal of Chapter 3 is to showcase the core syntax of the VB .NET programming language. As you would hope, you are introduced to the intrinsic data types ofVB .NET as well as the set of iteration and decision constructs. More important, you learn about the composition of a VB .NET class, and you make friends with a number of new .NET techniques, such as value and reference types, namespace development, and the role of the mighty System. Object.

Chapter 4: Object-Oriented Programming with VB .NET

Now that you can build complex stand-alone types, Chapter 4 focuses on the pil• lars of object technology: encapsulation, inheritance ("is-a" and "has-a''), and polymorphism (classical and ad hoc). The chapter begins with a high-level exam• ination of these key terms, and then quickly turns its attention to exploring how VB .NET supports each pillar. Along the way, you are exposed to new syntax used to define class properties, and you learn the ins and outs of developing class hier• archies. Finally, this chapter examines a new mechanism to handle runtime anomalies: Structured Exception Handling. The chapter ends with a discussion of the .NET garbage collection scheme, and you see how to programmatically inter• act with this service using the System.GC class type.

Chapter s: Interface and Collections

Like C++, Java, and VB 6.0, VB .NET supports the technique of interface-based programming. In this chapter you learn the role of an interface and understand how to define and implement such a creature in VB .NET. Once you can build types that support multiple interfaces, you learn a number of techniques you can use to obtain an interface reference from a valid type instance. The second half of this chapter examines a number of predefined interfaces defined within the .NET

XX Introduction class libraries and illustrates how to make use of the System. Collections name• space to build custom container types. You also learn how to build "cloneable" and "enumerable" types.

Chapter 6: Delegates, Events, and Callback Interfaces

This chapter rounds out your understanding of core OOP using VB .NET. To begin, you review the classic VB 6.0 event protocol, and you quickly see that VB .NET makes use of the same core keywords (Event, WithEvents, and RaiseEvent) to enable bidirectional communication. Under the hood, however, the .NET event architecture is founded on the use of delegates. The bulk of this chapter is spent examining the use of this type and several related topics, such as hooking into events dynamically at runtime using the new AddHandler and RemoveHandler statements.

Chapter 7: Assemblies, Threads, and AppDomains

At this point you should be very comfortable building stand-alone VB .NET appli• cations. This chapter illustrates how to break apart a monolithic EXE into discrete code libraries. Here, you learn about the internal composition of a .NET assembly and understand the distinction between "shared" and "private" assemblies. This entails a discussion of the Global Assembly Cache (GAC), XML configuration files, and side-by-side execution. To further illustrate the virtues of the CLR, this chap• ter also examines cross-language inheritance using C# and (gasp!) C++. The chapter wraps up with an examination of how to construct multithreaded appli• cations using VB .NET.

Chapter 8: Reflection and Attributes

Reflection is the process of runtime type discovery. This chapter examines the details behind the System. Reflection namespace and illustrates how to investigate the contents of an assembly on the fly. On a related note, you learn how to build an assembly (and its contained types) at runtime using the System.Reflection.Emit namespace. Chapter 8 also illustrates how to exercise late binding to a .NET type and dynamically invoke its members. Finally, the chapter wraps up with a discus• sion of attribute-based programming. As you will see, this technique allows you to augment compiler-generated metadata with application-specific information.

xxi Introduction

Chapter 9: Building a Better Window (Introducing Windows Forms)

Despite its name, the .NET platform has considerable support for building tradi• tional desktop applications. In this chapter, you come to understand how to build a stand-alone main window using the types contained in the System.Windows.Forms namespace. Once you understand the derivation of a Form, you then learn to add support for topmost and pop-up menu systems, toolbars, and status bars. As an added bonus, this chapter also examines how to programmatically manipulate the system registry and Windows 2000 event log.

Chapter 10: A Better Painting Framework (GDI+)

For the first time in VB's rich ten-year history, programmers are given the tools they need to build exotic, graphics-intensive applications. This chapter teaches you how to render geometric images, bitmaps, and complex textual images onto the Form's client area using VB .NET. On a related note, you learn how to drag images within a Form (in response to mouse movement), as well as how to per• form hit tests against geometric regions (in response to mouse clicks). This chapter ends with an examination of the .NET resource format which, as you might assume, is based on XML syntax.

Chapter 11: Programming with Windows Form Controls

This final chapter on Windows Forms examines how to program with the suite of GUI widgets provided by the .NET Framework. Here, you discover details behind the Calendar, DataGrid, and input validation controls, in addition to the vanilla-flavored TextBox, Button, and ListBox types (among others). In addition, you learn how to build custom .NET controls (and components) using VB .NET. The chapter wraps up with an examination of how to build custom dialog boxes and MDI applications, and you come to understand a new technique termed Form inheritance.

Chapter 12: Input, Output, and Object Serialization

The .NET Framework provides a number of types devoted to 10 activities. In this chapter you learn how to save and retrieve simple data types to (and from) files, memory locations, and string buffers. Of greater interest is the use of object seri• alization services. Using a small set of predefined attributes and a corresponding object graph, the Framework is able to persist related objects using an XML or xxii Introduction binary formatter. To illustrate object serialization at work, this chapter wraps up with a Windows Forms application that allows the end user to create and serialize custom class types for use at a later time.

Chapter 13: Interacting with Unmanaged Code

As bizarre as it may seem, Microsoft's Component Object Model (COM) can now be regarded as a legacy technology. As you most certainly know by this point in the book, the architecture of COM bears little resemblance to that of .NET. This chapter examines the details of how COM types and .NET types can live together in harmony through the use of COM Callable Wrappers (CCW) and Runtime Callable Wrappers (RCW). Here, you see how various COM constructs such as SAFEARRAYs, COM events, and COM enumerations map into VB .NET code. The chapter concludes by examining how to build .NET types that can take advantage of the COM+ runtime.

Chapter 14: Data Access with ADO.NET

To be perfectly blunt, ADO.NET bears little resemblance to classic ADO proper. As you discover, ADO.NET is a data access model specifically built for the discon• nected world. To begin, you learn how to create and populate an in-memory DataSet and establish relationships between the internal DataTables. The second half of this chapter examines how to make use of the OleDb and Sql managed providers to obtain access to relational database management systems such as Microsoft Access and SQL Server. Once you understand how to connect to a given data store, you learn how to insert, update, and remove data records as well as trigger logic contained within stored procedures.

Chapter 15: Web Development and ASP.NET

For the sake of completeness, this chapter begins with an overview of the Web programming model and examines how to build Web front ends (using HTML), how to perform client-side validation (using JavaScript), and how to request a response from a classic ASP Web application. Of course, if you are already "Web aware," you are free to skip these initial pages entirely. The bulk of the chapter provides a solid introduction to the ASP.NET architecture. Here, you learn about Web Controls, server-side event handling, and the core properties of the Page type (including the Request and Response properties). As you would hope, you learn how to build a Web-enabled front end that is able to display (and manipu• late) data retrieved using ADO.NET.

xxiii Introduction

Chapter 16: Building (and Understanding} Web Services

In this final chapter of this book, you examine the role of .NETWeb services. Simply put, a "Web service" is a unit of code that is activated using standard HTTP. Here you examine the surrounding technologies (WSDL, SOAP, and dis• covery services) that enable a Web service to take incoming client requests. Once you understand how to construct a VB .NET Web service, you then learn how to build a client-side proxy class, which hides the low-level SOAP logic from view.

xxiv