Nearly every solution, or "recipe," contains a complete, documented code sample showing you how to solve the specific problem, as well as a detailed discussion of how and why the underli
Trang 1By Jay Hilyard, Stephen Teilhet
Publisher: O'Reilly Pub Date: January 2006 Print ISBN-10: 0-596-10063-9 Print ISBN-13: 978-0-59-610063-6 Pages: 1184
Table of Contents | Index
With C# Cookbook, 2nd Edition, you'll be able to learn and improve your mastery of both
the C# language and the NET platform This updated bestseller has been completely revised to account for C# 2.0, the latest version of this popular object-oriented
programming language It also includes more than 100 new code solutions (over 300 overall) to common problems and tasks that you're sure to face as a C# programmer
Nearly every solution, or "recipe," contains a complete, documented code sample showing you how to solve the specific problem, as well as a detailed discussion of how and why the underling technology works This question-solution-discussion format is a proven teaching method, as any fan of O'Reilly's "Cookbook" series can attest to In fact, no other source offers a learn-as-you-go format quite like this.
Trang 3By Jay Hilyard, Stephen Teilhet
Publisher: O'Reilly Pub Date: January 2006 Print ISBN-10: 0-596-10063-9 Print ISBN-13: 978-0-59-610063-6 Pages: 1184
Trang 14Printed in the United States of America
Published by O'Reilly Media, Inc., 1005 Gravenstein HighwayNorth, Sebastopol, CA 95472
O'Reilly books may be purchased for educational, business, orsales promotional use Online editions are also available for
Copyeditor: Norma Emory Cover
Illustrator: Name Here
Proofreader: Genevieve
Rajewski Illustrators:
Robert Romano, Jessamyn Read, and Lesley Borash
Trang 15ISBN: 0-59610-063-9
[M]
Trang 17
C# is a language targeted at developers for the Microsoft NETplatform who have already worked with a C-like language such
as C, C++, or Java Unlike previous versions of C or C++ forthe Microsoft Windows platform, C# code runs under a
managed execution environment While C and C++ developers
using Visual Studio NET can write managed code using
Managed C++, C# offers a middle path between C++'s overallpower but sometimes difficult code and the higher-level taskorientation provided by Visual Basic NET Microsoft portrays C#
as a modern and innovative language for NET developmentthat will be familiar to current C++ programmers while allowingmore runtime control over the executing code
C# allows you to perform many C/C++-like functions such asdirect memory access via pointers and operator overloadingthat are not supported in Visual Basic NET C# is the system-level programming language for NET You can still do great
application-level work in C#, but it really shines when you need
to build code a little closer to the Framework
If you have seen C#, you may have noticed that it looks a lotlike Java; Java programmers will feel very much at home in C#once they learn the Framework SDK C# can also be a greatlanguage for Visual Basic NET programmers when they need alittle more control over what the code is doing and don't want tohave to write C++ to gain an advantage On the Web, you'll find
a large community of people doing really neat things with C#and tons of sample code on sites such as
http://www.gotdotnet.com, http://www.codeproject.com, and
http://www.4guysfromrolla.com
We put this book together based on programming problems weran into when we were first learning C# as well as during ourcontinued use of it Since the first edition we have encountered
Trang 18
it will help you get past some of the common (and not-so-common) pitfalls and initial questions everyone has when
learning a new language as well as the slightly off the beatenpath items that come up during a development cycle There arerecipes dealing with things we found missing from the NET
Framework Class Library (FCL), even though Microsoft has
provided tons of functionality to keep folks from reinventing thewheel Some of these solutions you might immediately use andsome may never darken your door, but we hope this book helpsyou get the most out of C# and the NET Framework
The book is laid out with respect to the types of problems youwill solve as you progress through your life as a C#
programmer These solutions are called recipes; each recipe
consists of a single problem, its solution, a discussion of thesolution and other relevant related information, and finally
where you can look for more information about the classes usedfrom the FCL, other books addressing this topic, related articles,and other recipes The question-answer format provides
complete solutions to problems, making the book easy to readand use Nearly every recipe contains a complete, documentedcode sample showing you how to solve the specific problem, aswell as a discussion of how the underlying technology worksand a list of alternatives, limitations, and other considerationswhen appropriate
Trang 19
You don't have to be an experienced C# or NET developer touse this bookit is designed for users of all levels This book
provides solutions to problems that developers face every day
as well as some that may come along infrequently The recipesare targeted at the real-world developer who needs to solveproblems now, not learn lots of theory first before being able tosolve the problem While reference or tutorial books can teachgeneral concepts, they do not generally provide the help youneed in solving real-world problems We chose to teach by
To save you even the effort of typing in the solution, we providethe sample code for the book on the O'Reilly web site to
facilitate the "editor inheritance" mode of development (copyand paste) as well as to help less experienced developers seegood programming practice in action The sample code provides
a running test harness that exercises each of the solutions, butenough of the code is provided in each solution in the book toallow you to implement the solution without the sample code.The sample code is available from the book's catalog page:
http://www.oreilly.com/catalog/csharpckbk2
Trang 20To run the samples in this book, you need a computer runningWindows 2000 or later (if you are using Windows NT 4.0, youcan use many, but not all, of the examples in this book; inparticular, ASP.NET and NET Web Services do not run on NT4.0) A few of the networking and XML solutions require
Microsoft Internet Information Server (IIS) Version 5 or later
To open and compile the samples in this book, you need VisualStudio NET 2005 If you are proficient with the downloadableFramework SDK and its command-line compilers, you shouldnot have any trouble following the text of this book and thecode samples
Trang 21The solutions in this book are developed using Visual Studio.NET 2005 The differences between Version 2.0 and Version1.1 of the NET Framework are significant and the sample codehas changed from the first edition to reflect that A complete list
of differences between Version 2.0 and Version 1.1 of the NETFramework can be found at
http://www.gotdotnet.com/team/upgrade/apiChanges.aspx
Trang 22
This book is organized into 20 chapters, each of which focuses
on a particular topic in creating C# solutions The followingparagraphs summarize each chapter to give you an overview ofthis book's contents:
Chapter 1, Numbers and Enumerations
This chapter focuses on the numeric and enumeration datatypes used in C# code Recipes cover such things as
numeric conversions, using bitwise operators on numbers,and testing strings to determine whether they contain anumeric value The display, conversion, and testing of
enumeration types and recipes on using enumerations thatconsist of bit flags are also shown
Chapter 2, Strings and Characters
This chapter covers both the String and Char data types.Various recipes show how to compare strings in variousways, encode/decode strings, break strings apart, and putthem back together again, to name a few
Chapter 3, Classes and Structures
This large chapter contains recipes dealing with both classand structure data types This chapter covers a wide range
of recipes from design patterns to converting a class tointeroperating with COM
Trang 23This is a new chapter focusing on the new generics capacity
in C#, which allows you to have code operate uniformly onvalues of different types There are recipes to help yourgeneral understanding of generics as well as when they areappropriate to use, what support is provided in the
Framework for them, and how to create custom
implementations of collections using generics
Chapter 5, Collections
This chapter examines recipes that make use of collections.The collection recipes make use ofas well as extend thefunctionality ofthe array (single, multi, and jagged), the
List<T>, and the Hashtable The new generic-based collectionsare explored, and the various ways to create your own
strongly typed collection are also discussed
Chapter 6, Iterators and Partial Types
In this chapter, two of the new features of C# are used tosolve very different programming problems We show howyou can implement iterators for generic and nongenerictypes and implement foreach functionality using iterators, aswell as custom iterator implementations The other feature
of C# in this chapter is partial types We show how you canuse partial types to do things like better segment your codeand how to generate code that is more easily extensible
Chapter 7, Exception Handling
Trang 24implement exception handling in your application
Preventing unhandled exceptions, reading and displayingstack traces, and throwing/rethrowing exceptions are
included recipes In addition, specific recipes show how toovercome some tricky situations, such as exceptions fromlate-bound called methods, and how to build a custom
exception visualizer for the debugger
Chapter 8, Diagnostics
This chapter explores recipes that use data types that fallunder the System.Diagnostics namespace Recipes deal withthe trace/Debug classes, event logs, processes, performancecounters, and custom debugger displays for your types
Chapter 9, Delegates, Events, and Anonymous Methods
This chapter's recipes show how delegates, events, andanonymous methods can be used in your applications
Recipes allow manipulation of delegates that call more thanone method, synchronous delegates, asynchronous
delegates, and Windows keyboard hooks Anonymous
methods are explored and recipes show their usage in place
of old-style delegates as well as their use in implementingclosures and functors
Chapter 10, Regular Expressions
This chapter covers a very useful set of classes that areused to run regular expressions against strings Recipesenumerate regular expression matches, break up stringsinto tokens, find/replace characters, and verify the syntax
Trang 25Chapter 12, Filesystem I/O
This chapter deals with filesystem interactions in four
distinct ways The first way is to look at typical file
based interactions; the third way deals with paths and
interactions; the second way looks at directory-or folder-temporary files; and the fourth way deals with advancedfilesystem I/O topics
Trang 26configuration Among the recipes in this chapter are usingthe new web browser control and setting up caching
Chapter 16, Networking
This chapter explores the connectivity options provided bythe NET Framework and how to programmatically accessnetwork resources Recipes for using TCP/IP directly, namedpipes for communication, building your own port scanner,and more are covered here
Chapter 17, Security
There are many ways to write secure code and protect datausing the NET Framework, and in this chapter, we exploreareas such as controlling access to types, encryption anddecryption, random numbers, securely storing data, andusing programmatic and declarative security
Trang 27This chapter discusses how C# allows you to step outside ofthe safe environment of managed code and write code that
is considered unsafe by the NET Framework The
possibilities and restrictions of using unsafe code in C# areaddressed by illustrating solutions to problems using unsafecode
Chapter 20, Toolbox
This chapter has recipes for those random sorts of
operations that developers run into over and over again,like determining locations of system resources, sending
email, and working with services It also covers some lessfrequently accessed but helpful application pieces like
message queuing, running code in a separate AppDomain,and finding the versions of assemblies in the GAC
In some cases, certain recipes are related In these cases, theSee Also section of the recipe as well as some text in the
Discussion will note the relationships
Trang 29This book uses the following typographic conventions:
Italic
Used for URLs, names of directories and files, options, andoccasionally for emphasis
Constant width
Used for program listings and for code items such as
commands, options, switches, variables, attributes, keys,functions, types, classes, namespaces, methods, modules,properties, parameters, values, objects, events, eventhandlers, XML tags, HTML tags, macros, the contents offiles, and the output from commands
Constant width bold
Used in program listings to highlight an important part ofthe code
//…
Ellipses in C# code indicate text that has been omitted forclarity
Trang 30Ellipses in XML Schemas and documents' code indicate textthat has been omitted for clarity
This icon indicates a tip, suggestion, or general note.
This icon indicates a warning or caution.
Trang 31
Nearly every recipe in this book contains one or more code
samples These samples are included in a single solution andare pieces of code and whole projects that are immediately
usable in your application Most of the code samples are writtenwithin a class or structure, making it easier to use within yourapplications In addition to this, any using directives are includedfor each recipe so that you will not have to search for whichones to include in your code
Complete error handling is included only in critical areas, such
as input parameters This allows you to easily see what is
correct input and what is not Many recipes omit error handling.This makes the solution easier to understand by focusing on thekey concepts
Trang 32This book is here to help you get your job done In general, youmay use the code in this book in your programs and
documentation You do not need to contact us for permissionunless you're reproducing a significant portion of the code Forexample, writing a program that uses several chunks of codefrom this book does not require permission Selling or
distributing a CD-ROM of examples from O'Reilly books does
require permission Answering a question by citing this bookand quoting example code does not require permission
Incorporating a significant amount of example code from this
book into your product's documentation does require
permission
We appreciate, but do not require, attribution An attributionusually includes the title, author, publisher, and ISBN For
example: "C# Cookbook, 2nd edition by Jay Hilyard and
10063-9."
Stephen Teilhet Copyright 2006 O'Reilly Media, Inc., 0-596-If you feel your use of code examples falls outside fair use orthe preceding permission, feel free to contact us at
permissions@oreilly.com
Trang 33To comment or ask technical questions about this book, sendemail to:
bookquestions@oreilly.com
For more information about our books, conferences, ResourceCenters, and the O'Reilly Network, see our web site at:
http://www.oreilly.com
Trang 34
When you see a Safari® Enabled icon on the cover ofyour favorite technology book, it means the book is availableonline through the O'Reilly Network Safari Bookshelf
Safari offers a solution that's better than e-books It's a virtuallibrary that lets you easily search thousands of top technologybooks, cut and paste code samples, download chapters, andfind quick answers when you need the most accurate, currentinformation Try it for free at http://safari.oreilly.com
Trang 35This book started for us after a long development cycle for anew product from Compuware called DevPartner
SecurityChecker Much was learned, and some of the conceptsfor recipes in this edition helped to build that product With theadvent of C# 2.0 and the new features in C#, we took the
opportunity to reexamine how we did things in the first edition
to see how we could improve the existing recipes as well aslearn better ways of accomplishing programming tasks with C#.During the process Jay moved on to other opportunities fromCompuware while Steve continued to help develop the
forthcoming version of SecurityChecker We have learned anincredible amount about C# and the Framework in general
while we worked hard to help bring you a better understanding
of how C# has evolved and how it can help you do your jobbetter in this edition
This book would have been impossible without the followingpeople and we'd like to acknowledge all of their efforts
Ralph Davis, our editor, who helped keep us on track, refereedthe technical discussions, and was a steadying influence on astormy project Thank you for all of your efforts during the
process and for your professionalism It was most appreciatedand impressive given the circumstances
Ian Griffiths and Nicholas Paldino, our technical editors, whogave us their honest takes on our efforts and made good
suggestions on how to make the recipes even better They
helped to make this an even better book and for that we thankthem."
From Jay Hilyard
Trang 36stages of the book I enjoyed working with you again, eventhough most of it was on nights and weekends this time
Special thanks to my wife Brooke to whom I owe an immensedebt of gratitude for so many things You are a fabulous motherand an even better wife Who would have thought I would bethe one to write the "Cookbooks"? Thank you and I love you
My sons, Owen and Andrew, understood when Daddy couldn't
go to the beach and went to bed willingly on nights when I
needed them to the most I am truly blessed to have two finesons
Thanks to Phil and Gail for being there to help in ways that onlygrandparents can
Thanks for Matt Pietrek for helping to explain why the 2.0
Framework reacted as it did when I tried new things beforethere were many other resources available
Thanks to the Compuware gang of my era that helped produceDevPartner Studio and SecurityChecker My perspective on
development using NET was expanded greatly from my
discussions and experiences with all of you and I wish you allthe very best I say thank you to Steve Munyan, Barry
Tannenbaum, Craig Neth, Kit Von Sück, Bob Newton, Garry
Poegel, Katie King, Alice Pizzuto, Xin Li, Charles Kekeh, TomWagner, Bill Holmes, Jeff Simmons, Russ Osterlund, John Lyon-Smith, Katrina Lyon-Smith, Ian Goodsell, Rich Chiodo, AndyNajberg, Bob Crowling, and everyone else
Thanks to Patrick Hynds, Duane LaFlotte, and Naveen Kohli forhelping to keep my NET interest high
Thanks to Tim Pelletier, Scott Cronshaw, Lance Simpson, DavidBennett, Suzanne Gibson, Kate Keisling, and Shawn McGowan
Trang 37is yet to come
Thanks to Kristen Acheson for being a great friend and a fan
Finally, thanks again to my family and friends for asking about abook they don't understand and for being excited for me
From Steve Teilhet
I'm proud to count Jay Hilyard as a good friend, excellent
coworker, and hardworking coauthor It's not every day that youfind a person who is not only a good friend, but you also work
worked in real-world applications
Thanks to the SecurityChecker development team (and friends)who helped me expand my knowledge of C# and also helped
me through the rough patches: Garry Poegel, Andrew Fournier,Katie King, Kelley-Sue LeBlanc, Xin Li, Alicia Rhoades, Tom
Wagner, Tim Weaver, Dave Chestnutt, Steve Munyan, Bob
Newton, Charles Kekeh, Barry Tannenbaum, and Dennis
Murphy Thanks for all your help and supportI think this calls for
Trang 38a celebration.
Trang 39Introduction
Recipe 1.1 Determining Approximate Equality Between aFraction and Floating-Point Value
Recipe 1.2 Converting Degrees to Radians
Recipe 1.3 Converting Radians to Degrees
Recipe 1.4 Using the Bitwise Complement Operator withVarious Data Types
Recipe 1.5 Testing for an Even or Odd Value
Recipe 1.6 Obtaining the High Word or Low Word of aNumber
Trang 40Recipe 1.22 Determining the Integral Part of a Decimal orDouble