SOURCE CODE ONLINE
Pro
VB 2010
.NET 4 Platform
Andrew Troelsen
and
Vidya Vrat Agarwal
Exploring the .NET universe with
Visual Basic 2010
Pro VB 2010 and
the .NET
4
Platform
■ ■ ■
Andrew Troelsen
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,
New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-ny@springer-sbm.com, or
visit www.springeronline.com.
For information on translations, please e-mail rights@apress.com, or visit www.apress.com.
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 www.apress.com/info/bulksales.
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(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.
To my lovely wife, sweet daughters, and my parents. I love you all.
iv
Contents at a Glance
About the Authors ... liv
About the Technical Reviewer ... lv
Acknowledgments ... lvi
Introduction ... lvii
■
Chapter 1: Introducing VB 2010 ... 1
■
Chapter 2: Building Visual Basic 2010 Applications ... 41
■
Chapter 3: Core VB 2010 Programming Constructs, Part I ... 71
■
Chapter 4: Core VB 2010 Programming Constructs, Part II ... 125
■
Chapter 5: Defining Encapsulated Class Types ... 169
■
Chapter 6: Understanding Inheritance and Polymorphism ... 227
■
Chapter 7: Understanding Structured Exception Handling ... 273
■
Chapter 8: Understanding Object Lifetime ... 303
■
Chapter 9: Working with Interfaces ... 333
■
Chapter 10: Understanding Generics ... 375
■
Chapter 11: Delegates, Events, and Lambdas ... 415
■
Chapter 12: Advanced VB 2010 Language Features ... 461
■
Chapter 13: LINQ to Objects ... 507
■
Chapter 14: Configuring .NET Assemblies ... 543
■
Chapter 16: Processes, AppDomains, and Object Contexts ... 653
■
Chapter 17: Understanding CIL and the Role of Dynamic Assemblies ... 687
■
Chapter 18: Dynamic Types and the Dynamic Language Runtime ... 739
■
Chapter 19: Multithreaded and Parallel Programming ... 765
■
Chapter 20: File I/O and Object Serialization ... 817
■
Chapter 21: ADO.NET Part I: The Connected Layer ... 869
■
Chapter 22: ADO.NET Part II: The Disconnected Layer ... 931
■
Chapter 23: ADO.NET Part III: The Entity Framework ... 999
■
Chapter 24: Introducing LINQ to XML ... 1041
■
Chapter 25: Introducing Windows Communication Foundation ... 1061
■
Chapter 26: Introducing Windows Workflow Foundation 4.0 ... 1127
■
Chapter 27: Introducing Windows Presentation Foundation and XAML ... 1165
■
Chapter 28: Programming with WPF Controls ... 1227
■
Chapter 29: WPF Graphics Rendering Services ... 1295
■
Chapter 30: WPF Resources, Animations, and Styles ... 1335
■
Chapter 31: WPF Control Templates and UserControls ... 1377
■
Chapter 32: Building ASP.NET Web Pages ... 1427
■
Chapter 33: ASP.NET Web Controls, Master Pages, and Themes ... 1477
■
Chapter 34: ASP.NET State Management Techniques ... 1523
■
Appendix A: Programming with Windows Forms ... 1561
■
Appendix B: Platform-Independent .NET Development with Mono ... 1613
vi
Contents
About the Authors ... liv
About the Technical Reviewer ... lv
Acknowledgments ... lvi
Introduction ... lvii
■
Chapter 1: Introducing VB 2010 ... 1
Understanding the Previous State of Affairs ... 1
Life As a C/Windows API Programmer ... 1
Life As a C++/MFC Programmer ... 2
Life As a Visual Basic 6.0 Programmer ... 2
Life As a Java Programmer ... 3
Life As a COM Programmer ... 3
The .NET Solution ... 4
Introducing the Building Blocks of the .NET Platform (the CLR, CTS, and CLS) ... 5
The Role of the Base Class Libraries ... 6
What Visual Basic 2010 Brings to the Table ... 6
Additional .NET-Aware Programming Languages ... 8
Life in a Multi-Language World ... 10
An Overview of .NET Assemblies ... 10
Single-File and Multi-File Assemblies ... 12
The Role of the Common Intermediate Language ... 12
The Role of .NET Type Metadata ... 15
Understanding the Common Type System ... 18
CTS Class Types ... 18
CTS Interface Types ... 19
CTS Structure Types ... 19
CTS Enumeration Types ... 20
CTS Delegate Types ... 20
CTS Type Members ... 21
Intrinsic CTS Data Types ... 21
Understanding the Common Language Specification ... 22
Ensuring CLS Compliance ... 24
Understanding the Common Language Runtime ... 24
The Assembly/Namespace/Type Distinction ... 26
The Role of the Microsoft Root Namespace ... 29
Accessing a Namespace Programmatically ... 29
Referencing External Assemblies ... 31
Exploring an Assembly Using ildasm.exe ... 32
Viewing CIL Code ... 33
Viewing Type Metadata ... 34
Viewing Assembly Metadata (aka the Manifest) ... 34
Exploring an Assembly Using Reflector ... 35
Deploying the .NET Runtime ... 37
The .NET Client Profile Runtime ... 37
The Platform-Independent Nature of .NET ... 37
Summary ... 39
■
Chapter 2: Building Visual Basic 2010 Applications ... 41
The Role of the .NET Framework 4.0 SDK ... 41
■ CONTENTS
viii
Building VB 2010 Applications Using vbc.exe ... 43
Specifying Input and Output Targets ... 44
Referencing External Assemblies ... 45
Referencing Multiple External Assemblies ... 46
Compiling Multiple Source Files ... 46
Working with VB 2010 Response Files ... 47
Building .NET Applications Using Notepad++ ... 49
Building .NET Applications Using Visual Basic 2010 Express ... 50
Some Unique Features of Visual Basic 2010 Express ... 51
Building .NET Applications Using Visual Studio 2010 ... 52
Some Unique Features of Visual Studio 2010 ... 53
Targeting the .NET Framework Using the New Project Dialog Box ... 53
Using the Solution Explorer Utility ... 54
The Class View Utility ... 57
The Object Browser Utility ... 58
Integrated Support for Code Refactoring ... 59
Code Expansions Techniques ... 61
The Visual Class Designer ... 62
The Integrated .NET Framework 4.0 SDK Documentation System ... 68
Summary ... 70
■
Chapter 3: Core VB 2010 Programming Constructs, Part I ... 71
The Role of the Module Type ... 71
Projects with Multiple Modules ... 73
Modules Are Not Creatable ... 74
Renaming Your Initial Module ... 75
The Anatomy of a Simple VB 2010 Program ... 76
Variations on the Main() Method ... 77
Specifying an Application Error Code ... 78
Processing Command-Line Arguments ... 80
Specifying Command-Line Arguments with Visual Studio 2010 ... 81
An Interesting Aside: Some Additional Members of the System.Environment Class ... 82
The System.Console Class ... 84
Basic Input and Output with the Console Class ... 85
Formatting Console Output ... 86
Formatting Numerical Data ... 86
Formatting Numerical Data Beyond Console Applications ... 88
System Data Types and VB 2010 Shorthand Notation ... 89
Variable Declaration and Initialization ... 91
Intrinsic Data Types and the New Operator ... 92
The Data Type Class Hierarchy ... 93
Members of Numerical Data Types ... 95
Members of System.Boolean ... 96
Members of System.Char ... 96
Parsing Values from String Data ... 97
System.DateTime and System.TimeSpan ... 98
The .NET 4.0 System.Numerics Namespace ... 98
Working with String Data ... 100
Basic String Manipulation ... 101
String Concatenation ... 102
Special Character Constants ... 103
End SubStrings and Equality ... 104
Strings Are Immutable ... 105
■ CONTENTS
x
Narrowing and Widening Data Type Conversions ... 108
Trapping Narrowing Data Conversions . ... 111
Understanding Option Strict . ... 112
Setting Project-wide Overflow Checking . ... 113
The Role of System.Convert . ... 114
Understanding Implicitly Typed Local Variables . ... 115
Restrictions on Implicitly Typed Variables . ... 116
Implicit Typed Data Is Strongly Typed Data . ... 117
Usefulness of Implicitly Typed Local Variables . ... 118
VB 2010 Iteration Constructs . ... 118
The For Loop . ... 119
The For Each Loop . ... 119
The While and Do/While Looping Constructs . ... 120
Decision Constructs and the Relational/Equality Operators . ... 121
The If/Then/Else Statement . ... 121
The Select/Case Statement . ... 123
Summary ... 124
■
Chapter 4: Core VB 2010 Programming Constructs, Part II . ... 125
Methods and Parameter Modifiers . ... 125
The ByVal Parameter Modifier . ... 126
The ByRef Modifier . ... 128
The <Out()> Attribute . ... 129
The ParamArray Modifier . ... 130
Defining Optional Parameters . ... 132
Invoking Methods using Named Parameters ... 133
Understanding VB 2010 Arrays ... 138
VB 2010 Array Initialization Syntax ... 139
Implicitly Typed Local Arrays ... 139
Defining an Array of Objects ... 140
Working with Multidimensional Arrays ... 141
Arrays As Arguments or Return Values ... 143
The System.Array Base Class ... 144
Understanding the Enum Type ... 146
Controlling the Underlying Storage for an Enum ... 147
Declaring Enum Variables ... 147
The System.Enum Type ... 148
Dynamically Discovering an Enum’s Name/Value Pairs ... 149
Understanding the Structure Type ... 152
Creating Structure Variables ... 153
Understanding Value Types and Reference Types ... 155
Value Types, References Types, and the Assignment Operator ... 156
Value Types Containing Reference Types ... 158
Passing Reference Types by Value ... 160
Passing Reference Types by Reference ... 162
Final Details Regarding Value Types and Reference Types ... 163
Understanding VB 2010 Nullable Types ... 164
Working with Nullable Types ... 165
The Nullable If Operator ... 166
Summary ... 167
■
Chapter 5: Defining Encapsulated Class Types ... 169
Introducing the VB 2010 Class Type ... 169
■ CONTENTS
xii
Understanding Constructors ... 173
The Role of the Default Constructor ... 173
Defining Custom Constructors ... 174
The Default Constructor Revisited ... 175
The Role of the Me Keyword ... 176
Chaining Constructor Calls Using Me ... 178
Observing Constructor Flow ... 181
Revisiting Optional Arguments ... 183
Understanding the Shared Keyword ... 184
Defining Shared Methods ... 184
Defining Shared Field Data ... 185
Defining Shared Constructors ... 188
Defining Modules in VB 2010... 190
Defining the Pillars of OOP ... 193
The Role of Encapsulation ... 193
The Role of Inheritance ... 194
The Role of Polymorphism ... 195
VB 2010 Access Modifiers ... 197
The Default Access Modifiers ... 197
Access Modifiers and Nested Types ... 198
The First Pillar: VB 2010 Encapsulation Services ... 198
Encapsulation Using Traditional Accessors and Mutators ... 199
Encapsulation Using .NET Properties ... 202
Using Properties within a Class Definition ... 206
Internal Representation of Properties ... 207
Controlling Visibility Levels of Property Get/Set Statements ... 210
Read-Only and Write-Only Properties ... 210
Understanding Automatic Properties ... 213
Interacting with Automatic Properties ... 214
Regarding Automatic Properties and Default Values ... 215
Understanding Object Initializer Syntax ... 217
Calling Custom Constructors with Initialization Syntax ... 218
Nested Objects ... 220
Working with Constant Field Data ... 221
Understanding Read-Only Fields ... 222
Shared Read-Only Fields ... 223
Understanding Partial Types ... 224
Summary ... 225
■
Chapter 6: Understanding Inheritance and Polymorphism ... 227
The Basic Mechanics of Inheritance ... 227
Specifying the Parent Class of an Existing Class ... 228
Regarding Multiple Base Classes ... 230
The NotInheritable Keyword ... 230
Revising Visual Studio Class Diagrams ... 232
The Second Pillar of OOP: The Details of Inheritance ... 235
Controlling Base Class Creation with the MyBase Keyword ... 237
Keeping Family Secrets: The Protected Keyword ... 239
Adding a NotInheritable Class ... 240
Programming for Containment/Delegation ... 241
Understanding Nested Type Definitions ... 243
The Third Pillar of OOP: VB’s Polymorphic Support ... 245
The Overridable and Overrides Keywords ... 246
Overriding Overridable Members Using Visual Studio 2010 ... 249
NotOverridable Members ... 250
■ CONTENTS
xiv
Understanding the Polymorphic Interface ... 252
Understanding Member Shadowing ... 257
Understanding Base Class/Derived Class Casting Rules ... 259
The VB TryCast Keyword ... 262
The VB Is Keyword ... 262
The Master Parent Class: System.Object ... 263
Overriding System.Object.ToString() ... 267
Overriding System.Object.Equals() ... 268
Overriding System.Object.GetHashCode() ... 269
Testing Your Modified Person Class ... 270
The Shared Members of System.Object ... 271
Summary ... 272
■
Chapter 7: Understanding Structured Exception Handling ... 273
Ode to Errors, Bugs, and Exceptions ... 273
The Role of .NET Exception Handling ... 274
The Atoms of .NET Exception Handling ... 275
The System.Exception Base Class ... 276
The Simplest Possible Example ... 277
Throwing a General Exception ... 280
Catching Exceptions ... 281
Configuring the State of an Exception ... 283
The TargetSite Property ... 283
The StackTrace Property ... 284
The HelpLink Property ... 284
The Data Property ... 285
Application-Level Exceptions (System.ApplicationException) ... 288
Building Custom Exceptions, Take One ... 289
Building Custom Exceptions, Take Two ... 291
Building Custom Exceptions, Take Three ... 292
Processing Multiple Exceptions ... 293
General Catch Statements ... 295
Rethrowing Exceptions ... 296
Inner Exceptions ... 296
The Finally Block ... 297
Who Is Throwing What? ... 298
The Result of Unhandled Exceptions ... 298
Debugging Unhandled Exceptions Using Visual Studio ... 299
A Brief Word Regarding Corrupted State Exceptions (CSE) ... 300
Summary ... 302
■
Chapter 8: Understanding Object Lifetime ... 303
Classes, Objects, and References ... 303
The Basics of Object Lifetime ... 305
The CIL of new ... 306
Setting Object References to Nothing ... 307
The Role of Application Roots ... 308
Understanding Object Generations ... 310
Concurrent Garbage Collection under .NET 1.0 - 3.5 ... 311
Background Garbage Collection under .NET 4.0 ... 311
The System.GC Type ... 312
■ CONTENTS
xvi
Building Finalizable Objects ... 316
Overriding System.Object.Finalize() ... 317
Detailing the Finalization Process ... 319
Building Disposable Objects ... 320
Using Keyword with VB 2010 ... 322
Building Finalizable and Disposable Types ... 324
A Formalized Disposal Pattern ... 325
Understanding Lazy Object Instantiation ... 327
Customizing the Creation of the Lazy Data ... 330
Summary ... 331
■
Chapter 9: Working with Interfaces ... 333
Understanding Interface Types ... 333
Interface Types vs. Abstract Base Classes ... 335
Defining Custom Interfaces ... 337
Implementing an Interface ... 339
Invoking Interface Members at the Object Level ... 342
Obtaining Interface References: The TryCast Keyword ... 343
Obtaining Interface References: The Is Keyword ... 343
Interfaces As Parameters ... 345
Interfaces As Return Values ... 348
Arrays of Interface Types ... 348
Implementing Interfaces Using Visual Studio 2010 ... 350
Resolving Name Clashes via Explicit Interface Implementation ... 351
Designing Interface Hierarchies ... 354
Multiple Inheritance with Interface Types ... 356
Building Cloneable Objects (ICloneable) ... 361
A More Elaborate Cloning Example ... 363
Building Comparable Objects (IComparable) ... 367
Specifying Multiple Sort Orders (IComparer) ... 371
Custom Properties, Custom Sort Types ... 373
Summary ... 373
■
Chapter 10: Understanding Generics ... 375
The Issues with Non-Generic Collections ... 375
The Issue of Performance ... 377
The Issue of Type Safety ... 381
The Role of Generic Type Parameters ... 386
Specifying Type Parameters for Generic Classes / Structures ... 387
Specifying Type Parameters for Generic Members ... 389
Specifying Type Parameters for Generic Interfaces ... 389
The System.Collections.Generic Namespace ... 391
Understanding Collection Initialization Syntax ... 392
Working with the List(Of T) Class ... 394
Working with the Stack(Of T) Class ... 397
Working with the Queue(Of T) Class ... 398
Working with the SortedSet(Of T) Class ... 400
Creating Custom Generic Methods ... 402
Inference of Type Parameters ... 405
Creating Custom Generic Structures and Classes ... 406
The Nothing Keyword in Generic Code ... 407
■ CONTENTS
xviii
Constraining Type Parameters ... 410
Examples Using the As Keyword ... 411
The Lack of Operator Constraints ... 412
Summary ... 413
■
Chapter 11: Delegates, Events, and Lambdas ... 415
Understanding the .NET Delegate Type ... 415
Defining a Delegate Type in VB 2010 ... 416
The System.MulticastDelegate and System.Delegate Base Classes ... 419
The Simplest Possible Delegate Example ... 421
Investigating a Delegate Object ... 422
Sending Object State Notifications Using Delegates ... 424
Enabling Multicasting ... 428
Removing Targets from a Delegate’s Invocation List ... 429
Method Group Conversion Syntax ... 431
Understanding Delegate Covariance... 432
Understanding Generic Delegates ... 435
Simulating Generic Delegates Without Generics ... 436
Understanding VB 2010 Events ... 437
The VB 2010 Event Keyword ... 439
Events under the Hood ... 440
Listening to Incoming Events ... 442
Simplifying Event Registration Using Visual Studio 2010 ... 444
Creating Custom Event Arguments ... 445
The Generic EventHandler(Of T) Delegate ... 446
Understanding VB 2010 Anonymous Methods ... 447
Understanding Lambda Expressions ... 450
Dissecting a Lambda Expression ... 453
Processing Arguments Within Multiple Statements ... 454
Lambda Expressions with Multiple (or Zero) Parameters ... 456
Retrofitting the CarEvents Example Using Lambda Expressions ... 457
Summary ... 459
■
Chapter 12: Advanced VB 2010 Language Features ... 461
Understanding Indexer Methods ... 461
Indexing Data Using String Values ... 464
Overloading Indexer Methods ... 465
Indexers with Multiple Dimensions ... 466
Indexer Definitions on Interface Types ... 467
Understanding Operator Overloading ... 467
Overloading Binary Operators ... 468
And What of the += and –= Operators? ... 470
Overloading Unary Operators ... 471
Overloading Equality Operators ... 472
Overloading Comparison Operators ... 473
The Internal Representation of Overloaded Operators ... 474
Final Thoughts Regarding Operator Overloading ... 476
Understanding Custom Type Conversions ... 477
Recall: Numerical Conversions ... 477
Recall: Conversions Among Related Class Types ... 478
Creating Custom Conversion Routines ... 479
Additional Explicit Conversions for the Square Type ... 482
Defining Implicit Conversion Routines ... 482
The Internal Representation of Custom Conversion Routines ... 484
■ CONTENTS
xx
Understanding Partial Methods . ... 496
Understanding Anonymous Types . ... 498
Summary ... 505
■
Chapter 13: LINQ to Objects ... 507
LINQ Specific Programming Constructs ... 507
Implicit Typing of Local Variables . ... 508
Object and Collection Initialization Syntax. ... 509
Lambda Expressions. ... 509
Extension Methods . ... 510
Anonymous Types . ... 511
Understanding the Role of LINQ ... 511
LINQ Expressions Are Strongly Typed... 513
The Core LINQ Assemblies . ... 513
Applying LINQ Queries to Primitive Arrays ... 514
Once Again, Without LINQ . ... 515
Reflecting Over a LINQ Result Set . ... 516
LINQ and Implicitly Typed Local Variables . ... 517
LINQ and Extension Methods . ... 519
The Role of Deferred Execution . ... 520
The Role of Immediate Execution . ... 521
Returning the Result of a LINQ Query . ... 522
Returning LINQ Results via Immediate Execution . ... 523
Applying LINQ Queries to Collection Objects . ... 524
Accessing Contained Subobjects . ... 525
Applying LINQ Queries to Nongeneric Collections . ... 526
Investigating the VB 2010 LINQ Query Operators ... 527
Basic Selection Syntax ... 529
Obtaining Subsets of Data ... 530
Projecting New Data Types ... 531
Obtaining Counts Using Enumerable ... 532
Reversing Result Sets ... 533
Sorting Expressions ... 533
LINQ As a Better Venn Diagramming Tool ... 534
Removing Duplicates ... 536
LINQ Aggregation Operations ... 536
The Internal Representation of LINQ Query Statements ... 537
Building Query Expressions with Query Operators (Revisited) ... 538
Building Query Expressions Using the Enumerable Type and Lambda Expressions ... 538
Building Query Expressions Using the Enumerable Type and Anonymous Methods ... 540
Building Query Expressions Using the Enumerable Type and Raw Delegates ... 541
Summary ... 542
■
Chapter 14: Configuring .NET Assemblies ... 543
Observing the Root Namespace ... 543
Defining Namespaces Beyond the Root ... 544
Defining Custom Namespaces ... 545
Resolving Name Clashes with Fully Qualified Names ... 547
Resolving Name Clashes with Aliases ... 548
Creating Nested Namespaces ... 550
The Role of .NET Assemblies ... 551
Assemblies Promote Code Reuse ... 551
Assemblies Establish a Type Boundary ... 552
Assemblies Are Versionable Units ... 552
Assemblies Are Self-Describing ... 552
■ CONTENTS
xxii
Understanding the Format of a .NET Assembly ... 553
The Windows File Header ... 553
The CLR File Header ... 555
CIL Code, Type Metadata, and the Assembly Manifest... 556
Optional Assembly Resources ... 557
Single-File and Multifile Assemblies ... 557
Building and Consuming a Single-File Assembly ... 559
Exploring the Manifest ... 563
Exploring the CIL ... 566
Exploring the Type Metadata ... 567
Building a VB 2010 Client Application ... 568
Building a C# Client Application ... 570
Cross-Language Inheritance in Action... 571
Building and Consuming a Multifile Assembly ... 572
Exploring the ufo.netmodule File ... 573
Exploring the airvehicles.dll File ... 573
Consuming a Multifile Assembly ... 574
Understanding Private Assemblies ... 575
The Identity of a Private Assembly ... 576
Understanding the Probing Process ... 576
Configuring Private Assemblies ... 577
Configuration Files and Visual Studio 2010 ... 579
Understanding Shared Assemblies ... 582
Understanding Strong Names ... 583
Generating Strong Names at the Command Line ... 585
Generating Strong Names using Visual Studio 2010 ... 587
Installing Strongly Named Assemblies to the GAC ... 588
Consuming a Shared Assembly ... 591
Configuring Shared Assemblies ... 593
Freezing the Current Shared Assembly ... 593
Building Shared Assembly Version 2.0.0.0 ... 594
Dynamically Redirecting to Specific Versions of a Shared Assembly ... 598
Understanding Publisher Policy Assemblies ... 599
Disabling Publisher Policy ... 600
Understanding the <codeBase> Element ... 600
The System.Configuration Namespace ... 603
Summary ... 604
■
Chapter 15: Type Reflection, Late Binding,
■
and Attribute-Based Programming ... 605
The Necessity of Type Metadata ... 605
Viewing (Partial) Metadata for the EngineState Enumeration ... 606
Viewing (Partial) Metadata for the Car Type ... 607
Examining a TypeRef ... 609
Documenting the Defining Assembly ... 609
Documenting Referenced Assemblies ... 609
Documenting String Literals ... 610
Understanding Reflection ... 611
The System.Type Class ... 612
Obtaining a Type Reference Using System.Object.GetType() ... 613
Obtaining a Type Reference Using System.Type.GetType() ... 613
Obtaining a Type Reference Using GetType() ... 614
Building a Custom Metadata Viewer ... 614
Reflecting on Methods ... 614
Reflecting on Fields and Properties ... 615
Reflecting on Implemented Interfaces ... 616
■ CONTENTS
xxiv
Implementing Main()... 617
Reflecting on Generic Types ... 619
Reflecting on Method Parameters and Return Values ... 619
Dynamically Loading Assemblies ... 621
Reflecting on Shared Assemblies ... 625
Understanding Late Binding ... 626
The System.Activator Class ... 627
Invoking Methods with No Parameters... 628
Invoking Methods with Parameters ... 629
Understanding the Role of .NET Attributes ... 630
Attribute Consumers ... 631
Applying Attributes in VB 2010 ... 632
VB 2010 Attribute Shorthand Notation ... 634
Specifying Constructor Parameters for Attributes ... 634
The Obsolete Attribute in Action ... 634
Building Custom Attributes ... 635
Applying Custom Attributes ... 636
Named Property Syntax ... 636
Restricting Attribute Usage ... 637
Assembly-Level (and Module-Level) Attributes ... 638
The Visual Studio 2010 AssemblyInfo.vb File ... 639
Reflecting on Attributes Using Early Binding ... 640
Reflecting on Attributes Using Late Binding ... 641
Putting Reflection, Late Binding, and Custom Attributes in Perspective ... 643
Building an Extendable Application ... 644
Building CommonSnappableTypes.dll ... 645
Building the C# Snap-In ... 646
Building an Extendable Windows Forms Application ... 646
Summary ... 651
■
Chapter 16: Processes, AppDomains, and Object Contexts ... 653
The Role of a Windows Process ... 653
The Role of Threads ... 654
Interacting with Processes Under the .NET Platform ... 656
Enumerating Running Processes ... 658
Investigating a Specific Process ... 660
Investigating a Process’s Thread Set ... 660
Investigating a Process’s Module Set ... 663
Starting and Stopping Processes Programmatically ... 666
Controlling Process Startup Using the ProcessStartInfo Class ... 666
Understanding .NET Application Domains ... 668
The System.AppDomain Class ... 668
Interacting with the Default Application Domain ... 671
Enumerating Loaded Assemblies ... 672
Receiving Assembly Load Notifications ... 674
Creating New Application Domains ... 674
Loading Assemblies into Custom Application Domains ... 677
Programmatically Unloading AppDomains ... 678
Understanding Object Context Boundaries ... 680
Context-Agile and Context-Bound Types ... 681
Defining a Context-Bound Object ... 681
Inspecting an Object’s Context ... 682
Summarizing Processes, AppDomains, and Context ... 684
■ CONTENTS
xxvi
■
Chapter 17: Understanding CIL and the Role of Dynamic Assemblies ... 687
Reasons for Learning the Grammar of CIL ... 687
Examining CIL Directives, Attributes, and Opcodes ... 688
The Role of CIL Directives ... 689
The Role of CIL Attributes ... 689
The Role of CIL Opcodes ... 689
The CIL Opcode/CIL Mnemonic Distinction ... 690
Pushing and Popping: The Stack-Based Nature of CIL ... 690
Understanding Round-Trip Engineering ... 692
The Role of CIL Code Labels ... 695
Interacting with CIL: Modifying an *.il File ... 696
Compiling CIL Code Using ilasm.exe ... 697
Authoring CIL Code Using SharpDevelop ... 701
The Role of peverify.exe ... 703
Understanding CIL Directives and Attributes ... 703
Specifying Externally Referenced Assemblies in CIL ... 703
Defining the Current Assembly in CIL ... 704
Defining Namespaces in CIL ... 705
Defining Class Types in CIL ... 705
Defining and Implementing Interfaces in CIL... 707
Defining Structures in CIL ... 708
Defining Enums in CIL... 708
Defining Generics in CIL ... 709
Compiling the CILTypes.il file ... 709
.NET Base Class Library, VB 2010, and CIL Data Type Mappings ... 711
Defining Type Members in CIL ... 712
Defining Field Data in CIL ... 712
Defining Properties in CIL ... 713
Defining Member Parameters ... 714
Examining CIL Opcodes ... 715
The .maxstack Directive ... 718
Declaring Local Variables in CIL ... 718
Mapping Parameters to Local Variables in CIL ... 719
The Hidden Me Reference ... 720
Representing Iteration Constructs in CIL ... 720
Building a .NET Assembly with CIL ... 721
Building CILCars.dll... 721
Building CILCarClient.exe ... 724
Understanding Dynamic Assemblies ... 727
Exploring the System.Reflection.Emit Namespace ... 727
The Role of the System.Reflection.Emit.ILGenerator ... 728
Emitting a Dynamic Assembly ... 729
Emitting the Assembly and Module Set ... 732
The Role of the ModuleBuilder Type ... 733
Emitting the HelloClass Type and the String Member Variable ... 734
Emitting the Constructors ... 735
Emitting the SayHello() Method ... 736
Using the Dynamically Generated Assembly ... 736
Summary ... 738
■
Chapter 18: Dynamic Types and the Dynamic Language Runtime ... 739
Basics of Dynamic Typing in VB 2010 ... 739
The Role of Dynamic Typing in VB 2010 ... 740
Calling Members on Dynamically Declared Data ... 742
The Role of the Microsoft.VisualBasic.dll Assembly ... 743
■ CONTENTS
xxviii
Limitations of the Dynamic Type ... 745
Practical Uses of the Dynamic Types ... 746
The Role of the Dynamic Language Runtime (DLR) ... 746
The Role of Expression Trees ... 747
The Role of the System.Dynamic Namespace ... 747
Dynamic Runtime Lookup of Expression Trees ... 748
Simplifying Late Bound Calls Using Dynamic Typing ... 748
Leveraging the Dynamic Typing to Pass Arguments ... 749
Simplifying COM Interoperability using Dynamic Data ... 751
The Role of Primary Interop Assemblies (PIAs) ... 753
Embedding Interop Metadata ... 754
Common COM Interop Pain Points ... 755
COM Interop using VB 2010 Language Features ... 756
COM Interop without VB 2010 Language Features ... 760
Summary ... 762
■
Chapter 19: Multithreaded and Parallel Programming ... 765
The Process/AppDomain/Context/Thread Relationship ... 765
The Problem of Concurrency ... 767
The Role of Thread Synchronization ... 767
A Brief Review of the .NET Delegate ... 767
The Asynchronous Nature of Delegates ... 770
The BeginInvoke() and EndInvoke() Methods ... 770
The System.IAsyncResult Interface ... 771
Invoking a Method Asynchronously ... 771
Synchronizing the Calling Thread ... 772
The Role of the AsyncCallback Delegate ... 774
The Role of the AsyncResult Class ... 776
The System.Threading Namespace ... 778
The System.Threading.Thread Class ... 779
Obtaining Statistics About the Current Thread ... 781
The Name Property ... 782
The Priority Property ... 783
Programmatically Creating Secondary Threads ... 783
Working with the ThreadStart Delegate ... 784
Working with the ParameterizedThreadStart Delegate ... 786
The AutoResetEvent Class ... 787
Foreground Threads and Background Threads ... 788
The Issue of Concurrency ... 790
Synchronization Using the VB 2010 SyncLock Keyword ... 793
Synchronization Using the System.Threading.Monitor Type ... 796
Synchronization Using the System.Threading.Interlocked Type ... 797
Synchronization Using the <Synchronization()> Attribute ... 798
Programming with Timer Callbacks ... 798
Understanding the CLR ThreadPool ... 800
Parallel Programming under the .NET Platform ... 802
The Task Parallel Library API ... 802
The Role of the Parallel Class ... 804
Understanding Data Parallelism ... 804
The Task Class... 806
Handling Cancelation Request ... 807
Understanding Task Parallelism ... 808
Parallel LINQ Queries (PLINQ) ... 812
Opting in to a PLINQ Query ... 813
Canceling a PLINQ Query ... 814
■ CONTENTS
xxx
■
Chapter 20: File I/O and Object Serialization ... 817
Exploring the System.IO Namespace ... 817
The Directory(Info) and File(Info) Types ... 819
The MustInherit FileSystemInfo Base Class . ... 819
Working with the DirectoryInfo Type . ... 820
Enumerating Files with the DirectoryInfo Type . ... 822
Creating Subdirectories with the DirectoryInfo Type . ... 823
Working with the Directory Type . ... 824
Working with the DriveInfo Class Type . ... 825
Working with the FileInfo Class . ... 827
The FileInfo.Create() Method . ... 828
The FileInfo.Open() Method . ... 829
The FileInfo.OpenRead() and FileInfo.OpenWrite() Methods . ... 830
The FileInfo.OpenText() Method . ... 831
The FileInfo.CreateText() and FileInfo.AppendText() Methods . ... 831
Working with the File Type . ... 832
Additional File-centric Members . ... 833
The MustInherit Stream Class . ... 834
Working with FileStreams . ... 835
Working with StreamWriters and StreamReaders ... 837
Writing to a Text File . ... 838
Reading from a Text File . ... 839
Directly Creating StreamWriter/StreamReader Types . ... 840
Working with StringWriters and StringReaders ... 840
Working with BinaryWriters and BinaryReaders ... 842
Understanding Object Serialization ... 846
The Role of Object Graphs ... 848
Configuring Objects for Serialization ... 849
Defining Serializable Types ... 849
Public Fields, Private Fields, and Public Properties ... 850
Choosing a Serialization Formatter... 851
The IFormatter and IRemotingFormatter Interfaces ... 851
Type Fidelity Among the Formatters... 852
Serializing Objects Using the BinaryFormatter ... 853
Deserializing Objects Using the BinaryFormatter ... 855
Serializing Objects Using the SoapFormatter ... 855
Serializing Objects Using the XmlSerializer ... 857
Controlling the Generated XML Data ... 858
Serializing Collections of Objects ... 859
Customizing the Soap/Binary Serialization Process ... 861
A Deeper Look at Object Serialization ... 862
Customizing Serialization Using ISerializable ... 862
Customizing Serialization Using Attributes ... 866
Summary ... 867
■
Chapter 21: ADO.NET Part I: The Connected Layer ... 869
A High-Level Definition of ADO.NET ... 869
The Three Faces of ADO.NET ... 871
Understanding ADO.NET Data Providers ... 871
The Microsoft-Supplied ADO.NET Data Providers ... 873
A Word Regarding System.Data.OracleClient.dll ... 875
Obtaining Third-Party ADO.NET Data Providers ... 875
■ CONTENTS
xxxii
The Types of the System.Data Namespace ... 876
The Role of the IDbConnection Interface ... 878
The Role of the IDbTransaction Interface ... 878
The Role of the IDbCommand Interface ... 878
The Role of the IDbDataParameter and IDataParameter Interfaces ... 879
The Role of the IDbDataAdapter and IDataAdapter Interfaces ... 880
The Role of the IDataReader and IDataRecord Interfaces ... 880
Abstracting Data Providers Using Interfaces ... 881
Increasing Flexibility Using Application Configuration Files ... 883
Creating the AutoLot Database ... 885
Creating the Inventory Table ... 885
Authoring the GetPetName() Stored Procedure ... 888
Creating the Customers and Orders Tables ... 889
Visually Creating Table Relationships ... 891
The ADO.NET Data Provider Factory Model ... 892
A Complete Data Provider Factory Example ... 893
A Potential Drawback with the Provide Factory Model... 897
The <connectionStrings> Element ... 897
Understanding the Connected Layer of ADO.NET ... 899
Working with Connection Objects ... 900
Working with ConnectionStringBuilder Objects ... 902
Working with Command Objects ... 903
Working with Data Readers ... 904
Obtaining Multiple Result Sets Using a Data Reader ... 906
Building a Reusable Data Access Library ... 907
Adding the Connection Logic ... 908
Adding the Insertion Logic ... 909
Adding the Update Logic ... 911
Adding the Selection Logic ... 911
Working with Parameterized Command Objects ... 912
Executing a Stored Procedure ... 914
Creating a Console UI–Based Front End ... 916
Implementing the Main() Method ... 917
Implementing the ShowInstructions() Method... 918
Implementing the ListInventory() Method ... 918
Implementing the DeleteCar() Method ... 919
Implementing the InsertNewCar() Method ... 920
Implementing the UpdateCarPetName() Method ... 921
Implementing LookUpPetName() ... 921
Understanding Database Transactions ... 923
Key Members of an ADO.NET Transaction Object ... 924
Adding a CreditRisks Table to the AutoLot Database ... 925
Adding a Transaction Method to InventoryDAL ... 926
Testing Your Database Transaction ... 928
Summary ... 929
■
Chapter 22: ADO.NET Part II: The Disconnected Layer ... 931
Understanding the Disconnected Layer of ADO.NET ... 931
Understanding the Role of the DataSet... 932
Key Properties of the DataSet ... 933
Key Methods of the DataSet ... 934
Building a DataSet ... 935
Working with DataColumns ... 935
Building a DataColumn ... 937
Enabling Autoincrementing Fields ... 937
■ CONTENTS
xxxiv
Working with DataRows ... 938
Understanding the RowState Property ... 940
Understanding the DataRowVersion Property ... 942
Working with DataTables ... 943
Inserting DataTables into DataSets ... 944
Obtaining Data in a DataSet ... 944
Processing DataTable Data Using DataTableReader Objects ... 945
Serializing DataTable/DataSet Objects As XML ... 947
Serializing DataTable/DataSet Objects in a Binary Format ... 948
Binding DataTable Objects to Windows Forms GUIs ... 949
Hydrating a DataTable from a Generic List(Of T) ... 951
Deleting Rows from a DataTable ... 953
Selecting Rows Based on Filter Criteria ... 955
Updating Rows Within a DataTable ... 958
Working with the DataView Type ... 958
Working with Data Adapters ... 960
A Simple Data Adapter Example ... 961
Mapping Database Names to Friendly Names ... 963
Adding Disconnection Functionality to AutoLotDAL.dll ... 964
Defining the Initial Class Type ... 964
Configuring the Data Adapter Using the SqlCommandBuilder ... 965
Implementing GetAllInventory() ... 966
Implementing UpdateInventory() ... 966
Setting Your Version Number ... 967
Testing the Disconnected Functionality... 967
Multitabled DataSet Objects and Data Relationships ... 968
Prepping the Data Adapters ... 969
Updating the Database Tables ... 971
Navigating Between Related Tables ... 972
The Windows Forms Database Designer Tools ... 975
Visually Designing the DataGridView ... 975
The Generated app.config File ... 980
Examining the Strongly Typed DataSet ... 980
Examining the Strongly Typed DataTable ... 982
Examining the Strongly Typed DataRow... 983
Examining the Strongly Typed Data Adapter ... 984
Completing the Windows Forms Application ... 985
Isolating Strongly Typed Database Code into a Class Library ... 986
Viewing the Generated Code ... 988
Selecting Data with the Generated Code ... 989
Inserting Data with the Generated Code ... 990
Deleting Data with the Generated Code... 991
Invoking a Stored Procedure using the Generated Code ... 992
Programming with LINQ to DataSet ... 992
The Role of the DataSet Extensions Library ... 994
Obtaining a LINQ-Compatible DataTable ... 994
The Role of the DataRowExtensions.Field(Of T)() Extension Method ... 996
Hydrating New DataTables from LINQ Queries ... 996
Summary ... 997
■
Chapter 23: ADO.NET Part III: The Entity Framework ... 999
Understanding the Role of Entity Framework ... 999
The Role of Entities ... 1001
The Building Blocks of the Entity Framework ... 1003
Building and Analyzing your First EDM ... 1010
■ CONTENTS
xxxvi
AutoLotDAL Version 4.0, Now with Entities ... 1028
Mapping the Stored Procedure ... 1029
The Role of Navigation Properties ... 1031
Using Navigation Properties within LINQ to Entity Queries ... 1033
Invoking a Stored Procedure ... 1034
Data Binding Entities to Windows Forms GUIs ... 1035
Adding the Data Binding Code ... 1038
Summary ... 1040
■
Chapter 24: Introducing LINQ to XML ... 1041
A Tale of Two XML APIs ... 1041
LINQ to XML As a Better DOM ... 1043
VB 2010 Literal Syntax As a Better LINQ to XML ... 1044
Members of the System.Xml.Linq Namespace ... 1045
The LINQ to XML Axis Methods ... 1048
The Oddness of XName (and XNamespace) ... 1049
Working with XElement and XDocument ... 1050
Generating Documents from Arrays and Containers ... 1053
Loading and Parsing XML Content ... 1054
Manipulating an in Memory XML Document ... 1055
Building the UI of the LINQ to XML App ... 1055
Import the Inventory.xml File ... 1056
Defining a LINQ to XML Helper Class ... 1057
Rigging up the UI to Your Helper Class ... 1058
Summary ... 1059
■
Chapter 25: Introducing Windows Communication Foundation ... 1061
A Potpourri of Distributed Computing APIs ... 1061
The Role of DCOM ... 1062
The Role of MSMQ ... 1063
The Role of .NET Remoting ... 1064
The Role of XML Web Services ... 1064
Named Pipes, Sockets, and P2P ... 1067
The Role of WCF... 1067
An Overview of WCF Features ... 1068
An Overview of Service-Oriented Architecture ... 1068
WCF: The Bottom Line ... 1070
Investigating the Core WCF Assemblies ... 1070
The Visual Studio WCF Project Templates ... 1071
The WCF Service Website Project Template ... 1073
The Basic Composition of a WCF Application ... 1073
The ABCs of WCF ... 1075
Understanding WCF Contracts ... 1075
Understanding WCF Bindings ... 1076
Understanding WCF Addresses ... 1079
Building a WCF Service ... 1080
The <ServiceContract()> Attribute ... 1081
The <OperationContract()> Attribute ... 1082
Service Types As Operational Contracts ... 1083
Hosting the WCF Service ... 1084
Establishing the ABCs Within an App.config File ... 1084
Coding Against the ServiceHost Type ... 1085
Specifying Base Addresses ... 1086
Details of the ServiceHost Type ... 1087
Details of the <system.serviceModel> Element ... 1089
■ CONTENTS
xxxviii
Building the WCF Client Application ... 1094
Generating Proxy Code Using svcutil.exe ... 1094
Generating Proxy Code Using Visual Studio 2010 ... 1095
Configuring a TCP-Based Binding ... 1097
Simplifying Configuration Settings with WCF 4.0 ... 1099
Default Endpoints in WCF 4.0 ... 1099
Exposing a Single WCF Service Using Multiple Bindings ... 1101
Changing Settings for a WCF Binding ... 1102
The WCF 4.0 Default MEX Behavior Configuration ... 1104
Refreshing the Client Proxy and Selecting the Binding ... 1105
Using the WCF Service Library Project Template ... 1107
Building a Simple Math Service ... 1107
Testing the WCF Service with WcfTestClient.exe ... 1108
Altering Configuration Files Using SvcConfigEditor.exe ... 1109
Hosting the WCF Service within a Windows Service ... 1110
Specifying the ABCs in Code ... 1112
Enabling MEX ... 1113
Creating a Windows Service Installer ... 1114
Installing the Windows Service ... 1116
Invoking a Service Asynchronously from the Client ... 1117
Designing WCF Data Contracts ... 1119
Using the Web-Centric WCF Service Project Template ... 1120
Implementing the Service Contract ... 1122
The Role of the *.svc File ... 1123
Examining the Web.config File ... 1123
Testing the Service ... 1124
■
Chapter 26: Introducing Windows Workflow Foundation 4.0 ... 1127
Defining a Business Process ... 1128
The Role of WF 4.0 ... 1128
Building a (Painfully) Simple Workflow ... 1129
Viewing the Underlying XAML ... 1131
The WF 4.0 Runtime ... 1133
Hosting a Workflow using WorkflowInvoker ... 1133
Hosting a Workflow using WorkflowApplication ... 1136
Recap of your First Workflow ... 1138
Examining the Workflow 4.0 Activities ... 1138
Control Flow Activities ... 1138
Flowchart Activities ... 1139
Messaging Activities ... 1140
The Runtime and Primitives Activities ... 1141
The Transaction Activities ... 1141
The Collection and Error Handling Activities ... 1142
Building a Flowchart Workflow ... 1142
Connecting Activities in a Flowchart ... 1143
Working with the InvokeMethod Activity ... 1144
Defining Workflow Wide Variables ... 1145
Working with the FlowDecision Activity ... 1145
Working with the TerminateWorkflow Activity ... 1146
Building the “True” Condition ... 1147
Working with the ForEach<T> Activity ... 1148
Completing the Application ... 1150
■ CONTENTS
xl
Isolating Workflows into Dedicated Libraries . ... 1153
Defining the Initial Project . ... 1153
Importing Assemblies and Namespaces . ... 1155
Defining the Workflow Arguments . ... 1155
Defining Workflow Variables . ... 1156
Working with the Assign Activity . ... 1157
Working with the If and Switch Activities . ... 1157
Building a Custom Code Activity . ... 1159
Consuming the Workflow Library . ... 1162
Retrieving the Workflow Output Argument . ... 1162
Summary ... 1164
■
Chapter 27: Introducing Windows Presentation Foundation and XAML . ... 1165
The Motivation Behind WPF ... 1165
Unifying Diverse APIs . ... 1166
Providing a Separation of Concerns via XAML ... 1167
Providing an Optimized Rendering Model . ... 1168
Simplifying Complex UI Programming . ... 1168
The Various Flavors of WPF . ... 1169
Traditional Desktop Applications . ... 1169
Navigation-Based WPF Applications. ... 1172
XBAP Applications . ... 1172
The WPF/Silverlight Relationship . ... 1174
Investigating the WPF Assemblies ... 1174
The Role of the Application Class . ... 1176
The Role of the Window Class . ... 1178
Building a WPF Application without XAML ... 1184
Creating a Strongly Typed Window . ... 1186
Interacting with Application Level Data ... 1188
Handling the Closing of a Window Object ... 1189
Intercepting Mouse Events ... 1190
Intercepting Keyboard Events ... 1191
Building a WPF Application using Only XAML ... 1193
Defining MainWindow in XAML ... 1194
Defining the Application Object in XAML ... 1195
Processing the XAML Files using msbuild.exe ... 1196
Transforming Markup into a .NET Assembly ... 1198
Mapping the Window XAML Data to VB 2010 Code ... 1198
The Role of BAML ... 1200
Mapping the Application XAML Data to VB 2010 Code ... 1201
XAML-to-Assembly Process Summary ... 1202
Understanding The Syntax of WPF XAML ... 1203
Introducing Kaxaml ... 1203
XAML XML Namespaces and XAML "Keywords" ... 1204
Controlling Class and Member Variable Declarations... 1207
XAML Elements, XAML Attributes and Type Converters ... 1208
Understanding XAML Property-Element Syntax ... 1209
Understanding XAML Attached Properties ... 1210
Understanding XAML Markup Extensions ... 1211
Building a WPF Application using Code-Behind Files ... 1213
Adding a Code File for the MainWindow Class ... 1213
Adding a Code File for the MyApp Class ... 1214
Processing the Code Files with msbuild.exe ... 1215
Building WPF Applications Using Visual Studio 2010 ... 1216
The WPF Project Templates ... 1216
Exploring the WPF Designer Tools ... 1217
■ CONTENTS
xlii
Implementing the Loaded Event ... 1222
Implementing the Button’s Click Event ... 1223
Implementing the Closed Event ... 1224
Testing the Application ... 1225
Summary ... 1226
■
Chapter 28: Programming with WPF Controls ... 1227
A Survey of the Core WPF Controls ... 1227
Working with WPF Controls Using Visual Studio 2010 ... 1229
The WPF Ink Controls... 1231
The WPF Document Controls ... 1232
WPF Common Dialog Boxes ... 1232
The Details Are in the Documentation ... 1232
Controlling Content Layout Using Panels ... 1233
Positioning Content Within Canvas Panels ... 1235
Positioning Content Within WrapPanel Panels ... 1237
Positioning Content Within StackPanel Panels ... 1239
Positioning Content Within Grid Panels ... 1240
Positioning Content Within DockPanel Panels ... 1242
Enabling Scrolling for Panel Types ... 1243
Building a Window’s Frame Using Nested Panels ... 1244
Building the Menu System ... 1245
Building the ToolBar ... 1247
Building the StatusBar ... 1247
Finalizing the UI Design ... 1247
Implementing the MouseEnter/MouseLeave Event Handlers ... 1248
Implementing the Spell Checking Logic ... 1249
Understanding WPF Control Commands ... 1250
The Intrinsic Control Command Objects ... 1250
Connecting Commands to Arbitrary Actions ... 1252
Working with the Open and Save Commands ... 1254
Building a WPF User Interface with Expression Blend ... 1256
Getting to know the Key Aspects of the Blend IDE ... 1256
Using the TabControl ... 1262
Building the Ink API Tab ... 1265
Designing the ToolBar ... 1266
The RadioButton Control ... 1269
The InkCanvas Control ... 1271
The ComboBox Control ... 1274
Saving, Loading, and Clearing InkCanvas Data ... 1276
Introducing the Documents API ... 1276
Block Elements and Inline Elements ... 1277
Document Layout Managers ... 1277
Building the Documents Tab ... 1278
Populating a FlowDocument using Blend ... 1279
Populating a FlowDocument Using Code ... 1281
Enabling Annotations and Sticky Notes ... 1282
Saving and Loading a Flow Document ... 1284
Introducing the WPF Data-Binding Model ... 1285
Building the Data Binding Tab ... 1286
Establishing Data Bindings using Blend ... 1286
The DataContext Property ... 1289
Data Conversion Using IValueConverter ... 1290
Establishing Data Bindings in Code ... 1291
Building the DataGrid Tab ... 1292
■ CONTENTS
xliv
■
Chapter 29: WPF Graphics Rendering Services ... 1295
Understanding WPF’s Graphical Rendering Services ... 1295
WPF Graphical Rendering Options ... 1296
Rendering Graphical Data Using Shapes ... 1297
Adding Rectangles, Ellipses, and Lines to a Canvas ... 1299
Removing Rectangles, Ellipses, and Lines from a Canvas ... 1302
Working with Polylines and Polygons ... 1304
Working with Paths ... 1304
WPF Brushes and Pens ... 1308
Configuring Brushes Using Visual Studio 2010 ... 1309
Configuring Brushes in Code ... 1310
Configuring Pens ... 1312
Applying Graphical Transformations ... 1312
A First Look at Transformations ... 1313
Transforming our Canvas Data ... 1314
Working with Shapes using Expression Blend ... 1316
Selecting a Shape to Render from the Tool Palette ... 1316
Converting Shapes to Paths ... 1318
Combining Shapes ... 1318
The Brush and Transformation Editors ... 1319
Rendering Graphical Data Using Drawings and Geometries ... 1321
Building a DrawingBrush using Geometries ... 1322
Painting with the DrawingBrush ... 1323
Containing Drawing Types in a DrawingImage ... 1324
Generating Complex Vector Graphics using Expression Design ... 1325
Exporting a Design Document to XAML ... 1326
Rendering Graphical Data Using the Visual Layer ... 1327
■
Chapter 30: WPF Resources, Animations, and Styles ... 1335
Understanding the WPF Resource System ... 1335
Working with Binary Resources ... 1336
Working with Object (Logical) Resources ... 1342
The Role of the Resources Property ... 1343
Defining Window-Wide Resources ... 1343
The {StaticResource} Markup Extension ... 1345
Changing a Resource after Extraction ... 1346
The {DynamicResource} Markup Extension ... 1346
Application-Level Resources ... 1347
Defining Merged Resource Dictionaries ... 1349
Defining a Resource-Only Assembly ... 1350
Extracting Resources in Expression Blend ... 1352
Understanding WPF’s Animation Services ... 1354
The Role of the Animation Class Types ... 1355
The To, From, and By Properties ... 1356
The Role of the Timeline Base Class ... 1356
Authoring an Animation in VB 2010 Code ... 1357
Controlling the Pacing of an Animation ... 1358
Reversing and Looping an Animation ... 1359
Authoring Animations in XAML ... 1360
The Role of Storyboards ... 1361
The Role of Event Triggers ... 1362
Animation Using Discrete Key Frames ... 1362
Understanding the Role of WPF Styles ... 1363
Defining and Applying a Style ... 1364
Overriding Style Settings ... 1365
Automatically Applying a Style with TargetType ... 1365
■ CONTENTS