Tải bản đầy đủ

1321 visual c 2010 recipes

  CYAN
  MAGENTA

  YELLOW
  BLACK

BOOKS FOR PROFESSIONALS BY PROFESSIONALS ®

Dear Reader,

WPF Recipes in C# 2010
Professional C# 2005
C# Programmers Cookbook
Programming .NET Security
Microsoft .NET XML Web
Services Step by Step
C# for Java Developers

• Application domains, reflection, and metadata
• Tasks, Threads, processes, and synchronization
• Files, directories, and I/O

• LINQ
• XML processing
• Windows Forms and Windows Presentation Foundation applications
• Database access using ADO.NET
• Networking and remoting
• Security and cryptography
• Unmanaged code interoperability
• Commonly used interfaces and patterns
• Windows integration

Programming .NET Security

This book shows you how to solve the types of development problems you will
face every day. It contains hundreds of recipes, presented in a concise problem/
solution format so that you can find the answer to your question fast and get
on with your development. Each recipe provides working code that demonstrates the solution, as well as additional information to give you a more in-depth
understanding of the classes and techniques used to solve the problem.

Microsoft .NET XML Web
Services Step by Step

Allen Jones & Adam Freeman

Adam Freeman, author of

Companion eBook

THE APRESS ROADMAP
Pro C# 2010 and
the .NET 4.0 Platform

Pro LINQ
in C# 2010

Visual C#
2010 Recipes

Pro WPF in
C# 2010


Accelerated
C# 2010
See last page for details
on $10 eBook version

www.apress.com

ISBN 978-1-4302-2525-6
5 54 9 9

US $54.99

Jones
Freeman

SOURCE CODE ONLINE

Recipes

C# for Java Developers

C# 2010

Allen Jones, author of

Whatever your situation, whatever the circumstance, one thing is certain: you
will always know what you want to do, but not necessarily how best to do it. C#
2010 development is no exception, and this book is an invaluable companion
when you are tackling a wide range of C# subjects:

Companion
eBook Available

Visual

Visual C# 2010 Recipes:
A Problem-Solution Approach

THE EXPERT’S VOICE ® IN C#

Visual

C#
2010
Recipes
A Problem-Solution Approach
Quick answers and ready-to-use code to get
you more productive in C# 2010 development

Allen Jones and Adam Freeman

Shelve in:
.NET
User level:
Intermediate–Advanced

9 781430 225256

www.it-ebooks.info

this print for content only—size & color not accurate

7.5 x 9.25 spine = 1.90625" 1016 page count


Visual C# 2010 Recipes
A Problem-Solution Approach

■■■
Allen Jones and Adam Freeman

www.it-ebooks.info


Visual C# 2010 Recipes: A Problem-Solution Approach
Copyright © 2010 by Allen Jones and 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-13 (pbk): 978-1-4302-2525-6
ISBN-13 (electronic): 978-1-4302-2526-3
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of
the trademark owner, with no intention of infringement of the trademark.
Publisher and President: Paul Manning
Lead Editor: Jonathan Hassell
Technical Reviewer: Mark Collins
Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell,
Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes,
Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft,
Matt Wade, Tom Welsh
Coordinating Editor: Anne Collett
Copy Editor: Damon Larson
Production Support: Patrick Cunningham
Indexer: Julie Grady
Artist: April Milne
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor,
New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-ny@springer-sbm.com, or
visit www.springeronline.com.
For information on translations, please e-mail rights@apress.com, or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use.
eBook versions and licenses are also available for most titles. For more information, reference our
Special Bulk Sales–eBook Licensing web page at www.apress.com/info/bulksales.
The information in this book is distributed on an “as is” basis, without warranty. Although every
precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have
any liability to any person or entity with respect to any loss or damage caused or alleged to be caused
directly or indirectly by the information contained in this work.
The source code for this book is available to readers at www.apress.com.

www.it-ebooks.info


