Programming VB.NET: A Guide for Experienced
Programmers GARY CORNELL AND JONATHAN MORRISON
APress Media, LLC
Programming VB.NET: A Guide for Experienced Programmers Copyright ©2002 by Gary Cornell 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-99-6 ISBN 978-1-4302-0847-1 (eBook) DOI 10.1007/978-1-4302-0847-1
'frademarked naines may appear in this book. Rather than use a trademark symbol 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: Ken Getz, Tim Walton
Managing Editor and Production Editor: Grace Wong
Copy Editors: Steve WIlent, 'fracy Brown Collins
Compositor: Susan Glinert Stevens
Artist: Allan Rasmussen
Indexer: Valerie Haynes Perry
Cover Designer: Karl Miyajima
Marketing Manager: Stephanie Rodriguez
In the United States, phone I-BOO-SPRINGER, email [email protected]. or visit http://www.springer-ny.com.
Outside the United States, fax +496221345229, email orders@springer .de, or visit http://www.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://www.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, neither the author nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work.
Dedication
To the people at Apress: the best group of people I can ever imagine working with.
iii
iv
Contents at a Glance
Dedication .............................................................................................................. iii
Contents .................................................................................................................... v
Acknowledgments ................................................................................................. viii
About This Book ...................................................................................................... ix
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8
Chapter 9
Introduction ..................................................................................... 1
The VB . NET IDE: Visual Studio . NET .............................. 11
Expressions, Operators, and Control Flow .................. .47
Classes and Objects (with a Short Introduction to Object-Oriented Programming) ....................................... 97
Inheritance and Interfaces ................................................. 177
Event Handling and Delegates ........................................... 237
Error Handling the VB . NET Way: Living with Exceptions ......................................................... 265
Windows Forms, Drawing, and Printing .......................... 279
Input/Output .............................................................................. 333
Chapter 10 Multithreading .......................................................................... 379
Chapter 11 A Brief Introduction to Database Access with VB .NET .............................................................................. 423
Chapter 12 A Brief Overview of ASP . NET .......................................... .443
Chapter 13 .NET Assemblies, Deployment, and COM Interop ........ .463
Index ......................................................................................................................... 479
Contents
Dedication ............................................................................................................ iii
Acknowledgments ............................................................................................ xiii
About This Book .............................................................................................. xv
Chapter 1 Introduction ........................................................................ 1
Visual Basic Then and Now .............................................................................. 1 The Versions of Visual Basic ........................................................................ 2 The • NET Men tali ty Shift ................................................................................ 3
The Common Language Runtime ...................................................................... 4 Completely Object Oriented ............................................................................... 5 Automatic Garbage Collection: Fewer Memory Leaks ..................................... 6
Structured Exception Handling ..................................................................... 6 True Multithreading ........................................................................................... 6 Why You Will Need To Learn a Whole Lot of New Concepts
to Use VB .NET ............................................................................................... 7 Should You Use C# and Not Bother with VB .NET? ................................ 9
Chapter 2 The VB • NET IDE: Visual Studio • NET ........... 11
Getting Started .................................................................................................. 12 Creating a New Solution ................................................................................... 13
A Tour of the Main Windows in the IDE .................................................. 17 The Editor ........................................................................................................... 19 The Solution Explorer ........................................................................................ 24 Properties Wmdow ............................................................................................ 25 References and the Reference Wmdow ........................................................... 26 Output Wmdow and Command Wmdow ........................................................ 27
Working with a Solution ................................................................................ 28 Adding Projects to a Solution ............................................................................ 33
Compiling ............................................................................................................... 34 Multiple Compilations ...................................................................................... 36 Build Options ..................................................................................................... 38 Debug vs. Release Versions ............................................................................... 39 Output Files ........................................................................................................ 40
v
Contents
Debugging in VB . NET ........................................................................................ 40 New Debugger Features ..................................................................................... 41
Chapter 3 Expressions, Operators, and Control Flow ............................................................. 47
Console Applications ........................................................................................ 48
Statements in VB .NET ...................................................................................... 51 Comments .................................................................................................................. 52 Variables and Variable Assignments ......................................................... 52 Literals and Their Associated Data Types ............................................ 54
Non-Nwneric literals ........................................................................................ 58 Declaring Variables .......................................................................................... 59
Conversion between Values of Different Types ............................................... 61 Strings .................................................................................................................... 64
String Functions ................................................................................................. 65 Formatting Data ................................................................................................. 68
Arithmetic Operators ........................................................................................ 69 Parentheses and Precedence ............................................................................. 72 Math Functions and Math Constants ............................................................... 73
Constants ................................................................................................................ 75 Repeating Operations-Loops ........................................................................... 75
Determinate Loops ....................... , ..................................................................... 75 Indeterminate Loops .......................................................................................... 77
Conditionals-Making Decisions .................................................................... 79 Scoping Changes ...................................................... .......................................... 80 Short Circuiting .................................................................................................. 81
Select Case ........................................................................................................... 81 The GoTo .................................................................................................................. 82 The Logical Operators on the Bit Level ................................................ 83 Arrays ...................................................................................................................... 84
The For-Each Construct .................................................................................... 86 Arrays with More than One Dimension ............................................................ 87
Procedures: User-Defined Functions and Subs ..................................... 87 Functions ............................................................................................................ 88 Sub Procedures ................................................................................................... 90 Using Arrays with Functions and Procedures .................................................. 92 Procedures with a Variable or Optional Nwnber of Arguments .................... 93
Recursion ................................................................................................................ 94
vi
Chapter 4 Classes and Objects (with a Short Introduction to Object-Oriented Programming) ...................................................................... 97
Introduction to OOP ......................................................................................... 98 Gasses As (Smart) User-Defined Types ........................................................... 99
The Vocabulary of OOP ................................................................................... 101 The Relationships between Gasses in Your Programs ................................. 101
How to Objectify Your Programs ............................................................... 107 What about Individual Objects? ............................................................... 109 Advantages to OOP ............................................................................................ 110 Creating Object Instances in VB .NET .................................................. 111
More on Constructors: Parameterized Constructors ................................... 114 Example: The String Gass .............................................................................. 115 Example: The StringBuilder Gass .................................................................. 115
Namespaces ........................................................................................................... 120 Imports ............................................................................................................. 120
Help and the (Vast) .NET Framework ...................................................... 124 Example: The Framework Collection Classes ............................................... 127
More on Object Variables ............................................................................ 134 Is and Nothing .................................................................................................. 136 TypeName and TypeOf ......................................................................................... 137 Subtleties of Passing Object Variables by Value ............................................ 138
Building Your Own Classes .......................................................................... 140 Overloading Gass Members ........................................................................... 144 More on Constructors ..................................................................................... 147 More on Properties .......................................................................................... 148 Scope of Variables ............................................................................................ 150 Nested Gasses .................................................................................................. 152
Shared Data and Shared Members Inside Classes .............................. 155 Shared Members .............................................................................................. 157
The Object Life Cycle ................................................................................... 158 Object Death .................................................................................................... 160
Value Types ......................................................................................................... 161 Enums ............................................................................................................... 163 Structure Types ................................................................................................ 165
Namespaces for Classes You Create ......................................................... 168 The Class View Window ................................................................................... 169 Debugging Object-Based Programs ............................................................. 170 Summary ................................................................................................................. 175
Contents
vii
Contents
Chapter 5 Inheritance and Interfaces ................................. 177
Inheritance Basics .......................................................................................... 178 Getting Started with Inheritance ...................................................... ............... 180 Overriding Properties and Methods ............................................................... 184 Abstract Base Classes ....................................................................................... 195
Object: The Ultimate Base Class .............................................................. 201 The Most Useful Members of Object ...................................................... ........ 202
The Fragile Base Class Problem: Versioning ...................................... 209 Overview of Interfaces ................................................................................. 215
Mechanics of Implementing an Interface ...................................................... 217
When to Use Interfaces~ When To Use Inheritance? ......................... 222 Important Interfaces in the .NET Framework ...................................... 222
ICloneable ......................................................................................................... 223 IDisposable ....................................................................................................... 225
Collections ......................................................................................................... 225 For Each and IEnumerable .............................................................................. 226
Chapter 6 Event Handling and Delegates ............................ 237
Event Handling from an OOP Point of View .......................................... 237 What Goes into the Functions Called by Events? .......................................... 239
Basic Event Raising ........................................................................................ 241 Hooking Up the listener Objects to Event Source Objects .......................... 243 Building Your Own Event Classes ................................................................... 247 Dynamic Event Handling ................................................................................ 249 Handling Events in an Inheritance Chain ...................................................... 253
Delegates .............................................................................................................. 254 Building Up a Delegate .................................................................................... 255 A More Realistic Example: Special Sorting ..................................................... 257 Delegates and Events ....................................................................................... 264
Chapter 7 Error Handling the VB .NET Way: Living with Exceptions ........................................... 265
Error Checking vs. Exception Handling ................................................. 266 First Steps in Exception Handling ................................................................... 267 Analyzing the Exception .................................................................................. 269 Multiple Catch Clauses .................................................................................... 269
Throwing Exceptions ........................................................................................ 272 Exceptions in the Food Chain ......................................................................... 275
And Finally ... Finally Blocks ......................................................................... 277 Some Tips for Using Exceptions ................................................................ 278
viii
Contents
Chapter 8 Windows Forms) Drawing) and Printing ....................................................................... 279
First, Some History ....................................................................................... 280 Form Designer Basics ..................................................................................... 281
Keeping Things in Proportion: The Anchor and Dock Properties ............... 284 The Tab Order Menu ....................................................................................... 287
Returning to a Simple Program ................................................................. 287 More Form Properties ..................................................................................... 292
Menu Controls and the New Visual Studio Menu Editor ................. 294 Context Menus ................................................................................................. 297 MDI Forms ....................................................................................................... 298 ColorDialog ...................................................................................................... 301 FontDialog ........................................................................................................ 302 FileDialogs ........................................................................................................ 302 Adding Controls at Run Time ......................................................................... 303
Form Inheritance: AKA Visual Inheritance ......................................... 305 Building Custom Controls through Control Inheritance ............... 306
Overriding an Event ......................................................................................... 306
The Inheritance Chains in the System. Windows. Forms Assembly .......................................................... 313 Basic Control Gass Functionality .................................................................. 316
Graphics: Using GDI+ ..................................................................................... 318 Simple Drawing ............................................................................................... 320 Drawing Text .................................................................................................... 321
Printing ............................................................................................................... 325
Chapter 9 Input/Output .................................................................... 333
Directories and Files ................................................................................... 334 The Path Class .................................................................................................. 335 The Directory Gass .......................................................................................... 336 The File Class ................................................................................................... 338
The DirectoryInfo and FileInfo Classes .............................................. 340 Working Recursively through a Directory Tree ............................................. 341 The Most Useful Members of the FileSystemlnfo, Filelnfo,
and Directorylnfo Classes ...................................................................... 344
Streams ................................................................................................................. 347 Writing to Files: File Streams .......................................................................... 350 Getting Binary Data into and out of Streams:
BinaryReader and BinaryWriter ................................................................ 355 TextReader, TextWriter, and Their Derived Gasses ....................................... 358 Object Streams: Persisting Objects ................................................................ 361 Simple Serialization ......................................................................................... 362
ix
Contents
Simple Deserialization ..................................................................................... 364 Network Streams ...................................................... ........................................ 370
Writing a File System Monitor .................................................................. 375 Going Further with File Monitoring ............................................................... 378
Chapter 10 Multithreading ................................................................ 379
Getting Started with Multithreading ..................................................... 380 The Mechanics of Thread Creation ................................................................ 383 Join ..................................................................................................................... 388 Thread Names, CurrentThread, and ThreadState ......................................... 389 The Threads Wmdow ...................................................... ................................. 390 Putting a Thread to Sleep ................................................................................. 391 Ending or Interrupting a Thread ..................................................................... 392 A More Serious Example: Screen Scraping Redux ......................................... 394
The Big Danger: Shared Data ...................................................................... 397 The Solution: Synchronization ........................................................................ 401 More on SyncLock and the Monitor Class .................. ................................... 403 Deadlock: the Danger of Synchronization .................................. ................... 404 Sharing Data as It Is Produced .............................................. .......................... 410
Multithreading a GUI Program .................................................................... 415
Chapter 11 A Brief Introduction to Database Access with VB .NET ..................................................................... 423
Why ADO .NET Is Not ADO++ ........................................................................... 423 Disconnected Data Sets: The New Way to Use Databases ............... .424 The Classes in System.Data.DLL ................................................................ 425
System.Data.OleDb .......................................................................................... 425 System.Data.SqIClient ..................................................................................... 429
Calling a Stored Procedure ........................................................................ .430 A More Complete VB • NET Database Application ................................ .431
Chapter 12 A Brief Overview of ASP . NET ........................... .443
Some History ....................................................................................................... 443 A Simple ASP • NET Web Application ........................................................ .444
What Gets Sent to the Client? .......................................................................... 448 The Web.config File .......................................................................................... 451
A Simple Web Service ...................................................................................... 455 Client -Side Use of a Web Service .................................................................... 458
x
Contents
Chapter 13 .NET Assemblies, Deployment, and COM Interop ............................................................... 463
How COM Works .................................................................................................... 464 . NET Assemblies ................................................................................................ 465
The Manifest .................................................................................................... 467 Drilling Down into a Manifest ........................................................................ 469
Shared Assemblies and the CAC ................................................................. 471 Adding and Removing Assemblies from the GAC ......................................... 473 Strong Names = Shared Names ...................................................................... 473 Generating a Key Pair ...................................................................................... 474 Signing an Assembly ........................................................................................ 476
COM Interoperability and Native DLL Function Calls ................... 476 DIL Function Calls .......................................................................................... 477
xi
Acknowledgments
ONE OF THE BEST PARTS of writing a book is when the author gets to thank those who have helped him or her, for rarely (and certainly not in this case) is a book solely the product of the names featured so prominently on the cover. First and foremost, I have to thank my friends and colleagues at Apress, but especially Grace Wong, whose efforts to get this book out under quite stressful conditions was nothing short of amazing! I would also like to thank Steve WIlent, Tracy Brown Collins, Susan Glinert Stevens, Valerie Haynes Perry for all their efforts on my behalf.
Next, Ken Getz did an amazingly thorough job of reviewing this book under terribly tight constraints. He caught dozens of obscurities and helped me avoid dozens of false steps (any errors that remain are solely my responsibilityl). Karen Watterson and TIm Walton made comments that were very useful as well. Rob Macdonald, Carsten Thomsen, and Bill Vaughn all helped me to understand how ADO .NET relates to classic ADO. Allen Holub helped me understand the intricacies of multithreading programs by reading and commenting on Chapter 10 under great time pressure. Thanks also go to my friend DanAppleman-suffice it to say that not only have I learned an immense amount about every version of Visual Basic from him, but his general guidance on so many things have helped me over many difficult spots during these stressful times. While my friend Jonathan Morrison had to step away from this project before it could be completed, his insights into VB were very helpful as I worked to finish this book.
Finally, thanks to all my family and friends who put up with my strange ways and my occasionally short temper for 10 so many months.
Gary Comell Berkeley, CA September 2001
xiii
About This Book
1ins BOOK IS A COMPREHENSIVE, hands-on guide to the Visual Basic.NET prograrrnning language addressed to readers with some programming background. No background in Visual Basic is required, however.
While I show you the syntax of VB .NET, this book is not designed to teach you syntax. I have taken this approach because trying to force VB .NET into the framework of older versions ofVB is ultimate1yse1f-defeating----you cannot take advantage of its power if you continue to think within an older paradigm.
First off, I have tried to give you a complete treatment of object -oriented programming in the context of the VB .NET language. I feel pretty strongly that without a firm foundation here, it is impossible to take full advantage of the power that VB .NET can bring to you.
Also, I have tried to cover at the least the fundamentals of every technique that a professional VB .NET developer will need to master. This includes topics like multithreading, which are too often skimped on in most books. This does not mean that I cover all the possible (or even the majority of) applications of VB .NET to the .NET platform; that would take a book two or three times the size of this one. This is a book about the techniques you need to master, not the applications themselves. (I have tried to make most of the examples realistic, avoiding toy code as much as possible.)
Finally, since most people reading this book will have programmed with some version of Visual Basic before, I have also tried to be as clear about the differences between VB .NET and earlier versions of VB as I could. However, I want to stress that this book does not assume any knowledge of earlier versions of VB, just some programming experience.
How This Book Is Organized
Chapter 1, "Introduction," explains what is so different about VB .NET. Experienced VB programmers will benefit from reading this chapter. Chapter 2, "The VB .NEI' IDE: Visual Studio .NET," introduces you to the Visual Studio .NET Integrated Development Environment (IDE). Chapter 3, "Expressions, Operators, and Control Flow," covers what I like to call the "vocabulary" of VB .NET. This is the basic syntax for code including variables, loops, and operators. Chapter 4, "Qasses and Objects (with a Very Short Introduction to Object-Oriented Programming)," is the first of the core object-oriented programming chapters. It shows you how to construct objects and use them. Chapter 5, "Inheritance and Interfaces," covers the other key parts of object-oriented programming in VB .NEI': inheritance and interfaces. This chapter also contains an introduction to the useful.NET collection classes which allow you to efficiently manage data inside a program. xv
About This Book
xvi
Chapter 6, "Event Handling and Delegates," takes up events and the new .NET notion of a delegate. Event-driven programming is still the key to good user interface design, and .NET depends on it just as much as Wmdows did. Chapter 7, "Error Handling the VB .NETWay: Uving with Exceptions," covers exceptions, the modem way of dealing with errors that lets you banish the archaic On Error GoTo syntax that has plagued VB since its start. Chapter 8, 'Wmdows Forms, Drawing, and Printing,," takes up building Windows user interfaces, graphics and printing. Although the browser is obviously becoming more important as a deliveryplatfonn, traditional Windows-based clients aren't going away, and this chapter gives you a firm foundation to build them under .NET. Chapter 9, "Input/Output," presents 110, with a complete treatment of streams, which are at the root of .NET's way of handling 110. Chapter 10, "Multithreading," is a concise treatment of the fundamentals ofmultithreading. Multithreading is an amazingly powerful technique of programming that is nonetheless fraught with peril. I hope this chapter does not just teach you enough "to be dangerous," but rather, enough so that you can use this powerful technique safely and effectively in your programs. Chapter 11, '~Briefintroduction to Database.Access with VB .NE'I;" and Chapter 12, '~Brief Overview of ASP .NET," are very brief introductions to two of the most important applications of.NET: ASP .NET andADO .NET. Please note these chapters are designed to give you just a taste, and you will have to look at more detailed books to learn how to use ASP .NET or ADO .NET in production-level code. Chapter 13, ".NET Assemblies, Deployment, and COM Interop," is a brief introduction to what goes on under the hood in .NET that includes a look the idea of assemblies and COM Interop. While I have tried to give you a flavor of these important topics, you will also need to consult a more advanced book to learn more about the topics.
Contacting Me
I would love to hear about your experiences with this book, suggestions for improvements, and any errata you may find. (The current list of errata may be found at the Apress Web site at W\WJ. apress. com). You can contact me at [email protected].
Gary Cornell Berkeley, CA September 2001
Note on the second printing: I have updated the text and screens to reflect the very minor changes needed for the first release candidate as well as corrected any errors that I found in the text or that have been pointed out to me. The downloadable code (www.apress.com) has been updated for RCO as well.