|
VB.NET Programmer's Cookbook
With a generous helping of code examples, code snippets, and solutions to common development problems - direct from expert programmers - this guide is the logical place for intermediate and advanced developers to start building development projects or learn more about Visual Basic .NET. It uses the cookbook technique - providing code plus instructions
on how to use each recipe - so developers can quickly apply the code to their own projects or simply play around with the ingredients to learn more about Visual Basic .NET.
Table of contents :
1 Strings and Regular Expressions 1
1.1 Combine Strings 2
1.2 Retrieve a Portion of a String 4
1.3 Create a String Consisting of a Repeated Character 5
1.4 Change the Case of All Characters in a String 5
1.5 Perform Case-Insensitive String Comparisons 6
1.6 Iterate Over All the Characters in a String 7
1.7 Parse a String Into Words 8
1.8 Find All Occurrences of Specific Text in a String 11
1.9 Replace All Occurrences of Specific Text in a String 13
1.10 Pad a String for Fixed-Width Display 14
1.11 Reverse a String 16
1.12 Insert a New Line in a String 17
1.13 Insert a Special Character in a String 18
1.14 Manipulate Strings Quickly with StringBuilder 19
1.15 Convert a String into a Byte Array 21
1.16 Get a String Representation of a Byte Array 23
1.17 Use Common Regular Expressions 25
1.18 Validate Input with a Regular Expression 29
1.19 Find All Occurrences of a Pattern in a String 30
1.20 Replace All Occurrences of a Pattern in a String 32
1.21 Manipulate a Filename 34
1.22 Manipulate a URI 35
1.23 Validate a Credit Card with Luhn's Algorithm 37
1.24 Validate an ISBN 38
1.25 Perform a SoundEx String Comparison 39
2 Numbers, Dates, and Other Data Types 43
2.1 Perform Mathematical and Trigonometric Operations 44
2.2 Convert a Number into a Formatted String 45
2.3 Generate a Random Number 47
2.4 Work with Non - Base 10 Number Systems 48
2.5 Work with Complex Numbers 49
2.6 Work with Vectors 53
2.7 Work with Matrixes 56
2.8 Work with Fractions Without Using Decimals 57
2.9 Evaluate a String Expression 60
2.10 Get the System Date and Time 63
2.11 Add and Subtract Dates and Times 63
2.12 Determine Days of the Week, Leap Years, and More 65
2.13 Get Day and Month Names in Other Languages 66
2.14 Format a Date 67
2.15 Generate a Culture-Invariant Date String 70
2.16 Validate a User-Supplied Date 70
2.17 Generate a GUID 71
2.18 Convert Basic Types to Binary 73
2.19 Test Byte Arrays for Equality 75
2.20 Convert the Name of an Enumerated Value into the Value 76
3 Arrays and Collections 79
3.1 Create and Populate an Array in One Step 80
3.2 Resize an Array 81
3.3 Create an Array That Is Not Bounded at Zero 82
3.4 Create a Jagged Array 83
3.5 Use a Dynamic ArrayList 85
3.6 Fill an ArrayList from an Array 87
3.7 Convert an ArrayList to an Array 87
3.8 Sort Items in an Array or ArrayList 89
3.9 Sort Non-Comparable Items in an Array or ArrayList 91
3.10 Use a Hashtable Instead of a Generic Collection 93
3.11 Enumerate Items in a Hashtable 96
3.12 Use a Queue (FIFO Collection) 97
3.13 Use a Stack (LIFO Collection) 98
3.14 Use a Sorted List 99
3.15 Create Shallow and Deep Copies of a Collection or Array 101
3.16 Create a Strongly Typed Collection 102
3.17 Create a Strongly Typed Dictionary Collection 105
3.18 Remove Items While Iterating Through a Collection 106
3.19 Iterate Through Collection Items in Random Order 108
4 Objects, Interfaces, and Patterns 111
4.1 Create a Value Type 112
4.2 Create a Cloneable Object 116
4.3 Create a Type-Safe Clone Method 118
4.4 Create a Comparable Object 119
4.5 Create a Disposable Object 121
4.6 Create an Object That Can Appear in the Component Tray 123
4.7 Create a Convertible Object 125
4.8 Create a Serializable Object 127
4.9 Serialize an Object to Disk 129
4.10 Clone a Serializable Object 131
4.11 Serialize Public Members of a Nonserializable Object 132
4.12 Perform Selective Serialization with the Memento Pattern 135
4.13 Throw a Custom Exception 140
4.14 Raise a Custom Event 142
4.15 Use the Singleton Pattern 144
4.16 Use the Factory Pattern 145
4.17 Use the Registry Pattern 148
4.18 Use the Lazy Initialization Pattern 149
5 Files and Directories 151
5.1 Manipulate a File 152
5.2 Manipulate a Directory 155
5.3 Retrieve File Version Information 156
5.4 Use Bitwise Arithmetic with File Attributes 158
5.5 Read to and Write from a Binary File 159
5.6 Filter Files with Wildcards 161
5.7 Process Files Recursively 162
5.8 Search for a File with Specific Text 164
5.9 Fill a TreeView with a Just-In-Time Directory Tree 167
5.10 Test Two Files for Equality 169
5.11 Monitor the File System for Changes 171
5.12 Create a Temporary File 174
5.13 Get the Executable Path 174
5.14 Set the Current Working Path 175
5.15 Use an Isolated Store 176
5.16 Read Application Configuration Settings 178
5.17 Create Custom Configuration Sections 180
5.18 Read Header Information from MP3 Files 182
5.19 Get Started with ZIP Files 184
5.20 Get Started with PDF Files 186
6 XML 187
6.1 Load an XML Document into Memory 188
6.2 Process All Nodes in a Document 191
6.3 Insert Nodes in an XML Document 193
6.4 Find Specific Elements by Name 195
6.5 Find Elements with an XPath Search 196
6.6 Load an XML Document into a Class 199
6.7 Use XML Serialization with Custom Objects 203
6.8 Perform an XSL Transform 208
6.9 Validate an XML Document Against a Schema 210
6.10 Store Binary Data with a Base64 Transform 215
7 Multithreading 219
7.1 Call Any Method Asynchronously with a Delegate 220
7.2 Wait for Several Asynchronous Calls to Complete 224
7.3 Wait for One of Many Asynchronous Calls to Complete 225
7.4 Use a Callback with an Asynchronous Call 227
7.5 Perform an Asynchronous Task with the Thread Class 231
7.6 Use Synchronization Code with Multiple Threads 234
7.7 Use the Thread Object with a Task That Requires Data 237
7.8 Use the Thread Object with a Task That Returns Data 239
7.9 Marshal User Interface Code to the Correct Thread 242
7.10 Stop a Thread Politely 247
7.11 Create a Thread Wrapper Class 249
7.12 Create a Reusable Task Processor 252
7.13 Use a Pool of Threads 255
8 Network Programming 259
8.1 Get Web Connectivity Information for the Current Computer 260
8.2 Get the IP Address of the Current Computer 261
8.3 Look Up a Host Name for an IP Address 262
8.4 Ping an IP Address 263
8.5 Download a File Using HTTP 264
8.6 Retrieve a Single Piece of Information from a Web Page 265
8.7 Find All Links in a Web Page 268
8.8 Communicate Using TCP 271
8.9 Create a Multithreaded TCP Network Server 275
8.10 Communicate Using UDP 278
8.11 Send a Broadcast Message 280
8.12 Send E-Mail Through SMTP 281
8.13 Retrieve E-Mail Through POP3 283
8.14 Access an FTP Site 291
9 Reflection 299
9.1 Generate a Dynamic About Box 299
9.2 List Assembly Dependencies 302
9.3 Get Type Information from a Class or an Object 303
9.4 Examine a Type for Members 305
9.5 Examine an Assembly for Types 308
9.6 Instantiate a Type by Name 311
9.7 Load an Assembly from a Remote Location 313
9.8 Invoke a Method by Name 314
9.9 Create, Apply, and Identify a Custom Attribute 317
9.10 Identify the Caller of a Procedure 320
9.11 Reflect on a WMI Class 323
9.12 Compile Source Code Programmatically 326
10 Windows Programming 329
10.1 Access the Registry 330
10.2 Retrieve Environment Variables 333
10.3 Handle Operating System Events 334
10.4 Access the Desktop and the Start Menu 336
10.5 Create Desktop or Start Menu Shortcuts 338
10.6 Start a Windows Application with a Main Subroutine 341
10.7 Retrieve Command-Line Parameters 344
10.8 Run the Application That Owns a File Extension 346
10.9 Find Other Running Processes 348
10.10 Terminate Another Process 351
10.11 Allow Only One Instance of Your Application to Run 352
10.12 Send Keystrokes to an Application 354
10.13 Force a Windows Shutdown or Logoff 356
10.14 Play a WAV File 357
10.15 Display the Standard Directory Selection Dialog Box 359
10.16 Use the Clipboard 362
10.17 Display Context-Sensitive Help 364
10.18 Catch Unhandled Errors 366
10.19 Create a Windows Installer Setup Project 367
10.20 Install the .NET Framework on a Client 370
10.21 Associate a File Extension with Your Application 371
11 Windows Controls 375
11.1 Add a Control at Runtime 375
11.2 Store Arbitrary Data in a Control 378
11.3 Replace a Control Array 380
11.4 Clear All Controls on a Form 382
11.5 Store Objects in a List 384
11.6 Force a ListBox to Scroll 386
11.7 Use a Hyperlink 388
11.8 Restrict a Text Box to Numeric Input 390
11.9 Use an Auto-Complete Combo Box 391
11.10 Sort a ListView Based on Any Column 393
11.11 Use the Drag-and-Drop Feature 395
11.12 Show a Linked Context Menu Generically 397
11.13 Use Part of the Main Menu for a Context Menu 398
11.14 Make a Multilingual Form 399
11.15 Use Form Inheritance 402
11.16 Create a Form That Can't Be Moved 403
11.17 Make a Borderless Form Movable 404
11.18 Save the Size and Location of a Form 406
11.19 Synchronize Controls on a Form 408
11.20 Create a System Tray Application 411
11.21 Apply Windows XP Control Styles 413
12 Printing and Drawing with GDI+ 417
12.1 Find All Installed Printers 418
12.2 Print a Simple Document 420
12.3 Print a Document That Has Multiple Pages 423
12.4 Print Centered Text 427
12.5 Print Wrapped Text 428
12.6 Print from a File 432
12.7 Display a Dynamic Print Preview 436
12.8 Retrieve Print Queue Information 438
12.9 Manage Print Jobs 441
12.10 Find All Installed Fonts 443
12.11 Convert the Format of an Image 444
12.12 Paint Static Content 448
12.13 Paint Dynamic Content 449
12.14 Use System Colors 452
12.15 Improve the Rendering Quality 453
12.16 Perform Hit Testing with Shapes 455
12.17 Draw Picture Thumbnails 457
12.18 Use Double Buffering to Increase Redraw Speed 459
12.19 Display an Irregularly Shaped Window 461
12.20 Create an Owner-Drawn Menu 463
12.21 Create an Owner-Drawn List Box 467
13 Windows Services 473
13.1 Use a Windows Service with a Timer 474
13.2 Use a Windows Service with a Thread 476
13.3 Create a Windows Service Installer 478
13.4 Debug a Windows Service 481
13.5 Retrieve Information About Installed Windows Services 483
13.6 Start and Stop a Windows Service Programmatically 485
13.7 Interact with Windows Services on Another Computer 486
13.8 Create a Windows Service That Uses a System Tray Icon 486
14 ADO.NET 491
14.1 Use Connection Pooling 492
14.2 Retrieve the Unique ID for a New Record 494
14.3 Retrieve the Unique ID for a New Record in a DataSet 497
14.4 Protect Against SQL Injection Attacks 499
14.5 Execute Multiple SQL Statements at Once 501
14.6 Use Column and Table Mappings 503
14.7 Use Last-In-Wins Concurrency with the DataAdapter 505
14.8 Optimize DataAdapter Performance with a Timestamp 508
14.9 Handle DataAdapter Concurrency Errors 511
14.10 Use a Transaction with the DataAdapter 513
14.11 Read Large Binary Fields Efficiently with a DataReader 516
14.12 Select a Subset of Data from a DataSet 518
14.13 Create a Custom Record Browser 520
14.14 Filter or Sort Data with a DataView 523
14.15 Create a Master-Details Form 526
14.16 Format Data-Bound Fields 528
14.17 Bind an Image Field to a PictureBox 530
14.18 Bind a Field to a List Control, and Restrict It to the Values from Another Table 532
14.19 Create a Calculated Column That Uses a Relationship 535
14.20 Create a Typed DataSet 537
14.21 Read an Excel File with ADO.NET 541
15 ASP.NET Web Applications 545
15.1 Enable Web Site Debugging 546
15.2 Store Information Between Requests 549
15.3 Add Line Breaks to a Label Control 554
15.4 Use JavaScript to Handle Key Presses, Mouse Movements, and More 555
15.5 Programmatically Set Control Focus 557
15.6 Upload a File 558
15.7 Use Custom Error Pages 561
15.8 Use Forms Authentication 562
15.9 Validate User Input 564
15.10 Use Page or Fragment Caching 568
15.11 Store Arbitrary Data in the ASP.NET Cache 570
15.12 Add Controls to a Web Form Dynamically 572
15.13 Load User Controls Programmatically 575
15.14 Dynamically Generate an Image 577
15.15 Dynamically Generate an Image on Part of a Page 581
15.16 Use the Internet Explorer Controls 584
15.17 Use a Dynamic Menu Control 589
16 Web Services 593
16.1 Avoid Hard-Coding the Web Service URL 594
16.2 Add Response Caching 596
16.3 Add Data Caching 597
16.4 Create a Transactional Web Method 599
16.5 Create a One-Way Web Method 602
16.6 Set Authentication Credentials for a Web Service 603
16.7 Use Session State 607
16.8 Upload or Download Large Binary Data 609
16.9 Send Out-of-Band Data in a SOAP Header 611
16.10 Trace a SOAP Message Using the SOAP Toolkit 615
16.11 Log SOAP Messages with a SOAP Extension 617
16.12 Call a Web Service from a Visual Basic 6 Client 622
17 Remoting and Enterprise Services 625
17.1 Make an Object Remotable 626
17.2 Register All the Remotable Classes in an Assembly 630
17.3 Host a Remote Object in IIS 632
17.4 Fire an Event over a Remoting Channel 634
17.5 Access a Remote Object Through an Interface 639
17.6 Control the Lifetime of a Remote Object 642
17.7 Use a Sponsor to Keep Remote Objects Alive 645
17.8 Control Versioning for Remote Objects 647
17.9 Use a One-Way Method 649
17.10 Track Multiple Clients with a Singleton 650
17.11 Create a COM+ Serviced Component 655
17.12 Prevent Duplicate Entries for Serviced Components 657
17.13 Create a Pooled Component 658
17.14 Use a COM+ Distributed Transaction 661
17.15 Write to the Windows Event Log 663
17.16 Find All the Message Queues on a Computer 665
17.17 Send a Custom Message Object Through Message Queuing 666
17.18 Use a Custom Performance Counter 669
18 Security and Cryptography 673
18.1 Retrieve Information About the Current Windows User 674
18.2 Use Windows Role-Based Security 675
18.3 Retrieve a List of All Windows Accounts or Groups 678
18.4 Log In to Another Account Programmatically 680
18.5 Impersonate the IIS User with ASP.NET 684
18.6 Use SSL Encryption with ASP.NET 686
18.7 Symmetrically Encrypt a File 688
18.8 Symmetrically Encrypt Any Data 693
18.9 Derive a Key from a Password 695
18.10 Asymmetrically Encrypt Data 697
18.11 Combine Asymmetric and Symmetric Encryption 700
18.12 Encrypt an Object 702
18.13 Verify That Data Hasn't Changed 705
18.14 Create a Tamper-Proof Hash Code 707
18.15 Create an XML Digital Signature 710
18.16 Store a Salted Password Hash in a Database 713
18.17 Generate a Secure Random Number 719
18.18 Generate a Secure Random GUID 721
18.19 Determine the Evidence Associated with an Assembly 722
18.20 Programmatically Restrict Code Permissions 723
19 Useful COM Interop 727
19.1 Use ADO Classic 727
19.2 Display a Web Page with Internet Explorer 729
19.3 Drive Internet Explorer 731
19.4 Drive Microsoft Word 733
19.5 Drive Microsoft Excel 736
19.6 Use MAPI to Send E-Mail Messages 740
19.7 Play Media Files 742
19.8 Use Masked Text Boxes
|