For my lovely wife Lena, and our three wonderful girls, Anya, Alexia, and Angelina. I love you all.
—Allen Jones
For my wife, Jacqui Griffyth, who I love a great deal.
—Adam Freeman

www.it-ebooks.info


Contents at a Glance
About the Author ...................................................................................................... xx
About the Technical Reviewers ............................................................................... xxi
Acknowledgments .................................................................................................. xxii
Introduction ........................................................................................................... xxiii
■Chapter 1: Application Development ....................................................................... 1
■Chapter 2: Data Manipulation ................................................................................ 53
■Chapter 3: Application Domains, Reflection, and Metadata ................................ 103
■Chapter 4: Threads, Processes, and Synchronization ......................................... 149
■Chapter 5: Files, Directories, and I/O................................................................... 205
■Chapter 6: XML Processing ................................................................................. 261
■Chapter 7: Windows Forms.................................................................................. 307
■Chapter 8: Graphics, Multimedia, and Printing .................................................. 369
■Chapter 9: Database Access ................................................................................ 423
■Chapter 10: Networking....................................................................................... 479
■Chapter 11: Security and Cryptography .............................................................. 543
■Chapter 12: Unmanaged Code Interoperability.................................................... 597

iv

www.it-ebooks.info


■ CONTENTS AT A GLANCE

■Chapter 13: Commonly Used Interfaces and Patterns ........................................ 619
■Chapter 14: Windows Integration ........................................................................ 683
■Chapter 15: Parallel Programming ...................................................................... 729
■Chapter 16: Using LINQ ........................................................................................ 749
■Chapter 17: Windows Presentation Foundation ................................................. 789
Index ....................................................................................................................... 905

v

www.it-ebooks.info


Contents
About the Author ...................................................................................................... xx
About the Technical Reviewers ............................................................................... xxi
Acknowledgments .................................................................................................. xxii
Introduction ........................................................................................................... xxiii
■Chapter 1: Application Development ....................................................................... 1
1-1. Create a Console Application from the Command Line .............................................. 2
1-2. Create a Windows-Based Application from the Command Line ................................ 5
1-3. Create and Use a Code Module .................................................................................. 9
1-4. Create and Use a Code Library from the Command Line ......................................... 11
1-5. Access Command-Line Arguments .......................................................................... 12
1-6. Include Code Selectively at Build Time .................................................................... 14
1-7. Access a Program Element That Has the Same Name As a Keyword ...................... 18
1-8. Create and Manage Strongly Named Key Pairs ........................................................ 19
1-9. Give an Assembly a Strong Name ............................................................................ 21
1-10. Verify That a Strongly Named Assembly Has Not Been Modified ........................... 23
1-11. Delay-Sign an Assembly ........................................................................................ 24
1-12. Sign an Assembly with an Authenticode Digital Signature .................................... 26
1-13. Create and Trust a Test Software Publisher Certificate ......................................... 28
1-14. Manage the Global Assembly Cache ...................................................................... 29
1-15. Prevent People from Decompiling Your Code ......................................................... 30
vi

www.it-ebooks.info


■ CONTENTS

1-16. Manipulate the Appearance of the Console ........................................................... 31
1-17. Create a Static Class .............................................................................................. 34
1-18. Create an Anonymous Type .................................................................................... 35
1-19. Create an ExpandoObject Dynamic Type................................................................ 37
1-20. Define an Automatically Implemented Property ..................................................... 39
1-21. Overload an Operator ............................................................................................. 41
1-22. Define a Conversion Operator ................................................................................ 44
1-23. Handle an Event with an Anonymous Function ...................................................... 46
1-24. Implement a Custom Indexer ................................................................................. 48
■Chapter 2: Data Manipulation ................................................................................ 53
2-1. Manipulate the Contents of a String Efficiently ........................................................ 54
2-2. Encode a String Using Alternate Character Encoding .............................................. 56
2-3. Convert Basic Value Types to Byte Arrays ................................................................ 59
2-4. Base64 Encode Binary Data ..................................................................................... 61
2-5. Validate Input Using Regular Expressions ................................................................ 65
2-6. Use Compiled Regular Expressions .......................................................................... 70
2-7. Create Dates and Times from Strings ...................................................................... 72
2-8. Add, Subtract, and Compare Dates and Times......................................................... 74
2-9. Sort an Array or a Collection .................................................................................... 77
2-10. Copy a Collection to an Array ................................................................................. 79
2-11. Use a Strongly Typed Collection ............................................................................. 81
2-12. Create a Generic Type ............................................................................................ 83
2-13. Store a Serializable Object to a File ....................................................................... 87
2-14. Serialize an Object Using JSON .............................................................................. 90
2-15. Read User Input from the Console.......................................................................... 93

vii

www.it-ebooks.info


■ CONTENTS

2-16. Using Large Integer Values .................................................................................... 96
2-17. Select Collection or Array Elements ....................................................................... 97
2-18. Remove Duplicate Items from an Array or Collection........................................... 100
■Chapter 3: Application Domains, Reflection, and Metadata ................................ 103
3-1. Create an Application Domain ................................................................................ 104
3-2. Create Types That Can Be Passed Across Application Domain Boundaries ........... 106
3-3. Avoid Loading Unnecessary Assemblies into Application Domains ....................... 109
3-4. Create a Type That Cannot Cross Application Domain Boundaries ........................ 111
3-5. Load an Assembly into the Current Application Domain ........................................ 111
3-6. Execute an Assembly in a Different Application Domain........................................ 114
3-7. Instantiate a Type in a Different Application Domain ............................................. 116
3-8. Pass Data Between Application Domains............................................................... 121
3-9. Unload Assemblies and Application Domains ........................................................ 124
3-10. Retrieve Type Information .................................................................................... 125
3-11. Test an Object’s Type ........................................................................................... 127
3-12. Instantiate an Object Using Reflection ................................................................. 129
3-13. Create a Custom Attribute .................................................................................... 133
3-14. Inspect the Attributes of a Program Element Using Reflection ............................ 136
3-15. Programmatically Discover the Members of a Type............................................. 137
3-16. Invoke a Type Member Using Reflection .............................................................. 140
3-17. Dynamically Invoke a Type Member .................................................................... 142
3-18. Create a Custom Dynamic Type ........................................................................... 143
■Chapter 4: Threads, Processes, and Synchronization ......................................... 149
4-1. Execute a Method Using the Thread Pool ............................................................... 151
4-2. Execute a Method Asynchronously ........................................................................ 154
viii

www.it-ebooks.info


■ CONTENTS

4-3. Execute a Method Periodically ............................................................................... 163
4-4. Execute a Method at a Specific Time ..................................................................... 166
4-5. Execute a Method by Signaling a WaitHandle Object ............................................. 167
4-6. Execute a Method Using a New Thread ................................................................. 169
4-7. Synchronize the Execution of Multiple Threads Using a Monitor ........................... 172
4-8. Synchronize the Execution of Multiple Threads Using an Event ............................ 178
4-9. Synchronize the Execution of Multiple Threads Using a Mutex ............................. 182
4-10. Synchronize the Execution of Multiple Threads Using a Semaphore ................... 185
4-11. Synchronize Access to a Shared Data Value ........................................................ 187
4-12. Know When a Thread Finishes ............................................................................. 190
4-13. Terminate the Execution of a Thread ................................................................... 191
4-14. Create a Thread-Safe Collection Instance ............................................................ 193
4-15. Start a New Process ............................................................................................. 195
4-16. Terminate a Process ............................................................................................ 199
4-17. Ensure That Only One Instance of an Application Can Execute Concurrently ...... 201
■Chapter 5: Files, Directories, and I/O................................................................... 205
5-1. Retrieve Information About a File, Directory, or Drive ............................................ 206
5-2. Set File and Directory Attributes ............................................................................ 211
5-3. Copy, Move, or Delete a File or Directory ............................................................... 213
5-4. Calculate the Size of a Directory ............................................................................ 216
5-5. Retrieve Version Information for a File ................................................................... 217
5-6. Show a Just-in-Time Directory Tree in the TreeView Control ................................ 219
5-7. Read and Write a Text File ..................................................................................... 222
5-8. Read and Write a Binary File .................................................................................. 224
5-9. Read a File Asynchronously ................................................................................... 226

