C# 3.0 Cookbook phần 10

95 3 0
C# 3.0 Cookbook phần 10

Đ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

Để khắc phục điều này, sử dụng phương pháp XmlDocument.ImportNode, mà sẽ tạo một bản sao (sâu khi tham số thứ hai là đúng, hoặc cạn, khi tham số thứ hai là sai) của nút bạn đang mang trên XmlDocument mới. Ví dụ, khi bạn thêm các thông tin vận chuyển như vậy:

You can see the series of events in the project in the output The point at which the Developer has had enough is highlighted: Added CTO to the project Added Director to the project Added Project Manager to the project Added Product Manager to the project Added Test Engineer to the project Added Technical Communications Professional to the project Added Operations Staff to the project Added Support Staff to the project Task (6267 for CTO) was added to developer Task (6267 for CTO) status was reported Task (6267 for CTO) priority was increased to for developer CTO intervened and changed priority for task (6267 for CTO) Task (6267 for Director) was added to developer Task (6267 for Director) status was reported Task (6267 for Director) priority was increased to for developer Director intervened and changed priority for task (6267 for Director) Task (6267 for Project Manager) was added to developer Task (6267 for Project Manager) status was reported Task (6267 for Project Manager) priority was increased to for developer Project Manager intervened and changed priority for task (6267 for Project Manager) Task (6267 for Product Manager) was added to developer Task (6267 for Product Manager) status was reported Task (6267 for Technical Communications Professional) was added to developer Task (6267 for Technical Communications Professional) status was reported Task (6267 for Operations Staff) was added to developer Task (6267 for Operations Staff) status was reported Task (6267 for Support Staff) was added to developer Task (6267 for Support Staff) status was reported Task (6267 for Test Engineer) was added to developer Task (5368 for CTO) was added to developer Task (5368 for Director) was added to developer Task (5368 for Project Manager) was added to developer Task (6153 for Product Manager) was added to developer Task (913 for Test Engineer) was added to developer Task (6153 for Technical Communications Professional) was added to developer Task (6153 for Operations Staff) was added to developer Task (6153 for Support Staff) was added to developer Task (6267 for Product Manager) executed by developer Task (6267 for Technical Communications Professional) executed by developer Task (6267 for Operations Staff) executed by developer Task (6267 for Support Staff) executed by developer Task (6267 for CTO) priority was increased to for developer CTO intervened and changed priority for task (6267 for CTO) Task (6267 for Director) priority was increased to for developer Director intervened and changed priority for task (6267 for Director) Task (6267 for Project Manager) priority was increased to for developer Project Manager intervened and changed priority for task (6267 for Project Manager) Task (6267 for Test Engineer) executed by developer Task (7167 for CTO) was added to developer Optimizing Read-Mostly Access | 767 Task (7167 for Director) was added to developer Task (7167 for Project Manager) was added to developer Task (5368 for Product Manager) was added to developer Task (6153 for Test Engineer) was added to developer Task (5368 for Technical Communications Professional) was added to developer Task (5368 for Operations Staff) was added to developer Task (5368 for Support Staff) was added to developer Task (5368 for CTO) executed by developer Task (5368 for Director) executed by developer Task (5368 for Project Manager) executed by developer Task (6267 for CTO) status was reported Task (6267 for Director) status was reported Task (6267 for Project Manager) status was reported Task (913 for Test Engineer) status was reported Task (6267 for Technical Communications Professional) status was reported Task (6267 for Technical Communications Professional) is done for Technical Communications Professional Task (6267 for Product Manager) status was reported Task (6267 for Product Manager) is done for Product Manager Task (6267 for Operations Staff) status was reported Task (6267 for Operations Staff) is done for Operations Staff Task (6267 for Support Staff) status was reported Task (6267 for Support Staff) is done for Support Staff Task (6153 for Product Manager) executed by developer Task (2987 for CTO) was added to developer Task (2987 for Director) was added to developer Task (2987 for Project Manager) was added to developer Task (7167 for Product Manager) was added to developer Task (4126 for Test Engineer) was added to developer Task (7167 for Technical Communications Professional) was added to developer Task (7167 for Support Staff) was added to developer Task (7167 for Operations Staff) was added to developer Task (913 for Test Engineer) executed by developer Task (6153 for Technical Communications Professional) executed by developer Developer has too many tasks, quitting! 21 tasks left unfinished Task (6153 for Operations Staff) executed by developer Task (5368 for CTO) priority was increased to for developer CTO intervened and changed priority for task (5368 for CTO) Task (5368 for Director) priority was increased to for developer Director intervened and changed priority for task (5368 for Director) Task (5368 for Project Manager) priority was increased to for developer Project Manager intervened and changed priority for task (5368 for Project Manager) Task (6153 for Support Staff) executed by developer Task (4906 for Product Manager) was added to developer Task (7167 for Test Engineer) was added to developer Task (4906 for Technical Communications Professional) was added to developer Task (4906 for Operations Staff) was added to developer Task (4906 for Support Staff) was added to developer Task (7167 for CTO) executed by developer Task (7167 for Director) executed by developer 768 | Chapter 18: Threading and Synchronization Task Task Task Task Task Task Task Task Task Task Task (7167 (5368 (6153 (5368 (5368 (5368 (2987 (2987 (2987 (7167 (4126 for for for for for for for for for for for Project Manager) executed by developer Product Manager) executed by developer Test Engineer) executed by developer Technical Communications Professional) executed by developer Operations Staff) executed by developer Support Staff) executed by developer CTO) executed by developer Director) executed by developer Project Manager) executed by developer Product Manager) executed by developer Test Engineer) executed by developer See Also The “ReaderWriterLockSlim” and “SQL Server Programming and Host Attributes” topics in the MSDN documentation Optimizing Read-Mostly Access | 769 Chapter 19 19 CHAPTER Toolbox 19 19.0 Introduction Every programmer has a certain set of routines that he refers back to and uses over and over again These utility functions are usually bits of code that are not provided by any particular language or framework This chapter is a compilation of utility routines that we have gathered during our time with C# and the NET Framework The type of things we share in this chapter are: • Determining the path for various locations in the operating system • Interacting with services • Inspecting the Global Assembly Cache • Message queuing It is a grab bag of code that can help to solve a specific need while you are working on a larger set of functionality in your application 19.1 Dealing with Operating System Shutdown, Power Management, or User Session Changes Problem You want to be notified whenever the operating system or a user has initiated an action that requires your application to shut down or be inactive (user logoff, remote session disconnect, system shutdown, hibernate/restore, etc.) This notification will allow you have your application respond gracefully to the changes 770 Solution Use the Microsoft.Win32.SystemEvents class to get notification of operating system, user session change, and power management events The RegisterForSystemEvents method shown next hooks up the five event handlers necessary to capture these events and would be placed in the initialization section for your code: public static void RegisterForSystemEvents( ) { // Always get the final notification when the event thread is shutting down // so we can unregister SystemEvents.EventsThreadShutdown += new EventHandler(OnEventsThreadShutdown); SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(OnPowerModeChanged); SystemEvents.SessionSwitch += new SessionSwitchEventHandler(OnSessionSwitch); SystemEvents.SessionEnding += new SessionEndingEventHandler(OnSessionEnding); SystemEvents.SessionEnded += new SessionEndedEventHandler(OnSessionEnded); } The EventsThreadShutdown event notifies you of when the thread that is distributing the events from the SystemEvents class is shutting down so that you can unregister the events on the SystemEvents class if you have not already done so The PowerModeChanged event triggers when the user suspends or resumes the system from a suspended state The SessionSwitch event is triggered by a change in the logged-on user The SessionEnding event is triggered when the user is trying to log off or shut down the system, and the SessionEnded event is triggered when the user is actually logging off or shutting down the system The events can be unregistered using the UnregisterFromSystemEvents method UnregisterFromSystemEvents should be called from the termination code of your Windows Form, user control, or any other class that may come and go, as well as from one other area shown later in the recipe: private static void UnregisterFromSystemEvents( ) { SystemEvents.EventsThreadShutdown -= new EventHandler(OnEventsThreadShutdown); SystemEvents.PowerModeChanged -= new PowerModeChangedEventHandler(OnPowerModeChanged); SystemEvents.SessionSwitch -= new SessionSwitchEventHandler(OnSessionSwitch); SystemEvents.SessionEnding -= new SessionEndingEventHandler(OnSessionEnding); SystemEvents.SessionEnded -= new SessionEndedEventHandler(OnSessionEnded); } Dealing with Operating System Shutdown, Power Management, or User Session Changes | 771 Since the events exposed by SystemEvents are static, if you are using them in a section of code that could be invoked multiple times (secondary Windows Form, user control, monitoring class, etc.), you must unregister your handlers, or you will cause memory leaks in the application The SystemEvents handler methods are the individual event handlers for each of the events that have been subscribed to in RegisterForSystemEvents The first handler to cover is the OnEventsThreadShutdown handler It is essential that your handlers are unregistered if this event fires, as the notification thread for the SystemEvents class is going away, and the class may be gone before your application is If you haven’t unregistered before that point, you will cause memory leaks, so add a call to UnregisterFromSystemEvents into this handler as shown here: private static void OnEventsThreadShutdown(object sender, EventArgs e) { Debug.WriteLine("System event thread is shutting down, no more notifications "); // Unregister all our events as the notification thread is going away UnregisterFromSystemEvents( ); } The next handler to explore is the OnPowerModeChanged method This handler can report the type of power management event through the Mode property of the PowerModeEventChangedArgs parameter The Mode property has the PowerMode enumeration type and specifies the event type through the enumeration value contained therein: private static void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e) { // Power mode is changing switch (e.Mode) { case PowerModes.Resume: Debug.WriteLine("PowerMode: OS is resuming from suspended state"); break; case PowerModes.StatusChange: Debug.WriteLine("PowerMode: There was a change relating to the power" + " supply (weak battery, unplug, etc )"); break; case PowerModes.Suspend: Debug.WriteLine("PowerMode: OS is about to be suspended"); break; } } The next three handlers all deal with operating system session states They are OnSessionSwitch, OnSessionEnding, and OnSessionEnded Handling all three of these events covers all of the operating system session state transitions that your 772 | Chapter 19: Toolbox application may need to worry about In OnSessionEnding, there is a SessionEndingEventArgs parameter, which has a Cancel member This Cancel member allows you to request that the session not end if set to false Code for the three handlers is shown in Example 19-1 Example 19-1 OnSessionSwitch, OnSessionEnding, and OnSessionEnded handlers private static void OnSessionSwitch(object sender, SessionSwitchEventArgs e) { // Check reason switch (e.Reason) { case SessionSwitchReason.ConsoleConnect: Debug.WriteLine("Session connected from the console"); break; case SessionSwitchReason.ConsoleDisconnect: Debug.WriteLine("Session disconnected from the console"); break; case SessionSwitchReason.RemoteConnect: Debug.WriteLine("Remote session connected"); break; case SessionSwitchReason.RemoteDisconnect: Debug.WriteLine("Remote session disconnected"); break; case SessionSwitchReason.SessionLock: Debug.WriteLine("Session has been locked"); break; case SessionSwitchReason.SessionLogoff: Debug.WriteLine("User was logged off from a session"); break; case SessionSwitchReason.SessionLogon: Debug.WriteLine("User has logged on to a session"); break; case SessionSwitchReason.SessionRemoteControl: Debug.WriteLine("Session changed to or from remote status"); break; case SessionSwitchReason.SessionUnlock: Debug.WriteLine("Session has been unlocked"); break; } } private static void OnSessionEnding(object sender, SessionEndingEventArgs e) { // True to cancel the user request to end the session, false otherwise e.Cancel = false; // Check reason switch(e.Reason) { case SessionEndReasons.Logoff: Debug.WriteLine("Session ending as the user is logging off"); break; case SessionEndReasons.SystemShutdown: Dealing with Operating System Shutdown, Power Management, or User Session Changes | 773 Example 19-1 OnSessionSwitch, OnSessionEnding, and OnSessionEnded handlers (continued) Debug.WriteLine("Session ending as the OS is shutting down"); break; } } private static void OnSessionEnded(object sender, SessionEndedEventArgs e) { switch (e.Reason) { case SessionEndReasons.Logoff: Debug.WriteLine("Session ended as the user is logging off"); break; case SessionEndReasons.SystemShutdown: Debug.WriteLine("Session ended as the OS is shutting down"); break; } } Discussion The NET Framework provides many opportunities to get feedback from the system when there are changes due to either user or system interactions The SystemEvents class exposes more events than just the ones used in this recipe For a full listing, see Table 19-1 Table 19-1 The SystemEvents events Value Description DisplaySettingsChanged User changed display settings DisplaySettingsChanging Display settings are changing EventsThreadShutdown Thread listening for system events is terminating InstalledFontsChanged User added or removed fonts PaletteChanged User switched to an application with a different palette PowerModeChanged User suspended or resumed the system SessionEnded User shut down the system or logged off SessionEnding User is attempting to shut down the system or log off SessionSwitch The currently logged-in user changed TimeChanged User changed system time TimerElapsed A Windows timer interval expired UserPreferenceChanged User changed a preference in the system UserPreferenceChanging User is trying to change a preference in the system 774 | Chapter 19: Toolbox Keep in mind that these are system events Therefore, the amount of work done in the handlers should be kept to a minimum, so the system can move on to the next task The notifications from SystemEvents come on a dedicated thread for raising these events In a Windows Forms application, you will need to get back on to the correct user interface thread before updating a UI with any of this information, using one of the various methods for doing so (Control.BeginInvoke, Control.Invoke, BackgroundWorker) See Also The “SystemEvents Class,” “PowerModeChangedEventArgs Class,” “SessionEndedEventArgs Class,” “SessionEndingEventArgs Class,” “SessionSwitchEventArgs Class,” “TimerElapsedEventArgs Class,” “UserPreferenceChangingEventArgs Class,” and “UserPreferenceChangedEventArgs Class” topics in the MSDN documentation 19.2 Controlling a Service Problem You need to programmatically manipulate a service that your application interacts with Solution Use the System.ServiceProcess.ServiceController class to control the service ServiceController allows you to interact with an existing service and to read and change its properties In the example, it will be used to manipulate the ASP.NET State Service The name, the service type, and the display name are easily available from the ServiceName, ServiceType, and DisplayName properties: ServiceController scStateService Console.WriteLine("Service Name: Console.WriteLine("Service Type: Console.WriteLine("Display Name: = " " " new ServiceController("COM+ Event System"); + scStateService.ServiceName); + scStateService.ServiceType.ToString( )); + scStateService.DisplayName); The ServiceType enumeration has a number of values, as shown in Table 19-2 Table 19-2 The ServiceType enumeration values Value Description Adapter Service that serves a hardware device FileSystemDriver Driver for the filesystem (kernel level) InteractiveProcess Service that communicates with the desktop KernelDriver Low-level hardware device driver Controlling a Service | 775 Table 19-2 The ServiceType enumeration values (continued) Value Description RecognizerDriver Driver for identifying filesystems on startup Win32OwnProcess Win32 program that runs as a service in its own process Win32ShareProcess Win32 program that runs as a service in a shared process such as SvcHost One useful task is to determine a service’s dependents The services that depend on the current service are accessed through the DependentServices property, an array of ServiceController instances (one for each dependent service): foreach (ServiceController sc in scStateService.DependentServices) { Console.WriteLine(scStateService.DisplayName + " is depended on by: " + sc.DisplayName); } To see the services that the current service does depend on, the ServicesDependedOn array contains ServiceController instances for each of those: foreach (ServiceController sc in scStateService.ServicesDependedOn) { Console.WriteLine(scStateService.DisplayName + " depends on: " + sc.DisplayName); } One of the most important things about services is what state they are in A service doesn’t much good if it is supposed to be running and it isn’t—or worse yet, it is supposed to be disabled (perhaps as a security risk) and isn’t To find out the current status of the service, check the Status property For this example, the original state of the service will be saved, so it can be restored later in the originalState variable: Console.WriteLine("Status: " + scStateService.Status); // Save original state ServiceControllerStatus originalState = scStateService.Status; If a service is stopped, it can be started with the Start method First, check if the service is stopped, and then, once Start has been called on the ServiceController instance, the WaitForStatus method should be called to make sure that the service started WaitForStatus can take a timeout value so that the application is not waiting forever for the service to start in the case of a problem: // If it is stopped, start it TimeSpan serviceTimeout = TimeSpan.FromSeconds(60); if (scStateService.Status == ServiceControllerStatus.Stopped) { scStateService.Start( ); // Wait up to 60 seconds for start scStateService.WaitForStatus(ServiceControllerStatus.Running, serviceTimeout); } Console.WriteLine("Status: " + scStateService.Status); 776 | Chapter 19: Toolbox 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, EndsWith method, 47–49 Format method, 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, 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, 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, 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, reusing parameterized queries, variables determining type, 101–103 environment, 468, 469 hash codes and, 401 implicitly typed local, 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, 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 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 ... Convert.ToInt32(base8, 8)); Converting a Number in Another Base to Base10 | 797 Console.WriteLine("Convert.ToInt32(base10, 10) = " + Convert.ToInt32(base10, 10) ); Console.WriteLine("Convert.ToInt32(base16, 16)... base10 Solution To convert a number in another base to base10, use the overloaded static Convert ToInt32 method on the Convert class: string string string string base2 = "11"; base8 = "17"; base10... Convert.ToInt32(base2, 2) = Convert.ToInt32(base8, 8) = Convert.ToInt32(base10, 10) Convert.ToInt32(base16, 16) 15 = 110 = 4607 Discussion The static Convert.ToInt32 method has an overload that

Ngày đăng: 11/05/2021, 03:54

Mục lục

  • C# 3.0 Cookbook

    • Threading and Synchronization

      • 18.11 Optimizing Read-Mostly Access

        • See Also

        • Toolbox

          • 19.0 Introduction

          • 19.1 Dealing with Operating System Shutdown, Power Management, or User Session Changes

            • Problem

            • Solution

            • Discussion

            • See Also

            • 19.2 Controlling a Service

              • Problem

              • Solution

              • Discussion

              • See Also

              • 19.3 List What Processes an Assembly Is Loaded In

                • Problem

                • Solution

                • Discussion

                • See Also

                • 19.4 Using Message Queues on a Local Workstation

                  • Problem

                  • Solution

                  • Discussion

                  • See Also

                  • 19.5 Finding the Path to the Current Framework Version

                    • Problem

                    • Solution

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

Tài liệu liên quan