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 54 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 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 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 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 ■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 Create a Console Application from the Command Line 1-2 Create a Windows-Based Application from the Command Line 1-3 Create and Use a Code Module 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 ■ INDEX System.Windows.Controls.ProgressBar class, 829, 862 System.Windows.Data.CollectionViewSour ce class, 849 System.Windows.Controls.RichTextBox control, 813 System.Windows.Data.RelativeSource property, 829 System.Windows.Controls.Slider control, 833, 835 System.Windows.Data.UpdateSourceTrigg er enumeration, 834 System.Windows.Controls.StackPanel property, 808 System.Windows.DependencyObject object, 790 System.Windows.Controls.StyleSelector class, 856 System.Windows.DependencyProperty property, 796, 834 System.Windows.Controls.TextBlock control, 834, 835 System.Windows.DependencyProperty property, 790 System.Windows.Controls.TextBlock property, 800 System.Windows.Documents.FlowDocum ent property, 813 System.Windows.Controls.TextBox control, 813, 833 System.Windows.Documents.TextSelectio n object, 814 System.Windows.Controls.TextBox controls, 837, 850 System.Windows.DragDrop class, 858 System.Windows.Controls.TextBox file, 823 System.Windows.Controls.TreeView control, 848 System.Windows.DragDropEffects enumeration, 859 System.Windows.Forms namespace Application class, System.Windows.Controls.UserControl control, 820, 822 AxHost control, 615 classes, 307 System.Windows.Controls.UserControl property, 793, 798 CommonDialog class, 241 System.Windows.ControlTemplate class, 828 FolderBrowserDialog class, 241 Control class, 379 System.Windows.Data.Binding markup extension, 833 Form class, System.Windows.Data.BindingExpression class, 834 Panel control, 383 System.Windows.Data.BindingMode enumeration, 833 PrintDialog class, 402 System.Windows.Data.CollectionView object, 849 OpenFileDialog class, 241 PictureBox control, 383 PrintPreviewControl class, 410 PrintPreviewDialog class, 410 973 www.it-ebooks.info ■ INDEX SaveFileDialog class, 241 System.Windows.Media.ImageBrush class, 879, 882 Timer class, 164 System.Windows.Media.LinearGradientBr ush class, 876 TreeNode class, 262 System.Windows.Forms.Integration.Eleme ntHost control, 363 System.Windows.FrameworkPropertyMet adata object, 791 System.Windows.FrameworkPropertyMet adataOptions enumeration, 791 System.Windows.Input namespace, 814, 823 System.Windows.Input.ApplicationComm ands class, 823 System.Windows.Input.CommandBinding class, 823 System.Windows.Input.CommandManage r class, 823 System.Windows.Input.InputGestureColle ction class, 823 System.Windows.Input.Keyboard class, 902 System.Windows.Input.Keys enumeration, 903 System.Windows.Media namespace, 871 System.Windows.Media.Animation.Paralle lTimeline object, 890 System.Windows.Media.SolidColorBrush class, 873 System.Windows.Media.SolidColorBrush property, 800 System.Windows.Media.TileBrush class, 879 System.Windows.PropertyMetadata object, 791 System.Windows.ResourceDictionary object, 799 System.Windows.Shapes.Path element, 866, 867, 871 System.Windows.Shapes.Rectangle object, 890 System.Windows.Shapes.Shape class, 867, 873, 876, 879 System.Windows.Style class, 828 System.Windows.Style resource, 854 System.Windows.SystemColors class, 874 System.Windows.TemplatePart attribute, 829 System.Windows.UIElement object, 363 System.Windows.Media.Animation.Timeli ne objects, 886 System.Windows.ValidateValueCallback property, 793 System.Windows.Media.Color structure, 873 System.Windows.Window object, 360, 890 System.Windows.Media.Colors class, 874 System.Windows.Media.Geometry class, 867, 871 System.Windows.Media.GeometryGroup static resource, 872 System.Windows.Window property, 796, 801 System.Windows.Window property, 800 System.Windows.Window.RenderTransfor m property, 793 974 www.it-ebooks.info ■ INDEX System.Xml namespace ■T XmlDocument class, 262, 449 TableDirect value, CommandType enumeration, 437 XmlNode class, 627 TableLayoutPanel container, 335 XmlNodeList class, 271 Tag property, 312 XmlNodeType enumeration, 262 Take extension method, 759–760 XmlReader class, 448 /target:exe switch, System.Xml.Linq.LoadOptions enumeration, 296 /target:module compiler switch, System.Xml.Linq.XElement class, 296, 298, 301 System.Xml.Serialization namespace Task class, 732–733 ContinueWith method, 738 IsCompleted property, 734 attribute classes, 287 Wait method, 734–735, 742 XmlSerializer class, 286 WaitAll method, 734–735, 742 System.Xml.Xsl namespace, 292 WaitAny method, 734,–735 SystemDirectory property, Environment class, 684 SystemOperator value, WindowsBuiltInRole enumeration, 565 SystemParameters.MinimumHorizontalDr agDistance property, 861 task dialog, displaying, 717–720 Task Parallel Library, 149, 729 Task.Result property, 732–733 TaskDialog class, 717–718 tasks SystemParameters.MinimumVerticalDrag Distance property, 861 canceling, 743–745 SystemProperties.System class, 712–713 exception handling in, 741–743 SystemSound class sharing data between, 745–747 example, 391–392 chaining together, 738–739 waiting for completion of, 734–736 Play method, 391 TCP System.Media namespace, 391 communicating with, 510–515 SystemSounds class, 391 SystemWidows.Window property, 799 SystemWindows.UIElement property, 796 multithreaded TCP server for asynchronous communications, 515–523 TCP client, template for, 513–514 TCP server, template for, 511–513 975 www.it-ebooks.info ■ INDEX TcpClient class, 510, 513 providing input error for with ErrorProvider component, 348 TcpListener class TextBox object, 835–838, 851 AcceptTcpClient method, 511, 515 BeginAcceptTcpClient method, 515, 516 EndAcceptTcpClient method, 515 System.Net.Sockets namespace, 510, 515 TextChanged event, 815 TextReader class, System.IO namespace, 111 TextSelection object, 814 text-to-speech, 417–419 TemplatePart attribute, 829 textures, filling shapes with, 882–885 templates TextWriter class, System.IO namespace, 111 TCP client, 513–514 Themes subfolder, 828, 831 TCP server, 511–513 this keyword, 48 XSL stylesheets, 293 Thread class temporary files, 238–239 Abort method, 124, 192 text creating and controling threads, 169 printing wrapped, 408–410 creating new object, 170 reading aloud, 417–419 CurrentPrincipal property, 568–569, 573 rich text, 813–817 text boxes CurrentUICulture property, 340 autocomplete, 329–331 IsAlive property, 190 restricting input, 326–329 Join method, 190 text files, reading and writing, 222–224 Text property, 341, 833–835, 837 Start method, 169–170, 192 Text value, CommandType enumeration, 437 configuring context menu for, 336 thread synchronization, 172 finding all instances on a form, 314 TextBox control, 833–834 KeyPress event, 329 System.Threading namespace, 568 Thread Pool class, method execution using, 151–154 TextBox class restricting input, 326–329 ResetAbort method, 192 ThreadAbortException class, 192 ThreadPool class GetAvailableThreads method, 154 QueueUserWorkItem method, 151 976 www.it-ebooks.info ■ INDEX RegisterWaitForSingleObject method, 167, 168 SetMaxThreads method, 153, 154 thread-safety, 194 ThreadStart class, 169 ThreadStart delegate, 170 threads, 149–150 ThreadState class, 170 creating a thread-safe collection instance, 193 ThreadStateException class, 170 thumbnails, showing for image, 389–391 creating and managing, 169–170 execute a method asynchronously, 154– 163 execute a method at a specific time, 166–167 execute a method by signaling a WaitHandle class, 167–169 TickCount property, Environment class, 685 Tile value, 883 TileBrush class, 879 TileMode property, 882–883 execute a method periodically, 163–166 execute a method using new thread, 169–172 TimedOut value, IPStatus enumeration, 508 Timeline class, 886 Timeout class execute a method using ThreadPool class, 151–154 Infinite property, 164, 166 in ready queu, 174 System.Threading namespace, 164 Timeout property in wait queue, 173 knowing when a thread finishes, 190– 191 synchronize SmtpClient class, 500 WebRequest class, 490 Timer class access to shared data, 187–190 Change method, 164 execution of multiple threads using a Monitor, 172–178 Dispose method, 164 execution of multiple threads using a Mutex, 182–184 System.Threading namespace, 164, 166 execution of multiple threads using a Semaphore, 185–187 execution of multiple threads using an event, 178–182 terminating execution of thread, 191– 193 periodic execution of methods, 164 System.Timers namespace, 164, 701 System.Windows.Forms namespace, 164 Timer object, 164, 166 TimerCallback delegate, 164, 166 times See dates and times 977 www.it-ebooks.info ■ INDEX TimeSpan structure, 166 add, subtract and compare dates and times, 75–77 operators supported by, 75 TreeNode class, 220 Title property, Console class, 32 System.Windows.Forms namespace, 262 Tlbexp.exe, 616 Tlbimp.exe, 394, 610–611, 707 Tag property, 312 To property, MailMessage class, 502 TreeView control ToArray method, 59, 79 BeforeExpand event, 219 ToBase64CharArray method, Convert class, 62 Fill method, 220 ToBase64String method, Convert class, 62 ToBoolean method, BitConverter class, 60 ToggleButton method, 827 showing a JIT directory tree, 219–222 showing XML document structure, 261–266 TryXXX methods, 143–145 ToInt32 method, BitConverter class, 60 tools, tweening, 892 two-way binding, 833–836 TopIndex property, ListBox class, 325 TwoWay value, 834–835, 851 TopMost property, Form class, 601 Type class, 125 ToString method, 844–845, 849 EmptyTypes field, 130 BitConverter class, 61, 583–584 GetConstructor method, 130 IFormattable interface, 652 GetNestedType method, 125 Object class, 562 GetNestedTypes method, 125 PhysicalAddress class, 482 Missing field, 614 SecureString class, 590 System namespace, 80, 446 StringBuilder class, 54 type information, retrieving, 125–127 TotalFreeSpace property, DriveInfo class, 240 trailing backslash (\), 234 Transform method, XslCompiledTransform class, 292 TransparentKey property, Form class, 378 System namespace, 164 Trace class, System.Diagnostics namespace, 18 Transaction property, command objects, 438 Type Library Exporter (Tlbexp.exe), 626 Type Library Importer (Tlbimp.exe), 394, 610–611, 707 type members determining, at runtime, 137–140 978 www.it-ebooks.info ■ INDEX invoking, dynamically, 142 UnicodeEncoding class, 57 invoking, using reflection, 140–142 Uniform value, 880 Type objects, methods that return, 125 UniformGrid event, 903 Type.GetNestedType method, 126 UniformToFill value, 880 Type.GetNestedTypes method, 126 Union method, 474, 477 typeof keyword, 125, 138, 314 Unload method, AppDomain class, 124 type(s) unmanaged code interoperability adding method to, without modifying, 675–677 calling a function in an unmanaged DLL, 597–601 creating custom dynamic, 143–147 calling an unmanaged function that uses a callback, 606–608 creating variant generic, 679,–681 calling an unmanaged function that uses a structure, 603–606 testing object, 127–129 exposing NET component through COM, 616–617 ■U UDP, communicating with, 523 releasing COM components quickly, 613–614 UdpClient class, System.Net.Sockets namespace, 523 retrieving handles for controls, Windows or files, 601–603 UI elements retrieving unmanaged error information, 608–610 docking to edge of form, 807–808 grid layout, 809–811 horizontal or vertical stacking, 805–806 using ActiveX controls in NET clients, 615–616 positioning to exact coordinates, 811– 812 using COM components in NET clients, 610–613 Unary negation (-) operator, 76 using optional parameters , 614–615 Unary plus (+) operator, 76 unmanaged code interoperability, 597–617 UnauthenticatedPrincipal value, PrincipalPolicy enumeration, 570 unmanaged errors, retrieving information, 608–610 Undo method, 573, 815 unmanaged functions Unicode, 56 calling function that uses a callback, 606–608 Unicode property, 57 Unicode string, Base64 encoding and decoding using Convert class, 62 using structure parameters, 603–606 979 www.it-ebooks.info ■ INDEX Unprotect method user interface, updating in multithreaded application, 354–356 ProtectedData class, 593 User property, HttpListenerContext class, 494 ProtectedMemory class, 593 SectionInformation class, 434 Unregister method, RegisteredWaitHandle class, 168 User value, WindowsBuiltInRole enumeration, 565 User32.dll, 598 Up value, OperationalStatus enumeration, 481 UserControl control, 793, 820 UpdateSource property, 834 UserDomainName property, Environment class, 685 UpdateSourceTrigger attribute, 833–835, 850 uploading methods, WebClient class, 489 Uri class, 538–540 UserInteractive property, Environment class, 685 UserName property Environment class, 685 UriBuilder class, 539–540 ProcessStartInfo class, 197 URIs, manipulation of, 538–541 users Url class, 560 Url property, WebBrowser control, 357 impersonating a Windows user, 572– 575 restricting which user can execute code, 568–572 UrlIdentityPermission class, 560 UseDefaultCredentials property, SmtpClient class, 501 Users field, Registry class, 695 user controls using statement, 197 application commands, supporting, 822–826 creating, 820–822 constructing Monitor class in, 203 Dispose pattern, 648 using statements, 550 user input UTF-16 character encoding, 56–58, 223 reading from console, 93–96 UTF7 property, UTF7Encoding class, 57 rich text, 813–817 UTF-7 Unicode, 223 multimedia and UTF7Encoding class, 57 dragging items from lists and dropping them on canvas, 858–861 UTF-8 encoding, 59 UTF8 property, UTF8Encoding class, 57 playing media files, 898–901 querying keyboard state, 902–904 980 www.it-ebooks.info ■ INDEX UTF-8 Unicode, 223 verifying UTF8Encoding class, 57 assembly’s strong name, 23 strong name assembly has not been modified, 23–24 ■V Validate method, XmlDocument class, 286 Version class, System namespace, 685 ValidateInput method, 69 version information, retrieving, 217–218 validation Version property input control, 348 Environment class, 685 input, using regular expressions, 65–69 OperatingSystem class, 686 XML documents against schema, 281– 286 ValidationEventHandler event, XmlReaderSettings class, 281–283 ValidOn property, AttributeUsageAttribute class, 134 Visual Studio XmlNode class, 262 Application Settings, 322 XmlReader class, 278 generating RCWs, 611 value types Windows Forms and, 308 converting from byte arrays, 59 -Vr switch, Strong Name tool, 25 converting to byte arrays, 59 -Vu switch, Strong Name tool, 26 converting to byte arrays, 60–61 var type, 761 variant generic types, creating, 679–681 VerifyByteHash method, 584 VerifyHexHash method, 584 VerticalScrollBarVisibility property, 814 Viewport property, 882–883 parameter objects, 442 VerifyB64Hash method, 584 VerticalAlignment property, 806 Viewbox property, 880, 882 Value property, 833–835, 863 VelocityProperty property, 793 vertical stacks, 805–806 video files, playing, 395–397 value of command, 293 Velocity property, 793 VersionString property, OperatingSystem class, 686 ■W W3C Document Object Model (DOM) See DOM (W3C Document Object Model) Wait method Monitor class, 174 Task class, 734–735, 742 981 www.it-ebooks.info ■ INDEX wait queue, 173 WebBrowser class, 295 WaitAll method WebBrowser control, 294, 356–358 Task class, 734–735, 742 displaying a web page, 356 WaitHandle class, 178 members, 357–358 WaitAny method WebClient class Task class, 734–735 CancelAsync method, 487 WaitHandle class, 178 Certificates property, 497 WaitCallback delegate, System.Threading namespace, 151 WaitForConnection method, 257 Credentials property, 497 data download methods, 486 OpenRead method, 490 WaitForExit method, Process class, 197, 200 System.Net namespace, 486, 490 uploading methods, 489 WaitHandle class, 167 WebException class, 490 method execution using, 167–169 WebPermission class, 550 methods for synchronizing thread execution, 178 WebPermissionAttribute class, 550 Mutex class derives from, 182 WebRequest class Semaphore class derives from, 185 Certificates property, 497 System.Threading namespace, 167, 178, 454 Create method, 490 waiting, 453–454 Credentials property, 497–498 GetResponse method, 490 WaitOne method, WaitHandle class, 178 WaitOrTimerCallback delegate, 167 System.Net namespace, 497 System.NET namespace, 111, 490 Warning value, EventLogEntryType enumeration, 690 Timeout property, 490 WebResponse class WAV files, playing, 392–393 WCF (Windows Communication Foundation), 479 GetResponseStream method, 491 WCF service, calling, 532–534 System.NET namespace, 111, 490 System.Net namespace, 497 web method, calling asynchronously, 526 where keyword, 98, 755 web pages, displaying, 356–359 Width property, 810, 859, 867, 899–900, 903 web service, creating SOAP-based, 526–532 Width property, 810 982 www.it-ebooks.info ■ INDEX wildcard expressions, find files that match, 230–231 Win32 API creating an immovable form, 341 displaying a web page, 356–359 core libraries, 598 displaying WPF Windows in, 360–363 functions for writing and reading INI files, 598 LogonUser function, 573 docking UI elements to edge of, 807– 808 drag-and-drop operations, 350 Win32 CryptoAPI, 19, 576 finding all MDI child forms, 319–321 Win32_Printer class, 412, 417 forcing a ListBox to scroll to most recently added item, 325–326 Win32_PrintJob class, 412 Win32Exception class, 197 laying out controls automatically, 335– 336 WinAPI functions, 601 making a borderless form movable, 343–346 Window.Closing event, 360 WindowHeight property, Console class, 33 Windows Jump List, 709–711 multilingual forms, 338–341 process all controls on form, 314–315 Windows API CodePack, 709–711 restrictingTextBox class input, 326–329 creating and displaying task dialogs using, 717–720 determining Internet connectivity using, 716–717 saving configuration settings for forms, 322–329 sorting a ListView by column, 332–335 tracking visible forms in application, 315–319 Windows applications creating from command-line, 5–6 example, 6–8 Windows Communication Foundation (WCF), 479 Windows event logs, writing to, 690–692 updating user interface in multithreaded application, 354– 356 using part of a main menu for a context menu, 336–338 using WPF controls in, 363–367 Windows forms, 307 adding a control programmatically, 309–311 animated system tray icon, 346–246 autocomplete Combo Box, 329–331 classes, 307 compared with WPF, 789 validating an input control, 348 Windows groups, determining if user is member of, 564–568 Windows integration, 683 accessing runtime environment information, 684–688 983 www.it-ebooks.info ■ INDEX checking Internet connectivity, 716–717 WindowsBase assembly, 803 creating a shortcut on Desktop or Start menu, 706–709 WindowsBuiltInRole enumeration, 565 creating a Windows service, 699–704 creating a Windows service installer, 704–706 creating Windows Jump List, 709–711 WindowsIdentity class GetCurrent method, 564 Impersonate method, 572–573 implements IIdentity interface, 564 overloaded constructors, 565 displaying task dialog, 717–720 obtaining elevated privileges, 726–727 reading and writing to the Windows registry, 692–695 reading performance counters, 724–726 retrieving the value of environment variable, 688–690 searching the Windows registry, 695– 699 writing event to Windows event log, 690–692 writing to custom performance counters, 720–724 System.Security.Principal namespace, 564, 572–573 WindowsPrincipal class implements IPrincipal interface, 564 IsInRole method, 564, 565 System.Security.Principal namespace, 564 WindowsPrincipal value, PrincipalPolicy enumeration, 570 WindowsSecurityContext class, 573 WindowStyle property, ProcessStartInfo class, 197 Windows Management Instrumentation (WMI), 412 WindowWidth property, Console class, 33 WM_CLOSE message, 200 Windows Presentation Foundation (WPF), 798 See also WPF applications WorkerReportsProgress property, 862–863 Windows registry WorkerSupportsCancellation property, 862–863 reading and writing to, 692–695 WorkingDirectory property, ProcessStartInfo class, 197 searching, 695–699 Windows Script Host, 706 WPF (Windows Presentation Foundation), 798 Windows search feature, 711–716 WPF applications Windows service, creating, 699–704 Windows Service Control Manager See SCM Windows service installer, creating, 704– 706 application-wide resources, 799–801 attached properties, 795–798 creating user controls, 820–820 984 www.it-ebooks.info ■ INDEX debugging bindings writing XML See XML processing using attached properties, 803–805 wshom.ocx file, 707 using IValueConverter, 801–803 WshShell class, 707 dependency properties, creating and using, 790–795 ■X displaying rotated controls, 818–820 x:Key property, 871 lookless custom controls, 826–831 X509Certificate2 class, 498 supporting application commands in user controls, 822–826 X509Certificate2UI class, 498 WPF controls, using in Windows forms, 367–367 X509CertificatesCollection class, 500 X509Store class, 498 WPF Windows, displaying in Windows forms, 360–363 XAttribute, 298–299 WrapContents property, FlowLayoutPanel container, 335 XComment class, 299 Write method XCData class, 299 XDeclaration class, 299 XElement, 298–299 BinaryWriter class, 225 XElement class, 301 StreamWriter class, 222 WriteAttributeString method, XmlWriter class, 278 Add method, 299, 303 Remove* method, 303 Replace* method, 303 WriteElementString method, XmlWriter class, 278 XElement.Load method, 296 WriteEndDocument method, XmlWriter class, 278 XML, and NET Framework integration, 261 WriteEndElement method, XmlWriter class, 278 XML documents WriteEntry method, EventLog class, 690 WriteLine method, StreamWriter class, 223 WriteObject method, 91 creating new, 267–268 obtaining from SQL Server query, 448– 452 XML processing, 261 WritePrivateProfileString function, 598 WriteStartDocument method, XmlWriter class, 278 WriteStartElement method, XmlWriter class, 278 appending notes in XML documents, 268–271 creating new XML tree to use with LINQ, 298–300 985 www.it-ebooks.info ■ INDEX creating schemas for NET classes, 290– 291 finding elements with XPath search, 274–278 finding specific elements by name, 271–272 ChildNodes property, 263 CloneNode method, 269 create methods, 266 creating and inserting nodes, 266 DocumentElement property, 262 generating a class from schemas, 291– 292 GetElementsByTagName method, 271 inserting nodes into XML documents, 266–268 LoadXML method, 262 loading XMLwith LINQ, 296–298 Save method, 266 modifying XML tree with LINQ, 303 Schemas property, 286 performing an XSL Transform, 292–295 SelectNodes method, 275 query XML with LINQ, 300–303 SelectSingleNode method, 275 reading and writing without loading document into memory, 278–281 System.Xml namespace, 262, 449 retrieving nodes from specific namespace, 272–274 XmlTextReader class and, 279 Load method, 262 Validate method, 286 XmlElement class serialization with custom objects, 286– 290 showing document structure in TreeView, 261–266 basic properties derived from XmlNode, 262, 263 GetElementsByTagName method, 272, 273 validating documents against a schema, 281–286 System.Xml.Serialization namespace, 287 XML Schema Definition (XSD), 281 XmlEnum class, 287 XML Schema Definition Tool (xsd.exe), 290–291 XmlException class, 283 XML schemas, 281 XmlIgnore class, 287 XmlAttribute class XmlNode class, 271 basic properties derived from XmlNode, 262, 263 AppendChild method, 266 System.Xml.Serialization namespace, 287 casting to XmlElement class, 272 XmlDocument class, 262 basic properties, 262–263 CloneNode method, 270 description, 262 986 www.it-ebooks.info ■ INDEX InsertAfter method, 266 XmlTextReader class, 279 InsertBefore method, 266 XmlTextWriter class, 278 SelectNodes method, 275 XmlWriter class, 295 SelectSingleNode method, 275 Create method, 278 System.Xml namespace, 627 example, 279, 280 XmlNodeList class, 271 Write methods, 278 XmlNodeList collection, ChildNodes property, XmlNode class, 262 XPath, expression syntax table, 276 XPath search, 274–278 XmlNodeType enumeration, 262 XSD (XML Schema Definition), 281 XmlReader class closing, 449 xsd.exe (XML Schema Definition Tool), 290–291 Create method, 278, 281, 283 XSL stylesheets, 293 enforcing schema rules, 283 XSL transforms, 292–295 example, 279, 280 XslCompiledTransform class, 292, 294–295 GetAttribute method, 279 XSLT (XSL transforms), 292–295 HasAttributes property, 279 XSLT stylesheet example, 293 properties, 278 XslTransform class, 294 Read method, 278, 281 ■Y ReadElementString method, 280 yield break statement, 636–637 reading XML, 278 yield return statement, 637, 640 ReadToDescendant method, 280 ypeof operator, 127 ReadToFollowing method, 280 ReadToNextSibling method, 280 ■Z System.Xml namespace, 448 Zone class, 560 XmlReaderSettings class, 281, 283 ZoneIdentityPermission class, 560 XmlRoot class, 287 XmlSerializer class, 287, 290–291 requirements for using, 287 System.Xml.Serialization namespace, 286 translating XML into objects, 289 987 www.it-ebooks.info .. .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... ReadString("Please enter your name : "); // Welcome the reader to Visual C# 2010 Recipes WriteString("Welcome to Visual C# 2010 Recipes, " + name); } } } The HelloWorld class listed next uses the... 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