ix

www.it-ebooks.info


■ CONTENTS

5-10. Find Files That Match a Wildcard Expression....................................................... 230
5-11. Test Two Files for Equality ................................................................................... 231
5-12. Manipulate Strings Representing File Names ...................................................... 233
5-13. Determine If a Path Is a Directory or a File .......................................................... 235
5-14. Work with Relative Paths ..................................................................................... 236
5-15. Create a Temporary File ....................................................................................... 238
5-16. Get the Total Free Space on a Drive ..................................................................... 239
5-17. Show the Common File Dialog Boxes ................................................................... 241
5-18. Use an Isolated Store ........................................................................................... 243
5-19. Monitor the File System for Changes ................................................................... 246
5-20. Access a COM Port ............................................................................................... 248
5-21. Get a Random File Name ...................................................................................... 249
5-22. Manipulate the Access Control List of a File or Directory .................................... 250
5-23. Compress Data ..................................................................................................... 253
5-24. Log Data to a File ................................................................................................. 254
5-25. Process a Log File ................................................................................................ 256
5-26. Communicate Between Processes ....................................................................... 257
■Chapter 6: XML Processing ................................................................................. 261
6-1. Show the Structure of an XML Document in a TreeView ....................................... 261
6-2. Insert Nodes in an XML Document ......................................................................... 266
6-3. Quickly Append Nodes in an XML Document ......................................................... 268
6-4. Find Specific Elements by Name ............................................................................ 271
6-5. Get XML Nodes in a Specific XML Namespace....................................................... 272
6-6. Find Elements with an XPath Search ..................................................................... 274
6-7. Read and Write XML Without Loading an Entire Document into Memory .............. 278

x

www.it-ebooks.info


■ CONTENTS

6-8. Validate an XML Document Against a Schema ...................................................... 281
6-9. Use XML Serialization with Custom Objects ........................................................... 286
6-10. Create a Schema for a .NET Class ........................................................................ 290
6-11. Generate a Class from a Schema ......................................................................... 291
6-12. Perform an XSL Transform ................................................................................... 292
6-13. Load XML with LINQ ............................................................................................. 296
6-14. Create a New XML Tree with LINQ ....................................................................... 298
6-15. Query XML with LINQ............................................................................................ 300
6-16. Modify an XML Tree with LINQ ............................................................................. 303
■Chapter 7: Windows Forms.................................................................................. 307
7-1. Add a Control Programmatically............................................................................. 309
7-2. Store Data with a Control ....................................................................................... 311
7-3. Process All the Controls on a Form ........................................................................ 314
7-4. Track the Visible Forms in an Application .............................................................. 315
7-5. Find All MDI Child Forms ........................................................................................ 319
7-6. Save Configuration Settings for a Form ................................................................. 322
7-7. Force a List Box to Scroll to the Most Recently Added Item................................... 325
7-8. Restrict a Text Box to Accept Only Specific Input .................................................. 326
7-9. Use an Autocomplete Combo Box or Text Box ....................................................... 329
7-10. Sort a List View by Any Column............................................................................ 332
7-11. Lay Out Controls Automatically ............................................................................ 335
7-12. Use Part of a Main Menu for a Context Menu ....................................................... 336
7-13. Make a Multilingual Form..................................................................................... 338
7-14. Create a Form That Cannot Be Moved .................................................................. 341
7-15. Make a Borderless Form Movable ........................................................................ 343

xi

www.it-ebooks.info


■ CONTENTS

