o'reilly - c sharp 3 0 cookbook 3rd edition jan 2008

888 8.7K 0
o'reilly - c sharp 3 0 cookbook 3rd edition jan 2008

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

C# 3.0 Cookbook ™ Other Microsoft NET resources from O’Reilly Related titles NET Books Resource Center Building a Web 2.0 Portal with ASP.NET 3.5 C# 3.0 Design Patterns Learning C# Programming ASP.NET Programming C# Visual C# 2005: A Developer’s Notebook™ dotnet.oreilly.com is a complete catalog of O’Reilly’s books on NET and related technologies, including sample chapters and code examples ONDotnet.com provides independent coverage of fundamental, interoperable, and emerging Microsoft NET programming and web services technologies Conferences O’Reilly brings diverse innovators together to nurture the ideas that spark revolutionary industries We specialize in documenting the latest tools and systems, translating the innovator’s knowledge into useful skills for those in the trenches Visit conferences.oreilly.com for our upcoming events Safari Bookshelf (safari.oreilly.com) is the premier online reference library for programmers and IT professionals Conduct searches across more than 1,000 books Subscribers can zero in on answers to time-critical questions in a matter of seconds Read the books on your Bookshelf from cover to cover or simply flip to the page you need Try it today for free THIRD EDITION C# 3.0 Cookbook ™ Jay Hilyard and Stephen Teilhet Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo C# 3.0 Cookbook™, Third Edition by Jay Hilyard and Stephen Teilhet Copyright © 2008 Jay Hilyard and Stephen Teilhet All rights reserved Printed in the United States of America Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472 O’Reilly books may be purchased for educational, business, or sales promotional use Online editions are also available for most titles (safari.oreilly.com) For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com Editor: John Osborn Production Editor: Adam Witwer Production Services: nSight, Inc Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrators: Robert Romano and Jessamyn Read Printing History: January 2004: First Edition January 2006: Second Edition December 2007: Third Edition Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc The Cookbook series designations, C# 3.0 Cookbook, the image of a garter snake, and related trade dress are trademarks of O’Reilly Media, Inc Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and O’Reilly Media, Inc was aware of a trademark claim, the designations have been printed in caps or initial caps While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein ISBN-10: 0-596-51610-X ISBN-13: 978-0-596-51610-9 [M] To Brooke My wife, my best friend, and the most supportive person I know This one was for you; you earned it —Jay Hilyard To my loving wife Kandis and my two wonderful sons, Patrick and Nicholas —Stephen Teilhet Table of Contents Preface xvii 1 Language Integrated Query (LINQ) 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 Query a Message Queue Using Set Semantics with Data Reuse Parameterized Queries with LINQ to SQL Sort Results in a Culture-Sensitive Manner Adding Functional Extensions for Use with LINQ Query and Join Across Data Repositories Querying Configuration Files with LINQ Creating XML Straight from a Database Being Selective About Your Query Results Using LINQ with Collections That Don’t Support IEnumerable 2 5 8 10 12 16 19 22 31 33 2 Strings and Characters 36 2.1 Determining the Kind of Character a Char Contains 2.2 Controlling Case Sensitivity When Comparing Two Characters 2.3 Finding the Location of All Occurrences of a String Within Another String 2.4 Controlling Case Sensitivity When Comparing Two Strings 2.5 Comparing a String to the Beginning or End of a Second String 2.6 Inserting Text into a String 2.7 Removing or Replacing Characters Within a String 2.8 Encoding Binary Data As Base64 2.9 Decoding a Base64-Encoded Binary 2.10 Converting a String Returned As a Byte[ ] Back into a String 2.11 Passing a String to a Method That Accepts Only a Byte[ ] 36 40 42 46 47 49 51 53 54 56 57 vii 2.12 2.13 2.14 2.15 2.16 2.17 2.18 Converting Strings to Other Types Creating a Delimited String Extracting Items from a Delimited String Iterating over Each Character in a String Pruning Characters from the Head and/or Tail of a String Testing a String for Null or Empty Appending a Line 59 62 63 64 65 66 67 3 Classes and Structures 68 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12 3.13 3.14 3.15 3.16 3.17 3.18 Creating Union-Type Structures Making a Type Sortable Making a Type Searchable Indirectly Overloading the +=, -=, /=, and *= Operators Indirectly Overloading the &&, ||, and ?: Operators Making Error-Free Expressions Reducing Your Boolean Logic Converting Between Simple Types in a Programming Language-Agnostic Manner Determining When to Use the cast Operator, the as Operator, or the is Operator Casting with the as Operator Determining a Variable’s Type with the is Operator Returning Multiple Items from a Method Parsing Command-Line Parameters Initializing a Constant Field at Runtime Building Cloneable Classes Assuring an Object’s Disposal Disposing of Unmanaged Resources Determining Where Boxing and Unboxing Occur 70 72 77 80 82 85 88 91 97 99 101 104 106 117 120 124 126 133 4 Generics 137 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 viii | Deciding When and Where to Use Generics Understanding Generic Types Replacing the ArrayList with Its Generic Counterpart Replacing the Stack and Queue with Their Generic Counterparts Using a Linked List Creating a Value Type That Can Be Initialized to Null Reversing the Contents of a Sorted List Making Read-Only Collections the Generic Way Table of Contents 137 138 146 150 155 158 160 162 4.9 4.10 4.11 4.12 Replacing the Hashtable with Its Generic Counterpart Using foreach with Generic Dictionary Types Constraining Type Arguments Initializing Generic Variables to Their Default Values 164 168 169 173 5 Collections 175 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 5.10 5.11 5.12 5.13 5.14 Swapping Two Elements in an Array Reversing an Array Quickly Writing a More Flexible StackTrace Class Determining the Number of Times an Item Appears in a List Retrieving All Instances of a Specific Item in a List Inserting and Removing Items from an Array Keeping Your List Sorted Sorting a Dictionary’s Keys and/or Values Creating a Dictionary with Max and Min Value Boundaries Storing Snapshots of Lists in an Array Persisting a Collection Between Application Sessions Testing Every Element in an Array or List Performing an Action on Each Element in an Array or List Creating a Read-Only Array or List 177 178 181 182 185 188 191 193 194 198 199 201 202 204 6 Iterators, Partial Types, and Partial Methods 206 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 6.10 Creating an Iterator on a Generic Type Creating an Iterator on a Nongeneric Type Creating Custom Enumerators Implementing Iterator Logic Forcing an Iterator to Stop Iterating Dealing with Finally Blocks and Iterators Implementing Nested foreach Functionality in a Class Organizing Your Interface Implementations Generating Code That Is No Longer in Your Main Code Paths Adding Hooks to Generated Entities 207 209 211 215 218 220 224 229 234 237 7 Exception Handling 240 7.1 7.2 7.3 7.4 7.5 Knowing When to Catch and Rethrow Exceptions Assuring Exceptions Are Not Lost When Using Finally Blocks Handling Exceptions Thrown from Methods Invoked via Reflection Preventing Unhandled Exceptions Getting Exception Information 247 248 251 254 256 Table of Contents | ix enumerating matches, 367–370 executing, 366 extracting groups, 370–373 finding last match, 375 finding matches, 387–389 returning entire lines in matches, 383–387 string replacement, 376–378 strings and, 366 tokenizers and, 379–380 verifying syntax, 373–375 Remote Desktop, 755 RemoveFromArray method, 189–190 RenameFile method, 453 renaming directories, 457, 458 files, 452–453 RequestCacheLevel enumeration BypassCache value, 541 CacheIfAvailable value, 541 CacheOnly value, 541 Default value, 541 NoCacheNoStore value, 541 Reload value, 541 Revalidate value, 541 RequestCachePolicy class, 541–543 resource cleanup (see garbage collection) ResponseCategories enumeration, 522, 523 RestoreObj method, 200 return statement, 222 return values delegates and, 321 lambda expressions and, 346 multicast delegates and, 322–324 multiple, 104–105 partial methods and, 238 RFC 792, 630 RFC 821, 632 RFC 959, 650 RFC 1951, 487 RFC 2396, 520, 535, 536 RFC 2616, 523 Richter, Jeffrey, 722 Rijndael algorithm, 663, 665–670 RijndaelManaged class GenerateIV method, 664 GenerateKey method, 663 IV property, 664 Key property, 664 SavedIV field, 664 SavedKey field, 664 root node, 428, 429 rounding numbers choosing algorithms, 800 for floating-point values, 799 narrowing conversions and, 804 RSA algorithm, 670 RsaCryptoServiceProvider class, 709 RsaProtectedConfigurationProvider class, 709 Rundll32 process, 291 runtime (see CLR) RuntimeEnvironment class, 783, 784 S SafeFileHandle class, 713–715 SafeHandleZeroOrMinusOneIsInvalid class, 715 SaferMemberAccess class IncrementNumericField method, 723 ModifyNumericField method, 723 ReadNumericField method, 723 salting hashed value, 676–683 SampleClassLibrary assembly, 509 SaveObj method, 200 SByte (sbyte) data type CLS compliance, 794 converting, 91, 93, 95, 96 listed, 793 Parse method support, 60 searching binary search trees, 418–432 data types, 77–80 event log entries, 299–302 interfaces, 330–332 strings, 36 with wildcards, 459–463 (see also patterns) SecretInner type, 493 SectionalListator class GetEnumerator method, 216 GetFilteredValues method, 216–218 GetFirstHalf method, 216–218 GetReverseFilteredValues method, 216–218 GetSecondHalf method, 216–218 SecureFunction function, 684 SecureString class Clear method, 698 Copy method, 697 Dispose method, 698 MakeReadOnly method, 697 protecting string data, 696–699 Index | 847 security assembly attack surface, 687 assembly permissions, 685, 686 asserting permissions, 683–685 changing security privileges, 693–696 cleaning cryptography info, 670–672 controlling access to types, 651–661 encrypting web.config file, 708–710 encrypting/decrypting files, 665–670 encrypting/decrypting strings, 661–665 protecting string data, 696–699 rights/audit information, 688–693 runtime and, 651 safer file handles, 713–715 securing stream data, 699–708 SecurityException reasons, 685, 710–712 storing data and, 676–683 string corruption, 672–676 Unicode encoding, 712, 713 security.config file, 548 SecurityAction enumeration Assert value, 710 Demand value, 710 DemandChoice value, 710 Deny value, 710 InheritanceDemand value, 711 InheritanceDemandChoice value, 711 LinkDemand value, 711 LinkDemandChoice value, 711 PermitOnly value, 711 RequestMinimum value, 711 RequestOptional value, 685, 711 RequestRefuse value, 687 RequestRefuseusing value, 711 SecurityException class Action property, 710, 712 Data property, 711, 712 Demanded property, 711, 712 DenySetInstance property, 711 FailedAssemblyInfo property, 711, 712 FirstPermissionThatFailed property, 711 GrantedSet property, 712 Method property, 711, 712 PermitOnlySetInstance property, 711 properties, 710–712 URL property, 711, 712 Zone property, 711 SecurityException exception, 685, 710–712 SecurityManager class, 686 SecurityZone enumeration Internet value, 711 Intranet value, 711 848 | Index MyComputer value, 711 NoZone value, 711 Trusted value, 711 Untrusted value, 711 select keyword accessing multiple data domains, 19 description, 3, 557 Semaphore class, 692 SemaphoreAccessRule class, 692 semaphores, 734–738 SerializableAttribute attribute, 507 SerializationException exception, 263 serializing classes, 263 objects, 123 service packs, 791, 792 ServiceController class CanPauseAndContinue property, 777 CanStop property, 777 Close method, 778 Continue method, 777 DependentServices property, 776 DisplayName property, 775 overview, 775–778 ServiceName property, 775 ServicesDependedOn array, 776 ServiceType property, 775 Start method, 776 Status property, 776, 778 Stop method, 777 WaitForStatus method, 776, 777 ServiceType enumeration Adapter value, 775 FileSystemDriver value, 775 InteractiveProcess value, 775 KernelDriver value, 775 RecognizerDriver value, 776 Win32OwnProcess value, 776 Win32ShareProcess value, 776 SessionEndedEventArgs class, 775 SessionEndingEventArgs class, 773, 775 sessions change notifications, 770–775 collections persisting between, 199–200 terminal, 755 SessionSwitchEventArgs class, 775 set method, 340 Set operators, 5–8 SetEquals method, 447 sets defined, 446 difference operation, 446, 447 equivalence operation, 447 intersection operation, 446, 447 subset operation, 446, 447 superset operation, 446, 447 union operation, 446, 447 SHA-256 algorithm, 672–676 SHA256Managed class, 397, 672–676 SHA512Managed class, 679 shallow copying, 120–122 SharedMemoryManager class code example, 744–750 named Mutex, 738, 740 ReceiveObject method, 743–744 SendObject method, 741–743 SetupSharedMemory method, 740–741 shift and add hash algorithm, 397 short data type (see Int16 data type) shutdown, notification for, 770–775 SignedNumber structure, 70, 71 SignedNumberWithText structure, 72 simple hash algorithm, 395, 400 Simple Mail Transfer Protocol (SMTP), 631–636 simple types, 793, 794 Single (float) data type calculated hash, 398 converting, 91, 93, 95 listed, 793, 794 narrowing conversions, 804 Parse method support, 60 SingleInstance enumeration value, 305 SMTP (Simple Mail Transfer Protocol), 631–636 SmtpClient class, 631–636 snapshots, storing in arrays, 198, 199 SOAP, 455, 548 Social Security number, 390, 696–697 Socket class, 636–641 SocketException exception, 517 SortedDictionary class, 428 SortedDictionary class, 194 SortedList class binary trees and, 428 collection classes and, 176 Compare method, 78 CompareTo method, 78 ContainsKey method, 78 ContainsValue method, 78 reversing sorted list, 160–162 SortedList class Add method, 192 foreach loops and, 168–169 reversing sorted list, 160–162 searching data types, 78–80 sorting data types, 72–77 sorting lists, 191–193 sorting application-specific, 10–12 data types, 72–77 keys/values, 193–194 List class, 191–193 reversing list contents, 160–162 space character delimiting character, 63 trimming from strings, 65 special characters, 383 spoolsv process, 291 SQL injection, 392 SQL Server (Microsoft) ReaderWriterLockSlim and, 760 tying database tables to cache, 531 SqlCacheDependency class, 530–531, 540 SqlCacheDependencyAdmin class, 531 SqlMetal utility, 18, 24 Square class searching data types, 77, 78 sorting data types, 72–75 SSL protocol, 699–708 SslStream class AuthenticateAsClient method, 708 AuthenticateAsServer method, 706 CertificateValidationCallback method, 708 Close method, 708 GetServerCert method, 705 securing stream data, 699–708 Stack class Clone method, 153 generic counterparts, 137, 150–154 IsSynchronized property, 153 snapshots of lists, 198 Synchronized method, 153 SyncRoot property, 153 stack traces, 269–272 StackOverflowException exception, 246 StackTrace class, 181–182 standard output stream, 787–789 Standard Query Operators, 5–8 StandardOutput stream, 311 Startup event handler, 282 State Service (ASP.NET), 775–778 Statement lambda, 348 Index | 849 static fields cloning and, 122 const fields and, 119 per-thread, 716–719 storing thread-specific data, 730–733 storage child nodes in n-ary trees, 432–444 data securely, 676–683 isolated, 676–682 objects in binary trees, 428 thread-specific data, 730–733 Storeadm.exe utility, 682 stream data, securing, 699–708 StreamReader class obtaining HTML from URLs, 528 ReadLine method, 381, 383–387 ReadToEnd method, 528 StreamWriter class capturing output, 788 Close method, 131, 473 Write method, 474 WriteLine method, 454, 470 string alias, 36 String class class sensitivity, 41 Compare method, 46, 47, 47–49 Contains method, 4 EndsWith method, 47–49 Format method, 9 IndexOf method, 42–46 IndexOfAny method, 42–46 Insert method, 49–50 IsNullOrEmpty method, 66 Join method, 62, 63 protecting string data, 698 reference types and, 36 Remove method, 51–53 Replace method, 51–53 Split method, 62, 63, 176, 469 StartsWith method, 47–49 StringBuilder class and, 36 Trim method, 65, 66 TrimEnd method, 65, 66 TrimStart method, 65, 66 (see also strings) StringBuilder class AppendFormat method, 53 AppendLine method, 67 exception handling and, 253 functionality, 36 Insert method, 50 inserting text, 50 850 | Index Remove method, 51–53 Replace method, 51–53 string-concatenation hash algorithm, 399 StringDictionary class, 176 strings appending lines, 67 case sensitivity for comparisons, 46, 47 comparing to other, 47–49 converting, 91, 93, 94, 96 converting base types, 798 converting byte[], 56–57 converting to other types, 59–62 counting lines of text, 380–383 decoding binary data, 54–55 delimited, 62, 63 determining valid numbers, 798, 799 encoding binary data, 53–54 encrypting/decrypting, 661–665 enumerating matches, 367–370 enumeration values as, 804–807 exception handling, 246 extracting groups, 370–373 finding all occurrences within, 42–46 finding last match, 375 finding specific matches, 387–389 getting exception information, 257 handling invalid characters, 569–572 inserting text, 49–50 iterating characters, 64–65 passing byte[] to methods, 57–59 protecting data, 696–699 pruning characters from, 65, 66 regular expressions and, 366 removing characters, 51–53 returning entire lines for matches, 383–387 searching, 36 string replacement, 376–378 string-concatenation hash, 399 testing for null/empty, 66 tokenizing, 379–380 verifying uncorrupted, 672–676 (see also String class) struct keyword, 135 StructLayoutAttribute Class, 70–72 structures binary search trees, 418–432 boxing and, 69, 135 classes and, 68, 69 constructors and, 69 deep copies and, 123 delegates and, 316 HashSet object, 444–448 inheritance and, 70 interfaces and, 69, 135 multiple return values and, 104 n-ary trees, 432–444 one-to-many maps, 410–418 passing by value, 69 performance and, 68, 70 polymorphism and, 69, 70 priority queues, 402–410 reference types and, 68 union-type, 70–72 usage recommendations, 69 ValueType class and, 68 Subgroup class, 227, 229 subset operation, 446, 447 subtraction operator, 80–82 Sum function, 28 superset operation, 446, 447 svchost process, 291 SwapElementsInArray method, 177 switch statement, 777, 808, 809 SymmetricAlgorithm class Clear method, 131, 670–672 encrypting/decrypting files, 665–670 SymmetricExceptWith method, 447 synchronization multiple processes, 738–750 thread, 721–725 synchronous delegates, 327–330 System processes, 780 System.Attribute, 236 System.CLSCompliantAttribute, 234 System.Collections namespace, 175 System.Collections.ArrayList type, 331 System.Collections.Generic namespace, 175 System.Collections.Specialized namespace, 175–176 System.Configuration assembly, 21 System.Cryptography namespace, 665 System.Diagnostics namespace, 286 System.IO.Pipes namespace, 622 System.Messaging.MessageQueue class (see MessageQueue class) System.Reflection.Emit namespace, 501 System.Runtime.Remoting.Messaging namespace, 328 System.SerializeableAttribute, 234 System.Text namespace, 56, 58 System.Text.RegularExpressions namespace, 36, 366 System.Xml.XPath namespace, 555 %SystemDrive% environment variable, 469 SystemEvents class change notifications, 771–775 DisplaySettingsChanged event, 774 DisplaySettingsChanging event, 774 EventsThreadShutdown event, 771, 774 InstalledFontsChanged event, 774 OnEventsThreadShutdown handler, 772 OnPowerModeChanged method, 772 OnSessionEnded handler, 772 OnSessionEnding handler, 772 OnSessionSwitch handler, 772 PaletteChanged event, 774 PowerModeChanged event, 771, 774 RegisterForSystemEvents method, 771, 772 SessionEnded event, 771, 774 SessionEnding event, 771, 774 SessionSwitch event, 771, 774 TimeChanged event, 774 TimerElapsed event, 774 UnregisterFromSystemEvents method, 771, 772 UserPreferenceChanged event, 774 UserPreferenceChanging event, 774 SystemException class, 246, 261 T tab character, 65 tables accessing, 18 tying to cache, 530–531 TakeSnapshotOfList method, 198, 199 TargetInvocationException exception, 252, 253 TaskManager, 290–292 TCP (Transmission Control Protocol) securing stream data, 699–708 writing TCP clients, 612–615 writing TCP servers, 606–611 TcpClient class Close method, 131, 611 Connect method, 615 GetStream method, 609 Read method, 615 SslStream class and, 705 Write method, 615 writing TCP clients, 612–615 TCPClient_SSL class, 699–701 TcpListener class AcceptTcpClient method, 607, 611 Start method, 611 Index | 851 TCPServer class Address property, 607 overview, 611 Port property, 607 StopListening method, 608, 611 TCPServer_SSL class, 701–703 temperature scales, 801, 802 Terminal Services, 755 terminal services box, 5, 6 terminal sessions, 755 ternary operator, 87 Test class className attribute, 510 methodName attribute, 510 priority queues, 406 TestArrayReversal method, 179, 180 TestCompressNewFile method, 486 TestDynamicInvocation method, 507–511 TestFindSubstrings method, 368–369 TestIndividualInvokesExceptions method, 327 testing elements, 201–202 null/empty strings, 66 permissions via proxies, 659 for valid enumeration values, 808–810 TestInvoke method, 251–253 TestInvokeIntReturn class, 323, 326 TestSort method, 75, 78 TestStaticField method, 718 text converting to enumerations, 807, 808 counting lines, 380–383 inserting into strings, 49–50 matching substrings, 367–370 regular expressions and, 366 TextReader class, 172 TextWriter class, 29, 788 this keyword, 14 Thread class AllocateDataSlot method, 730–733 AllocateNamedDataSlot method, 730–733 asynchronous delegates, 729 FreeNamedDataSlot method, 733 GetData method, 730, 733 GetNamedDataSlot method, 730–733 Start method, 726, 736 thread local storage (TLS), 730–733 ThreadException event, 279–280 ThreadException exception, 727 852 | Index ThreadPool class asynchronous delegates, 729 ProcessClient method, 607, 609, 611 QueueUserWorkItem method, 475, 727 writing TCP clients, 613 threads accessor functions, 719–725 asynchronous delegates and, 328 atomic operations, 755–757 defined, 716 events and, 750–752, 752–755 exception handling and, 244, 255, 279 read-mostly operations, 757–769 shutdown notification, 771 silent termination, 725–727 static fields and, 716–719 storing data privately, 730–733 synchronizing, 721–725 ThreadStart delegate silent termination, 725–727 static fields and, 718 ThreadStaticAttribute attribute, 716–719 throw keyword, 222, 246, 247, 248 ThrowException method, 249 TIME /T command, 469 time, matching patterns, 390 Timer100Ns performance counter, 307 Timer100nsInverse performance counter, 307 TimerElapsedEventArgs class, 775 timestamps directory, 455–457 file, 450, 451 TLS (thread local storage), 730–733 tokenizers, 379–380 toolbox capturing output, 787–789 controlling services, 775–778 listing loaded assemblies, 778–780 path to NET Framework version, 783, 784 registered assembly versions, 784–787 running applications, 789–791 system change notifications, 770–775 workstation message queues, 780–783 ToString method accessing multiple data domains, 18 base type conversions, 798 displaying enumeration values, 805–807 set operations, 6 string-concatenation hash, 399 ToUpperInvariant method case sensitivity, 41 finding all string occurrences, 44 Trace class control output, 287–290 overview, 286 WriteLine method, 454 TraceFactory class, 307–310 TraceSwitch class configuration files and, 288 Level property, 288 trace levels supported, 289, 290 tracing controlling output, 287–290 enabling/disabling, 307–310 overview, 286 transferring data via HTTP, 619–621 files via FTP, 648–650 transformations, XML extending, 595–599 overview, 572–579 passing parameters, 601–605 TransformWithParameters method, 601–605 Transmission Control Protocol (see TCP) trees creating n-ary trees, 432–444 defined, 428 directory, 464–466 functionality, 428 triple point of water, 802 TripleDES algorithm, 665–670 TripleDESCryptoServiceProvider class, 670 true operator, 82–85 TrueForAll method, 201, 202 try/catch blocks asynchronous delegates and, 275 catching/throwing exceptions, 247–251 converting data types, 94 exception handling and, 241–244, 324, 330 getting exception information, 256–259 iterators and, 222–224 silent thread termination, 725–727 unhandled exceptions and, 254–256 try/finally blocks catching/throwing exceptions, 248–251 exception handling and, 241, 243–245, 327 iterators and, 220–224 silent thread termination, 725–727 unhandled exceptions and, 254–256 TryParse method, 62, 798 two-dimensional arrays, 177 Type class BaseType property, 502 BindGenericParameters method, 514–515 GetInterface method, 330 GetInterfaces method, 330 GetMember method, 499–500 GetMethod method, 498, 510 GetMethods method, 498, 512 GetNestedTypes method, 501 GetType method, 501, 502 IsGenericType method, 511–512 IsSerializable property, 507 IsSerialized property, 505–507 IsSubclassOf method, 504, 505 overridden methods, 494 U uint data type (see UInt32 data type) UInt16 (ushort) data type CLS compliance, 794 converting, 91, 93, 95, 96 listed, 793 Parse method support, 60 UInt32 (uint) data type bitwise complement operator, 796, 797 CLS compliance, 794 converting, 91, 93, 95, 96 hash codes and, 401 listed, 793 narrowing conversions, 804 Parse method support, 60 UInt64 (ulong) data type bitwise complement operator, 796, 797 CLS compliance, 794 converting, 91, 93, 95, 96 listed, 793 Parse method support, 60 ulong data type (see UInt64 data type) unary functions, 364 unbox command, 134 unboxing operations as operator and, 100 casting operator and, 98 determining occurrences, 133–136 generics and, 138, 144 is operator and, 103 unchecked keyword, 96 unescaping data, 535–536 UnhandledException event, 256, 279–280, 727 Index | 853 UnicodeEncoding class converting strings, 56–58 GetBytes method, 675 secure encoding, 712, 713 uniform resource identifier (URI), 518–521, 535, 537–539 Union method, 5, 7 union operation, 446, 447 union type, 70–72 UnionWith method, 447 Unknown enumeration value, 305 unmanaged resources, disposing of, 126–133 URI (uniform resource identifier), 518–521, 535, 537–539 Uri class creating objects, 526 EscapeDataString method, 535, 536 EscapeUriString method, 535, 536 parsing URIs, 518–521 UnescapeDataString method, 535, 536 UriBuilder class overview, 537–539 Query property, 537 Uri property, 539 UriBuilderFix class, 537, 538 UriFormatException exception, 520 URL obtaining HTML from, 527, 528 transferring data via HTTP, 619–621 XmlUrlResolver class and, 578 urn:xslext namespace, 596 user accounts, 305, 695 User class, 682 user identity, storing, 676–683 UserPreferenceChangedEventArgs class, 775 UserPreferenceChangingEventArgs class, 775 UserSettings class CreateHashedPassword method, 679, 680, 682 IsPasswordValid method, 680, 682 Password property, 676, 678, 680, 681 storing data securely, 676–683 User property, 676, 678 ushort data type (see UInt16 data type) using directive case sensitive comparisons, 41 extension methods and, 14 using statement and, 125 using statement assuring object disposal, 124–126 clearing cryptography info, 672 854 | Index try/finally blocks and, 243 using directive and, 125 UTFEncoding class, 712, 713 utility routines (see toolbox) V validating modified XML documents, 591–595 numbers in strings, 798, 799 XML documents, 558–563 ValidationHandler class HandleValidation method, 592 ValidXml property, 592, 593 ValidShape enumeration, 805 value equality, 401 value types cast operator and, 98 constraining arguments, 172 generics and, 138 initializing to null, 158–160 reference types and, 72 simple types as, 793 ValueType class boxing and, 69 inheritance and, 794 strings and, 36 structures and, 68 var keyword description, 3, 557 querying message queues, 4 reusing parameterized queries, 9 variables determining type, 101–103 environment, 468, 469 hash codes and, 401 implicitly typed local, 3 initializing generic, 173–174 lambda expressions and, 347, 356 local, 512–514 outer, 347, 348 using statement and, 125 vector array, 65 version control comparing information, 477–479 const fields and, 119 GAC and, 784–787 operating systems, 791, 792 path to NET Framework, 783, 784 Visual Basic NET language, xvii visual designer (LINQ to SQL), 24 wVisual Studio PartialclassAddin add-in, 234–236 Team System for Developers/Team Suite, 136 VS.NET, 134 W WaitForChangedResult structure ChangeType property, 476 Name property, 476 OldName property, 476 overview, 476 TimedOut property, 476 WaitForZipCreation method, 474 WaitHandle class, 744, 754 WatcherChangeTypes enumeration, 476 WatchForAppEvent method, 303 WCF (Windows Communication Foundation), 625 Web application configuration files, 539–541 cached results and performance, 541–543 communicating with web servers, 524, 525 current connection settings, 641–648 escaping/unescaping data, 535–536 going through proxies, 525–527 handling web server errors, 522–523 hostname/IP address conversion, 517, 518 IP address/hostname conversion, 516, 517 obtaining HTML from URLs, 527, 528 prebuilding ASP.NET web sites, 532–534 reading XML, 552–554 tying tables to cache, 530–531 UriBuilder class, 537–539 web browser control, 528–530 web server error pages, 543–547 web browsers embedding functionality, 528–530 simulating form execution, 615–618 Web parsing URIs, 518–521 web servers communicating with, 524, 525 custom error pages, 543–547 handling errors, 522–523 simulating form execution, 615–618 Web Services, 455 web sites, prebuilding, 532–534 web.config file ASP.NET-based, 289 encrypting, 708–710 manipulating, 540 tying database tables to cache, 531 WebBrowser class, 528–530 WebBrowserNavigatedEventArgs class, 529 WebClient class DownloadData method, 619–621 DownloadFile method, 620 OpenRead method, 621 UploadData method, 619–621 UploadFile method, 620 UploadValues method, 615–618 WebConfigurationManager class accessing settings, 540 OpenWebConfiguration method, 539, 709 overview, 539–541 WebPermission class, 686 WebProxy class constructing objects, 526 Credentials property, 526 proxies and, 526 WebRequest class Create method, 648 DefaultWebProxy property, 526, 527 GetSystemWebProxy method, 526 HttpWebRequest class and, 524 proxy information, 647 web communications, 525 WebResponse class, 525 WeightedMovingAverage methods, 12–16 where keyword constraining type arguments, 172–173 creating generic types, 515 description, 3, 557 interface search mechanisms, 330–332 Where query operator, 6 while loops, 551 whitespace command-line parameters, 112 common patterns, 390 trimming from strings, 66 wildcards finding assembly members, 499 searching with, 459–463 Win32Exception exception, 780 Windows Communication Foundation (WCF), 625 Windows Firewall, 630 Index | 855 Windows Forms controlling debugging output, 289 displaying HTML, 528–530 generating code, 236 silent thread termination, 727 system change notifications, 771 unhandled exceptions, 279–280 Windows Forms controls, 236, 316 Windows Presentation Foundation (WPF), 281–283 WindowsAccountType enumeration, 656, 657 WinInet API, 641–648 workstations, message queues, 780–783 World Wide Web (see Web) WPF (Windows Presentation Foundation), 281–283 WriteExceptionShortDetail method, 253 X X.509 certificates, 704–708 XAML files, 282 XAttribute class, 551 Xbox360, 734–738 XCData class, 569–572 XComment class, 551, 569 XDocument class data in document order, 551 detecting document changes, 566–569 Load method, 553, 591 modified XML documents, 591–595 overview, 548 reading XML on Web, 552–554 Root property, 569 Validate method, 558–563, 591–595 WriteElementInfo method, 568 XDocumentType class, 569 XDR validation, 558–563 XElement class accessing multiple data domains, 18–19 assembling XML documents, 585–591 creating documents, 564–566 creating XML documents, 566 creating XML from databases, 27 data in document order, 551 handling invalid characters, 569–572 Load method, 553 overview, 548 splitting XML documents, 579–584 XDocument class and, 569 XPathSelectElements method, 555 XHTML strings, 391 856 | Index XLINQ (see LINQ to XML) XML (Extensible Markup Language) creating from databases, 22–30 debugging output, 289 extending transformations, 595–599 handling invalid characters, 569–572 inferring schemas, 599–600 LINQ to XML, 1, 18, 27–30 matching patterns, 391 overview, 548 reformatting output, 313 transformation parameters, 601–605 transforming, 572–579 XML documents assembling, 585–591 creating programmatically, 564–566 detecting changes, 566–569 order in accessing data, 548–552 querying contents, 554–558 reading on Web, 552–554 tearing apart, 579–584 transforming, 572–579 validating, 558–563 validating modified, 591–595 XmlDocument class assembling XML documents, 587–591 creating XML documents, 565, 566 handling invalid characters, 571 ImportNode method, 591 modified XML documents, 591–595 overview, 548 SelectNodes method, 33 splitting XML documents, 581 storing data securely, 676 Validate method, 593 XmlElement class handling invalid characters, 571 InnerText property, 570, 571, 572 InnerXML property, 571, 572 XmlMessageFormatter class, 781 XmlNode class, 584, 594 XmlNodeList class, 33 XmlNodeReader class, 594 XmlNodeType enumeration Attribute value, 552 CDATA value, 552 Comment value, 552 Document value, 552 DocumentFragment value, 552 DocumentType value, 552 Element value, 552 EndElement value, 552 EndEntity value, 552 Entity value, 552 EntityReference value, 552 None value, 552 Notation value, 552 ProcessingInstruction value, 552 SignificantWhitespace value, 552 Text value, 552 Whitespace value, 552 XmlDeclaration value, 552 xmlns:xslext namespace, 596 XmlReader class Create method, 554 creating XML documents, 566 modified XML documents, 591–595 overview, 548 Read method, 548–552 reading XML on Web, 552–554 Settings property, 551, 558–563 XmlResolver class, 578 XmlSchemaInference class, 599–600 XmlSecureResolver class, 578 XmlUrlResolver class, 554, 578 XmlWriter class creating XML documents, 564, 566 creating XML from databases, 29 handling invalid characters, 569 overview, 548 WriteAttributeString method, 569 WriteCData method, 569, 570 WriteElementString method, 569, 570 WriteString method, 569 WriteValue method, 569 XPath, 556–558 XPathDocument class, 555 XPathNavigator class, 555 XPathNodeIterator class, 555 XProcessingInstruction class, 569 XSD (XML schema) generating code, 236 getting in bulk, 599–600 validating, 558–563 xsl:text element, 578 xsl:value-of element, 596 XslCompiledTransform class, 574, 578 xslext:GetErrata method, 596 XSLT document( ) function, 602 extending transformations, 595–599 transformation parameters, 602–605 XML transformations, 574–578 XsltArgumentList class AddExtensionObject method, 595, 596 AddParam method, 602 transformation parameters, 602 XsltSettings class, 602 Y yield break statement, 218, 219 yield statement, 206, 227 Z zip codes, matching patterns, 391, 393 Index | 857 About the Authors Jay Hilyard has been developing Windows applications for more than 15 years and for NET for more than 7 of those He has published numerous articles in MSDN Magazine, and he currently works on the New Product Team at Newmarket International in Portsmouth, New Hampshire Stephen Teilhet has been working with the NET platform since the pre-alpha version of the NET 1.0 Framework was being developed by Microsoft Currently, he works for Ounce Labs, enhancing their static security code analysis tool to find vulnerabilities in several languages, including C# and Visual Basic Colophon The animal on the cover of C# 3.0 Cookbook, Third Edition, is a garter snake (Thamnophis sirtalis) Named because their longitudinal stripes resemble those on garters once used to hold up men’s socks, garter snakes are easily identified by their distinctive stripes: a narrow stripe down the middle of the back with a broad stripe on each side of it Color and pattern variations enable them to blend into their native environments, helping them evade predators They are the most common snake in North America and the only species of snake found in Alaska Garter snakes have keeled scales—one or more ridges down the central axis of the scales—giving them a rough texture and lackluster appearance Adult garter snakes generally range in length between 46 and 130 centimeters (one and a half feet to over four feet) Females are usually larger than males, with shorter tails and a bulge where the body and tail meet Female garters are ovoviviparous, meaning they deliver “live” young that have gestated in soft eggs Upon delivery, most of the eggs and mucous membranes have broken, which makes their births appear live Occasionally, a baby will be born still inside its soft shell A female will usually deliver 10 to 40 babies: the largest recorded number of live babies birthed by a garter snake is 98 Once emerging from their mothers, baby garters are completely independent and must begin fending for themselves During this time they are most susceptible to predation, and over half of all baby garters die before they are one year old Garter snakes are one of the few animals able to eat toads, newts, and other amphibians with strong chemical defenses Although diets vary depending on their environments, garter snakes mostly eat earthworms and amphibians; however, they occasionally dine on baby birds, fish, and small rodents Garter snakes have toxic saliva (harmless to humans), which they use to stun or kill their prey before swallowing them whole The cover image is from a 19th-century engraving from the Dover Pictorial Archive The cover font is Adobe ITC Garamond The text font is Linotype Birka; the heading font is Adobe Myriad Condensed; and the code font is LucasFont’s TheSans Mono Condensed ... Functors x | Table of Contents 31 8 32 2 32 4 32 7 33 0 33 2 34 4 34 8 35 2 35 6 36 1 10 Regular Expressions 36 6 10. 1 10. 2 10 .3 10. 4 10. 5 10. 6 10. 7 10. 8 10. 9... 59 62 63 64 65 66 67 Classes and Structures 68 3. 1 3. 2 3. 3 3. 4 3. 5 3. 6 3. 7 3. 8 3. 9 3. 10 3. 11 3. 12 3. 13 3.14 3. 15 3. 16 3. 17 3. 18 Creating Union-Type... the custom configuration section containing chapter information: CSharpRecipesConfigurationSection recipeConfig = ConfigurationManager.GetSection("CSharpRecipesConfiguration") as CSharpRecipesConfigurationSection;

Ngày đăng: 31/03/2014, 16:52

Từ khóa liên quan

Mục lục

  • C# 3.0 Cookbook

    • Table of Contents

    • Preface

      • Who This Book Is For

      • What You Need to Use This Book

      • Platform Notes

      • How This Book Is Organized

      • What Was Left Out

      • Conventions Used in This Book

      • About the Code

      • Using Code Examples

      • Comments and Questions

      • Safari® Books Online

      • Acknowledgments

        • From Jay Hilyard

        • From Steve Teilhet

        • Language Integrated Query (LINQ)

          • 1.0 Introduction

          • 1.1 Query a Message Queue

            • Problem

            • Solution

            • Discussion

            • See Also

            • 1.2 Using Set Semantics with Data

              • Problem

              • Solution

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan