C# 4.0 How-To 1289664196, 9780672330636, 0672330636, 2012022022

Real Solutions for C# 4.0 ProgrammersNeed fast, robust, efficient code solutions for Microsoft C# 4.0? This book deliver

161 49 6MB

English Pages 653 [673] Year 2010

Report DMCA / Copyright

DOWNLOAD PDF FILE

Table of contents :
Cover......Page 1
Table of Contents......Page 5
How-To Benefit from This Book......Page 18
How-To Continue Expanding Your Knowledge......Page 20
Part I: C# Fundamentals......Page 22
1 Type Fundamentals......Page 24
Create a Class......Page 25
Define Fields, Properties, and Methods......Page 26
Define Static Members......Page 27
Add a Constructor......Page 28
Initialize Properties at Construction......Page 29
Use const and readonly......Page 30
Derive from a Class......Page 31
Call a Base Class Constructor......Page 32
Override a Base Class’s Method or Property......Page 33
Implement Interfaces......Page 36
Create a Struct......Page 38
Create an Anonymous Type......Page 39
Prevent Instantiation with an Abstract Base Class......Page 40
Interface or Abstract Base Class?......Page 41
2 Creating Versatile Types......Page 44
Format a Type with ToString( )......Page 45
Make Types Equatable......Page 49
Make Types Sortable......Page 51
Give Types an Index......Page 53
Notify Clients when Changes Happen......Page 55
Overload Appropriate Operators......Page 56
Convert One Type to Another......Page 57
Prevent Inheritance......Page 58
Allow Value Type to Be Null......Page 59
3 General Coding......Page 62
Declare Variables......Page 63
Defer Type Checking to Runtime (Dynamic Types)......Page 64
Use Dynamic Typing to Simplify COM Interop......Page 66
Create Multidimensional Arrays......Page 67
Alias a Namespace......Page 68
Use the Conditional Operator (?:)......Page 69
Use the Null-Coalescing Operator (??)......Page 70
Add Methods to Existing Types with Extension Methods......Page 71
Call Methods with Default Parameters......Page 72
Call Methods with Named Parameters......Page 73
Defer Evaluation of a Value Until Referenced......Page 74
Enforce Code Contracts......Page 75
4 Exceptions......Page 80
Catch an Exception......Page 81
Catch Multiple Exceptions......Page 82
Rethrow an Exception......Page 83
(Almost) Guarantee Execution with finally......Page 84
Get Useful Information from an Exception......Page 85
Create Your Own Exception Class......Page 87
Catch Unhandled Exceptions......Page 89
Usage Guidelines......Page 93
5 Numbers......Page 94
Decide Between Float, Double, and Decimal......Page 95
Use Enormous Integers (BigInteger)......Page 96
Use Complex Numbers......Page 97
Format Numbers in a String......Page 99
Convert a String to a Number......Page 103
Convert Between Number Bases......Page 104
Convert a Number to Bytes (and Vice Versa)......Page 106
Determine if a Number Is Prime......Page 108
Count the Number of 1 Bits......Page 109
Round Numbers......Page 110
Generate Better Random Numbers......Page 113
Generate Unique IDs (GUIDs)......Page 114
6 Enumerations......Page 116
Declare an Enumeration......Page 117
Declare Flags as an Enumeration......Page 118
Convert an Enumeration to an Integer (and Vice Versa)......Page 119
Convert a String to an Enumeration......Page 120
Attach Metadata to Enums with Extension Methods......Page 121
Enumeration Tips......Page 123
7 Strings......Page 126
Convert a String to Bytes (and Vice Versa)......Page 127
Create a Custom Encoding Scheme......Page 128
Compare Strings Correctly......Page 132
Change Case Correctly......Page 133
Concatenate Strings: Should You Use StringBuilder?......Page 134
Concatenate Collection Items into a String......Page 136
Append a Newline Character......Page 137
Split a String......Page 138
Convert Binary Data to a String (Base-64 Encoding)......Page 139
Reverse Words......Page 141
Sort Number Strings Naturally......Page 142
8 Regular Expressions......Page 148
Extract Groups of Text......Page 149
Replace Text......Page 150
Match and Validate......Page 151
Help Regular Expressions Perform Better......Page 154
9 Generics......Page 156
Create a Generic List......Page 157
Create a Generic Method......Page 158
Create a Generic Interface......Page 159
Create a Generic Class......Page 160
Create a Generic Delegate......Page 162
Constrain the Generic Type......Page 163
Convert IEnumerable to IEnumerable (Covariance)......Page 166
Convert IComparer to IComparer (Contravariance)......Page 167
Create Tuples (Pairs and More)......Page 168
Part II: Handling Data......Page 170
10 Collections......Page 172
Pick the Correct Collection Class......Page 173
Initialize a Collection......Page 174
Iterate over a Collection Independently of Its Implementation......Page 175
Create a Custom Collection......Page 176
Create Custom Iterators for a Collection......Page 180
Reverse an Array......Page 183
Reverse a Linked List......Page 184
Count the Number of Times an Item Appears......Page 185
Implement a Priority Queue......Page 186
Create a Trie (Prefix Tree)......Page 190
11 Files and Serialization......Page 194
Create, Read, and Write Files......Page 195
Delete a File......Page 197
Combine Streams (Compress a File)......Page 198
Get File Security Description......Page 200
Enumerate Drives......Page 202
Enumerate Directories and Files......Page 203
Browse for Directories......Page 204
Search for a File or Directory......Page 205
Manipulate File Paths......Page 207
Watch for File System Changes......Page 209
Serialize Objects......Page 211
Store Data when Your App Has Restricted Permissions......Page 215
12 Networking and the Web......Page 218
Get This Machine’s Hostname and IP Address......Page 219
Ping a Machine......Page 220
Create a TCP/IP Client and Server......Page 221
Send an Email via SMTP......Page 225
Download Web Content via HTTP......Page 226
Upload a File with FTP......Page 230
Embed a Web Browser in Your Application......Page 231
Consume an RSS Feed......Page 233
Produce an RSS Feed Dynamically in IIS......Page 237
Communicate Between Processes on the Same Machine (WCF)......Page 239
Communicate Between Two Machines on the Same Network (WCF)......Page 246
Communicate over the Internet (WCF)......Page 248
Discover Services During Runtime (WCF)......Page 250
13 Databases......Page 254
Create a New Database from Visual Studio......Page 255
Connect and Retrieve Data......Page 257
Insert Data into a Database Table......Page 262
Delete Data from a Table......Page 263
Run a Stored Procedure......Page 264
Use Transactions......Page 265
Bind Data to a Control Using a DataSet......Page 267
Detect if Database Connection Is Available......Page 275
Automatically Map Data to Objects with the Entity Framework......Page 276
14 XML......Page 278
Serialize an Object to and from XML......Page 279
Write XML from Scratch......Page 283
Read an XML File......Page 285
Validate an XML Document......Page 287
Query XML Using XPath......Page 288
Transform Database Data to XML......Page 290
Transform XML to HTML......Page 291
Part III: User Interaction......Page 294
15 Delegates, Events, and Anonymous Methods......Page 296
Decide Which Method to Call at Runtime......Page 297
Subscribe to an Event......Page 299
Publish an Event......Page 300
Ensure UI Updates Occur on UI Thread......Page 302
Use Anonymous Methods as Quick-and-Easy Event Handlers......Page 305
Take Advantage of Contravariance......Page 308
16 Windows Forms......Page 312
Create Modal and Modeless Forms......Page 313
Add a Menu Bar......Page 314
Add a Status Bar......Page 317
Add a Toolbar......Page 318
Create a Split Window Interface......Page 319
Inherit a Form......Page 321
Create a User Control......Page 325
Use a Timer......Page 330
Use Application and User Configuration Values......Page 331
Use ListView Efficiently in Virtual Mode......Page 334
Take Advantage of Horizontal Wheel Tilt......Page 336
Cut and Paste......Page 340
Automatically Ensure You Reset the Wait Cursor......Page 344
17 Graphics with Windows Forms and GDI+......Page 346
Use the System Color Picker......Page 347
Convert Colors Between RGB to HSV......Page 348
Draw Shapes......Page 352
Create Pens......Page 354
Create Custom Brushes......Page 356
Use Transformations......Page 358
Draw Images......Page 361
Draw Transparent Images......Page 362
Draw to an Off-Screen Buffer......Page 363
Access a Bitmap’s Pixels Directly for Performance......Page 364
Draw with Anti-Aliasing......Page 365
Draw Flicker-Free......Page 366
Resize an Image......Page 367
Create a Thumbnail of an Image......Page 368
Take a Multiscreen Capture......Page 369
Get the Distance from the Mouse Cursor to a Point......Page 371
Determine if a Point Is Inside a Circle......Page 372
Determine if a Point Is Inside an Ellipse......Page 373
Determine if Two Rectangles Intersect......Page 374
Print and Print Preview......Page 375
18 WPF......Page 382
Show a Window......Page 383
Add a Menu Bar......Page 384
Add a Toolbar......Page 386
Use Standard Commands......Page 387
Use Custom Commands......Page 388
Enable and Disable Commands......Page 391
Expand and Collapse a Group of Controls......Page 392
Respond to Events......Page 393
Separate Look from Functionality......Page 394
Use Triggers to Change Styles at Runtime......Page 395
Bind Control Properties to Another Object......Page 396
Convert Values to a Different Type During Data Binding......Page 400
Specify How Bound Data Is Displayed......Page 402
Define the Look of Controls with Templates......Page 403
Animate Element Properties......Page 405
Render 3D Geometry......Page 406
Put Video on a 3D Surface......Page 409
Put Interactive Controls onto a 3D Surface......Page 412
Use WPF in a WinForms App......Page 415
Use WinForms in a WPF Application......Page 417
19 ASP.NET......Page 418
View Debug and Trace Information......Page 419
Determine Web Browser Capabilities......Page 421
Redirect to Another Page......Page 422
Use Forms Authentication for User Login......Page 423
Use Master Pages for a Consistent Look......Page 426
Add a Menu......Page 428
Bind Data to a GridView......Page 429
Create a User Control......Page 431
Create a Flexible UI with Web Parts......Page 435
Create a Simple AJAX Page......Page 440
Do Data Validation......Page 442
Maintain Application State......Page 446
Maintain UI State......Page 447
Maintain User Data in a Session......Page 448
Store Session State......Page 450
Use Cookies to Restore Session State......Page 451
Use ASP.NET Model-View-Controller (MVC)......Page 453
20 Silverlight......Page 460
Create a Silverlight Project......Page 461
Play a Video......Page 462
Build a Download and Playback Progress Bar......Page 466
Response to Timer Events on the UI Thread......Page 468
Put Content into a 3D Perspective......Page 469
Make Your Application Run out of the Browser......Page 470
Capture a Webcam......Page 472
Print a Document......Page 474
Part IV: Advanced C#......Page 476
21 LINQ......Page 478
Query an Object Collection......Page 479
Order the Results......Page 480
Filter a Collection......Page 481
Perform a Join......Page 482
Query XML......Page 483
Query the Entity Framework......Page 484
Query a Web Service (LINQ to Bing)......Page 486
Speed Up Queries with PLINQ (Parallel LINQ)......Page 489
22 Memory Management......Page 490
Measure Memory Usage of Your Application......Page 491
Clean Up Unmanaged Resources Using Finalization......Page 492
Clean Up Managed Resources Using the Dispose Pattern......Page 494
Create a Cache That Still Allows Garbage Collection......Page 499
Use Pointers......Page 502
Speed Up Array Access......Page 503
Prevent Memory from Being Moved......Page 504
Allocate Unmanaged Memory......Page 505
23 Threads, Asynchronous, and Parallel Programming......Page 508
Easily Split Work Among Processors......Page 509
Use Data Structures in Multiple Threads......Page 512
Call a Method Asynchronously......Page 513
Use the Thread Pool......Page 514
Create a Thread......Page 515
Exchange Data with a Thread......Page 516
Protect Data Used in Multiple Threads......Page 517
Use Interlocked Methods Instead of Locks......Page 520
Protect Data in Multiple Processes......Page 521
Limit Applications to a Single Instance......Page 522
Limit the Number of Threads That Can Access a Resource......Page 523
Signal Threads with Events......Page 526
Use a Multithreaded Timer......Page 529
Use a Reader-Writer Lock......Page 530
Use the Asynchronous Programming Model......Page 532
24 Reflection and Creating Plugins......Page 536
Enumerate Types in an Assembly......Page 537
Add a Custom Attribute......Page 538
Invoke a Method on a Dynamically Instantiated Class......Page 540
Implement a Plugin Architecture......Page 542
25 Application Patterns and Tips......Page 546
Use a Stopwatch to Profile Your Code......Page 547
Mark Obsolete Code......Page 548
Combine Multiple Events into a Single Event......Page 549
Implement an Observer (aka Subscriber) Pattern......Page 553
Use an Event Broker......Page 557
Remember the Screen Location......Page 560
Implement Undo Using Command Objects......Page 562
Use Model-View-ViewModel in WPF......Page 569
Understand Localization......Page 579
Localize a Windows Forms Application......Page 580
Localize an ASP.NET Application......Page 581
Localize a WPF Application......Page 582
Localize a Silverlight Application......Page 587
Deploy Applications Using ClickOnce......Page 589
26 Interacting with the OS and Hardware......Page 592
Get CPU and Other Hardware Information......Page 593
Invoke UAC to Request Admin Privileges......Page 595
Write to the Event Log......Page 598
Access the Registry......Page 600
Manage Windows Services......Page 601
Create a Windows Service......Page 602
Call Native Windows Functions Using P/Invoke......Page 605
Call C Functions in a DLL from C#......Page 606
Use Memory-Mapped Files......Page 607
Ensure Your Application Works in Both 32-bit and 64-bit Environments......Page 608
Take Advantage of Windows 7 Features......Page 610
Retrieve Power State Information......Page 612
27 Fun Stuff and Loose Ends......Page 614
Create a Nonrectangular Window......Page 615
Create a Notification Icon......Page 619
Create a Screen Saver in WPF......Page 622
Show a Splash Screen......Page 631
Play a Sound File......Page 636
Shuffle Cards......Page 637
Appendix: Essential Tools......Page 638
Reflector......Page 639
NUnit......Page 640
FXCop......Page 643
Virtual PC......Page 644
Process Explorer and Process Monitor......Page 645
LINQPad......Page 647
Where to Find More Tools......Page 648
A......Page 650
C......Page 652
D......Page 655
E......Page 656
F......Page 657
H......Page 658
L......Page 659
M......Page 661
N......Page 662
P......Page 663
R......Page 664
S......Page 665
T......Page 667
W......Page 668
X–Z......Page 670

C# 4.0 How-To
 1289664196, 9780672330636, 0672330636, 2012022022

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up