7-16. Create an Animated System Tray Icon ................................................................. 346
7-17. Validate an Input Control ...................................................................................... 348
7-18. Use a Drag-and-Drop Operation ........................................................................... 350
7-19. Update the User Interface in a Multithreaded Application ................................... 354
7-20. Display a Web Page in a Windows-Based Application ......................................... 356
7-21. Display WPF Windows in a Windows Forms Application ...................................... 360
7-22. Display WPF Controls in Windows Forms ............................................................. 363
■Chapter 8: Graphics, Multimedia, and Printing .................................................. 369
8-1. Find All Installed Fonts ........................................................................................... 370
8-2. Perform Hit Testing with Shapes............................................................................ 372
8-3. Create an Irregularly Shaped Control ..................................................................... 376
8-4. Create a Movable Sprite ......................................................................................... 379
8-5. Create a Scrollable Image ...................................................................................... 383
8-6. Perform a Screen Capture ...................................................................................... 385
8-7. Use Double Buffering to Increase Redraw Speed .................................................. 386
8-8. Show a Thumbnail for an Image ............................................................................ 389
8-9. Play a Simple Beep or System Sound .................................................................... 391
8-10. Play a WAV File ..................................................................................................... 392
8-11. Play a Sound File .................................................................................................. 393
8-12. Play a Video .......................................................................................................... 395
8-13. Retrieve Information About Installed Printers ...................................................... 398
8-14. Print a Simple Document...................................................................................... 401
8-15. Print a Multipage Document ................................................................................. 404
8-16. Print Wrapped Text ............................................................................................... 408
8-17. Show a Dynamic Print Preview ............................................................................ 410

xii

www.it-ebooks.info


■ CONTENTS

8-18. Manage Print Jobs ............................................................................................... 412
8-19. Perform Text-to-Speech ....................................................................................... 417
8-20. Recognize Characters in an Image (OCR) ............................................................. 419
■Chapter 9: Database Access ................................................................................ 423
9-1. Connect to a Database ........................................................................................... 425
9-2. Use Connection Pooling .......................................................................................... 428
9-3. Create a Database Connection String Programmatically ....................................... 431
9-4. Store a Database Connection String Securely........................................................ 433
9-5. Execute a SQL Command or Stored Procedure ...................................................... 436
9-6. Use Parameters in a SQL Command or Stored Procedure ..................................... 441
9-7. Process the Results of a SQL Query Using a Data Reader ..................................... 445
9-8. Obtain an XML Document from a SQL Server Query .............................................. 448
9-9. Perform Asynchronous Database Operations Against SQL Server ......................... 452
9-10. Write Database-Independent Code ...................................................................... 456
9-11. Discover All Instances of SQL Server on Your Network........................................ 460
9-12. Create an In-Memory Cache................................................................................. 462
9-13. Create a DataSet Programmatically ..................................................................... 466
9-14. Perform a LINQ Query........................................................................................... 468
9-15. Perform a LINQ Query with Entity Types .............................................................. 471
9-16. Compare LINQ DataSet Results ............................................................................ 473
■Chapter 10: Networking....................................................................................... 479
10-1. Obtain Information About the Local Network Interface ........................................ 480
10-2. Detect Changes in Network Connectivity ............................................................. 484
10-3. Download Data over HTTP or FTP ......................................................................... 486
10-4. Download a File and Process It Using a Stream ................................................... 490
xiii

www.it-ebooks.info


■ CONTENTS

