introducing visual c# 2010 - rd.springer.com978-1-4302-3172-1/1.pdf · chapter 4: c# fundamentals...
TRANSCRIPT
Introducing Visual C# 2010
� � �
Adam Freeman
Introducing Visual C# 2010
Copyright © 2010 by Adam Freeman
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.
ISBN 978-1-4302-3171-4
ISBN 978-1-4302-3172-1
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.
President and Publisher: Paul Manning Lead Editor: Ewan Buckingham Technical Reviewer: Damien Foggon Editorial Board: 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: Anne Collett and Kelly Moritz Copy Editor: Kim Wimpsett and Mary Behr Compositor: Bytheway Publishing Services Indexer: BIM Indexing & Proofreading Services Artist: April Milne Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer Science+Business Media, LLC., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders- [email protected], or visit www.springeronline.com.
For information on translations, please e-mail [email protected], 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.
The source code for this book is available to readers at www.apress.com.
(eBook)
Dedicated to my wife, Jacqui Griffyth.
� CONTENTS AT A GLANCE
iv
Contents at a Glance
� About the Author............................................................................................... xxxii � About the Technical Reviewer ......................................................................... xxxiii � Acknowledgments ........................................................................................... xxxiv
PART 1 � � � Getting Started..................................................................................1 � Chapter 1: Introduction...........................................................................................3
� Chapter 2: Getting Ready ........................................................................................7
� Chapter 3: Understanding C# and the .NET Framework........................................17
PART 2 � � � The C# Language.............................................................................31 � Chapter 4: C# Fundamentals and Keyword Reference..........................................33
� Chapter 5: Numeric and Boolean Types................................................................91
� Chapter 6: Classes and Objects ..........................................................................131
� Chapter 7: Fields.................................................................................................183
� Chapter 8: Properties, Indexers, and Operators .................................................203
� Chapter 9: Methods.............................................................................................229
� Chapter 10: Delegates, Events, and Anonymous Methods..................................305
� Chapter 11: Namespaces ....................................................................................337
� Chapter 12: Interfaces, Structs, and Enums .......................................................355
� Chapter 13: Arrays..............................................................................................385
� Chapter 14: Exceptions .......................................................................................419
� Chapter 15: Generic and Anonymous Types .......................................................453
� Chapter 16: Strings and Characters ...................................................................481
� CONTENTS AT A GLANCE
v
� Chapter 17: Attributes ........................................................................................519
� Chapter 18: Garbage Collection ..........................................................................539
PART 3 � � � The .NET Class Library ..................................................................549
� Chapter 19: Collections.......................................................................................551
� Chapter 20: Files, Streams, and IO .....................................................................621
� Chapter 21: Networking & WCF ..........................................................................675
� Chapter 22: Time & Dates ...................................................................................711
� Chapter 23: Serialization ....................................................................................735
� Chapter 24: Serialization ....................................................................................735
� Chapter 25: Asynchronous Methods and Parallel Loops ....................................815
� Chapter 26: Other Useful Features and Classes..................................................833
PART 4 � � � Data and Databases ......................................................................861
� Chapter 27: LINQ to Objects ................................................................................863
� Chapter 28: Parallel LINQ....................................................................................915
� Chapter 29: LINQ to XML.....................................................................................925
� Chapter 30: LINQ to Entities................................................................................965
� Chapter 31: LINQ to DataSet .............................................................................1001
PART 5 � � � User Interfaces............................................................................1031
� Chapter 32: Windows Forms.............................................................................1033
� Chapter 33: Windows Presentation Foundation................................................1069
� Chapter 34: ASP.NET.........................................................................................1099
� Chapter 35: Silverlight ......................................................................................1125
PART 6 � � � Advanced Topics.........................................................................1159
� Chapter 36: Windows Integration .....................................................................1161
� Chapter 37: Cryptography and Security............................................................1185
� Chapter 38: Testing and Debugging..................................................................1201
� Index .................................................................................................................1231
� CONTENTS
vi
Contents
� About the Authors............................................................................................. xxxii � About the Technical Reviewers ....................................................................... xxxiii � Acknowledgments ........................................................................................... xxxiv
PART 1 � � � Getting Started..................................................................................1 � Chapter 1: Introduction...........................................................................................3
Who Should Read This Book?............................................................................................3 What Is Covered in This Book? ..........................................................................................3
What Do You Need to Read This Book? .............................................................................4 What Is the Structure of This Book? ..................................................................................4 What Is in Each Chapter?...................................................................................................4
Getting the Example Code .................................................................................................5 Finding More Information ..................................................................................................6
The MSDN C# Programming Guide........................................................................................................... 6 Online Forums .......................................................................................................................................... 6 Other Books .............................................................................................................................................. 6
Summary ...........................................................................................................................6
� Chapter 2: Getting Ready ........................................................................................7
Installing the Software.......................................................................................................7 Installing Visual Studio 2010 .................................................................................................................... 7 Installing SQL Server 2008 ....................................................................................................................... 9 Installing the Silverlight Tools ................................................................................................................ 10 Downloading the Sample Code and Data ............................................................................................... 10
� CONTENTS
vii
Creating Your First C# Project..........................................................................................10 Creating the Project................................................................................................................................ 11 Editing the Code ..................................................................................................................................... 13 Compiling and Running the Program...................................................................................................... 14
Features That I Use Before Explaining Them...................................................................14 The using statements ............................................................................................................................. 14 The namespace statement ..................................................................................................................... 15 The class statement ............................................................................................................................... 15 The Main method.................................................................................................................................... 15 The Code Comments............................................................................................................................... 16 The Console.WriteLine and Console.ReadLine methods......................................................................... 16
Summary .........................................................................................................................16
� Chapter 3: Understanding C# and the .NET Framework........................................17
C# and the .NET Framework at a Glance .........................................................................17 Introducing C# ........................................................................................................................................ 17 Introducing the .NET Framework............................................................................................................ 18 The Relationship between C# and the .NET Framework ........................................................................ 19 Understanding Assemblies..................................................................................................................... 20
The Key Features of C# and the .NET Framework ...........................................................22 Understanding Object-Orientation .......................................................................................................... 22 Understanding Type Safety .................................................................................................................... 22 Understanding Automatic Memory Management ................................................................................... 23 Understanding the Just-In-Time Compiler ............................................................................................. 23 Understanding Parallel Processing......................................................................................................... 23 Understanding Unmanaged/Native Code Support .................................................................................. 24 Understanding the .NET Technology Spectrum ...................................................................................... 24
Understanding .NET Cross-Platform Support ..................................................................29 Summary .........................................................................................................................30
� CONTENTS
viii
PART 2 � � � The C# Language.............................................................................31 � Chapter 4: C# Fundamentals and Keyword Reference..........................................33
Language Fundamentals .................................................................................................33 A Simple C# Program.............................................................................................................................. 33 C# Syntax................................................................................................................................................ 34 Types ...................................................................................................................................................... 41
Common Programming Tasks .........................................................................................46 Assigning Values .................................................................................................................................... 46 Making Comparisons.............................................................................................................................. 47 Performing Selections ............................................................................................................................ 49 Iterating Data Items................................................................................................................................ 53
Keyword and Operator Reference....................................................................................60 Type Keywords ....................................................................................................................................... 61 Modifiers................................................................................................................................................. 69 Selection Keywords ................................................................................................................................ 75 Iterator Keywords ................................................................................................................................... 75 Jump Keywords...................................................................................................................................... 76 Exception Handling Keywords ................................................................................................................ 77 Arithmetic Overflow Keywords ............................................................................................................... 78 Synchronization Keywords ..................................................................................................................... 79 Parameter Keywords .............................................................................................................................. 79 Namespace Keywords ............................................................................................................................ 81 Literal Keywords..................................................................................................................................... 82 Object Keywords..................................................................................................................................... 83 LINQ Keywords ....................................................................................................................................... 84 Other Keywords ...................................................................................................................................... 84 Operators................................................................................................................................................ 87
Summary .........................................................................................................................89
� CONTENTS
ix
� Chapter 5: Numeric and Boolean Types................................................................91
Numeric Types.................................................................................................................92 Using Numeric Literals ........................................................................................................................... 93 Implicit and Explicit Numeric Type Conversions..................................................................................... 98 Using Overflow Checking...................................................................................................................... 101 Using Struct Members.......................................................................................................................... 103
Using Numeric Operators...............................................................................................109 Arithmetic Operators ............................................................................................................................ 109 Unary Operators.................................................................................................................................... 113 Relational Operators ............................................................................................................................. 116 Logical Operators ................................................................................................................................. 118 Assignment Operators .......................................................................................................................... 122
Working with Very Large Integer Values........................................................................126
The Boolean Type ..........................................................................................................127 Using Boolean Literals.......................................................................................................................... 127 Using Boolean Results.......................................................................................................................... 128 Using Struct Members.......................................................................................................................... 129
Summary .......................................................................................................................130
� Chapter 6: Classes and Objects ..........................................................................131
Creating a Basic Class ...................................................................................................132 Adding Features to a Class................................................................................................................... 133 Creating Objects from Classes ............................................................................................................. 136 Using Objects........................................................................................................................................ 139
Class Inheritance ...........................................................................................................150 Understanding Inheritance ................................................................................................................... 153 Understanding Encapsulation............................................................................................................... 159 Understanding Polymorphism .............................................................................................................. 160
� CONTENTS
x
Casting Objects and Type Checking ..............................................................................165 Implicit vs. Explicit Casting................................................................................................................... 165 Type Conversion Exceptions................................................................................................................. 169 Avoiding Explicit Cast Exceptions......................................................................................................... 170 Boxing and Unboxing............................................................................................................................ 173
Using Nested Classes ....................................................................................................175
Using Class Modifiers ....................................................................................................176 Creating Static Classes......................................................................................................................... 176 Creating Abstract Classes .................................................................................................................... 178 Creating Sealed Classes....................................................................................................................... 179 Creating Partial Classes........................................................................................................................ 179 Using Access Modifiers ........................................................................................................................ 180
Summary .......................................................................................................................181
� Chapter 7: Fields.................................................................................................183
Defining and Using Fields ..............................................................................................184 Defining Fields...................................................................................................................................... 184 Initializing Fields................................................................................................................................... 184 Reading and Updating Fields................................................................................................................ 186 The Fourth Stage of the Life Cycle ....................................................................................................... 193
Applying Field Modifiers ................................................................................................193 Creating Static Fields ........................................................................................................................... 194 Creating Read-Only Fields .................................................................................................................... 196 Applying Access Modifiers ................................................................................................................... 199 Hiding Base Class Fields ...................................................................................................................... 199 Using the volatile Keyword ................................................................................................................... 201
Summary .......................................................................................................................201
� CONTENTS
xi
� Chapter 8: Properties, Indexers, and Operators .................................................203
Creating a Property........................................................................................................204 Creating a Field-Backed Property......................................................................................................... 204 Using a Property ................................................................................................................................... 207 Creating an Automatically Implemented Property ................................................................................ 208 Creating an Asymmetric Property......................................................................................................... 209 Creating a Computed Property ............................................................................................................. 209 Mapping a Property Type to a Field Type ............................................................................................. 210 Using Access Modifiers ........................................................................................................................ 210 Using Other Modifiers........................................................................................................................... 211
Creating an Indexer .......................................................................................................215 Using Multiple Indexers ........................................................................................................................ 216 Creating a Validating Indexer ............................................................................................................... 217 Creating an Indexer with Multiple Arguments ...................................................................................... 218
Creating Custom Operators ...........................................................................................219 Creating Custom Unary Operators ........................................................................................................ 219 Creating Custom Binary Operators ....................................................................................................... 221 Creating Custom Conversion Operators................................................................................................ 225
Summary .......................................................................................................................227
� Chapter 9: Methods.............................................................................................229
Creating and Using a Simple Method ............................................................................231 Defining the Method Name................................................................................................................... 232 Defining the Result Type ...................................................................................................................... 232 Defining the Parameters....................................................................................................................... 233 Defining the Modifiers .......................................................................................................................... 234 Defining the Method Body .................................................................................................................... 237 Using the Methods................................................................................................................................ 238
� CONTENTS
xii
Understanding Parameters ............................................................................................239 Using Value Parameters ....................................................................................................................... 239 Using Reference Parameters................................................................................................................ 243 Using Output Parameters ..................................................................................................................... 245 Using Parameter Arrays........................................................................................................................ 247 Using Optional Parameters ................................................................................................................... 249 Using Named Parameters..................................................................................................................... 250
Understanding Method Bodies.......................................................................................251 Using Local Variables ........................................................................................................................... 251 Using Method Results........................................................................................................................... 256
Understanding Method Modifiers ..................................................................................257 Using Access Modifiers ........................................................................................................................ 257 Creating Static Methods ....................................................................................................................... 257 Creating Virtual Methods ...................................................................................................................... 258 Creating Sealed Methods ..................................................................................................................... 258 Creating Abstract Methods................................................................................................................... 259
Overloading Methods.....................................................................................................259 Hiding and Overriding Methods .....................................................................................262
Hiding Methods..................................................................................................................................... 263 Overriding Methods .............................................................................................................................. 265 Sealing Methods................................................................................................................................... 267 Understanding Method Specialization.................................................................................................. 268
Special Methods ............................................................................................................269 The Main Method.................................................................................................................................. 269 Constructors ......................................................................................................................................... 272 Destructors ........................................................................................................................................... 290 Iterator Blocks ...................................................................................................................................... 291 Partial Methods .................................................................................................................................... 296 Abstract Methods ................................................................................................................................. 299
� CONTENTS
xiii
Extension Methods ............................................................................................................................... 301 Summary .......................................................................................................................304
� Chapter 10: Delegates, Events, and Anonymous Methods..................................305
Using Delegates.............................................................................................................306 Using Delegates for Callbacks.............................................................................................................. 308 Multicasting with Delegates ................................................................................................................. 310 Delegating Selectively .......................................................................................................................... 312 Interrogating Delegates ........................................................................................................................ 313
Using Events ..................................................................................................................315 Defining and Publishing EventHandler Pattern Events .............................................................................. 317 Creating Nongeneric Events ...................................................................................................................... 322 Creating Events Without Custom Data....................................................................................................... 323 Applying Modifiers to Events ..................................................................................................................... 325 Using Action and Func Delegates ..................................................................................326
Using Action Delegates......................................................................................................................... 326 Using Func Delegates........................................................................................................................... 328
Anonymous Methods .....................................................................................................329 Capturing Outer Variables..................................................................................................................... 331
Lambda Expressions......................................................................................................334 Summary .......................................................................................................................336
� Chapter 11: Namespaces ....................................................................................337
Consuming Namespaces ...............................................................................................337 Using Fully Qualified Names................................................................................................................. 338 Importing Namespaces......................................................................................................................... 339
Creating Namespaces....................................................................................................340 Nesting Namespaces............................................................................................................................ 342 Logically Nesting Namespaces............................................................................................................. 343 Spreading Namespaces Across Files ................................................................................................... 344
� CONTENTS
xiv
Adding Types to Existing Namespaces................................................................................................. 346 Disambiguating Namespaces and Types.......................................................................347
Disambiguation with Fully Qualified Names......................................................................................... 349 Disambiguating with Aliases ................................................................................................................ 349 Aliasing Namespaces ........................................................................................................................... 350 Resolving Type or Namespace Hiding .................................................................................................. 351
Summary .......................................................................................................................353
� Chapter 12: Interfaces, Structs, and Enums .......................................................355
Using Interfaces.............................................................................................................356 Defining and Using a Simple Interface ................................................................................................. 356 Specifying Interface Members.............................................................................................................. 358 Deriving Interfaces ............................................................................................................................... 362 Defining a Partial Interface................................................................................................................... 365 Implementing Interfaces....................................................................................................................... 365
Using Structs .................................................................................................................371 Defining and Instantiating a Struct....................................................................................................... 371 Differences Between Structs and Classes............................................................................................ 374 Copying a Struct ................................................................................................................................... 376
Using an Enum...............................................................................................................380 Defining an Enum ................................................................................................................................. 380 Using an Enum...................................................................................................................................... 381 Using Underlying Types and Numeric Values ....................................................................................... 382 Combining Enum Values....................................................................................................................... 383
Summary .......................................................................................................................384
� Chapter 13: Arrays..............................................................................................385
Defining and Initializing Arrays......................................................................................387 Getting and Setting Array Values...................................................................................389
Using Array Initializers...................................................................................................391
� CONTENTS
xv
Enumerating Arrays .......................................................................................................393 Enumerating with a for Loop ................................................................................................................ 393 Enumerating with a foreach Loop ........................................................................................................ 395 Enumerating Using IEnumerator and IEnumerator<T> ........................................................................ 396 Breaking from Enumerations................................................................................................................ 398
Using System.Array Members .......................................................................................400 Sorting Arrays....................................................................................................................................... 400 Processing All of the Elements in an Array........................................................................................... 401 Resizing and Copying an Array............................................................................................................. 402 Finding Items in an Array ..................................................................................................................... 406
Using Arrays with LINQ ..................................................................................................408 Using Arrays as Collections ...........................................................................................409
Using Multidimensional Arrays ......................................................................................409 Using Rectangular Arrays ..................................................................................................................... 410 Using Jagged Arrays............................................................................................................................. 415
Summary .......................................................................................................................418
� Chapter 14: Exceptions .......................................................................................419
Handling Exceptions ......................................................................................................420 Using try Statements and catch Clauses.............................................................................................. 421 Handling Different Exception Types...................................................................................................... 424 Nesting try Statements......................................................................................................................... 427 Using Exception Members.................................................................................................................... 427 Using finally Clauses ............................................................................................................................ 430
Throwing Exceptions .....................................................................................................432 Rethrowing Exceptions......................................................................................................................... 436 Creating and Throwing Custom Exceptions.......................................................................................... 438 Throwing Meaningful Exceptions ......................................................................................................... 441
Summary .......................................................................................................................451
� CONTENTS
xvi
� Chapter 15: Generic and Anonymous Types .......................................................453
Using Generic Types ......................................................................................................454 Defining a Generic Class....................................................................................................................... 456 Creating Objects from Generic Classes ................................................................................................ 456 Implementing and Using Generic Class Members................................................................................ 457 Defining Multiple Parameter Types ...................................................................................................... 460 Casting from Parameterized Types ...................................................................................................... 461 Constraining Parameterized Types....................................................................................................... 462 Defining a Method-Specific Parameterized Type ................................................................................. 465 Deriving from a Generic Base Class ..................................................................................................... 467 Creating Generic Interfaces .................................................................................................................. 471 Creating Generic Structs ...................................................................................................................... 472 Type Variance ....................................................................................................................................... 472 Using the default Keyword ................................................................................................................... 477
Using Anonymous Types................................................................................................478
Summary .......................................................................................................................480
� Chapter 16: Strings and Characters ...................................................................481
Working with Characters ...............................................................................................482 Expressing Characters Using Literals ................................................................................................... 482 Performing Operations on Characters .................................................................................................. 483 Using Struct Members.......................................................................................................................... 484
Using Strings .................................................................................................................486 Expressing Strings Using String Literals .............................................................................................. 486 Performing Operations on Strings ........................................................................................................ 488 Using Regular Expressions ................................................................................................................... 495 Using Class Members ........................................................................................................................... 496
� CONTENTS
xvii
Using the StringBuilder Class ........................................................................................502 Creating a StringBuilder Object ............................................................................................................ 502 Using a StringBuilder Object................................................................................................................. 502
Formatting Strings.........................................................................................................507 Using Composite Formatting ................................................................................................................ 507 Formatting Types.................................................................................................................................. 511 Creating String Representations of Custom Types............................................................................... 514 Performing Custom Composite Formatting .......................................................................................... 516
Summary .......................................................................................................................518
� Chapter 17: Attributes ........................................................................................519
Using Attributes .............................................................................................................519 Applying Attributes with Parameters.................................................................................................... 521
Testing for an Attribute..................................................................................................522 Testing for an Attribute Applied to a Class ........................................................................................... 522 Testing for an Attribute Applied to a Field ............................................................................................ 525 Testing for an Attribute Applied to a Property ...................................................................................... 528 Testing for an Attribute Applied to a Method........................................................................................ 530
Creating a Custom Attribute ..........................................................................................532 Using a Custom Attribute...................................................................................................................... 533 Defining Properties in a Custom Attribute ............................................................................................ 535 Controlling How a Custom Attribute Can Be Used ................................................................................ 535 Controlling Attribute Inheritance .......................................................................................................... 537
Summary .......................................................................................................................538
� Chapter 18: Garbage Collection ..........................................................................539
Explicitly Running the Garbage Collector.......................................................................540
Implementing a Destructor ............................................................................................541 Destructors vs. Finalizers ..................................................................................................................... 542 Problems with Destructors ................................................................................................................... 543
� CONTENTS
xviii
Using Disposal ...............................................................................................................544 Using Weak References.................................................................................................546
Summary .......................................................................................................................547
PART 3 � � � The .NET Class Library ..................................................................549 � Chapter 19: Collections.......................................................................................551
The ICollection<T> Interface .........................................................................................553
Generic Lists ..................................................................................................................554 The IList<T> Interface.......................................................................................................................... 555 The List<T> Collection ......................................................................................................................... 556 The LinkedList<T> Collection............................................................................................................... 575 The SortedList<TKey, TVal> Collection ................................................................................................ 581
Generic Dictionaries.......................................................................................................585 The IDictionary<TKey, TVal> Interface................................................................................................. 586 The KeyValuePair<TKey, TVal> Structure ............................................................................................ 588 The Dictionary<TKey, TVal> Collection ................................................................................................ 589 The SortedDictionary<TKey, TVal> Collection...................................................................................... 593
Generic Sets ..................................................................................................................595 The ISet<T> Interface .......................................................................................................................... 595 The HashSet<T> Collection.................................................................................................................. 597 The SortedSet<T> Collection ............................................................................................................... 599
Generic Queues and Stacks...........................................................................................602 The Queue<T> Collection..................................................................................................................... 602 The Stack<T> Collection ...................................................................................................................... 604
Other Generic Collection Interfaces ...............................................................................606 The IComparer<T> Interface ................................................................................................................ 606 The IEqualityComparer<T> Interface ................................................................................................... 608
Treating Arrays as Collections .......................................................................................609
� CONTENTS
xix
Creating Constrained Collections...................................................................................613 Read-Only Lists ......................................................................................................................................... 613 Other Read-Only Collections...................................................................................................................... 614 Legacy Collections.........................................................................................................617
Summary .......................................................................................................................619
� Chapter 20: Files, Streams, and IO .....................................................................621
Working with Files and Directories................................................................................622 Using the System.IO.Directory Class .................................................................................................... 622 Using the FileInfo and DirectoryInfo Classes ........................................................................................ 630 Using the System.IO.File Class ............................................................................................................. 639 Using the System.IO.Path Class............................................................................................................ 643 Monitoring for Changes ........................................................................................................................ 645
Working with Streams, Readers, and Writers................................................................650 Using Streams ...................................................................................................................................... 650 Using Readers and Writers ................................................................................................................... 666
Summary .......................................................................................................................673
� Chapter 21: Networking & WCF ..........................................................................675
Requesting Data ............................................................................................................675 Using WebClient Members to Configure a Request .............................................................................. 677 Using WebClient Members to Retrieve Data......................................................................................... 679 Using WebClient Events........................................................................................................................ 682
Programming with Sockets ...........................................................................................684 Creating a Simple TCP Client & Server ................................................................................................. 684 Writing a Parallel Server....................................................................................................................... 691
The Windows Communication Foundation ....................................................................693 Creating the WCF Server ...................................................................................................................... 694 Creating the WCF Client........................................................................................................................ 697
� CONTENTS
xx
Other Useful Network Classes .......................................................................................700 Writing a Simple Web Server................................................................................................................ 700 Using Connectionless Networking........................................................................................................ 704 Using the Domain Name System .......................................................................................................... 707
Summary .......................................................................................................................709
� Chapter 22: Time & Dates ...................................................................................711
Measuring Small Amounts of Time................................................................................712
Working with Periods of Time........................................................................................715 Creating and Using TimeSpan Values................................................................................................... 715 Performing Operations on TimeSpan Values ........................................................................................ 719 Formatting TimeSpan Strings............................................................................................................... 720
Working with Particular Dates and Times .....................................................................723 Creating and Using DateTime Values ................................................................................................... 724 Performing Operations on DateTime Values......................................................................................... 727 Formatting DateTime Strings................................................................................................................ 730
Summary .......................................................................................................................733
� Chapter 23: Serialization ....................................................................................735
Using Binary Serialization..............................................................................................736 Serializing Graphs of Objects ............................................................................................................... 739 Serializing Multiple Objects to a Single Stream ................................................................................... 741 Selectively Serializing Fields ................................................................................................................ 744 Using Serialization Callbacks ............................................................................................................... 745 Version Tolerance................................................................................................................................. 748
Using SOAP Serialization ...............................................................................................752 Version Tolerance................................................................................................................................. 754 Serializing Generic Objects................................................................................................................... 755
Using XML Serialization .................................................................................................755 Selectively Serializing Fields ................................................................................................................ 757
� CONTENTS
xxi
Mapping Members to Elements and Attributes .................................................................................... 758 Changing the Name for Attributes and Elements ................................................................................. 759
Using Data Contract Serialization ..................................................................................760 Preparing a Class for Data Contract Serialization................................................................................. 760 Generating Portable XML...................................................................................................................... 761 Generating .NET-specific XML.............................................................................................................. 762 Generating JSON .................................................................................................................................. 764
Summary .......................................................................................................................765
� Chapter 24: Serialization ....................................................................................735
Understanding Single- and Multi-Threaded Execution..................................................768 Getting Started with Tasks ............................................................................................772
Creating a Task..................................................................................................................................... 772 Starting a Task ..................................................................................................................................... 773 Waiting for a Task................................................................................................................................. 774
Getting Results from Tasks............................................................................................776
Passing Parameters to a Task .......................................................................................778 Getting the Status of a Task ..........................................................................................780
Using the Status Properties.................................................................................................................. 782 Canceling Tasks.............................................................................................................782
Checking and Throwing in a Single Statement .................................................................................... 784 Cancelling Multiple Tasks..................................................................................................................... 786
Handling Task Exceptions..............................................................................................787 Handling an Exception in a Task Body.................................................................................................. 787 Handling an Exception from a Trigger Method ..................................................................................... 789 Dealing with Exceptions using Task Properties.................................................................................... 792 Using a Custom Exception Escalation Policy ........................................................................................ 794
Chaining Tasks Together ...............................................................................................796 Creating a Simple Continuation ............................................................................................................ 796
� CONTENTS
xxii
Getting Details of the Antecedent......................................................................................................... 797 Providing a Continuation Result ........................................................................................................... 798 Creating Chains of Continuations ......................................................................................................... 800 Creating Selective Continuations.......................................................................................................... 801
Sharing Data between Tasks.........................................................................................803 Understanding a Critical Region ........................................................................................................... 806 Creating a Critical Region ..................................................................................................................... 806 Avoiding Synchronization ..................................................................................................................... 808
Using Concurrent Collections.........................................................................................809 Summary .......................................................................................................................813
� Chapter 25: Asynchronous Methods and Parallel Loops ....................................815
Using Asynchronous Methods .......................................................................................816 Using Pre-Built Asynchronous Methods ............................................................................................... 816 Asynchronously Calling Any Method .................................................................................................... 819 Waiting for an Asynchronous Method to Complete .............................................................................. 820 Mixing Asynchronous Methods and Tasks ........................................................................................... 823
Using Parallel Loops ......................................................................................................824 Creating a Parallel ForEach Loop.......................................................................................................... 824 Creating a Parallel For Loop ................................................................................................................. 826 Breaking and Stopping Parallel Loops.................................................................................................. 827
Summary .......................................................................................................................831
� Chapter 26: Other Useful Features and Classes..................................................833
Converting Between Types ............................................................................................834
Returning Multiple Results from Methods Using Tuples................................................836 Aliasing Generic Types ..................................................................................................839
Using Nullable Types .....................................................................................................841 Using the Null-Coalescing Operator ..................................................................................................... 842
� CONTENTS
xxiii
Working with the Console..............................................................................................843 Reading from and Writing to the Console............................................................................................. 843 Making the Console Beep..................................................................................................................... 846 Modifying the Appearance of the Console............................................................................................ 846
Generating Random Numbers........................................................................................848 Converting Strings to and from Bytes............................................................................849
Getting Environment Information...................................................................................850 Performing Math Operations..........................................................................................852
Using Conditional Compilation.......................................................................................853 Using Visual Studio to Define Symbols................................................................................................. 855 Conditionally Compiling Methods ......................................................................................................... 856
Checking Network Connectivity.....................................................................................857 Listening for Connectivity Changes ...................................................................................................... 859
Summary .......................................................................................................................860
PART 4 � � � Data and Databases ......................................................................861 � Chapter 27: LINQ to Objects ................................................................................863
Performing a Simple LINQ Query ...................................................................................864 Understanding LINQ to Objects Data Sources ...................................................................................... 866 Understanding Query Results ............................................................................................................... 867 Understanding Query Types ................................................................................................................. 870
Performing LINQ Operations ..........................................................................................874 Filtering Data ........................................................................................................................................ 874 Projecting Data ..................................................................................................................................... 876 Ordering Data ....................................................................................................................................... 881 Grouping Data....................................................................................................................................... 885
Using Method Syntax.....................................................................................................891 Understanding Deferred Execution................................................................................895
Reusing Queries ................................................................................................................................... 895
� CONTENTS
xxiv
Referring to Variables........................................................................................................................... 896 Forcing Immediate Execution ............................................................................................................... 897
Converting Query Results ..............................................................................................899 Using Legacy Collections as LINQ Data Sources ...........................................................902
Explicitly Specifying the Range Variable Type...................................................................................... 902 Using Cast and OfType Extension Methods .......................................................................................... 903
Performing Advanced LINQ Operations..........................................................................905 Aggregating Data.................................................................................................................................. 905 Joining Data.......................................................................................................................................... 907 Creating Combinations of Data............................................................................................................. 910 Creating Additional Range Variables .................................................................................................... 911
Summary .......................................................................................................................913
� Chapter 28: Parallel LINQ....................................................................................915
Performing a Parallel LINQ Query ..................................................................................915 Understanding PLINQ Result Ordering ...........................................................................918
Preserving Order in a PLINQ query ....................................................................................................... 920 Forcing Parallel Execution .............................................................................................921 Performing Queries without Results ..............................................................................922
Summary .......................................................................................................................923
� Chapter 29: LINQ to XML.....................................................................................925
Using the LINQ XML Classes..........................................................................................926 Creating XML Declaratively .................................................................................................................. 926 Populating an XElement or XDocument with an IEnumerable .............................................................. 933 Reading and Writing XML Files............................................................................................................. 934 Processing XML Declaratively .............................................................................................................. 936 Modifying XML...................................................................................................................................... 940
Using LINQ to XML Queries ............................................................................................944 Querying XML for Data.......................................................................................................................... 945
� CONTENTS
xxv
Creating XML from LINQ Queries .......................................................................................................... 946 Create Objects from XML...................................................................................................................... 949 Modifying and Transforming XML Data ................................................................................................ 950 Sorting XML .......................................................................................................................................... 957 Grouping XML ....................................................................................................................................... 958 Using Parallel LINQ to Process XML ..................................................................................................... 960
Summary .......................................................................................................................963
� Chapter 30: LINQ to Entities................................................................................965
Getting Ready ................................................................................................................966 Preparing the Database ........................................................................................................................ 967 Creating the Model ............................................................................................................................... 967
Using LINQ to Entities ....................................................................................................973 Using the Data Model Context .............................................................................................................. 974 Using Table Properties and Row Objects.............................................................................................. 975 Understanding the IQueryable<T> Interface ........................................................................................ 977 Enumerating the Results ...................................................................................................................... 978
Navigating Using Foreign Key Relationships .................................................................979 Querying Using Navigation Properties .................................................................................................. 982 Using Navigation Data Efficiently ......................................................................................................... 983
Performing Common Database Operations....................................................................985 Querying Data....................................................................................................................................... 985 Inserting Data into the Database .......................................................................................................... 993 Updating Data in the Database............................................................................................................. 996 Deleting Data ........................................................................................................................................ 998
Enabling Concurrency Checking ....................................................................................999 Summary .....................................................................................................................1000
� Chapter 31: LINQ to DataSet .............................................................................1001
Connecting to and Querying a Database......................................................................1002
� CONTENTS
xxvi
Setting Up the Database..................................................................................................................... 1002 Creating a Connection to the Database .............................................................................................. 1004 Executing a SQL Query ....................................................................................................................... 1010
Understanding the DataSet Class ................................................................................1012 Enumerating Results with DataTable and DataRow Objects .............................................................. 1014
Querying DataSets with LINQ.......................................................................................1016 Perform Joins on a DataSet................................................................................................................ 1018 Comparing Data.................................................................................................................................. 1021
Performing Database Operations Using Cached Data..................................................1024 Inserting Data ..................................................................................................................................... 1024 Modifying Data ................................................................................................................................... 1027 Deleting Data ...................................................................................................................................... 1029
Summary .....................................................................................................................1030
PART 5 � � � User Interfaces............................................................................1031 � Chapter 32: Windows Forms.............................................................................1033
Building a Stand-Alone Window Forms Program.........................................................1033 Creating the Project............................................................................................................................ 1034 Adding the Controls ............................................................................................................................ 1036 Setting the Control Properties ............................................................................................................ 1038 Adding the MenuStrip and StatusStrip ............................................................................................... 1041 Setting the Control Names.................................................................................................................. 1043 Setting the Tab Order ......................................................................................................................... 1045 Wiring the Controls ............................................................................................................................. 1045 Setting the Icon .................................................................................................................................. 1053 Testing the Program ........................................................................................................................... 1053
Using Windows Forms Data Binding............................................................................1053 Creating the Project and Creating the Data Model ............................................................................. 1053 Creating and Using the Object Data Source ....................................................................................... 1054
� CONTENTS
xxvii
Formatting the Grid Control ................................................................................................................ 1056 Loading the Data ................................................................................................................................ 1058 Wiring the Save Button....................................................................................................................... 1058 Testing the Program ........................................................................................................................... 1059 Two Program Variations ..................................................................................................................... 1060
Windows 7 UI Integration.............................................................................................1063 Using Aero Glass................................................................................................................................. 1063
Summary .....................................................................................................................1066
� Chapter 33: Windows Presentation Foundation................................................1069
Building a Stand-Alone WPF Program .........................................................................1069 Creating the Project............................................................................................................................ 1069 Adding the Controls ............................................................................................................................ 1072 Setting the Control Properties ............................................................................................................ 1074 Adding the StatusBar Item.................................................................................................................. 1076 Adding the Menu Item ........................................................................................................................ 1077 Setting the Tab Order ......................................................................................................................... 1077 Wiring the Controls ............................................................................................................................. 1078 Managing the Focus ........................................................................................................................... 1081 Setting the Program Icon and Window Name..................................................................................... 1082 Testing the Program ........................................................................................................................... 1082
Using WPF Data Binding ..............................................................................................1083 Formatting the DataGrid Control......................................................................................................... 1084 Loading the Data ................................................................................................................................ 1085 Wiring the Button................................................................................................................................ 1085 Testing the Program ........................................................................................................................... 1086
Using WPF-Specific Features ......................................................................................1086 Using WPF Animations........................................................................................................................ 1086 Using WPF Commands ....................................................................................................................... 1090
� CONTENTS
xxviii
Summary .....................................................................................................................1098
� Chapter 34: ASP.NET.........................................................................................1099
Building a Web Forms Program...................................................................................1099 Creating the Project............................................................................................................................ 1099 Adding the Controls ............................................................................................................................ 1102 Setting the Control Properties ............................................................................................................ 1104 Setting the Tab Order ......................................................................................................................... 1106 Wiring the Button Control ................................................................................................................... 1107 Setting the Focus................................................................................................................................ 1107 Testing the Program ........................................................................................................................... 1108
Using Web Forms Data Binding ...................................................................................1108 Create the Project and the Entity Data Model..................................................................................... 1109 Adding the Web Form ......................................................................................................................... 1109 Creating the Web Forms Data Source ................................................................................................ 1109 Adding the GridView Control............................................................................................................... 1111 Testing the Program ........................................................................................................................... 1112
Using ASP.NET Dynamic Data......................................................................................1113 Creating the Project............................................................................................................................ 1113 Creating the Entity Data Model........................................................................................................... 1114 Registering the Data Model ................................................................................................................ 1114 Testing the Program ........................................................................................................................... 1114 Customizing a Dynamic Data Application........................................................................................... 1116
Summary .....................................................................................................................1124
� Chapter 35: Silverlight ......................................................................................1125
Creating the Swimming Calculator ..............................................................................1126 Creating the Project............................................................................................................................ 1126 Defining the Layout............................................................................................................................. 1128 Adding the TextBox Controls .............................................................................................................. 1131
� CONTENTS
xxix
Adding the Label Controls .................................................................................................................. 1132 Adding the TextBlock Control ............................................................................................................. 1133 Adding the Button Control .................................................................................................................. 1134 Adjusting the Layout........................................................................................................................... 1135 Wiring the Button................................................................................................................................ 1136 Adding a Child Window....................................................................................................................... 1137
Using a WCF RIA Service .............................................................................................1140 Creating the Project............................................................................................................................ 1141 Creating the Data Model ..................................................................................................................... 1141 Creating the Domain Service Class .................................................................................................... 1142 Creating the Silverlight Client............................................................................................................. 1144 Testing the Application....................................................................................................................... 1149
Using Silverlight Out-of-Browser Support ...................................................................1149 Configuring the Out-of-Browser Support............................................................................................ 1150
Using a Silverlight Program Out-of-Browser ...............................................................1152 Making Installation Part of the Interface ............................................................................................ 1153 Using Other Out-of-Browser Features ................................................................................................ 1157
Summary .....................................................................................................................1157
PART 6 � � � Advanced Topics.........................................................................1159 � Chapter 36: Windows Integration .....................................................................1161
Using the Windows Event Log .....................................................................................1161 Reading an Event Log......................................................................................................................... 1162 Writing to an Event Log ...................................................................................................................... 1165
Using Elevated Privileges ............................................................................................1167 Creating a Windows Service........................................................................................1169
Creating the Service Class.................................................................................................................. 1170 Adding the Service Functionality ........................................................................................................ 1172 Adding the Service Installer................................................................................................................ 1174
� CONTENTS
xxx
Add the MSI Installer .......................................................................................................................... 1175 Installing the Service .......................................................................................................................... 1177 Creating the Client .............................................................................................................................. 1179
Using the Windows Registry ........................................................................................1179 Searching the Registry ....................................................................................................................... 1179 Reading and Modifying the Registry................................................................................................... 1182
Summary .....................................................................................................................1183
� Chapter 37: Cryptography and Security............................................................1185
Encrypting and Decrypting Data ..................................................................................1186 Creating and Using Encryption Keys................................................................................................... 1186 Encrypting Data .................................................................................................................................. 1189 Decrypting Data.................................................................................................................................. 1190 Using the Windows Data Protection API ............................................................................................. 1191
Using Hash Codes........................................................................................................1193 Generating a Hash Code ..................................................................................................................... 1194 Verifying a Hash Code......................................................................................................................... 1196
Generating Secure Random Numbers .........................................................................1197 Working Securely with Strings ....................................................................................1198
Summary .....................................................................................................................1200
� Chapter 38: Testing and Debugging..................................................................1201
Using the Debug and Trace Classes ............................................................................1202 Using the Debug Class........................................................................................................................ 1202 Using the Trace Class ......................................................................................................................... 1212
Using Static Code Analysis ..........................................................................................1214 Selecting the Code Analysis Rules ..................................................................................................... 1214 Performing Static Analysis ................................................................................................................. 1215 Dealing with a Rule Violation.............................................................................................................. 1216
� CONTENTS
xxxi
Using Code Contracts ..................................................................................................1221 Installing and Enabling Code Contract Support .................................................................................. 1221 Writing Code Contracts....................................................................................................................... 1222 Using the Static Checker .................................................................................................................... 1226 Using the Runtime Checker ................................................................................................................ 1229
Summary .....................................................................................................................1230
� Index .................................................................................................................1231
xxxii
About the Author
� Adam Freeman is an experienced IT professional who has held senior positions in a range of companies, most recently as chief technology officer and chief operating officer of a global bank. Now retired, he spends his time writing and training for his first competitive triathlon. This is his tenth book on programming and his eighth on .NET.
xxxiii
About the Technical Reviewer
� Damien Foggon is a developer, writer, and technical reviewer in cutting-edge technologies and has contributed to more than 50 books on .NET, C#, Visual Basic and ASP.NET. He is the co-founder of the Newcastle based user-group NEBytes (online at http://www.nebytes.net), is a multiple MCPD in .NET 2.0 and .NET 3.5 and can be found online at http://blog.littlepond.co.uk.
� INTRODUCTION
xxxiv
Acknowledgments
I would like to thank everyone at Apress for working so hard to bring this book to print. In particular, I would like to thank Anne Collett and Kelly Moritz for keeping things on track and Ewan Buckingham for commissioning and editing the book. I would also like to thank Kim Wimpsett and Damien Foggon, whose respective efforts as copy editor and technical reviewer made this book far better than it would have been without them.