C# Cookbook, Second Edition
By
Jay Hilyard,
Stephen Teilhet
January 2006
Pages: 1184
| Table of Contents
| Index
| Sample Chapter
| Colophon
Table of Contents
-
Chapter 1 Numbers and Enumerations
-
Introduction
-
Determining Approximate Equality Between a Fraction and Floating-Point Value
-
Converting Degrees to Radians
-
Converting Radians to Degrees
-
Using the Bitwise Complement Operator with Various Data Types
-
Testing for an Even or Odd Value
-
Obtaining the High Word or Low Word of a Number
-
Converting a Number in Another Base to Base10
-
Determining Whether a String Is a Valid Number
-
Rounding a Floating-Point Value
-
Choosing a Rounding Algorithm
-
Converting Celsius to Fahrenheit
-
Converting Fahrenheit to Celsius
-
Safely Performing a Narrowing Numeric Cast
-
Finding the Length of Any Three Sides of a Right Triangle
-
Finding the Angles of a Right Triangle
-
Displaying an Enumeration Value as a String
-
Converting Plain Text to an Equivalent Enumeration Value
-
Testing for a Valid Enumeration Value
-
Testing for a Valid Enumeration of Flags
-
Using Enumerated Members in a Bit Mask
-
Determining if One or More Enumeration Flags Are Set
-
Determining the Integral Part of a Decimal or Double
-
Chapter 2 Strings and Characters
-
Introduction
-
Determining the Kind of Character a char Contains
-
Determining Whether a Character Is Within a Specified Range
-
Controlling Case Sensitivity When Comparing Two Characters
-
Finding All Occurrences of a Character Within a String
-
Finding the Location of All Occurrences of a String Within Another String
-
Implementing a Poor Man's Tokenizer to Deconstruct a String
-
Controlling Case Sensitivity When Comparing Two Strings
-
Comparing a String to the Beginning or End of a Second String
-
Inserting Text into a String
-
Removing or Replacing Characters Within a String
-
Encoding Binary Data as Base64
-
Decoding a Base64-Encoded Binary
-
Converting a String Returned as a Byte[ ] Back into a String
-
Passing a String to a Method That Accepts only a Byte[ ]
-
Converting Strings to Other Types
-
Formatting Data in Strings
-
Creating a Delimited String
-
Extracting Items from a Delimited String
-
Setting the Maximum Number of Characters a StringBuilder Can Contain
-
Iterating over Each Character in a String
-
Improving String Comparison Performance
-
Improving StringBuilder Performance
-
Pruning Characters from the Head and/or Tail of a String
-
Testing a String for Null or Empty
-
Appending a Line
-
Encoding Chunks of Data
-
Chapter 3 Classes and Structures
-
Introduction
-
Creating Union-Type Structures
-
Allowing a Type to Represent Itself as a String
-
Converting a String Representation of an Object into an Actual Object
-
Implementing Polymorphism with Abstract Base Classes
-
Making a Type Sortable
-
Making a Type Searchable
-
Indirectly Overloading the +=, -=, /=, and *= Operators
-
Indirectly Overloading the &&, ||, and ?: Operators
-
Turning Bits On or Off
-
Making Error-Free Expressions
-
Minimizing (Reducing) Your Boolean Logic
-
Converting Between Simple Types in a 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
-
Implementing Polymorphism with Interfaces
-
Calling the Same Method on Multiple Object Types
-
Adding a Notification Callback Using an Interface
-
Using Multiple Entry Points to Version an Application
-
Preventing the Creation of an Only Partially Initialized Object
-
Returning Multiple Items from a Method
-
Parsing Command-Line Parameters
-
Retrofitting a Class to Interoperate with COM
-
Initializing a Constant Field at Runtime
-
Writing Code That Is Compatible with the Widest Range of Managed Languages
-
Building Cloneable Classes
-
Assuring an Object's Disposal
-
Releasing a COM Object Through Managed Code
-
Creating an Object Cache
-
Rolling Back Object Changes
-
Disposing of Unmanaged Resources
-
Determining Where Boxing and Unboxing Occur
-
Chapter 4 Generics
-
Introduction
-
Deciding When and Where to Use Generics
-
Understanding Generic Types
-
Getting the Type of a Generic Type
-
Replacing the ArrayList with Its Generic Counterpart
-
Replacing the Stack and Queue with Their Generic Counterparts
-
Implementing 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
-
Replacing the Hashtable with Its Generic Counterpart
-
Using foreach with Generic Dictionary Types
-
Constraining Type Arguments
-
Initializing Generic Variables to Their Default Values
-
Chapter 5 Collections
-
Introduction
-
Swapping Two Elements in an Array
-
Reversing an Array Quickly
-
Reversing a Two-Dimensional Array
-
Reversing a Jagged Array
-
Writing a More Flexible StackTrace Class
-
Determining the Number of Times an Item Appears in a List<T>
-
Retrieving All Instances of a Specific Item in a List<T>
-
Inserting and Removing Items from an Array
-
Keeping Your List<T> Sorted
-
Sorting a Dictionary's Keys and/or Values
-
Creating a Dictionary with Max and Min Value Boundaries
-
Displaying an Array's Data as a Delimited String
-
Storing Snapshots of Lists in an Array
-
Persisting a Collection Between Application Sessions
-
Testing Every Element in an Array or List<T>
-
Performing an Action on Each Element in an Array or List<T>
-
Creating a Read-Only Array or List<T>
-
Chapter 6 Iterators and Partial Types
-
Introduction
-
Implementing Nested foreach Functionality in a Class
-
Creating Custom Enumerators
-
Creating an Iterator on a Generic Type
-
Creating an Iterator on a Non-generic Type
-
Creating Iterators That Accept Parameters
-
Adding Multiple Iterators on a Single Type
-
Implementing Iterators as Overloaded Operators
-
Forcing an Iterator to Stop Iterating
-
Dealing with Finally Blocks and Iterators
-
Organizing Your Interface Implementations
-
Generating Code That Is No Longer in Your Main Code Paths
-
Chapter 7 Exception Handling
-
Introduction
-
Verifying Critical Parameters
-
Knowing When to Catch and Rethrow Exceptions
-
Identifying Exceptions and Their Usage
-
Handling Derived Exceptions Individually
-
Assuring Exceptions Are Not Lost When Using Finally Blocks
-
Handling Exceptions Thrown from Methods Invoked via Reflection
-
Debugging Problems When Loading an Assembly
-
Mapping Back and Forth Between Managed Exceptions and HRESULTs
-
Handling User-Defined HRESULTs
-
Preventing Unhandled Exceptions
-
Getting Exception Information
-
Getting to the Root of a Problem Quickly
-
Creating a New Exception Type
-
Obtaining a Stack Trace
-
Breaking on a First-Chance Exception
-
Preventing the Nefarious TypeInitializationException
-
Handling Exceptions Thrown from an Asynchronous Delegate
-
Giving Exceptions the Extra Info They Need with Exception.Data
-
Looking at Exceptions in a New Way Using Visualizers
-
Dealing with Unhandled Exceptions in WinForms Applications
-
Chapter 8 Diagnostics
-
Introduction
-
Controlling Tracing Output in Production Code
-
Providing Fine-Grained Control over Debugging/Tracing Output
-
Creating Your Own Custom Switch Class
-
Compiling Blocks of Code Conditionally
-
Determining Whether a Process Has Stopped Responding
-
Using Event Logs in Your Application
-
Changing the Maximum Size of a Custom Event Log
-
Searching Event Log Entries
-
Watching the Event Log for a Specific Entry
-
Finding All Sources Belonging to a Specific Event Log
-
Implementing a Simple Performance Counter
-
Implementing Performance Counters That Require a Base Counter
-
Enabling and Disabling Complex Tracing Code
-
Capturing Standard Output for a Process
-
Creating Custom Debugging Displays for Your Classes
-
Determining Current appdomain Settings Information
-
Boosting the Priority of a Process Programmatically
-
Looking at Your Runtime Environment and Seeing What You Can Do About It
-
Chapter 9 Delegates, Events, and Anonymous Methods
-
Introduction
-
Controlling When and If a Delegate Fires Within a Multicast Delegate
-
Obtaining Return Values from Each Delegate in a Multicast Delegate
-
Handling Exceptions Individually for Each Delegate in a Multicast Delegate
-
Converting Delegate Invocation from Synchronous to Asynchronous
-
Wrapping Sealed Classes to Add Events
-
Passing Specialized Parameters to and from an Event
-
An Advanced Interface Search Mechanism
-
An Advanced Member Search Mechanism
-
Observing Additions and Modifications to a Hashtable
-
Using the Windows Keyboard Hook
-
Tracking and Responding to the Mouse
-
Using Anonymous Methods
-
Set up Event Handlers Without the Mess
-
Using Different Parameter Modifiers in Anonymous Methods
-
Using Closures in C#
-
Performing Multiple Operations on a List Using Functors
-
Chapter 10 Regular Expressions
-
Introduction
-
Enumerating Matches
-
Extracting Groups from a MatchCollection
-
Verifying the Syntax of a Regular Expression
-
Quickly Finding Only the Last Match in a String
-
Replacing Characters or Words in a String
-
Augmenting the Basic String Replacement Function
-
Implementing a Better Tokenizer
-
Compiling Regular Expressions
-
Counting Lines of Text
-
Returning the Entire Line in Which a Match Is Found
-
Finding a Particular Occurrence of a Match
-
Using Common Patterns
-
Documenting Your Regular Expressions
-
Using Built-in Regular Expressions to Parse ASP. NET Pages
-
Chapter 11 Data Structures and Algorithms
-
Introduction
-
Creating a Hash Code for a Data Type
-
Creating a Priority Queue
-
Creating a Double Queue
-
Determining Where Characters or Strings Do Not Balance
-
Creating a One-to-Many Map (MultiMap)
-
Creating a Binary Tree
-
Creating an n-ary Tree
-
Creating a Set Object
-
Chapter 12 Filesystem I/O
-
Introduction
-
Creating, Copying, Moving, or Deleting a File
-
Manipulating File Attributes
-
Renaming a File
-
Determining Whether a File Exists
-
Choosing a Method of Opening a File or Stream for Reading and/or Writing
-
Accessing Part of a File Randomly
-
Outputting a Platform-Independent EOL Character
-
Creating, Writing to, and Reading from a File
-
Determining Whether a Directory Exists
-
Creating, Copying, Moving, or Deleting a Directory
-
Manipulating Directory Attributes
-
Renaming a Directory
-
Searching for Directories or Files Using Wildcards
-
Obtaining the Directory Tree
-
Parsing a Path
-
Parsing Paths in Environment Variables
-
Verifying a Path
-
Using a Temporary File in Your Application
-
Opening a File Stream with Just a File Handle
-
Writing to Multiple Output Files at One Time
-
Launching and Interacting with Console Utilities
-
Locking Subsections of a File
-
Watching the Filesystem for Specific Changes to One or More Files or Directories
-
Waiting for an Action to Occur in the Filesystem
-
Comparing Version Information of Two Executable Modules
-
Querying Information for All Drives on a System
-
Encrypting/Decrypting an Existing File
-
Compressing and Decompressing Your Files
-
Chapter 13 Reflection
-
Introduction
-
Listing Referenced Assemblies
-
Listing Exported Types
-
Finding Overridden Methods
-
Finding Members in an Assembly
-
Finding Members Within an Interface
-
Determining and Obtaining Nested Types Within an Assembly
-
Displaying the Inheritance Hierarchy for a Type
-
Finding the Subclasses of a Type
-
Finding All Serializable Types Within an Assembly
-
Filtering Output When Obtaining Members
-
Dynamically Invoking Members
-
Providing Guidance to Obfuscators
-
Determining if a Type or Method Is Generic
-
Reading Manifest Resources Programmatically
-
Accessing Local Variable Information
-
Creating a Generic Type
-
Chapter 14 Web
-
Introduction
-
Converting an IP Address to a Hostname
-
Converting a Hostname to an IP Address
-
Parsing a URI
-
Forming and Validating an Absolute Uri
-
Handling Web Server Errors
-
Communicating with a Web Server
-
Going Through a Proxy
-
Obtaining the HTML from a URL
-
Using the New Web Browser Control
-
Tying Database Tables to the Cache
-
Caching Data with Multiple Dependencies
-
Prebuilding an ASP.NET Web Site Programmatically
-
Escaping and Unescaping Data for the Web
-
Using the UriBuilder Class
-
Inspect and Change Your Web Application Configuration
-
Working with HTML
-
Using Cached Results When Working with HTTP for Faster Performance
-
Checking out a Web Server's Custom Error Pages
-
Determining the Application Mappings for ASP.NET Set Up on IIS
-
Chapter 15 XML
-
Introduction
-
Reading and Accessing XML Data in Document Order
-
Reading XML on the Web
-
Querying the Contents of an XML Document
-
Validating XML
-
Creating an XML Document Programmatically
-
Detecting Changes to an XML Document
-
Handling Invalid Characters in an XML String
-
Transforming XML
-
Tearing Apart an XML Document
-
Putting Together an XML Document
-
Validating Modified XML Documents Without Reloading
-
Extending XSLT Transformations
-
Getting Your Schema in Bulk from Existing XML Files
-
Passing Parameters to XSLT Transformations
-
Chapter 16 Networking
-
Introduction
-
Writing a TCP Server
-
Writing a TCP Client
-
Simulating Form Execution
-
Downloading Data from a Server
-
Using Named Pipes to Communicate
-
Pinging Programmatically
-
Send SMTP Mail Using the SMTP Service
-
Check out Your Network Connectivity
-
Use Sockets to Scan the Ports on a Machine
-
Use the Current Internet Connection Settings
-
Download a File Using FTP
-
Chapter 17 Security
-
Introduction
-
Controlling Access to Types in a Local Assembly
-
Encrypting/Decrypting a String
-
Encrypting and Decrypting a File
-
Cleaning up Cryptography Information
-
Verifying that a String Remains Uncorrupted Following Transmission
-
Wrapping a String Hash for Ease of Use
-
A Better Random Number Generator
-
Storing Data Securely
-
Making a Security Assert Safe
-
Preventing Malicious Modifications to an Assembly
-
Verifying That an Assembly Has Been Granted Specific Permissions
-
Minimizing the Attack Surface of an Assembly
-
Obtaining Security/Audit Information
-
Granting/Revoking Access to a File or Registry Key
-
Protecting String Data with Secure Strings
-
Securing Stream Data
-
Encrypting web.config Information
-
Obtaining the Full Reason a SecurityException Was Thrown
-
Achieving Secure Unicode Encoding
-
Obtaining a Safer File Handle
-
Chapter 18 Threading and Synchronization
-
Introduction
-
Creating Per-Thread Static Fields
-
Providing Thread-Safe Access to Class Members
-
Preventing Silent Thread Termination
-
Polling an Asynchronous Delegate
-
Timing out an Asynchronous Delegate
-
Being Notified of the Completion of an Asynchronous Delegate
-
Determining Whether a Request for a Pooled Thread Will Be Queued
-
Configuring a Timer
-
Storing Thread-Specific Data Privately
-
Granting Multiple Access to Resources with a Semaphore
-
Synchronizing Multiple Processes with the Mutex
-
Using Events to Make Threads Cooperate
-
Get the Naming Rights for Your Events
-
Performing Atomic Operations Among Threads
-
Chapter 19 Unsafe Code
-
Introduction
-
Controlling Changes to Pointers Passed to Methods
-
Comparing Pointers
-
Navigating Arrays
-
Manipulating a Pointer to a Fixed Array
-
Returning a Pointer to a Particular Element in an Array
-
Creating and Using an Array of Pointers
-
Switching Unknown Pointer Types
-
Converting a String to a char*
-
Declaring a Fixed-Size Structure with an Embedded Array
-
Chapter 20 Toolbox
-
Introduction
-
Dealing with Operating System Shutdown, Power Management, or User Session Changes
-
Controlling a Service
-
List What Processes an Assembly Is Loaded In
-
Using Message Queues on a Local Workstation
-
Finding the Path to the Current Framework Version
-
Determining the Versions of an Assembly That Are Registered in the Global Assembly Cache (GAC)
-
Getting the Windows Directory
-
Capturing Output from the Standard Output Stream
-
Running Code in Its Own appdomain
-
Determining the Operating System and Service Pack Version of the Current Operating System
-
Colophon
Return to C# Cookbook