10-5. Respond to HTTP Requests from Within Your Application.................................... 492
10-6. Get an HTML Page from a Site That Requires Authentication .............................. 497
10-7. Send E-mail Using SMTP ...................................................................................... 499
10-8. Resolve a Host Name to an IP Address ................................................................ 504
10-9. Ping an IP Address ............................................................................................... 507
10-10. Communicate Using TCP .................................................................................... 510
10-11. Create a Multithreaded TCP Server That Supports Asynchronous
Communications ............................................................................................................ 515
10-12. Communicate Using UDP.................................................................................... 523
10-13. Create a SOAP-Based Web Service .................................................................... 526
10-14. Call a WCF Service Using a Dynamically Generated Service Proxy .................... 532
10-15. Process the Content of an Atom or RSS Feed .................................................... 534
10-16. Manipulate URIs ................................................................................................. 538
■Chapter 11: Security and Cryptography .............................................................. 543
11-1. Allow Partially Trusted Code to Use Your Strongly Named Assembly .................. 544
11-2. Disable Code Access Security .............................................................................. 547
11-3. Disable Execution Permission Checks ................................................................. 548
11-4. Ensure the Runtime Grants Specific Permissions to Your Assembly ................... 549
11-5. Limit the Permissions Granted to Your Assembly ................................................ 552
11-6. View the Permissions Required by an Assembly ................................................. 554
11-7. Determine at Runtime If Your Code Has a Specific Permission ........................... 558
11-8. Restrict Who Can Extend Your Classes and Override Class Members ................. 559
11-9. Inspect an Assembly’s Evidence .......................................................................... 562
11-10. Determine If the Current User Is a Member of a Specific Windows Group......... 564
11-11. Restrict Which Users Can Execute Your Code .................................................... 568
11-12. Impersonate a Windows User............................................................................. 572
xiv

www.it-ebooks.info


■ CONTENTS

11-13. Create a Cryptographically Random Number ..................................................... 575
11-14. Calculate the Hash Code of a Password ............................................................. 577
11-15. Calculate the Hash Code of a File....................................................................... 581
11-16. Verify a Hash Code ............................................................................................. 583
11-17. Ensure Data Integrity Using a Keyed Hash Code ................................................ 586
11-18. Work with Security-Sensitive Strings in Memory............................................... 589
11-19. Encrypt and Decrypt Data Using the Data Protection API ................................... 592
■Chapter 12: Unmanaged Code Interoperability.................................................... 597
12-1. Call a Function in an Unmanaged DLL.................................................................. 597
12-2. Get the Handle for a Control, Window, or File ...................................................... 601
12-3. Call an Unmanaged Function That Uses a Structure ............................................ 603
12-4. Call an Unmanaged Function That Uses a Callback ............................................. 606
12-5. Retrieve Unmanaged Error Information ................................................................ 608
12-6. Use a COM Component in a .NET Client ............................................................... 610
12-7. Release a COM Component Quickly ..................................................................... 613
12-8. Use Optional Parameters ...................................................................................... 614
12-9. Use an ActiveX Control in a .NET Client ................................................................ 615
12-10. Expose a .NET Component Through COM ........................................................... 616
■Chapter 13: Commonly Used Interfaces and Patterns ........................................ 619
13-1. Implement a Custom Serializable Type ................................................................ 620
13-2. Implement a Cloneable Type ................................................................................ 626
13-3. Implement a Comparable Type ............................................................................ 631
13-4. Implement an Enumerable Collection .................................................................. 636
13-5. Implement an Enumerable Type Using a Custom Iterator .................................... 640
13-6. Implement a Disposable Class ............................................................................. 647
xv

www.it-ebooks.info


■ CONTENTS

13-7. Implement a Formattable Type ............................................................................ 651
13-8. Implement a Custom Exception Class .................................................................. 655
13-9. Implement a Custom Event Argument .................................................................. 659
13-10. Implement the Singleton Pattern........................................................................ 661
13-11. Implement the Observer Pattern ........................................................................ 663
13-12. Implement a Parallel Producer-Consumer Pattern............................................. 669
13-13. Perform Lazy Object Initialization ....................................................................... 671
13-14. Use Optional Parameters .................................................................................... 673
13-15. Add a Method to a Type Without Modifying It .................................................... 675
13-16. Call an Object Member Dynamically .................................................................. 677
13-17. Create a Variant Generic Type ............................................................................ 679
■Chapter 14: Windows Integration ........................................................................ 683
14-1. Access Runtime Environment Information ........................................................... 684
14-2. Retrieve the Value of an Environment Variable .................................................... 688
14-3. Write an Event to the Windows Event Log ............................................................ 690
14-4. Read and Write to the Windows Registry ............................................................. 692
14-5. Search the Windows Registry .............................................................................. 695
14-6. Create a Windows Service ................................................................................... 699
14-7. Create a Windows Service Installer...................................................................... 704
14-8. Create a Shortcut on the Desktop or Start Menu ................................................. 706
14-9. Create a Windows 7 Jump List ............................................................................. 709
14-10. Use Windows Search.......................................................................................... 711
14-11. Check Internet Connectivity ............................................................................... 716
14-12. Display a Task Dialog ......................................................................................... 717
14-13. Write Custom Performance Counters ................................................................. 720

