Wrox Professional VB 2005 Nov 2005 ISBN 0764575368 pdf
TEAM LinG Professional VB 2005
Professional VB 2005
Bill Evjen, Billy Hollis, Rockford Lhotka,
Tim McCarthy, Rama Ramachandran,
Kent Sharkey, Bill Sheldon Professional VB 2005 Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256
Copyright © 2006 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada
ISBN-10: 0-7645-7536-8 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1
1B/SW/RQ/QV/IN Library of Congress Cataloging-in-Publication Data: Professional Visual Basic 2005 / Bill Evjen ... [et al.]. p. cm. Includes index.
ISBN-13: 978-0-7645-7536-5 (paper/website)
ISBN-10: 0-7645-7536-8 (paper/website) 1. Microsoft Visual BASIC.
QA76.73.B3P7485 2005 005.2’768 — dc22 2005012585 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of
the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization throughpayment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923,
(978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department,Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY : THE PUBLISHER AND THE AUTHOR MAKE NO REPRESEN-
TATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF
THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WAR-
RANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY
SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUIT-
ABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT
ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL
ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT.
NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE
FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A
POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER
ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT
For general information on our other products and services please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trade-marks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries,
and may not be used without written permission. Visual Basic is a registered trademark of Microsoft Corporation in the
United States and/or other countries. All other trademarks are the property of their respective owners. Wiley Publishing,Inc., is not associated with any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be availablein electronic books.
About the Authors Bill Evjen is an active proponent of .NET technologies and community-based learning initiatives for
.NET. He has been actively involved with .NET since the first bits were released in 2000. In the same year, Bill founded the St. Louis .NET User Group ( www.stlnet.org ), one of the world’s first .NET user groups. Bill is also the founder and the executive director of the International .NET Association (INETA – www.ineta.org ), which represents more than 375,000 members worldwide.
Based in St. Louis, Missouri, Bill is an acclaimed author and speaker on ASP.NET and XML Web Services. He has written or coauthored more than 10 books, including Professional C# 2005 and Professional ASP.NET 2.0 (Wrox), XML Web Services for ASP.NET, ASP.NET Professional Secrets (Wiley), and more.
Bill is a technical director for Reuters, the international news and financial services company, and he travels the world speaking to major financial institutions about the future of the IT industry. He gradu- ated from Western Washington University in Bellingham, Washington, with a Russian language degree. When he isn’t tinkering on the computer, he can usually be found at his summer house in Toivakka, Finland. You can reach Bill at firstname.lastname@example.org .
To Kalle – Welcome to the family!
Billy Hollis is coauthor of the first book ever published on Visual Basic .NET, VB.NET Programming onthe Public Beta (Wrox Press) as well as numerous other books and articles on .NET. Billy is a Microsoft
regional director and an MVP, and he was selected as one of the original .NET “Software Legends.” He writes a monthly column for MSDN Online and is heavily involved in training, consultation, and soft- ware development on the Microsoft .NET platform, focusing on smart-client development and commer- cial packages. He frequently speaks at industry conferences such as Microsoft’s Professional Developer Conference, TechEd, and COMDES. Billy is a member of the INETA speakers’ bureau and speaks at user group meetings all over the United States.
Rockford Lhotka is the principal technology evangelist for Magenic Technologies ( www.magenic.com ),
a company focused on delivering business value through applied technology and one of the nation’s premiere Microsoft Gold Certified Partners. Rockford is the author of several books, including Expert
Visual Basic .NET and C# Business Objects. He is a Microsoft Software Legend, regional director, MVP, and
INETA speaker. He is a columnist for MSDN Online and contributing author for Visual Studio Magazine, and he regularly presents at major conferences around the world — including Microsoft PDC, Tech Ed,
VS Live! and VS Connections. For more information go to www.lhotka.net .
For my Mom and Dad, whose love and guidance have been invaluable in my life. Thank you!
Tim McCarthy is a principal engineer at InterKnowlogy, where he architects and builds highly scalable
n -tier web and smart-client applications utilizing the latest Microsoft platforms and technologies. Tim’s
expertise covers a wide range of Microsoft technologies, including, but not limited to: .NET Framework (ASP.NET/Smart Clients/Web Services), Active Directory, UDDI, SQL Server, Windows SharePoint Services/SharePoint Portal Server 2003, and Service Oriented Architecture (SOA) applications. Tim has worked as a project technical lead/member as well as in a technical consulting role for several Fortune 500 companies. He has held the Microsoft Certified Solution Developer (MCSD) and Microsoft Certified Trainer (MCT) certifications for several years and was one of the first wave of developers to earn the Microsoft Certified Application Developer (MCAD) for .NET and MCSD for .NET certifications. He also holds the Microsoft Certified Database Administrator certification for SQL Server 2000. Tim has been an author and technical reviewer for several books from Wrox Press and most recently was a lead author on Professional VB.NET 2003. His other books include Professional Commerce Server 2000, and Professional ADO 2.5 Programming. Tim is currently working as a lead author on the next edition of
Professional VB.NET . Tim has written numerous articles for the Developer .NET Update newsletter, devel-
oped packaged presentations for MSDN, and has written a whitepaper for Microsoft on using COM+ services in .NET. He has also written articles for SQL Server Magazine and Windows & .NET Magazine. Tim has spoken at technical conferences around the world and several San Diego area user groups (includ- ing both .NET and SQL Server groups) and he has been a regular speaker at the Microsoft Developer Days conference in San Diego for the last several years. Tim has also delivered MSDN webcasts, many of which were repeat requests from Microsoft. Tim also teaches custom .NET classes to companies in need of expert .NET mentoring and training. Tim holds a B.B.A. in marketing from the Illinois Institute of Technology as well as an M.B.A. in market- ing from National University. Before becoming an application developer, Tim was an officer in the United States Marine Corps. Tim’s passion for .NET is only surpassed by his passion for Notre Dame athletics.
I dedicate this book to everybody in my family who supports me. Jasmine, some day you will be writing books, too!
Rama Ramachandran is a software architect at DKR Capital, a major hedge fund company in Stamford,
Connecticut. He is a Microsoft Certified Solutions Developer and Site-Builder and has excelled in designing and developing WinForms and Web applications using .NET, ASP.NET, Visual Basic and SQL Server. Rama has more than 15 years’ experience with all facets of the software development lifecycle and has cowritten Introducing .NET, Professional ASP Data Access, Professional Visual InterDev Programming (all Wrox Press), and four books on classic Visual Basic. Rama is also the “ASP Pro” at Devx.com , where he maintains ASP-related columns. He teaches .NET Development and Web Development for Fairfield University’s master’s degree in software engineering, and at the University of Connecticut. You can reach Rama at email@example.com .
This book is dedicated to my wife, Beena, and our children, Ashish and Amit. They make my life whole. I’m great at writing about technology but get tongue-tied trying to say how much I love and care about the three of you. I am grateful to our prayer-answering God for your laughing, mischievous, adoring lives. Thanks for being there, Beens. I love you.
Kent Sharkey. Born in an igloo and raised by wolves in a strange realm called “Manitoba,” Kent
Sharkey wandered the wilderness until found by a group of kind technical evangelists and migrated to Redmond. He now is content strategist (yeah, he doesn’t know what he’s supposed to do either) for ASP.NET content on MSDN. When not answering email he dreams of sleeping, complains to everyone around (come to think of it, he does that while answering email as well), and attempts to keep his house- mates (Babi, Cica, and Squirrel) happy.
As with all else, to Margaret. Thank you.
Bill Sheldon is a software architect and engineer originally from Baltimore, Maryland. Holding a degree
in Computer Science from the Illinois Institute of Technology (IIT) and a Microsoft Certified Solution Developer (MCSD) qualification, Bill has been employed as an engineer since resigning his commission with the U.S. Navy following the first Gulf War. Bill is involved with the San Diego .NET User Group and writes for Windows and .NET magazines, including the twice monthly Developer .NET Update email newsletter. He is also a frequent online presenter for MSDN and speaks at live events such as Microsoft Developer Days. He lives with his wife, Tracie, in Southern California, where he is employed as a princi- pal engineer with InterKnowlogy. You can reach Bill at firstname.lastname@example.org .
Acquisitions Editor Katie Mohr Development Editors Eileen Bien Calabro Ami Frank Sullivan Technical Editor Brian Patterson Production Editor Pamela Hanley Copy Editor Foxxe Editorial Services Editorial Manager Mary Beth Wakefield Vice President & Executive Group Publisher Richard Swadley Vice President and Publisher Joseph B. Wikert
Project Coordinator Ryan Steffen Graphics and Production Specialists Carrie A. Foster Lauren Goddard Denny Hager Barbara Moore Lynsey Osborn Alicia South Quality Control Technicians Laura Albert John Greenough Leeann Harney Jessica Kramer Brian H. Walls Proofreading TECHBOOKS Production Services Indexing Broccoli Information Management
Contents Introduction xxv
12 Web Services
16 Major Differences in .NET 2.0
15 The Future of .NET
15 Easier Deployment
15 Libraries of Prewritten Functionality
14 Reducing Barriers to Internet Development
14 A Spectrum of Programming Models
14 How .NET Affects You
13 .NET Drives Changes in Visual Basic
13 Some Things Never Change . . .
13 No Internal Use of COM
12 The Role of COM
12 XML as the .NET Metalanguage
11 Console Applications
1 What Is .NET?
11 Web Forms
10 Windows Forms
9 User and Program Interfaces
8 What Is in the .NET Class Framework?
8 The Next Layer — The .NET Class Framework
7 A Common Type System
7 Multiple-Language Integration and Support
4 Key Design Goals
3 The Common Language Runtime
2 An Overview of the .NET Framework
2 What’s Wrong with DNA and COM?
1 A Broad and Deep Platform for the Future
17 x Contents
19 Visual Studio .NET — Startup
64 Performing Explicit Conversions
50 Chapter 3: Variables and Type
51 Differences of Value and Reference Types
52 Value Types (Structures)
54 Primitive Types
54 Explicit Conversions
63 Compiler Options
66 Reference Types (Classes)
47 Recording and Using Macros in Visual Studio 2005
68 The Object Class
68 The String Class
70 The DBNull Class and IsDBNull() Function
76 Parameter Passing
47 The Server Explorer
20 Visual Studio .NET
30 Working with Visual Basic 2005
21 The Solution Explorer
22 My Project
24 Assembly Information Screen
25 The New Code Window
26 The Properties Window
29 Dynamic Help
31 Form Properties Set in Code
46 The Command Window
32 Enhancing the Sample Application
34 Adding a Control and Event Handler
34 Customizing the Code
35 Build Configurations
40 Building Applications
43 Useful Features of Visual Studio
46 The Task List
Contents Retired Keywords and Methods
80 Elements of Visual Basic 6.0 Removed in .NET
81 Chapter 4: Object Syntax Introduction
83 Object-Oriented Terminology
84 Objects, Classes, and Instances
84 Composition of an Object
85 Working with Objects
88 Object Declaration and Instantiation
88 Object References
90 Dereferencing Objects
90 Early versus Late Binding
90 Creating Classes
94 Creating Basic Classes
94 Constructor Methods 114 Termination and Cleanup 115
Advanced Concepts 116
Overloading Methods 116 Overloading Constructor Methods 119 Shared Methods, Variables, and Events 120 Operator Overloading 125 Delegates 128 Classes versus Components 133
Chapter 5: Inheritance and Interfaces 137
Inheritance 138Implementing Inheritance
140 Multiple Interfaces
187 Object Interfaces
187 Secondary Interfaces 189
Chapter 6: The Common Language Runtime 197Elements of a .NET Application 198
Modules 198 Assemblies 199 Types 200
Generic Types 267 Generic Methods 275 Constraints 276 Generics and Late Binding 280
Creating Generics 267
261 Generic Methods 265
260 Generic Types
259 Using Generics
Versioning and Deployment 201
Chapter 7: Applying Objects and Components 223Abstraction 223 Encapsulation 227 Polymorphism 230 Method Signatures 230 Implementing Polymorphism 230
Traditional “Garbage Collection” 211 Faster Memory Allocation for Objects 218 Garbage Collector Optimizations 220
IL Disassembler 209 Memory Management 210
The Common Type System 203 Metadata 204 Better Support for Metadata 205 Attributes 206 The Reflection API 208
Cross-Language Integration 203
Better Support for Versioning 201 Better Deployment 202
When to Use Inheritance 242 Inheritance and Multiple Interfaces 246 How Deep to Go? 252 Fragile Base Class Issue 254
Contents Chapter 9: Namespaces
283 What Is a Namespace?
284 Namespaces and References
287 Common Namespaces 289
Importing and Aliasing Namespaces 291
Importing Namespaces 292 Referencing Namespaces in ASP.NET 293 Aliasing Namespaces 294
Creating Your Own Namespaces 295 My 298
My.Application 299 My.Computer 303 My.Forms 307 My.Resources 308 My.User 308 My.WebServices 308
Chapter 10: Exception Handling and Debugging 311A Brief Review of Error Handling in VB6 312 Exceptions in .NET 314
Important Properties and Methods of an Exception 314 How Exceptions Differ from the Err Object in VB6 315
Structured-Exception-Handling Keywords in VB.NET 315
The Try, Catch, and Finally Keywords 316 The Throw Keyword 318 Throwing a New Exception 319 The Exit Try Statement 320 Nested Try Structures 321 The Message Property 323 The InnerException and TargetSite Properties 323
Interoperability with VB6-Style Error Handling 328 Error Logging 329
Writing to Trace Files 333
Analyzing Problems and Measuring Performance via the Trace Class 335
Summary 338 xiv Contents
Chapter 11: Data Access with ADO.NET 2.0 341ADO.NET 2.0 Architecture Enhancements 342 ADO.NET Components 343
370 Properties 371 Stored Procedure XML Structure 372 Methods 373 Using DataSet Objects to Bind to DataGrids 385
XML Stream-Style Parsers 399
System.Xml Document Support 399
Source Code Style Attributes 397
XML Serialization 392
Chapter 12: Using XML in Visual Basic 2005 389An Introduction to XML 391
.NET Data Providers 344
Working with the Common Provider Model 366 Connection Pooling Enhancements in ADO.NET 2.0 369 Building a Data Access Component
361 ADO.NET DataTable Objects 363 ADO.NET 2.0 Enhancements to the DataSet and DataTable 364
DataTableCollection 359 DataRelationCollection 360 ExtendedProperties 360 Creating and Using DataSet Objects
The DataSet Component 359
DataReader Object 350 Executing Commands Asynchronously 352 DataAdapter Objects 354 SQL Server .NET Data Provider 358 OLE DB .NET Data Provider 359
Connection Object 344 Command Object 345 Using Stored Procedures with Command Objects 346
Writing an XML Stream 400 Reading an XML Stream 405 Using the MemoryStream Object 414 Document Object Model (DOM) 418
470 Dealing with Exceptions Using the SecurityException Class 471 Cryptography Basics
The System.Windows.Forms Namespace 502 Using Forms 502
Default Instances of Forms 498 Changes in Existing Controls 499 New Controls 500 Replacements for Older Windows Forms Controls 501
The Importance of Windows Forms 498 Summary of Changes in Windows Forms version 2.0 498
Chapter 14: Windows Forms 497
473 Hash Algorithms
Figuring the Minimum Permissions Required for Your Application 465 Using Visual Studio to Figure Minimum Permissions 467 Security Tools
XSLT Transforms 424
Managing Code Access Permissions 449 Managing Security Policy 454
Code Access Permissions 445 Role-Based Permissions 446 Identity Permissions 449
Chapter 13: Security in the .NET Framework 2.0 439Security Concepts and Definitions 440 Permissions in the System.Security.Permissions Namespace 442
XML and SQL Server 2005 436
432 ADO.NET and SQL Server 2000’s Built-In XML Features 434
XSLT Transforming between XML Standards 429 Using XML in Visual Basic 2005 430 Other Classes and Interfaces in System.Xml.Xsl 432
Showing Forms via Sub Main 503 Setting the Startup Form 503 Startup Location 504 Form Borders 505 Always on Top — The TopMost Property 505 Owned Forms 505 xvi Contents
Making Forms Transparent and Translucent 507 Visual Inheritance 508 Scrollable Forms 509
Forms at Runtime 509 Controls 510
Control Tab Order 511 Control Arrays 511 Automatic Resizing and Positioning of Controls 513
FlowLayoutPanel Control 517 TableLayoutPanel Control 520 Extender Provider Controls 520 Advanced Capabilities for Data Entry 523 Validating Data Entry 526 Toolbars and the New ToolStrip Control 528 Menus 531 Common Dialogs 533 Drag and Drop 535 Panel and GroupBox Container Controls 538 Summary of Standard Windows.Forms Controls 539
Retired Controls 543 Using ActiveX Controls 543 Other Handy Programming Tips 543 MDI Forms 544 An MDI Example in VB.NET 545 Dialog Forms 547
552 Developing Custom Controls in .NET 552
Inherit from an Existing Control 553 Build a Composite Control 553 Write a Control from Scratch 554
Inheriting from an Existing Control 554
Overview of the Process 554 Adding Additional Logic to a Custom Control 555
Other Useful Attributes 559 Defining a Custom Event for the Inherited Control 560
Creating a CheckedListBox that Limits the Number of Selected Items 560
The Control and UserControl Base Classes 564
The Control Class 564 The UserControl Class 565
Contents A Composite UserControl
A More Complex Example 594 The Processing Flow of ASP.NET Web Forms 596
Chapter 17: ASP.NET 2.0 Advanced Features 627Applications and Pages 627
Web Forms versus ASP 609 Transferring Control among Web Forms 611 A Final Example 611
The Web Form’s Lifecycle 607 Event Categories 608
Events in Web Forms 606
The Concept of Server-Side Controls 598 HTML Server Controls 600 ASP.NET Server Controls 602 Validation Controls 604 User Controls 605
The Controls Available in Web Forms 598
Single-File Page Model 590 Code-Behind Page Model 591 The Template for Presentation 593
566 Creating a Composite UserControl
The Anatomy of a Web Form 590
Setting Up the Environment 584 The HelloWorld Web Form 584
Chapter 16: Building Web Applications 583A Web Site in Action 583
Attaching an Icon for the Toolbox 579 Embedding Controls in Other Controls 580
Painting a Custom Control with GDI+ 573
Building a Control from Scratch 572
567 How Does Resize Work? 568 Setting a Minimum Size 568 Exposing Properties of Subcontrols 568 Stepping Through the Example 569
Cross-Page Posting 628 ASP.NET Advanced Compilation 632 xviii Contents
Master Pages 634
Assemblies and Deployment 678
Application Deployment 692
Chapter 19: Deployment 691
The Assembly Class 687 Putting Assemblies to Work 689
Dynamic Loading of Assemblies 687
Application Isolation 681 Side-by-Side Execution 682 Self-Describing 682 Version Policies 682 Configuration Files 684
Versioning Issues 681
Application-Private Assemblies 678 Shared Assemblies 679
The Identity Section 675 Referenced Assemblies 677
Creating a Master Page 635 Creating the Content Page 637 Declaring the Master Page Application-Wide 641
Assemblies 672 The Manifest 673
Chapter 18: Assemblies 671
Configuring ASP.NET 666 Summary 668
Membership and Role Management 661 Personalization 665
Using the SiteMapPath Server Control 654 Menu Server Control 656 The TreeView Server Control 657
652 Navigation 653
642 Using the GridView and SqlDataSource Controls 643 Allowing for Editing and Deleting of Records with the GridView 648 Don’t Stop There!
Providing Default Content in Your Master Page 642 Data-Driven Applications
Why Is Deployment Easier in .NET? 692
XCOPY Deployment 694 Using the Windows Installer 694
Visual Studio .NET Deployment Projects 695 Project Templates
696 Creating a Deployment Project 698 Walkthroughs 698
Modifying the Deployment Project 710
Project Properties 711 The File System Editor 714 The Registry Editor 719 The File Types Editor 722 The User Interface Editor 723 The Custom Actions Editor 726 The Launch Conditions Editor 729
Building 732 Internet Deployment of Windows Applications 733
No-Touch Deployment 733 ClickOnce Deployment 735 Custom Deployment Options 745
748 COM and .NET in Practice 749
A Legacy Component 749 The .NET Application 752 Trying It All Out 754 Using TlbImp Directly 755 Late Binding 756
ActiveX Controls 761
A Legacy ActiveX Control 761 A .NET Application, Again 763 Trying It All Out, Again 766
Using .NET Components in the COM World 766 A .NET Component
767 RegAsm 769 TlbExp 772
Summary 772 xx Contents Chapter 21: Enterprise Services
773 Transactions 774
What Is a Thread? 803
Introduction to Web Services 835 Early Architectural Designs 837
Chapter 23: XML Web Services 835
A Quick Tour 812 Threading Options 815 Manually Creating a Thread 820 Shared Data 822 Avoid Sharing Data 823 Sharing Data with Synchronization 825 Synchronization Objects 827
Implementing Threading 812
Processes, AppDomains, and Threads 805 Thread Scheduling 807 Thread Safety and Thread Affinity 809 When to Use Threads 809 Designing a Background Task 811 Interactive Applications 811
Chapter 22: Threading 803
The ACID Test 774
An Example of Queued Components 793 Transactions with Queued Components 799
Queued Components 792
Just-In-Time 791 Object Pooling 792 Holding Things Up 792
Other Aspects of Transactions 791
An Example of Transactions 776
Transactional Components 775
The Network Angle 837 Application Development 837 Merging the Two with the Web 837 The Foundations of Web Services 838
Contents The Problems
The Downside 868
879 Using IIS As a Remoting Host 890 Using Activator.GetObject 894 Interface-Based Design 895 Using Generated Proxies 897
879 A Simple Example
872 SingleCall, Singleton, and Activated Objects 875 Implementing Remoting
872 Basic Terminology
871 Remoting Overview
Where We Go from Here 869
Security 868 State 868 Transactions 868 Speed and Connectivity 868
The Secure Sockets Layer 867 Directory-Level Security 867 Other Types of Security 868
839 The Other Players 840 What All the Foundations Missed 841
Security in Web Services 866
Why Web Services? 861 How This All Fits Together 862 State Management for XML Web Services 862 Using DNS As a Model 863
Architecting with Web Services 861
858 System.Web.Services.Description Namespace 859 System.Web.Services.Discovery Namespace 860 System.Web.Services.Protocols Namespace 860
858 System.Web.Services Namespace
Using Visual Studio 2005 to Build Web Services 848 Visual Basic and System.Web.Services
Building a Web Service 844 A Realistic Example 848
Summary 898 xxii Contents Chapter 25: Windows Services
899 Example Windows Services
Writing Events Using an Eventlog 922 Creating a FileSystemWatcher 923
Web Requests (and Responses) 935 Simplifying Common Web Requests with WebClient 952
The System.Net Namespace 935
933 Ports: They’re Not Just for Ships 934 Firewalls: Can’t Live with Them, Can’t Live without Them 934
Getting Your Message Across: Protocols, Addresses, and Ports 931 Addresses and Names
Chapter 26: Network Programming 931
To Debug a Service 927
Debugging the Service 927
Custom Commands 919 Passing Strings to a Service 921 Creating a File Watcher 922
899 Characteristics of a Windows Service 900 Interacting with Windows Services 901 Creating a Windows Service 902
More About ServiceController 919
The ServiceController Class 916 Integrating a ServiceController into the Example 917
Communicating with the Service 915
Creating a Performance Counter 912 Integrating the Counter into the Service 914 Changing the Value in the Performance Counter 914
Monitoring a Performance Counter 912
Installing the Service 910 Starting the Service 910 Uninstalling the Service 911
Creating a Windows Service with Visual Basic 906 Creating a Counter Monitor Service 907
The .NET Framework Classes for Windows Services 902 Other Types of Windows Services 905
Creating Your Own Web Server with HttpListener 955 Summary 963
965 Sockets 969
Building the Application 970 Creating Conversation Windows 972 Sending Messages 980 Shutting Down the Application 986
Using Internet Explorer in Your Applications 990 Windows Forms and HTML — No Problem!
Appendix A: The Visual Basic Compiler 1001Appendix B: Visual Basic Resources 1017
In 2002, Visual Basic took the biggest leap in innovation since it was released, with the introduction of Visual Basic .NET (as it was renamed). After more than a decade, Visual Basic was overdue for a major overhaul. But .NET goes beyond an overhaul. It changes almost every aspect of software development.
From integrating Internet functionality to creating object-oriented frameworks, Visual Basic .NET chal- lenged traditional VB developers to learn dramatic new concepts and techniques. 2005 brings us an enhanced Visual Basic language (renamed this time Visual Basic 2005). New features have been added that cement this language’s position as a true object-oriented language. With Visual Basic 2005, it is still going to be a challenge for the traditional VB6 developers to learn, but it is an easy road and books like this are here to help you on your path. First, it’s necessary to learn the differences between Visual Basic 2005 and the older versions. In some cases, the same functionality is implemented in a different way. This was not done arbitrarily — there are good reasons for the changes. But you must be prepared to unlearn old habits and form new ones. Next, you must be open to the new concepts. Full object orientation, new component techniques, new visual tools for both local and Internet interfaces — all of these and more must become part of your skill set to effectively develop applications in Visual Basic. In this book, we cover Visual Basic virtually from start to finish. We begin by looking at the .NET Framework and end by looking at the best practices for deploying .NET applications. In between, we look at everything from database access to integration with other technologies such as XML, along with investigating the new features in detail. You will see that Visual Basic 2005 has emerged as a powerful yet easy-to-use language that will allow you to target the Internet just as easily as the desktop.
The Impor tance of V isual Basic
Early in the adoption cycle of .NET, Microsoft’s new language, C#, got the lion’s share of attention. But as .NET adoption has increased, Visual Basic’s continuing importance has also been apparent. Microsoft has publicly stated that they consider Visual Basic the language of choice for applications where devel- oper productivity is one of the highest priorities.
Future development of Visual Basic is emphasizing capabilities that enable access to the whole expanse of the .NET Framework in the most productive way, while C# development is emphasizing the experi- ence of writing code. That fits the traditional role of Visual Basic as the language developers use in the real world to create business applications as quickly as possible.
This difference is more than academic. One of the most important advantages of the .NET Framework is that it allows applications to be written with dramatically less code. In the world of business applica- tions, the goal is to concentrate on writing business logic and to eliminate routine coding tasks as much as possible. The value in this new world is not in churning out lots of code — it is in writing robust, use- ful applications with as little code as possible. Introduction
Visual Basic is an excellent fit for this type of development, which makes up the bulk of software devel- opment in today’s economy. And it will grow to be an even better fit as it is refined and evolved for exactly that purpose.
Who Is This Book For?
This book is written to help experienced developers learn about Visual Basic 2005. From those who are just starting the transition from earlier versions to those who have used Visual Basic for a while and need to gain a deeper understanding, this book provides a discussion on the most common program- ming tasks and concepts you need.
Professional Visual Basic 2005 offers a wide-ranging presentation of Visual Basic concepts, but the .NET
Framework is so large and comprehensive that no single book can cover it all. The most important area in which this book does not attempt to be complete is Web development. While chapters discussing the basics of browser-based programming in Visual Basic are included, professional Web developers should instead refer to Professional ASP.NET 2.0 (Wrox Press).
What You Need to Use This Book
Although, it is possible to create Visual Basic applications using the command-line tools contained in the .NET Framework SDK, you will need Visual Studio 2005 (Professional or higher), which includes the .NET Framework SDK, to get the most out of this book. You may use Visual Studio .NET 2002 or Visual Studio 2003 instead, but there may be cases where much of the lessons will just not work because func- tionalities and capabilities will not be available in these older versions.
In addition: ❑ Some chapters make use of SQL Server 2005. However, you can also run the example code using Microsoft’s SQL Express, which ships with Visual Studio 2005.
❑ Several chapters make use of Internet Information Services (IIS). IIS ships with Windows 2003 Server, Windows 2000 Server, Windows 2000 Professional, and Windows XP, although it is not installed by default.
Chapter 21 makes use of MSMQ to work with queued transactions. MSMQ ships with Windows 2003 Server, Windows 2000 Server, Windows 2000 Professional, and Windows XP, although it is not installed by default.
What Does This Book Cover?
much it changes application development. You gain an understanding of why you need .NET by looking at what’s wrong with the current development technologies, including COM and the DNA architectural model. Then, we look at how .NET corrects the drawbacks by using the common language runtime (CLR).
Chapter 2, “Introducing Visual Basic 2005 and Visual Studio 2005” — This chapter provides a first look
at a Visual Basic application. As we develop this application, you’ll take a tour of some of the new fea- tures of Visual Studio 2005.
Chapter 3, “Variables and Types” — This chapter introduces many of the types commonly used in Visual Basic. The main goal of this chapter is to familiarize you with value and reference types and to
help those with a background in VB6 understand some of the key differences in how variables are defined in Visual Basic.
Chapter 4, “Object Syntax Introduction” — This is the first of three chapters that explore object-
oriented programming in Visual Basic. This chapter will define objects, classes, instances, encapsulation, abstraction, polymorphism, and inheritance.
Chapter 5, “Inheritance and Interfaces” — This chapter examines inheritance and how it can be used
within Visual Basic. We create simple and abstract base classes and demonstrate how to create base classes from which other classes can be derived.
Chapter 6, “The Common Language Runtime” — This chapter examines the core of the .NET platform,
the common language runtime (CLR). The CLR is responsible for managing the execution of code com- piled for the .NET platform. We cover versioning and deployment, memory management, cross-language integration, metadata, and the IL Disassembler.
Chapter 7, “Applying Objects and Components” — This chapter puts the theory of Chapters 4 and 5
into practice. The four defining object-oriented concepts (abstraction, encapsulation, polymorphism, inheritance) are discussed, and we explain how these concepts can be applied in design and develop- ment to create effective object-oriented applications.
Chapter 8, “Generics” — This chapter focuses on one of the biggest enhancements to Visual Basic in this
version — generics. Generics enables you to make a generic collection that is still strongly typed — pro- viding fewer chances for errors, increasing performance, and giving you Intellisense features when you are working with your collections.
Chapter 9, “Namespaces” — This chapter introduces namespaces and their hierarchical structure. An
explanation of namespaces and some common ones are given. In addition, you learn how to create new namespaces, and how to import and alias existing namespaces within projects. This chapter also looks at the new My namespace that was made available in Visual Basic 2005.
Chapter 10, “Exception Handling and Debugging” — This chapter covers how error handling and debugging work in Visual Basic 2005 by discussing the CLR exception handler and the new Try . . .
Catch . . . Finally structure. We also look at error and trace logging, and how you can use these meth-ods to obtain feedback on how your program is working. Chapter 11, “Data Access with ADO.NET 2.0” — This chapter focuses on what you will need to know
about the ADO.NET object model to be able to build flexible, fast, and scalable data access objects and applications. The evolution of ADO into ADO.NET is explored, and the main objects in ADO.NET that you need to understand in order to build data access into your .NET applications are explained. Introduction
Chapter 12, “Using XML in Visual Basic 2005” — This chapter presents the features of the .NET Framework that facilitate the generation and manipulation of XML. We describe the .NET Framework’s XML-related namespaces, and a subset of the classes exposed by these namespaces is examined in detail. This chapter also touches on a set of technologies that utilize XML, specifically ADO.NET and SQL Server. Chapter 13, “Security in the .NET Framework 2.0” — This chapter examines the additional tools and func-
tionality with regard to the security provided by .NET. Caspol.exe and Permview.exe , which assist in establishing and maintaining security policies, are discussed. The System.Security.Permissions namespace is looked at, and we discuss how it relates to managing permissions. Finally, we examine the
System.Security.Cryptography namespace and run through some code to demonstrate the capabilities of this namespace.
Chapter 14, “Windows Forms” — This chapter looks at Windows Forms, concentrating primarily on
forms and built-in controls. What is new and what has been changed from the previous versions of Visual Basic are discussed, along with the System.Windows.Forms namespace.
Chapter 15, “Windows Forms Advanced Features” — This chapter looks at some of the more advancedfeatures that are available to you in building your Windows Forms applications. Chapter 16, “Building Web Applications” — This chapter explores Web forms and how you can benefit
from their use. Using progressively more complex examples, this chapter explains how .NET provides the power of Rapid Application Development (normally associated with Windows applications) for the development of Web applications.
Chapter 17, “ASP.NET 2.0 Advanced Features” — This chapter looks at a lot of the new and advanced
features that have been made available to you with the latest release of ASP.NET 2.0. Examples of items covered include cross-page posting, master pages, site navigation, personalization, and more.
Chapter 18, “Assemblies” — This chapter examines assemblies and their use within the CLR. The struc- ture of an assembly, what it contains, and the information it contains is examined. Chapter 19, “Deployment” — This chapter examines the manifest of the assembly, and its role in deploy-
ment will be looked at. We also look at what Visual Studio 2005 and the CLR have to offer you when you come to deploy your applications.
Chapter 20, “Working with Classic COM and Interfaces” — This chapter discusses COM and .NETcomponent interoperability, and what tools are provided to help link the two technologies. Chapter 21, “Enterprise Services” — This chapter explores the .NET component services — in particular, transaction processing and queued components.
Chapter 22, “Threading” — This chapter explores threading and explains how the various objects in
the .NET Framework enable any of its consumers to develop multithreaded applications. We examine how threads can be created, how they relate to processes, and the differences between multitasking and multithreading.
Chapter 23, “XML Web Services” — This chapter looks at how to create and consume Web services