1298 Visual Basic 2010 Unleashed

  Alessandro Del Sole ®

  Visual Basic 2010 U N L E A S H E D

  Visual Basic ® 2010 Unleashed Copyright © 2010 by Pearson Education, Inc.

  All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein.

ISBN-10: 0-672-33154-3

  ISBN-13: 978-0-672-33154-1 Library of Congress Cataloging-in-Publication Data Del Sole, Alessandro.

  Visual Basic 2010 unleashed / Alessandro Del Sole. p. cm. Includes index.

  ISBN 978-0-672-33100-8 1. BASIC (Computer program language) 2. Microsoft Visual BASIC. I. Title. QA76.73.B3D467 2010 005.2'768--dc22

  2010012721 Printed in the United States of America First Printing: May 2010

  Trademarks

  All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Pearson Education, Inc. cannot attest to the accu- racy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.

  Warning and Disclaimer

  Every effort has been made to make this book as complete and as accurate as possi- ble, but no warranty or fitness is implied. The information provided is on an “as is” basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book.

  Bulk Sales

  Pearson offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact: U.S. Corporate and Government Sales 1-800-382-3419 corpsales@pearsontechgroup.com For sales outside of the U.S., please contact: International Sales

  • 1-317-581-3793 international@pearsontechgroup.com Editor-in-Chief Karen Gettman Executive Editor Neil Rowe Acquisitions Editor Brook Farling Development Editor Mark Renfrow Managing Editor Patrick Kanouse Project Editor Mandie Frank Copy Editor Apostrophe Editing Services Indexer WordWise Publishing Services LLC Proofreader The Wordsmithery LLC Technical Editor Matt Kleinwaks Publishing Coordinator Cindy Teeters Designer Gary Adair Compositor Mark Shirar

  Contents at a Glance

  Part I Learning the Basics of VB

  1 Introducing the .NET Framework 4.0.............................................................1

  2 Getting Started with the Visual Studio 2010 IDE .......................................11

  3 The Anatomy of a Visual Basic Project.........................................................59

  4 Data Types and Expressions..........................................................................85

  5 Debugging Visual Basic 2010 Applications ................................................177

  6 Handling Errors and Exceptions.................................................................207

  Part II Object-Oriented Programming with Visual Basic 2010

  7 Class Fundamentals ....................................................................................225

  8 Managing an Object’s Lifetime...................................................................267

  9 Organizing Types Within Namespaces.......................................................281

  10 Modules.......................................................................................................295

  11 Structures and Enumerations .....................................................................299

  12 Inheritance ..................................................................................................317

  13 Interfaces .....................................................................................................341

  14 Generics and Nullable Types ......................................................................359

  15 Delegates and Events ..................................................................................371

  16 Working with Collections...........................................................................385

  17 Visually Designing Objects .........................................................................407 18 “Generate From Usage” Coding Techniques..............................................421 Part III Advanced VB Language features

  19 Manipulating Files and Streams .................................................................429

  20 The My Namespace.....................................................................................451

  21 Advanced Language Features......................................................................485

  Part IV Data Access with ADO.NET and LINQ

  22 Introducing ADO.NET and DataSets . ........................................................513

  23 Introducing LINQ .......................................................................................523

  24 LINQ to Objects .........................................................................................531

  27 Introducing ADO.NET Entity Framework ..................................................603

  41 Creating and Consuming WCF Services ....................................................927

  Part IX Applications Deployment

  52 Building Customizations for Microsoft Office .........................................1119

  51 Advanced Compilations with MSBuild ....................................................1105

  50 Documenting the Source Code ................................................................1091

  49 Platform Invokes and Interoperability with the COM Architecture .......1075

  48 Coding Attributes......................................................................................1065

  47 Reflection ..................................................................................................1043

  46 Working with Assemblies .........................................................................1029

  45 Parallel Programming ...............................................................................1005

  44 Processes and Multithreading.....................................................................993

  43 Serialization.................................................................................................971

  Part VIII Advanced .NET Framework with VB 2010

  42 Implementing and Consuming WCF Data Services ..................................949

  Part VII Networking and Exposing Data Through Networks

  28 Manipulating Xml Documents with LINQ and Xml Literals ....................635

  40 Building and Deploying Applications for Windows Azure........................899

  39 Building Rich Internet Applications with Silverlight.................................871

  38 Publishing ASP.NET Web Applications ......................................................865

  37 Building ASP.NET Web Applications .........................................................839

  Part VI Building Web Applications

  36 Localizing Applications...............................................................................829

  35 Introducing Data-Binding...........................................................................799

  34 Manipulating Documents and Media ........................................................781

  33 Brushes, Styles, Templates, and Animations in WPF .................................745

  32 WPF Common Controls .............................................................................715

  31 Creating WPF Applications ........................................................................681

  30 Creating Windows Forms 4.0 Applications................................................665

  Part V Building Windows Applications

  29 Overview of Parallel LINQ ..........................................................................655

  53 Understanding the Global Assembly Cache . ..........................................1137 Visual Basic 2010 Unleashed

  Contents at a Glance Part X Mastering the Visual Studio 2010 IDE

  56 Advanced IDE Features . ...........................................................................1175

  57 Introducing the Visual Studio Extensibility . ..........................................1199

  58 Advanced Analysis Tools. .........................................................................1223

  59 Testing Code with Unit Tests, Test-Driven Development, and Code Contracts .........................................................................................1251 Appendixes

  A Installing Visual Studio 2010. ..................................................................1275

  B Useful Resources and Tools for Visual Basic. .................................1281 Index.

  .............................................................................................................1285

  Table of Contents

  

  

   Where Is the .NET Framework . ............................................................2 The .NET Framework Architecture . ......................................................2

   Writing Managed Code .........................................................................4 .NET Assemblies. ...................................................................................5

  

  Windows Software Development Kit ....................................................7

  

  

  Get Started Tab ....................................................................................13 The Guidance and Resources Tab........................................................13 The Latest News Tab ............................................................................14

   Creating Visual Basic Projects .............................................................16 Multitargeting . ....................................................................................17 Accessing Recent and Online Templates.............................................18 Searching for Installed Templates .......................................................20 Creating Reusable Projects and Items Templates................................21 Creating Your First Visual Basic 2010 Project .....................................21 Finding Visual Basic Projects . .............................................................23 Working with the Code Editor ............................................................24

   The Solution Explorer Window...........................................................27 Error List Window . .............................................................................28 The Properties Window . .....................................................................30 Output Window. .................................................................................31

  Contents

  Debug and Release Configurations . ...................................................38 Other Compile Options. .....................................................................41 Advanced Compile Options . ..............................................................44

   Debugging an Application...................................................................47 Breakpoints and Data Tips . ................................................................49 About Runtime Errors. ........................................................................52 Edit and Continue . .............................................................................53

   Online Help and the MSDN Library . .................................................55 Object Browser Window. ....................................................................55

  

   Classes ..................................................................................................60 Properties .............................................................................................60 Methods ...............................................................................................60 Modules ...............................................................................................61 Structures .............................................................................................61 Inheritance...........................................................................................61 Namespaces..........................................................................................62 Accessing Members..............................................................................63 Imports Directives................................................................................64

  #Region..#End Region Directives........................................................64

  Attributes .............................................................................................65 A New Feature: Implicit Line Continuation .......................................65

  

  Dissecting My Project ..........................................................................70 Application.MyApp . ...........................................................................70 AssemblyInfo.vb . ................................................................................72 Resources and the Resources.resx File .................................................73 Application Settings. ...........................................................................77

   Adding References to COM Libraries . ................................................82 Deploy Without PIAs. .........................................................................83 Final Considerations. ..........................................................................84

  

  

  Visual Basic 2010 Unleashed Introducing Value Types and Reference Types ...................................86

  System.Object and System.ValueType ...............................................87

   .NET Framework Primitive Value Types ..............................................90 Using Value Types................................................................................92 Working with BigInteger ...................................................................100 Building Custom Value Types ...........................................................101

   .NET Framework Primitive Reference Types .....................................103

   Memory Allocation............................................................................104 Object-Oriented Differences ..............................................................107 Performance Differences....................................................................109 What Custom Type Should I Choose? ..............................................109

   Understanding Implicit Conversions................................................110 Boxing and Unboxing . .....................................................................112 Deep Copy and Shallow Copy ..........................................................114 The GetType Keyword........................................................................118

   Widening and Narrowing Conversions ............................................119

   Working with Strings.........................................................................125 Working with Dates...........................................................................137 Working with Time. ..........................................................................143 Working with TimeZone and TimeZoneInfo ......................................144 Working with GUIDs .........................................................................147 Working with Arrays. ........................................................................148

   Arithmetic Operators .........................................................................155 Assignment Operators .......................................................................157 Logical, Bitwise and Shift Operators .................................................158 Concatenation Operators ..................................................................163 Comparison Operators ......................................................................164

   Iterations ............................................................................................166 Loops..................................................................................................169 Conditional Code Blocks...................................................................171 Constants ...........................................................................................174

  With..End With statement ................................................................175

  Contents

  

  Debugging in Steps ............................................................................178 Mixed Mode Debugging ....................................................................180 “Just My Code” Debugging ...............................................................180 Working with Breakpoints and Trace Points.....................................182 Locals Window . ................................................................................185 Command Window . .........................................................................185 Call Stack Window . ..........................................................................186 Watch Windows. ...............................................................................187 Threads Window. ..............................................................................189 Autos Window . .................................................................................190

  

  Debug

  The Class .................................................................................192

  Trace

  The Class .................................................................................194 Understanding Trace Listeners . ........................................................195 Using Debug Attributes in Your Code...............................................201

  

  Are You Upgrading from Visual Basic 6? . ........................................209

  System.Exception

  , Naming Conventions and Specialization .........209

  Try..Catch..Finally

  ........................................................................209

  Throw

  The Keyword . .........................................................................218

  When

  The Keyword . ...........................................................................222 Catching Exceptions Without a Variable..........................................224

  

  

   Nested Classes....................................................................................226

   Avoiding Ambiguities with Local Variables . ....................................228

   Read-Only Properties .........................................................................231 Write-Only Properties ........................................................................231

  Visual Basic 2010 Unleashed Exposing Custom Types ....................................................................232 Accessing Properties. .........................................................................232 Default Properties . ............................................................................233

  

  Invoking Methods .............................................................................236 Methods Arguments: ByVal and ByRef .............................................237 Overloading Methods ........................................................................242 Exit from Methods.............................................................................245

  

  Overloading Constructors .................................................................254 Object Initializers. .............................................................................256

   Shared Classes ....................................................................................258 Shared Fields . ....................................................................................258 Shared Properties ...............................................................................259 Shared Methods .................................................................................259 Shared Constructors ..........................................................................261

   Where Do I Need to Apply? . ............................................................262 Marking Assemblies and Types as CLS-Compliant ...........................263 Naming Conventions . ......................................................................263 Rules About Classes . .........................................................................265 Rules About Properties. .....................................................................265 Rules About Methods . ......................................................................265 Rules About Arrays.............................................................................266

  

   Using..End Using Statement.............................................................273

  Putting Dispose and Finalize Together...........................................273

  Interacting with the Garbage Collector . ..........................................277 Understanding Generations and

  

  CType

  

  

  

  

  ...................................................311 Using Enums As Return Values From Methods ................................314 Enum Values As Bit Flags...................................................................315 Enumerations and Common Language Specification ......................315

  