xvi

www.it-ebooks.info


■ CONTENTS

14-14. Read Performance Counters .............................................................................. 724
14-15. Obtain Elevated Privileges .................................................................................. 726
■Chapter 15: Parallel Programming ...................................................................... 729
15-1. Perform Simple Parallel Tasks ............................................................................. 729
15-2. Return a Result from a Task ................................................................................. 732
15-3. Wait for Tasks to Complete .................................................................................. 734
15-4. Parallel Process a Collection ................................................................................ 736
15-5. Chain Tasks Together ........................................................................................... 738
15-6. Write a Cooperative Algorithm ............................................................................. 739
15-7. Handle Exceptions in Tasks.................................................................................. 741
15-8. Cancel a Task ....................................................................................................... 743
15-9. Share Data Between Tasks .................................................................................. 745
■Chapter 16: Using LINQ ........................................................................................ 749
16-1. Perform a Simple LINQ Query............................................................................... 749
16-2. Filter Items from a Data Source ........................................................................... 755
16-3. Filter a Data Source by Type ................................................................................ 757
16-4. Filter Ranges of Elements .................................................................................... 759
16-5. Select Multiple Member Values ............................................................................ 760
16-6. Filter and Select from Multiple Data Sources....................................................... 762
16-7. Use Permutations of Data Sources ....................................................................... 765
16-8. Concatenate Data Sources ................................................................................... 767
16-9. Group Result Elements by Attribute ..................................................................... 769
16-10. Sort Query Results.............................................................................................. 774
16-11. Compare Data Sources....................................................................................... 776
16-12. Aggregate Data Sources..................................................................................... 778
xvii

www.it-ebooks.info


■ CONTENTS

16-13. Share Values Within a Query .............................................................................. 780
16-14. Create Custom LINQ Extension Methods ............................................................ 782
16-15. Convert from IEnumerable<> ............................................................................ 784
■Chapter 17: Windows Presentation Foundation ................................................. 789
17-1. Create and Use a Dependency Property ............................................................... 790
17-2. Create and Use an Attached Property .................................................................. 795
17-3. Define Application-Wide Resources ..................................................................... 799
17-4. Debug Data Bindings Using an IValueConverter ................................................... 801
17-5. Debug Bindings Using Attached Properties .......................................................... 803
17-6. Arrange UI Elements in a Horizontal or Vertical Stack ......................................... 805
17-7. Dock UI Elements to the Edges of a Form ............................................................ 807
17-8. Arrange UI Elements in a Grid .............................................................................. 809
17-9. Position UI Elements Using Exact Coordinates ..................................................... 811
17-10. Get Rich Text Input from a User ......................................................................... 813
17-11. Display a Control Rotated ................................................................................... 818
17-12. Create a User Control ......................................................................................... 820
17-13. Support Application Commands in a User Control ............................................. 822
17-14. Create a Lookless Custom Control ..................................................................... 826
17-15. Create a Two-Way Binding ................................................................................. 833
17-16. Bind to a Command ............................................................................................ 836
17-17. Use Data Templates to Display Bound Data ....................................................... 844
17-18. Bind to a Collection with the Master-Detail Pattern ........................................... 848
17-19. Change a Control’s Appearance on Mouseover.................................................. 854
17-20. Change the Appearance of Alternate Items in a List .......................................... 856
17-21. Drag Items from a List and Drop Them on a Canvas .......................................... 858

