Pro VB 2010 and the .NET 4.0 Platform
® THE EXPERT’S VOICE
Pro and the
VB 2010
.NET 4 Platform
Exploring the .NET universe with Visual Basic 2010
and Andrew Troelsen Vidya Vrat Agarwal
Pro VB 2010 and the .NET 4 Platform ■ ■ ■ Andrew Troelsen and Vidya Vrat Agarwal
Pro VB 2010 and the .NET 4 Platform
Copyright © 2010 by Andrew Troelsen and Vidya Vrat Agarwal
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-13 (pbk): 978-1-4302-2985-8
ISBN-13 (electronic): 978-1-4302-2986-5 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Trademarked names 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.President and Publisher: Paul Manning Lead Editor: Ewan Buckingham Technical Reviewer: Andy Olsen Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell,
Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh Coordinating Editor: Debra Kelly
Copy Editors: Mary Behr, Patrick Meader, Katie Stence, and Sharon Terdeman Production Support: Patrick Cunningham Indexer: BIM Indexing & Proofreading Services Artist: April Milne Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor,
rNew York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail visit For information on translations, please e-mail
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use.
eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at The information in this book is distributed on an “as is” basis, without warranty. Although everyprecaution has been taken in the preparation of this work, neither the author(s) 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. The source code for this book is available to readers atRest peacefully.
To the memory of my wonderful grandmother, Maxine. I love you, Gerta.
- –Andrew Troelsen To my lovely wife, sweet daughters, and my parents. I love you all.
- –Vidya Vrat Agarwal
Contents at a Glance
About the Authors
Chapter 1: Introducing VB 2010 ■
Chapter 2: Building Visual Basic 2 ■
Chapter 3: Core VB 2010 Programming Constructs, Part I ■
Chapter 4: Core VB 2010 Programming Constructs, Part II ■
Chapter 5: Defining Encapsulated Class Types ■
Chapter 6: Understanding Inheritance and Polymorphism ■
Chapter 7: Understanding Structured Exception Handling ■
Chapter 8: Understanding Object Lifetime ■
Chapter 9: Working with Interfaces ■
Chapter 10: Understanding Generics ■
Chapter 11: Delegates, Events, and Lambdas ■
Chapter 12: Advanced VB 2010 Language Features ■
Chapter 13: LINQ to Objects ■
Chapter 14: Configuring .NET Assemblies ■
Chapter 15: Type Reflection, Late Binding, ■ and Attribute-Based Programming
■
■
Chapter 27: Introducing Windows Presentation Foundation and XAML ■
Appendix A: Programming with Windows Forms .............................................. 1561 ■
Chapter 34: ASP.NET State Management Techniques ....................................... 1523 ■
Chapter 33: ASP.NET Web Controls, Master Pages, and Themes ■
Chapter 32: Building ASP.NET Web Pages ■
Chapter 31: WPF Control Templates and UserControls ■
Chapter 30: WPF Resources, Animations, and Styles ■
Chapter 29: WPF Graphics Rendering Services ■
Chapter 28: Programming with WPF Controls ■
Chapter 26: Introducing Windows Workflow Foundation 4.0 ■
Chapter 16: Processes, AppDomains, and Object Contexts ■
Chapter 25: Introducing Windows Communication Foundation ■
Chapter 24: Introducing LINQ to XML ■
Chapter 23: ADO.NET Part III: The Entity Framework ■
Chapter 22: ADO.NET Part II: The Disconnected Layer ■
Chapter 21: ADO.NET Part I: The Connected Layer ■
Chapter 20: File I/O and Object Serialization ■
Chapter 19: Multithreaded and Parallel Programming ■
Chapter 18: Dynamic Types and the Dynamic Language Runtime ■
Chapter 17: Understanding CIL and the Role of Dynamic Assemblies ■
Appendix B: Platform-Independent .NET Development with Mono .................... 1613 Index ..................................................................................................................... 1635
Contents
About the Authors
Chapter 1: Introducing VB 2010 ■
Understanding the Previous State of Affairs Life As a C/Windows API Programmer ............................................................................................ Life As a Visual Basic 6.0 Programmer ......................................................................................... Life As a COM Programmer ......................................................................................................
The .NET Solution ............................................................................................................. The Role of the Base Class Libraries ..........................................................................................
Additional .NET-Aware Programming Languages Life in a Multi-Language World ................................................................................................
An Overview of .NET Assemblies ..................................................................................... 10
Single-File and Multi-File Assemblies ......................................................................................... The Role of .NET Type Metadata ................................................................................................
Understanding the Common Type System
CTS Class Types ...............................................................................................................
CTS Structure Types ...........................................................................................................
CTS Delegate Types ............................................................................................................
Intrinsic CTS Data Types ......................................................................................................
Understanding the Common Language Specification
Ensuring CLS Compliance .......................................................................................................
Understanding the Common Language Runtime
The Role of the Microsoft Root Namespace ......................................................................................
Referencing External Assemblies ...............................................................................................
Exploring an Assembly Using ildasm.exe
Viewing CIL Code ..............................................................................................................
Viewing Assembly Metadata (aka the Manifest) ..................................................................................
Exploring an Assembly Using Reflector
The .NET Client Profile Runtime ...............................................................................................
The Platform-Independent Nature of .NET
Chapter 2: Building Visual Basic 2
■
The Role of the .NET Framework 4.0 SDK
The Visual Studio 2010 Command Prompt .........................................................................................
Building VB 2010 Applications Using vbc.exe Specifying Input and Output Targets ........................................................................................... Referencing Multiple External Assemblies ...................................................................................... Working with VB 2010 Response Files ...........................................................................................
Building .NET Applications Using Notepad++ Some Unique Features of Visual Basic 2010 Express
Building .NET Applications Using Visual Studio 2010 ...................................................... 52
Some Unique Features of Visual Studio 2010 .................................................................................... Using the Solution Explorer Utility ........................................................................................... The Object Browser Utility .................................................................................................... Code Expansions Techniques .................................................................................................... The Integrated .NET Framework 4.0 SDK Documentation System
Summary .......................................................................................................................
Chapter 3: Core VB 2010 Programming Constructs, Part I ■
The Role of the Module Type ........................................................................................... 71
Projects with Multiple Modules ................................................................................................ Renaming Your Initial Module ..................................................................................................
The Anatomy of a Simple VB 2010 Program
Variations on the Main() Method ...............................................................................................
Processing Command-Line Arguments .............................................................................................
An Interesting Aside: Some Additional Members of the System.Environment Class
Basic Input and Output with the Console Class .................................................................................
Formatting Numerical Data .....................................................................................................
System Data Types and VB 2010 Shorthand Notation ..................................................... 89
Variable Declaration and Initialization .......................................................................................
The Data Type Class Hierarchy .................................................................................................
Members of System.Boolean .....................................................................................................
Parsing Values from String Data ...............................................................................................
The .NET 4.0 System.Numerics Namespace ........................................................................................
Working with String Data ............................................................................................... 100
Basic String Manipulation .....................................................................................................
Special Character Constants ...................................................................................................
Strings Are Immutable .........................................................................................................
Narrowing and Widening Data Type Conversions ......................................................... Trapping Narrowing Data Conversions . ............................................................................................... Setting Project-wide Overflow Checking . ............................................................................................
Understanding Implicitly Typed Local Variables . .......................................................... Restrictions on Implicitly Typed Variables . .......................................................................................... Usefulness of Implicitly Typed Local Variables . ...................................................................................
VB 2010 Iteration Constructs . ....................................................................................... The For Loop . ....................................................................................................................................... The While and Do/While Looping Constructs . ......................................................................................
Decision Constructs and the Relational/Equality Operators . ........................................ The If/Then/Else Statement . ................................................................................................................
Summary .......................................................................................................................
Chapter 4: Core VB 2010 Programming Constructs, Part II . ■
Methods and Parameter Modifiers . .............................................................................. 125
The ByVal Parameter Modifier . ............................................................................................................ The <Out()> Attribute . ......................................................................................................................... Defining Optional Parameters . ............................................................................................................. Understanding Method Overloading . ...................................................................................................
Understanding VB 2010 Arrays
VB 2010 Array Initialization Syntax ...........................................................................................
Defining an Array of Objects ..................................................................................................
Arrays As Arguments or Return Values ..........................................................................................
Understanding the Enum Type
Controlling the Underlying Storage for an Enum ................................................................................
The System.Enum Type ..........................................................................................................
Understanding the Structure Type
Creating Structure Variables ..................................................................................................
Understanding Value Types and Reference Types
Value Types, References Types, and the Assignment Operator
Passing Reference Types by Value ..............................................................................................
Final Details Regarding Value Types and Reference Types
Understanding VB 2010 Nullable Types
Working with Nullable Types ...................................................................................................
Summary .......................................................................................................................
Chapter 5: Defining Encapsulated Class Types
■
Introducing the VB 2010 Class Type
Allocating Objects with the New Keyword .......................................................................................
Understanding Constructors The Role of the Default Constructor ........................................................................................... The Default Constructor Revisited .............................................................................................
The Role of the Me Keyword Chaining Constructor Calls Using Me ........................................................................................... Revisiting Optional Arguments .................................................................................................
Understanding the Shared Keyword Defining Shared Methods ....................................................................................................... Defining Shared Constructors ..................................................................................................
Defining the Pillars of OOP The Role of Encapsulation ..................................................................................................... The Role of Polymorphism ......................................................................................................
VB 2010 Access Modifiers The Default Access Modifiers ..................................................................................................
The First Pillar: VB 2010 Encapsulation Services .......................................................... 198
Encapsulation Using Traditional Accessors and Mutators Using Properties within a Class Definition .................................................................................... Controlling Visibility Levels of Property Get/Set Statements Shared Properties .............................................................................................................
Understanding Automatic Properties
Interacting with Automatic Properties .........................................................................................
Understanding Object Initializer Syntax
Calling Custom Constructors with Initialization Syntax ........................................................................
Working with Constant Field Data
Understanding Read-Only Fields ................................................................................................
Understanding Partial Types
Chapter 6: Understanding Inheritance and Polymorphism
■
The Basic Mechanics of Inheritance
Specifying the Parent Class of an Existing Class ..............................................................................
The NotInheritable Keyword ....................................................................................................
Controlling Base Class Creation with the MyBase Keyword
Adding a NotInheritable Class .................................................................................................
Programming for Containment/Delegation
Understanding Nested Type Definitions .........................................................................................
The Third Pillar of OOP: VB’s Polymorphic Support ....................................................... 245
The Overridable and Overrides Keywords ........................................................................................
NotOverridable Members ........................................................................................................
Understanding the Polymorphic Interface ....................................................................................... Understanding Base Class/Derived Class Casting Rules
The VB TryCast Keyword ........................................................................................................ The Master Parent Class: System.Object
Overriding System.Object.ToString() ........................................................................................... Overriding System.Object.GetHashCode() ........................................................................................ The Shared Members of System.Object ...........................................................................................
Summary .......................................................................................................................
Chapter 7: Understanding Structured Exception Handling ■
Ode to Errors, Bugs, and Exceptions The Atoms of .NET Exception Handling ..........................................................................................
The Simplest Possible Example Throwing a General Exception ..................................................................................................
Configuring the State of an Exception The TargetSite Property ....................................................................................................... The HelpLink Property .........................................................................................................
System-Level Exceptions (System.SystemException)
Application-Level Exceptions (System.ApplicationExc
Building Custom Exceptions, Take One ..........................................................................................
Building Custom Exceptions, Take Three ........................................................................................
Processing Multiple Exceptions
General Catch Statements ......................................................................................................
Inner Exceptions ..............................................................................................................
Who Is Throwing What?
Debugging Unhandled Exceptions Using Visual Studio
Summary .......................................................................................................................
■
Chapter 8: Understanding Object Lifetime
Building Finalizable Objects Overriding System.Object.Finalize() ...........................................................................................
Building Disposable Objects Using Keyword with VB 2010 ....................................................................................................
Building Finalizable and Disposable Types A Formalized Disposal Pattern .................................................................................................
Understanding Lazy Object Instantiation Customizing the Creation of the Lazy Data .....................................................................................
Summary .......................................................................................................................
Chapter 9: Working with Interfaces ■
Understanding Interface Types Interface Types vs. Abstract Base Classes .....................................................................................
Defining Custom Interfaces Invoking Interface Members at the Object Level
Obtaining Interface References: The TryCast Keyword Interfaces As Parameters Arrays of Interface Types Resolving Name Clashes via Explicit Interface Implementation
Multiple Inheritance with Interface Types ..................................................................................... Building Enumerable Types (IEnumerable and IEnumerator)
Building Cloneable Objects (ICloneable)
A More Elaborate Cloning Example ..............................................................................................
Building Comparable Objects (IComparable)
Specifying Multiple Sort Orders (IComparer) ...................................................................................
Summary .......................................................................................................................
Chapter 10: Understanding Generics
■
The Issues with Non-Generic Collections
The Issue of Performance ......................................................................................................
The Role of Generic Type Parameters
Specifying Type Parameters for Generic Classes / Structures
Specifying Type Parameters for Generic Interfaces .............................................................................
The System.Collections.Generic Namespace
Understanding Collection Initialization Syntax ................................................................................
Working with the Stack(Of T) Class ............................................................................................
Working with the SortedSet(Of T) Class ........................................................................................
Creating Custom Generic Methods
Inference of Type Parameters ..................................................................................................
Creating Custom Generic Structures and Classes
The Nothing Keyword in Generic Code ...........................................................................................
Constraining Type Parameters Examples Using the As Keyword .................................................................................................
Summary ....................................................................................................................... ■
Chapter 11: Delegates, Events, and Lambdas
Understanding Lambda Expressions
Dissecting a Lambda Expression ................................................................................................
Lambda Expressions with Multiple (or Zero) Parameters
Summary .......................................................................................................................
Chapter 12: Advanced VB 2010 Language Features
■
Understanding Indexer Methods
Indexing Data Using String Values .............................................................................................
Indexers with Multiple Dimensions .............................................................................................
Understanding Operator Overloading
Overloading Binary Operators ..................................................................................................
Overloading Unary Operators ...................................................................................................
Overloading Comparison Operators ..............................................................................................
Final Thoughts Regarding Operator Overloading .................................................................................
Understanding Custom Type Conversions ..................................................................... 477
Recall: Numerical Conversions .................................................................................................
Creating Custom Conversion Routines ...........................................................................................
Defining Implicit Conversion Routines .........................................................................................
Understanding Extension Methods ...............................................................................................
Understanding Partial Methods . .......................................................................................................... Summary .......................................................................................................................
Chapter 13: LINQ to Objects ................................................................................ ■
LINQ Specific Programming Constructs ........................................................................ Implicit Typing of Local Variables . ....................................................................................................... Lambda Expressions. ........................................................................................................................... Anonymous Types . ..............................................................................................................................
Understanding the Role of LINQ .................................................................................... LINQ Expressions Are Strongly Typed...................................................................................................
Applying LINQ Queries to Primitive Arrays .................................................................... Once Again, Without LINQ . ................................................................................................................... LINQ and Implicitly Typed Local Variables . .......................................................................................... The Role of Deferred Execution . ..........................................................................................................
Returning the Result of a LINQ Query . .......................................................................... Returning LINQ Results via Immediate Execution . ..............................................................................
Applying LINQ Queries to Collection Objects . ............................................................... 524
Accessing Contained Subobjects . ....................................................................................................... Filtering Data Using OfType(Of T)() . .....................................................................................................
Investigating the VB 2010 LINQ Query Operators .......................................................... 527
Basic Selection Syntax ........................................................................................................
Projecting New Data Types .....................................................................................................
Reversing Result Sets .........................................................................................................
LINQ As a Better Venn Diagramming Tool ........................................................................................
LINQ Aggregation Operations ...................................................................................................
The Internal Representation of LINQ Query Statements
Building Query Expressions with Query Operators (Revisited)
Building Query Expressions Using the Enumerable Type and Anonymous Methods
Summary .......................................................................................................................
Chapter 14: Configuring .NET Assemblies
■
Observing the Root Namespace ..................................................................................................
Defining Custom Namespaces ....................................................................................................
Resolving Name Clashes with Aliases ...........................................................................................
The Role of .NET Assemblies ......................................................................................... 551
Assemblies Promote Code Reuse .................................................................................................
Assemblies Are Versionable Units ..............................................................................................
Assemblies Are Configurable ...................................................................................................
Understanding the Format of a .NET Assembly The Windows File Header ....................................................................................................... CIL Code, Type Metadata, and Single-File and Multifile Assemblies ..........................................................................................
Building and Consuming a Single-File Assembly Exploring the Manifest ........................................................................................................ Exploring the Type Metadata ................................................................................................... Building a C# Client Application ..............................................................................................
Building and Consuming a Multifile Assembly Exploring the ufo.netmodule File .............................................................................................. Consuming a Multifile Assembly ................................................................................................
Understanding Private Assemblies The Identity of a Private Assembly ............................................................................................ Configuring Private Assemblies ................................................................................................
Understanding Shared Assemblies Understanding Strong Names .................................................................................................... Generating Strong Names using Visual Studio 2010
Consuming a Shared Assembly Exploring the Manifest of SharedCarLibClient ..................................................................................
Configuring Shared Assemblies
Freezing the Current Shared Assembly ..........................................................................................
Dynamically Redirecting to Specific Versions of a Shared Assembly
Understanding Publisher Policy Assemblies
Disabling Publisher Policy ....................................................................................................
Understanding the <codeBase> Element
Summary .......................................................................................................................
Chapter 15: Type Reflection, Late Binding, ■
and Attribute-Based Programming
■
The Necessity of Type Metadata
Viewing (Partial) Metadata for the EngineState Enumeration
Examining a TypeRef ...........................................................................................................
Documenting Referenced Assemblies .............................................................................................
Understanding Reflection
The System.Type Class .........................................................................................................
Obtaining a Type Reference Using System.Type.GetType()
Building a Custom Metadata Viewer .............................................................................. 614
Reflecting on Methods .........................................................................................................
Reflecting on Implemented Interfaces ..........................................................................................
Implementing Main()............................................................................................................ Reflecting on Method Parameters and Return Values
Dynamically Loading Assemblies Understanding Late Binding
The System.Activator Class .................................................................................................... Invoking Methods with Parameters ..............................................................................................
Understanding the Role of .NET Attributes Attribute Consumers ...........................................................................................................
VB 2010 Attribute Shorthand Notation .......................................................................................... The Obsolete Attribute in Action ..............................................................................................
Building Custom Attributes Applying Custom Attributes .................................................................................................... Restricting Attribute Usage ...................................................................................................
Assembly-Level (and Module-Level) Attributes The Visual Studio 2010 AssemblyInfo.vb File ...................................................................................
Reflecting on Attributes Using Early Binding Putting Reflection, Late Binding, and Custom Attributes in Perspective
Building CommonSnappableTypes.dll .............................................................................................
Building the C# Snap-In .......................................................................................................
Summary .......................................................................................................................
Chapter 16: Processes, AppDomains, and Object Contexts
■
The Role of a Windows Process
The Role of Threads ...........................................................................................................
Interacting with Processes Under the .NET Platform
Enumerating Running Processes .................................................................................................
Investigating a Process’s Thread Set ..........................................................................................
Starting and Stopping Processes Programmatically
Understanding .NET Application Domains
The System.AppDomain Class ....................................................................................................
Interacting with the Default Application Domain
Enumerating Loaded Assemblies .................................................................................................
Creating New Application Domains
Loading Assemblies into Custom Application Domains
Understanding Object Context Boundaries
Context-Agile and Context-Bound Types .........................................................................................
Inspecting an Object’s Context ................................................................................................
Summarizing Processes, AppDomains, and Context
Chapter 17: Understanding CIL and the Role of Dynamic Assemblies ■
Reasons for Learning the Grammar of CIL The Role of CIL Directives .................................................................................................... The Role of CIL Opcodes .......................................................................................................
Pushing and Popping: The Stack-Based Nature of CIL The Role of CIL Code Labels ................................................................................................... Compiling CIL Code Using ilasm.exe ............................................................................................ The Role of peverify.exe ......................................................................................................
Understanding CIL Directives and Attributes ................................................................. 703
Specifying Externally Referenced Assemblies in CIL ............................................................................ Defining Namespaces in CIL .................................................................................................... Defining and Implementing Interfaces in CIL.................................................................................... Defining Enums in CIL.......................................................................................................... Compiling the CILTypes.il file ................................................................................................
.NET Base Class Library, VB 2010, and CIL Data Type Mappings Defining Field Data in CIL ....................................................................................................
Defining Properties in CIL ....................................................................................................
Examining CIL Opcodes
The .maxstack Directive .......................................................................................................