System.Enum

  Using Enumerations ..........................................................................310 Useful Methods from

  .............................................................................307

  Overloading

  Why Are Namespaces So Useful? ......................................................285 Nested Namespaces. ..........................................................................286 Scope . ................................................................................................289 Root Namespace . ..............................................................................289

  

   No Constructor ..................................................................................297 No Inheritance Support.....................................................................297 No Interface Implementation............................................................297

   Scope ..................................................................................................296

  

  Directives . ...........................................................................291 Namespaces and Common Language Specification .........................294

  Imports

  Keyword. ...............................................................................290

  Global

  Contents

  NotOverridable Keyword ..................................................................328

  IComparable Interface ................................................................351

   Declaring Delegates ...........................................................................372 Combining Delegates: Multicast Delegates.......................................374

  

  

  Consuming Generic Types ................................................................362 Implementing Generic Methods .......................................................363 Understanding Constraints . .............................................................363 Overloading Type Parameters. ..........................................................366

  

  IFormattable Interface ..............................................................356

  The

  IConvertible Interface ..............................................................353

  The

  The

  Overloading Derived Members . .......................................................328

  IEnumerable Interface ................................................................348

  The

  Passing Interfaces As Method Arguments . .......................................345

  

  

  

  MyBase Keyword.................................................................................332 MyClass Keyword ...............................................................................334

  

  NotInheritable Keyword ..................................................................329 MustInherit and MustOverride Keywords .......................................330

   Visual Basic 2010 Unleashed

  Contents

  Raising Events ....................................................................................378 Creating Custom Events....................................................................381

  

  The ArrayList Collection .................................................................386 The Queue Collection. .......................................................................389 The Stack Collection. .......................................................................390 The HashTable Collection .................................................................390 The ListDictionary Collection ........................................................391 The OrderedDictionary Collection ..................................................391 The SortedList Collection ...............................................................392 The HybridDictionary Collection ....................................................392 The StringCollection Collection ....................................................392 The StringDictionary Collection ....................................................393 The NameValueCollection Collection...............................................393 The BitArray Collection . .................................................................393 The Bitvector32 Collection..............................................................394

   The List(Of T) Collection...................................................................395 Working with Collection Initializers.................................................397 The ReadOnlyCollection(Of T) Collection .......................................398 The Dictionary(Of TKey, TValue) Collection ....................................399 The SortedDictionary(Of TKey, TValue) Collection..........................400 The ObservableCollection(Of T) Collection .....................................400 The ReadonlyObservableCollection(Of T) Collection ......................402 The LinkedList(Of T) Collection .......................................................403 The Queue(Of T) and Stack(Of T) Collections ..................................405

  

  

  Enabling the Class Designer . ............................................................408 Adding and Designing Objects..........................................................409 Implementing Derived Classes. ........................................................413 Creating Multiple Diagrams . ............................................................416 Exporting the Diagram . ....................................................................416

  Visual Basic 2010 Unleashed

   Generating Shared Members . ...........................................................425 On-the-Fly Code and Object Initializers ...........................................425

   Interfaces Additions...........................................................................428

  

  

  System.IO.Path

  The Class.................................................................430

  System.IO.Directory

  The Class .......................................................431

  System.IO.DirectoryInfo

  The Class ................................................434

  System.IO.DriveInfo

  The Class .......................................................434

  System.IO.File

  The Class.................................................................436

  System.IO.FileInfo

  The Class .........................................................438 Handling File Exceptions. .................................................................439 Understanding Permissions. .............................................................439

   Reading and Writing Text Files .........................................................441 Reading and Writing Binary Files......................................................442 Using Memory Streams . ...................................................................442 Using Streams with Strings................................................................443 Compressing Data with Streams .......................................................444 Networking with Streams . ................................................................448

  

  

  

  

   Retrieving Assembly Information . ...................................................452 Working with Cultures . ....................................................................453 Deployment and Environment Information ....................................454

  

   Working with the File System ...........................................................457 Working with the Clipboard . ...........................................................458 Playing Audio Files . ..........................................................................459 Managing the Keyboard . ..................................................................460 Working with the Registry . ..............................................................460

   My.Settings Events ...........................................................................469

  Coding Custom Extension Methods . ...............................................495 Exporting Extension Methods. .........................................................497

  Data Providers....................................................................................514 Connection Modes ............................................................................515 Understanding Connections and Data Readers................................515

  

  

  Covariance .........................................................................................509 Contra Variance .................................................................................510

  

  Type Inference and Lambda Expressions . ........................................503 Multiline Lambdas. ...........................................................................504 Sub Lambdas . ....................................................................................505 Lexical Closures . ...............................................................................506

  

  Multidimensional and Jagged Arrays . ..............................................489

  Getting Resources by Name in Code . ..............................................474

  Local Type Inference Scope . .............................................................488

  Option Infer Directive .....................................................................487

  

  Understanding Application Events ...................................................483

  

   Extending My.Application and My.Computer ...................................478 Extending My.Resources and My.Settings . ....................................480

  

  Contents

  Visual Basic 2010 Unleashed

  

  

  

  

  Understanding Deferred Execution. .................................................539

  Projection Operators..........................................................................542 Restriction Operators .........................................................................543 Aggregation Operators.......................................................................544

  Let

  Understanding the Keyword.......................................................546 Conversion Operators........................................................................546 Generation Operators ........................................................................548 Ordering Operators. ..........................................................................549 Set Operators. ....................................................................................550 Grouping Operators...........................................................................551 Union Operators . ..............................................................................553 Equality Operators . ...........................................................................556 Quantifiers . .......................................................................................556 Concatenation Operators ..................................................................557 Elements Operators............................................................................557 Partitioning Operators .......................................................................558

  

   Prerequisites .......................................................................................562 Understanding LINQ to SQL Classes ................................................562 Behind the Scenes of LINQ to SQL Classes.......................................573

  

  Inserting Entities................................................................................579 Updating Entities...............................................................................583 Deleting Entities ................................................................................584 Mapping Stored Procedures...............................................................584 Using the Log.....................................................................................587

  Handling Optimistic Concurrency....................................................590 Using SQL Syntax Against Entities....................................................591

   Writing the Connection String .........................................................593

  

   Building Complex Queries with Anonymous Types . ......................598

   Understanding CopyToDataTable . ....................................................598 Understanding Field(Of T) and SetField(Of T) ...........................600

  

  Understanding the ObjectContext class: The Visual Basic Mapping . .............................................................612

  Entity Designer Tool Windows..........................................................617

  Instantiating the ObjectContext . .....................................................620 Adding Entities . ................................................................................623 Deleting Entities . ..............................................................................624 Updating Entities. .............................................................................625 Handling Optimistic Concurrency. ..................................................626 Validating Data . ................................................................................627

  

  

  The System.Xml.Linq Namespace. ...................................................636

  LINQ Queries with Xml Literals........................................................644 Understanding Embedded Expressions .............................................646

  

  

  Simulating an Intensive Work...........................................................656 Contents

  Measuring Performances of a PLINQ Query .....................................657 Ordering Sequences . .........................................................................659

  AsParallel and Binary Operators. ...................................................660

  Using ParallelEnumerable ...............................................................660 Controlling PLINQ Queries . .............................................................661

  

  

  

  What’s New in Windows Forms 4.0..................................................667 Available Windows Forms Controls . ................................................667

  

  Providing Custom Validation............................................................674 Understanding Chart Control ...........................................................675 Populating the Chart Control ...........................................................677 Running the Sample Application ......................................................680

  

  Improvements in WPF 4 ...................................................................682

  Declaring and Using Controls with the Designer and XAML. ........689

  A More Thorough Discussion: Introducing the Routed Events . .....695

  The Grid Panel...................................................................................697 The StackPanel Panel .......................................................................700 The WrapPanel Panel .........................................................................701 The Canvas Panel ...............................................................................703 The DockPanel Panel .........................................................................703 The ViewBox Panel .............................................................................704

   Instantiating Windows at Runtime...................................................706

  Visual Basic 2010 Unleashed

  Contents

  

  

  

  

  Border

  ................................................................................................717

  Button

  ................................................................................................718

  Calendar

  ............................................................................................718

  CheckBox

  ............................................................................................719

  ComboBox

  ............................................................................................720

  DataGrid

  ............................................................................................721

  DatePicker

  .........................................................................................721

  DocumentViewer

  .................................................................................723

  Ellipse

  ..............................................................................................723

  Expander

  ............................................................................................723

  Frame

  . ................................................................................................724

  GroupBox

  ............................................................................................725

  Image

  . ................................................................................................726

  Label

  . ................................................................................................726

  ListBox

  ..............................................................................................727

  ListView

  ............................................................................................728

  MediaElement

  .....................................................................................729

  Menu

  . ..................................................................................................729

  PasswordBox

  .......................................................................................732

  ProgressBar

  .......................................................................................732

  RadioButton

  .......................................................................................734

  Rectangle

  ...........................................................................................734

  RichTextBox

  .......................................................................................734

  ScrollBar

  ...........................................................................................735

  ScrollViewer

  .....................................................................................735

  Separator

  ...........................................................................................736

  Slider

  ................................................................................................736

  StatusBar

  ...........................................................................................737

  TabContro

  l..........................................................................................737

  TextBlock

  ...........................................................................................738

  TextBox

  ..............................................................................................739

  ToolBar

  ..............................................................................................740

  TreeView

  ............................................................................................741

  WebBrowser

  .........................................................................................742

  WindowsFormsHost

  ..............................................................................742

  Visual Basic 2010 Unleashed

  

  Applying a SolidColorBrush . ...........................................................747 Applying a LinearGradientBrush .....................................................748 Applying a RadialGradientBrush .....................................................749 Applying an ImageBrush . ..................................................................751 Applying SelectionBrush and CaretBrush ......................................753 Applying a VisualBrush . ..................................................................754 Applying a DrawingBrush . ................................................................755 Applying a BitmapCacheBrush ...........................................................757

   Styles Inheritance ..............................................................................761 Understanding Triggers .....................................................................761

  

  Applying RotateTransform . .............................................................767 Applying ScaleTransform . ...............................................................767 Applying SkewTransform . .................................................................768 Applying TranslateTransform ..........................................................768 Applying Multiple Transforms . ........................................................769

   Applying DoubleAnimation . .............................................................771 Applying ColorAnimation . ...............................................................773 Working with Animation Events . ....................................................775 Creating Animations with Visual Basic. ...........................................776

  

  Understanding the RichTextBox Control . .......................................795