xviii

www.it-ebooks.info


■ CONTENTS

17-22. Display the Progress of a Long-Running Operation
and Allow the User to Cancel It ...................................................................................... 862
17-23. Draw Two-Dimensional Shapes ......................................................................... 866
17-24. Create Reusable Shapes .................................................................................... 871
17-25. Draw or Fill a Shape Using a Solid Color ............................................................ 873
17-26. Fill a Shape with a Linear or Radial Color Gradient ............................................ 875
17-27. Fill a Shape with an Image ................................................................................. 879
17-28. Fill a Shape with a Pattern or Texture ................................................................ 882
17-29. Animate the Property of a Control ...................................................................... 886
17-30. Animate Several Properties in Parallel ............................................................... 889
17-31. Create a Keyframe-Based Animation ................................................................. 892
17-32. Animate an Object Along a Path ......................................................................... 894
17-33. Play a Media File ................................................................................................ 898
17-34. Query Keyboard State......................................................................................... 902
Index ....................................................................................................................... 905

xix

www.it-ebooks.info


About the Authors
■Allen Jones has a master’s degree in software engineering from Oxford
University and 20 years industry experience covering a wide range of IT
disciplines. He has spent the last ten years leading the development of
innovative commercial software solutions in areas such as security, content
management, trading, portfolio management, strategic planning, and real-time
search. Allen is a partner at QuantumBlack, a design and technology studio that
applies visual analytics to help organizations make faster decisions and smarter
investments, and earn new revenues.

■Adam Freeman is an experienced IT professional who has held senior
positions at a range of companies, most recently as chief technology officer and
chief operating officer of a global bank. He started his career in programming
and still finds it one of the most engaging and interesting ways to spend a day.

xx

www.it-ebooks.info


About the Technical Reviewer
■Mark Collins has developed software for over 25 years, mostly using the
Microsoft stack. He has served many roles, including development manager,
architect, team lead, database administrator, and project manager. He has
extensive experience in retail (point-of-sale and inventory) and customer
relationship management (CRM) solutions. Mark currently serves as a senior
software engineer for a nonprofit organization, providing a custom CRM, mail
processing, and fulfillment system.

xxi

www.it-ebooks.info


Acknowledgments
We would like to thank everyone at Apress for working so hard to bring this book to print. In particular,
we would like to thank Anne Collett and Jonathan Hassell. We would also like to thank Damon Larson
and Mark Collins, whose respective efforts as copy editor and technical reviewer made this book far
better than it would have been without them.
Allen Jones
Adam Freeman

xxii

www.it-ebooks.info


Introduction
Mastering the development of Microsoft .NET Framework applications in C# is less about knowing the
C# language and more about knowing how to use the functionality of the .NET Framework class library
most effectively. Visual C# 2010 Recipes explores the breadth of the .NET Framework class library and
provides specific solutions to common and interesting programming problems. Each solution (or recipe)
is presented in a succinct problem/solution format, and most are accompanied by working code
samples.
Visual C# 2010 Recipes is not intended to teach you how to program, nor to teach you C#. However,
if you have even the most rudimentary experience programming applications built on the .NET
Framework using C#, you will find this book to be an invaluable resource.
Ideally, when you are facing a problem, this book will contain a recipe that provides the solution, or
at least it will point you in the right direction. Even if you just want to broaden your knowledge of the
.NET Framework class library, Visual C# 2010 Recipes is the perfect resource to assist you.
However, you cannot become proficient with C# and the classes in the .NET Framework class library
merely by reading about them. Rather, you must use them and experiment with them by writing code,
code, and more code. The structure and content of this book and the real-world applicability of the
solutions it provides offer the perfect starting point from which to kick-start your own experimentation.
Allen Jones
Adam Freeman

xxiii

www.it-ebooks.info


www.it-ebooks.info


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×