Tải bản đầy đủ (.pdf) (2,017 trang)

2006 oreilly c sharp cookbook, 2nd edition

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.43 MB, 2,017 trang )

C#Cookbook,2ndEdition
ByJayHilyard,StephenTeilhet
...............................................
Publisher:O'Reilly
PubDate:January2006
PrintISBN-10:0-596-10063-9
PrintISBN-13:978-0-59-610063-6
Pages:1184

TableofContents|Index

WithC#Cookbook,2ndEdition,you'llbeabletolearnandimproveyourmasteryofboth
theC#languageandthe.NETplatform.Thisupdatedbestsellerhasbeencompletely
revisedtoaccountforC#2.0,thelatestversionofthispopularobject-oriented
programminglanguage.Italsoincludesmorethan100newcodesolutions(over300
overall)tocommonproblemsandtasksthatyou'resuretofaceasaC#programmer.
Nearlyeverysolution,or"recipe,"containsacomplete,documentedcodesampleshowing
youhowtosolvethespecificproblem,aswellasadetaileddiscussionofhowandwhythe
underlingtechnologyworks.Thisquestion-solution-discussionformatisaproventeaching
method,asanyfanofO'Reilly's"Cookbook"seriescanattestto.Infact,noothersource
offersalearn-as-you-goformatquitelikethis.
C#Cookbook,2ndEditionisorganizedinto20chapters,eachofwhichfocusesona
particulartopicincreatingC#solutions.Here'sjustatasteofwhat'scovered:
Numericdatatypes
Stringsandcharacters
Classesandstructures
Generics
Exceptionhandling
Delegates,events,andanonymousmethods
Filesysteminteractions
Websiteaccess




XMLusage(includingXPathandXSLT)
Networking
Threading
Unsafecode

Bestofall,youdon'thavetobeanexperiencedC#or.NETdevelopertouseC#
Cookbook,2ndEdition.Youjusthavetobesomeonewhowantstosolveaproblemnow,
withouthavingtolearnalltherelatedtheoryfirst.


C#Cookbook,2ndEdition
ByJayHilyard,StephenTeilhet
...............................................
Publisher:O'Reilly
PubDate:January2006
PrintISBN-10:0-596-10063-9
PrintISBN-13:978-0-59-610063-6
Pages:1184

TableofContents|Index















































Copyright
Dedication
Preface
WhoThisBookIsFor
WhatYouNeedtoUseThisBook
PlatformNotes
HowThisBookIsOrganized
WhatWasLeftOut
ConventionsUsedinThisBook
AbouttheCode
UsingCodeExamples
CommentsandQuestions
SafariEnabled
Acknowledgments
Chapter1.NumbersandEnumerations
Introduction
Recipe1.1.DeterminingApproximateEqualityBetweenaFractionandFloatingPointValue
Recipe1.2.ConvertingDegreestoRadians
Recipe1.3.ConvertingRadianstoDegrees
Recipe1.4.UsingtheBitwiseComplementOperatorwithVariousDataTypes
Recipe1.5.TestingforanEvenorOddValue
Recipe1.6.ObtainingtheHighWordorLowWordofaNumber
Recipe1.7.ConvertingaNumberinAnotherBasetoBase10
















































































Recipe1.8.DeterminingWhetheraStringIsaValidNumber
Recipe1.9.RoundingaFloating-PointValue
Recipe1.10.ChoosingaRoundingAlgorithm
Recipe1.11.ConvertingCelsiustoFahrenheit
Recipe1.12.ConvertingFahrenheittoCelsius
Recipe1.13.SafelyPerformingaNarrowingNumericCast
Recipe1.14.FindingtheLengthofAnyThreeSidesofaRightTriangle
Recipe1.15.FindingtheAnglesofaRightTriangle
Recipe1.16.DisplayinganEnumerationValueasaString
Recipe1.17.ConvertingPlainTexttoanEquivalentEnumerationValue
Recipe1.18.TestingforaValidEnumerationValue
Recipe1.19.TestingforaValidEnumerationofFlags
Recipe1.20.UsingEnumeratedMembersinaBitMask

Recipe1.21.DeterminingifOneorMoreEnumerationFlagsAreSet
Recipe1.22.DeterminingtheIntegralPartofaDecimalorDouble
Chapter2.StringsandCharacters
Introduction
Recipe2.1.DeterminingtheKindofCharacteracharContains
Recipe2.2.DeterminingWhetheraCharacterIsWithinaSpecifiedRange
Recipe2.3.ControllingCaseSensitivityWhenComparingTwoCharacters
Recipe2.4.FindingAllOccurrencesofaCharacterWithinaString
Recipe2.5.FindingtheLocationofAllOccurrencesofaStringWithinAnother
String
Recipe2.6.ImplementingaPoorMan'sTokenizertoDeconstructaString
Recipe2.7.ControllingCaseSensitivityWhenComparingTwoStrings
Recipe2.8.ComparingaStringtotheBeginningorEndofaSecondString
Recipe2.9.InsertingTextintoaString
Recipe2.10.RemovingorReplacingCharactersWithinaString
Recipe2.11.EncodingBinaryDataasBase64
Recipe2.12.DecodingaBase64-EncodedBinary
Recipe2.13.ConvertingaStringReturnedasaByte[]BackintoaString
Recipe2.14.PassingaStringtoaMethodThatAcceptsonlyaByte[]
Recipe2.15.ConvertingStringstoOtherTypes
Recipe2.16.FormattingDatainStrings
Recipe2.17.CreatingaDelimitedString
Recipe2.18.ExtractingItemsfromaDelimitedString
Recipe2.19.SettingtheMaximumNumberofCharactersaStringBuilderCan
Contain
Recipe2.20.IteratingoverEachCharacterinaString
















































































Recipe2.21.ImprovingStringComparisonPerformance
Recipe2.22.ImprovingStringBuilderPerformance
Recipe2.23.PruningCharactersfromtheHeadand/orTailofaString
Recipe2.24.TestingaStringforNullorEmpty
Recipe2.25.AppendingaLine
Recipe2.26.EncodingChunksofData
Chapter3.ClassesandStructures
Introduction
Recipe3.1.CreatingUnion-TypeStructures
Recipe3.2.AllowingaTypetoRepresentItselfasaString
Recipe3.3.ConvertingaStringRepresentationofanObjectintoanActualObject
Recipe3.4.ImplementingPolymorphismwithAbstractBaseClasses
Recipe3.5.MakingaTypeSortable
Recipe3.6.MakingaTypeSearchable
Recipe3.7.IndirectlyOverloadingthe+=,-=,/=,and*=Operators
Recipe3.8.IndirectlyOverloadingthe&&,||,and?:Operators
Recipe3.9.TurningBitsOnorOff

Recipe3.10.MakingError-FreeExpressions
Recipe3.11.Minimizing(Reducing)YourBooleanLogic
Recipe3.12.ConvertingBetweenSimpleTypesinaLanguage-AgnosticManner
Recipe3.13.DeterminingWhentoUsetheCastOperator,theasOperator,orthe
isOperator
Recipe3.14.CastingwiththeasOperator
Recipe3.15.DeterminingaVariable'sTypewiththeisOperator
Recipe3.16.ImplementingPolymorphismwithInterfaces
Recipe3.17.CallingtheSameMethodonMultipleObjectTypes
Recipe3.18.AddingaNotificationCallbackUsinganInterface
Recipe3.19.UsingMultipleEntryPointstoVersionanApplication
Recipe3.20.PreventingtheCreationofanOnlyPartiallyInitializedObject
Recipe3.21.ReturningMultipleItemsfromaMethod
Recipe3.22.ParsingCommand-LineParameters
Recipe3.23.RetrofittingaClasstoInteroperatewithCOM
Recipe3.24.InitializingaConstantFieldatRuntime
Recipe3.25.WritingCodeThatIsCompatiblewiththeWidestRangeofManaged
Languages
Recipe3.26.BuildingCloneableClasses
Recipe3.27.AssuringanObject'sDisposal
Recipe3.28.ReleasingaCOMObjectThroughManagedCode
Recipe3.29.CreatinganObjectCache


















































































Recipe3.30.RollingBackObjectChanges
Recipe3.31.DisposingofUnmanagedResources
Recipe3.32.DeterminingWhereBoxingandUnboxingOccur
Chapter4.Generics
Introduction
Recipe4.1.DecidingWhenandWheretoUseGenerics
Recipe4.2.UnderstandingGenericTypes
Recipe4.3.GettingtheTypeofaGenericType
Recipe4.4.ReplacingtheArrayListwithItsGenericCounterpart
Recipe4.5.ReplacingtheStackandQueuewithTheirGenericCounterparts
Recipe4.6.ImplementingaLinkedList
Recipe4.7.CreatingaValueTypeThatCanBeInitializedtoNull
Recipe4.8.ReversingtheContentsofaSortedList
Recipe4.9.MakingRead-OnlyCollectionstheGenericWay
Recipe4.10.ReplacingtheHashtablewithItsGenericCounterpart
Recipe4.11.UsingforeachwithGenericDictionaryTypes
Recipe4.12.ConstrainingTypeArguments
Recipe4.13.InitializingGenericVariablestoTheirDefaultValues
Chapter5.Collections

Introduction
Recipe5.1.SwappingTwoElementsinanArray
Recipe5.2.ReversinganArrayQuickly
Recipe5.3.ReversingaTwo-DimensionalArray
Recipe5.4.ReversingaJaggedArray
Recipe5.5.WritingaMoreFlexibleStackTraceClass
Recipe5.6.DeterminingtheNumberofTimesanItemAppearsinaList<T>
Recipe5.7.RetrievingAllInstancesofaSpecificIteminaList<T>
Recipe5.8.InsertingandRemovingItemsfromanArray
Recipe5.9.KeepingYourList<T>Sorted
Recipe5.10.SortingaDictionary'sKeysand/orValues
Recipe5.11.CreatingaDictionarywithMaxandMinValueBoundaries
Recipe5.12.DisplayinganArray'sDataasaDelimitedString
Recipe5.13.StoringSnapshotsofListsinanArray
Recipe5.14.PersistingaCollectionBetweenApplicationSessions
Recipe5.15.TestingEveryElementinanArrayorList<T>
Recipe5.16.PerforminganActiononEachElementinanArrayorList<T>
Recipe5.17.CreatingaRead-OnlyArrayorList<T>
Chapter6.IteratorsandPartialTypes
Introduction

















































































Recipe6.1.ImplementingNestedforeachFunctionalityinaClass
Recipe6.2.CreatingCustomEnumerators
Recipe6.3.CreatinganIteratoronaGenericType
Recipe6.4.CreatinganIteratoronaNon-genericType
Recipe6.5.CreatingIteratorsThatAcceptParameters
Recipe6.6.AddingMultipleIteratorsonaSingleType
Recipe6.7.ImplementingIteratorsasOverloadedOperators
Recipe6.8.ForcinganIteratortoStopIterating
Recipe6.9.DealingwithFinallyBlocksandIterators
Recipe6.10.OrganizingYourInterfaceImplementations
Recipe6.11.GeneratingCodeThatIsNoLongerinYourMainCodePaths
Chapter7.ExceptionHandling
Introduction
Recipe7.1.VerifyingCriticalParameters
Recipe7.2.KnowingWhentoCatchandRethrowExceptions
Recipe7.3.IdentifyingExceptionsandTheirUsage
Recipe7.4.HandlingDerivedExceptionsIndividually
Recipe7.5.AssuringExceptionsAreNotLostWhenUsingFinallyBlocks
Recipe7.6.HandlingExceptionsThrownfromMethodsInvokedviaReflection
Recipe7.7.DebuggingProblemsWhenLoadinganAssembly
Recipe7.8.MappingBackandForthBetweenManagedExceptionsand
HRESULTs

Recipe7.9.HandlingUser-DefinedHRESULTs
Recipe7.10.PreventingUnhandledExceptions
Recipe7.11.GettingExceptionInformation
Recipe7.12.GettingtotheRootofaProblemQuickly
Recipe7.13.CreatingaNewExceptionType
Recipe7.14.ObtainingaStackTrace
Recipe7.15.BreakingonaFirst-ChanceException
Recipe7.16.PreventingtheNefariousTypeInitializationException
Recipe7.17.HandlingExceptionsThrownfromanAsynchronousDelegate
Recipe7.18.GivingExceptionstheExtraInfoTheyNeedwithException.Data
Recipe7.19.LookingatExceptionsinaNewWayUsingVisualizers
Recipe7.20.DealingwithUnhandledExceptionsinWinFormsApplications
Chapter8.Diagnostics
Introduction
Recipe8.1.ControllingTracingOutputinProductionCode
Recipe8.2.ProvidingFine-GrainedControloverDebugging/TracingOutput
Recipe8.3.CreatingYourOwnCustomSwitchClass












































































Recipe8.4.CompilingBlocksofCodeConditionally
Recipe8.5.DeterminingWhetheraProcessHasStoppedResponding
Recipe8.6.UsingEventLogsinYourApplication
Recipe8.7.ChangingtheMaximumSizeofaCustomEventLog
Recipe8.8.SearchingEventLogEntries
Recipe8.9.WatchingtheEventLogforaSpecificEntry
Recipe8.10.FindingAllSourcesBelongingtoaSpecificEventLog
Recipe8.11.ImplementingaSimplePerformanceCounter
Recipe8.12.ImplementingPerformanceCountersThatRequireaBaseCounter
Recipe8.13.EnablingandDisablingComplexTracingCode
Recipe8.14.CapturingStandardOutputforaProcess
Recipe8.15.CreatingCustomDebuggingDisplaysforYourClasses
Recipe8.16.DeterminingCurrentappdomainSettingsInformation
Recipe8.17.BoostingthePriorityofaProcessProgrammatically
Recipe8.18.LookingatYourRuntimeEnvironmentandSeeingWhatYouCan
DoAboutIt
Chapter9.Delegates,Events,andAnonymousMethods
Introduction
Recipe9.1.ControllingWhenandIfaDelegateFiresWithinaMulticastDelegate
Recipe9.2.ObtainingReturnValuesfromEachDelegateinaMulticastDelegate
Recipe9.3.HandlingExceptionsIndividuallyforEachDelegateinaMulticast
Delegate
Recipe9.4.ConvertingDelegateInvocationfromSynchronoustoAsynchronous
Recipe9.5.WrappingSealedClassestoAddEvents
Recipe9.6.PassingSpecializedParameterstoandfromanEvent
Recipe9.7.AnAdvancedInterfaceSearchMechanism
Recipe9.8.AnAdvancedMemberSearchMechanism
Recipe9.9.ObservingAdditionsandModificationstoaHashtable
Recipe9.10.UsingtheWindowsKeyboardHook
Recipe9.11.TrackingandRespondingtotheMouse

Recipe9.12.UsingAnonymousMethods
Recipe9.13.SetupEventHandlersWithouttheMess
Recipe9.14.UsingDifferentParameterModifiersinAnonymousMethods
Recipe9.15.UsingClosuresinC#
Recipe9.16.PerformingMultipleOperationsonaListUsingFunctors
Chapter10.RegularExpressions
Introduction
Recipe10.1.EnumeratingMatches















































































Recipe10.2.ExtractingGroupsfromaMatchCollection
Recipe10.3.VerifyingtheSyntaxofaRegularExpression
Recipe10.4.QuicklyFindingOnlytheLastMatchinaString
Recipe10.5.ReplacingCharactersorWordsinaString
Recipe10.6.AugmentingtheBasicStringReplacementFunction

Recipe10.7.ImplementingaBetterTokenizer
Recipe10.8.CompilingRegularExpressions
Recipe10.9.CountingLinesofText
Recipe10.10.ReturningtheEntireLineinWhichaMatchIsFound
Recipe10.11.FindingaParticularOccurrenceofaMatch
Recipe10.12.UsingCommonPatterns
Recipe10.13.DocumentingYourRegularExpressions
Recipe10.14.UsingBuilt-inRegularExpressionstoParseASP.NETPages
Chapter11.DataStructuresandAlgorithms
Introduction
Recipe11.1.CreatingaHashCodeforaDataType
Recipe11.2.CreatingaPriorityQueue
Recipe11.3.CreatingaDoubleQueue
Recipe11.4.DeterminingWhereCharactersorStringsDoNotBalance
Recipe11.5.CreatingaOne-to-ManyMap(MultiMap)
Recipe11.6.CreatingaBinaryTree
Recipe11.7.Creatingann-aryTree
Recipe11.8.CreatingaSetObject
Chapter12.FilesystemI/O
Introduction
Recipe12.1.Creating,Copying,Moving,orDeletingaFile
Recipe12.2.ManipulatingFileAttributes
Recipe12.3.RenamingaFile
Recipe12.4.DeterminingWhetheraFileExists
Recipe12.5.ChoosingaMethodofOpeningaFileorStreamforReadingand/or
Writing
Recipe12.6.AccessingPartofaFileRandomly
Recipe12.7.OutputtingaPlatform-IndependentEOLCharacter
Recipe12.8.Creating,Writingto,andReadingfromaFile
Recipe12.9.DeterminingWhetheraDirectoryExists

Recipe12.10.Creating,Copying,Moving,orDeletingaDirectory
Recipe12.11.ManipulatingDirectoryAttributes
Recipe12.12.RenamingaDirectory
Recipe12.13.SearchingforDirectoriesorFilesUsingWildcards













































































Recipe12.14.ObtainingtheDirectoryTree
Recipe12.15.ParsingaPath
Recipe12.16.ParsingPathsinEnvironmentVariables
Recipe12.17.VerifyingaPath
Recipe12.18.UsingaTemporaryFileinYourApplication
Recipe12.19.OpeningaFileStreamwithJustaFileHandle
Recipe12.20.WritingtoMultipleOutputFilesatOneTime
Recipe12.21.LaunchingandInteractingwithConsoleUtilities
Recipe12.22.LockingSubsectionsofaFile
Recipe12.23.WatchingtheFilesystemforSpecificChangestoOneorMore
FilesorDirectories

Recipe12.24.WaitingforanActiontoOccurintheFilesystem
Recipe12.25.ComparingVersionInformationofTwoExecutableModules
Recipe12.26.QueryingInformationforAllDrivesonaSystem
Recipe12.27.Encrypting/DecryptinganExistingFile
Recipe12.28.CompressingandDecompressingYourFiles
Chapter13.Reflection
Introduction
Recipe13.1.ListingReferencedAssemblies
Recipe13.2.ListingExportedTypes
Recipe13.3.FindingOverriddenMethods
Recipe13.4.FindingMembersinanAssembly
Recipe13.5.FindingMembersWithinanInterface
Recipe13.6.DeterminingandObtainingNestedTypesWithinanAssembly
Recipe13.7.DisplayingtheInheritanceHierarchyforaType
Recipe13.8.FindingtheSubclassesofaType
Recipe13.9.FindingAllSerializableTypesWithinanAssembly
Recipe13.10.FilteringOutputWhenObtainingMembers
Recipe13.11.DynamicallyInvokingMembers
Recipe13.12.ProvidingGuidancetoObfuscators
Recipe13.13.DeterminingifaTypeorMethodIsGeneric
Recipe13.14.ReadingManifestResourcesProgrammatically
Recipe13.15.AccessingLocalVariableInformation
Recipe13.16.CreatingaGenericType
Chapter14.Web
Introduction
Recipe14.1.ConvertinganIPAddresstoaHostname
Recipe14.2.ConvertingaHostnametoanIPAddress
















































































Recipe14.3.ParsingaURI
Recipe14.4.FormingandValidatinganAbsoluteUri
Recipe14.5.HandlingWebServerErrors
Recipe14.6.CommunicatingwithaWebServer
Recipe14.7.GoingThroughaProxy
Recipe14.8.ObtainingtheHTMLfromaURL
Recipe14.9.UsingtheNewWebBrowserControl
Recipe14.10.TyingDatabaseTablestotheCache
Recipe14.11.CachingDatawithMultipleDependencies
Recipe14.12.PrebuildinganASP.NETWebSiteProgrammatically
Recipe14.13.EscapingandUnescapingDatafortheWeb
Recipe14.14.UsingtheUriBuilderClass
Recipe14.15.InspectandChangeYourWebApplicationConfiguration
Recipe14.16.WorkingwithHTML
Recipe14.17.UsingCachedResultsWhenWorkingwithHTTPforFaster
Performance

Recipe14.18.CheckingoutaWebServer'sCustomErrorPages
Recipe14.19.DeterminingtheApplicationMappingsforASP.NETSetUponIIS
Chapter15.XML
Introduction
Recipe15.1.ReadingandAccessingXMLDatainDocumentOrder
Recipe15.2.ReadingXMLontheWeb
Recipe15.3.QueryingtheContentsofanXMLDocument
Recipe15.4.ValidatingXML
Recipe15.5.CreatinganXMLDocumentProgrammatically
Recipe15.6.DetectingChangestoanXMLDocument
Recipe15.7.HandlingInvalidCharactersinanXMLString
Recipe15.8.TransformingXML
Recipe15.9.TearingApartanXMLDocument
Recipe15.10.PuttingTogetheranXMLDocument
Recipe15.11.ValidatingModifiedXMLDocumentsWithoutReloading
Recipe15.12.ExtendingXSLTTransformations
Recipe15.13.GettingYourSchemainBulkfromExistingXMLFiles
Recipe15.14.PassingParameterstoXSLTTransformations
Chapter16.Networking
Introduction
Recipe16.1.WritingaTCPServer
Recipe16.2.WritingaTCPClient
Recipe16.3.SimulatingFormExecution














































































Recipe16.4.DownloadingDatafromaServer
Recipe16.5.UsingNamedPipestoCommunicate
Recipe16.6.PingingProgrammatically
Recipe16.7.SendSMTPMailUsingtheSMTPService
Recipe16.8.CheckoutYourNetworkConnectivity
Recipe16.9.UseSocketstoScanthePortsonaMachine
Recipe16.10.UsetheCurrentInternetConnectionSettings
Recipe16.11.DownloadaFileUsingFTP
Chapter17.Security
Introduction
Recipe17.1.ControllingAccesstoTypesinaLocalAssembly
Recipe17.2.Encrypting/DecryptingaString
Recipe17.3.EncryptingandDecryptingaFile
Recipe17.4.CleaningupCryptographyInformation
Recipe17.5.VerifyingthataStringRemainsUncorruptedFollowingTransmission
Recipe17.6.WrappingaStringHashforEaseofUse
Recipe17.7.ABetterRandomNumberGenerator
Recipe17.8.StoringDataSecurely
Recipe17.9.MakingaSecurityAssertSafe
Recipe17.10.PreventingMaliciousModificationstoanAssembly
Recipe17.11.VerifyingThatanAssemblyHasBeenGrantedSpecific
Permissions

Recipe17.12.MinimizingtheAttackSurfaceofanAssembly
Recipe17.13.ObtainingSecurity/AuditInformation
Recipe17.14.Granting/RevokingAccesstoaFileorRegistryKey
Recipe17.15.ProtectingStringDatawithSecureStrings
Recipe17.16.SecuringStreamData
Recipe17.17.Encryptingweb.configInformation
Recipe17.18.ObtainingtheFullReasonaSecurityExceptionWasThrown
Recipe17.19.AchievingSecureUnicodeEncoding
Recipe17.20.ObtainingaSaferFileHandle
Chapter18.ThreadingandSynchronization
Introduction
Recipe18.1.CreatingPer-ThreadStaticFields
Recipe18.2.ProvidingThread-SafeAccesstoClassMembers
Recipe18.3.PreventingSilentThreadTermination
Recipe18.4.PollinganAsynchronousDelegate
Recipe18.5.TimingoutanAsynchronousDelegate




































































Recipe18.6.BeingNotifiedoftheCompletionofanAsynchronousDelegate
Recipe18.7.DeterminingWhetheraRequestforaPooledThreadWillBe
Queued
Recipe18.8.ConfiguringaTimer
Recipe18.9.StoringThread-SpecificDataPrivately
Recipe18.10.GrantingMultipleAccesstoResourceswithaSemaphore
Recipe18.11.SynchronizingMultipleProcesseswiththeMutex
Recipe18.12.UsingEventstoMakeThreadsCooperate

Recipe18.13.GettheNamingRightsforYourEvents
Recipe18.14.PerformingAtomicOperationsAmongThreads
Chapter19.UnsafeCode
Introduction
Recipe19.1.ControllingChangestoPointersPassedtoMethods
Recipe19.2.ComparingPointers
Recipe19.3.NavigatingArrays
Recipe19.4.ManipulatingaPointertoaFixedArray
Recipe19.5.ReturningaPointertoaParticularElementinanArray
Recipe19.6.CreatingandUsinganArrayofPointers
Recipe19.7.SwitchingUnknownPointerTypes
Recipe19.8.ConvertingaStringtoachar*
Recipe19.9.DeclaringaFixed-SizeStructurewithanEmbeddedArray
Chapter20.Toolbox
Introduction
Recipe20.1.DealingwithOperatingSystemShutdown,PowerManagement,or
UserSessionChanges
Recipe20.2.ControllingaService
Recipe20.3.ListWhatProcessesanAssemblyIsLoadedIn
Recipe20.4.UsingMessageQueuesonaLocalWorkstation
Recipe20.5.FindingthePathtotheCurrentFrameworkVersion
Recipe20.6.DeterminingtheVersionsofanAssemblyThatAreRegisteredinthe
GlobalAssemblyCache(GAC)
Recipe20.7.GettingtheWindowsDirectory
Recipe20.8.CapturingOutputfromtheStandardOutputStream
Recipe20.9.RunningCodeinItsOwnappdomain
Recipe20.10.DeterminingtheOperatingSystemandServicePackVersionof
theCurrentOperatingSystem
AbouttheAuthors
Colophon

Index


Copyright©2006O'ReillyMedia,Inc.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles(safari.oreilly.com).Formoreinformation,contact
ourcorporate/institutionalsalesdepartment:(800)998-9938or


Editor:

JohnOsborn

Cover
Designer:

EmmaColby

Production
Editor:

MaryBrady

Interior
Designer:


DavidFutato

Copyeditor:

NormaEmory

Cover
Illustrator:

NameHere

Proofreader:

Genevieve
Rajewski

Illustrators:

RobertRomano,JessamynRead,and
LesleyBorash

Indexer:

EllenTroutman

Zaig

Printing
History:




January2004:

FirstEdition.

January2006:

SecondEdition.




NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
TheCookbookseriesdesignations,C#Cookbookbooktitle>,the
imageofagartersnake,andrelatedtradedressare
trademarksofO'ReillyMedia,Inc.
<insertspecialtrademarkinfohere>
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorsassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.
ISBN:0-59610-063-9
[M]





Dedication
Jay
ToOwenandDrew,
Thankyouforteachingmehowtobeakidagain
Iloveyouboth,
Daddy
Steve
Tomytwolovingsons,PatrickandNicholasTeilhet



Preface
C#isalanguagetargetedatdevelopersfortheMicrosoft.NET
platformwhohavealreadyworkedwithaC-likelanguagesuch
asC,C++,orJava.UnlikepreviousversionsofCorC++for
theMicrosoftWindowsplatform,C#coderunsundera
managedexecutionenvironment.WhileCandC++developers
usingVisualStudio.NETcanwritemanagedcodeusing
ManagedC++,C#offersamiddlepathbetweenC++'soverall
powerbutsometimesdifficultcodeandthehigher-leveltask
orientationprovidedbyVisualBasic.NET.MicrosoftportraysC#
asamodernandinnovativelanguagefor.NETdevelopment
thatwillbefamiliartocurrentC++programmerswhileallowing
moreruntimecontrolovertheexecutingcode.
C#allowsyoutoperformmanyC/C++-likefunctionssuchas
directmemoryaccessviapointersandoperatoroverloading

thatarenotsupportedinVisualBasic.NET.C#isthesystemlevelprogramminglanguagefor.NET.Youcanstilldogreat
application-levelworkinC#,butitreallyshineswhenyouneed
tobuildcodealittleclosertotheFramework.
IfyouhaveseenC#,youmayhavenoticedthatitlooksalot
likeJava;JavaprogrammerswillfeelverymuchathomeinC#
oncetheylearntheFrameworkSDK.C#canalsobeagreat
languageforVisualBasic.NETprogrammerswhentheyneeda
littlemorecontroloverwhatthecodeisdoinganddon'twantto
havetowriteC++togainanadvantage.OntheWeb,you'llfind
alargecommunityofpeopledoingreallyneatthingswithC#
andtonsofsamplecodeonsitessuchas
,,and
.
Weputthisbooktogetherbasedonprogrammingproblemswe
ranintowhenwewerefirstlearningC#aswellasduringour
continueduseofit.Sincethefirsteditionwehaveencountered


awholenewsetofproblemstoovercomeandwiththehelpof
C#2.0,wehavecreatednewsolutionsforthem.Wehopethat
itwillhelpyougetpastsomeofthecommon(andnot-socommon)pitfallsandinitialquestionseveryonehaswhen
learninganewlanguageaswellastheslightlyoffthebeaten
pathitemsthatcomeupduringadevelopmentcycle.Thereare
recipesdealingwiththingswefoundmissingfromthe.NET
FrameworkClassLibrary(FCL),eventhoughMicrosofthas
providedtonsoffunctionalitytokeepfolksfromreinventingthe
wheel.Someofthesesolutionsyoumightimmediatelyuseand
somemayneverdarkenyourdoor,butwehopethisbookhelps
yougetthemostoutofC#andthe.NETFramework.
Thebookislaidoutwithrespecttothetypesofproblemsyou

willsolveasyouprogressthroughyourlifeasaC#
programmer.Thesesolutionsarecalledrecipes;eachrecipe
consistsofasingleproblem,itssolution,adiscussionofthe
solutionandotherrelevantrelatedinformation,andfinally
whereyoucanlookformoreinformationabouttheclassesused
fromtheFCL,otherbooksaddressingthistopic,relatedarticles,
andotherrecipes.Thequestion-answerformatprovides
completesolutionstoproblems,makingthebookeasytoread
anduse.Nearlyeveryrecipecontainsacomplete,documented
codesampleshowingyouhowtosolvethespecificproblem,as
wellasadiscussionofhowtheunderlyingtechnologyworks
andalistofalternatives,limitations,andotherconsiderations
whenappropriate.




WhoThisBookIsFor
Youdon'thavetobeanexperiencedC#or.NETdeveloperto
usethisbookitisdesignedforusersofalllevels.Thisbook
providessolutionstoproblemsthatdevelopersfaceeveryday
aswellassomethatmaycomealonginfrequently.Therecipes
aretargetedatthereal-worlddeveloperwhoneedstosolve
problemsnow,notlearnlotsoftheoryfirstbeforebeingableto
solvetheproblem.Whilereferenceortutorialbookscanteach
generalconcepts,theydonotgenerallyprovidethehelpyou
needinsolvingreal-worldproblems.Wechosetoteachby
example,thenaturalwayformostpeopletolearn.
Themajorityoftheproblemsaddressedinthisbookare
frequentlyfacedbyC#developers,butsomeofthemore

advancedproblemscallformoreintricatesolutionsthat
combinemanytechniques.Eachrecipeisdesignedtohelpyou
quicklyunderstandtheproblem,learnhowtosolveit,andfind
outanypotentialtrade-offsorramificationstohelpyousolve
yourproblemsquickly,efficiently,andwithminimaleffort.
Tosaveyoueventheeffortoftypinginthesolution,weprovide
thesamplecodeforthebookontheO'Reillywebsiteto
facilitatethe"editorinheritance"modeofdevelopment(copy
andpaste)aswellastohelplessexperienceddeveloperssee
goodprogrammingpracticeinaction.Thesamplecodeprovides
arunningtestharnessthatexerciseseachofthesolutions,but
enoughofthecodeisprovidedineachsolutioninthebookto
allowyoutoimplementthesolutionwithoutthesamplecode.
Thesamplecodeisavailablefromthebook'scatalogpage:
/>

WhatYouNeedtoUseThisBook
Torunthesamplesinthisbook,youneedacomputerrunning
Windows2000orlater(ifyouareusingWindowsNT4.0,you
canusemany,butnotall,oftheexamplesinthisbook;in
particular,ASP.NETand.NETWebServicesdonotrunonNT
4.0).AfewofthenetworkingandXMLsolutionsrequire
MicrosoftInternetInformationServer(IIS)Version5orlater.
Toopenandcompilethesamplesinthisbook,youneedVisual
Studio.NET2005.Ifyouareproficientwiththedownloadable
FrameworkSDKanditscommand-linecompilers,youshould
nothaveanytroublefollowingthetextofthisbookandthe
codesamples.



PlatformNotes
ThesolutionsinthisbookaredevelopedusingVisualStudio
.NET2005.ThedifferencesbetweenVersion2.0andVersion
1.1ofthe.NETFrameworkaresignificantandthesamplecode
haschangedfromthefirsteditiontoreflectthat.Acompletelist
ofdifferencesbetweenVersion2.0andVersion1.1ofthe.NET
Frameworkcanbefoundat
/>



HowThisBookIsOrganized
Thisbookisorganizedinto20chapters,eachofwhichfocuses
onaparticulartopicincreatingC#solutions.Thefollowing
paragraphssummarizeeachchaptertogiveyouanoverviewof
thisbook'scontents:

Chapter1,NumbersandEnumerations
Thischapterfocusesonthenumericandenumerationdata
typesusedinC#code.Recipescoversuchthingsas
numericconversions,usingbitwiseoperatorsonnumbers,
andtestingstringstodeterminewhethertheycontaina
numericvalue.Thedisplay,conversion,andtestingof
enumerationtypesandrecipesonusingenumerationsthat
consistofbitflagsarealsoshown.

Chapter2,StringsandCharacters
ThischaptercoversboththeStringandChardatatypes.
Variousrecipesshowhowtocomparestringsinvarious
ways,encode/decodestrings,breakstringsapart,andput

thembacktogetheragain,tonameafew.

Chapter3,ClassesandStructures
Thislargechaptercontainsrecipesdealingwithbothclass
andstructuredatatypes.Thischaptercoversawiderange
ofrecipesfromdesignpatternstoconvertingaclassto
interoperatingwithCOM.


Chapter4,Generics
Thisisanewchapterfocusingonthenewgenericscapacity
inC#,whichallowsyoutohavecodeoperateuniformlyon
valuesofdifferenttypes.Therearerecipestohelpyour
generalunderstandingofgenericsaswellaswhentheyare
appropriatetouse,whatsupportisprovidedinthe
Frameworkforthem,andhowtocreatecustom
implementationsofcollectionsusinggenerics.

Chapter5,Collections
Thischapterexaminesrecipesthatmakeuseofcollections.
Thecollectionrecipesmakeuseofaswellasextendthe
functionalityofthearray(single,multi,andjagged),the
List<T>,andtheHashtable.Thenewgeneric-basedcollections
areexplored,andthevariouswaystocreateyourown
stronglytypedcollectionarealsodiscussed.

Chapter6,IteratorsandPartialTypes
Inthischapter,twoofthenewfeaturesofC#areusedto
solveverydifferentprogrammingproblems.Weshowhow
youcanimplementiteratorsforgenericandnongeneric

typesandimplementforeachfunctionalityusingiterators,as
wellascustomiteratorimplementations.Theotherfeature
ofC#inthischapterispartialtypes.Weshowhowyoucan
usepartialtypestodothingslikebettersegmentyourcode
andhowtogeneratecodethatismoreeasilyextensible.

Chapter7,ExceptionHandling


Therecipesinthischapterfocusonthebestwaysto
implementexceptionhandlinginyourapplication.
Preventingunhandledexceptions,readinganddisplaying
stacktraces,andthrowing/rethrowingexceptionsare
includedrecipes.Inaddition,specificrecipesshowhowto
overcomesometrickysituations,suchasexceptionsfrom
late-boundcalledmethods,andhowtobuildacustom
exceptionvisualizerforthedebugger.

Chapter8,Diagnostics
Thischapterexploresrecipesthatusedatatypesthatfall
undertheSystem.Diagnosticsnamespace.Recipesdealwith
thetrace/Debugclasses,eventlogs,processes,performance
counters,andcustomdebuggerdisplaysforyourtypes.

Chapter9,Delegates,Events,andAnonymousMethods
Thischapter'srecipesshowhowdelegates,events,and
anonymousmethodscanbeusedinyourapplications.
Recipesallowmanipulationofdelegatesthatcallmorethan
onemethod,synchronousdelegates,asynchronous
delegates,andWindowskeyboardhooks.Anonymous

methodsareexploredandrecipesshowtheirusageinplace
ofold-styledelegatesaswellastheiruseinimplementing
closuresandfunctors.

Chapter10,RegularExpressions
Thischaptercoversaveryusefulsetofclassesthatare
usedtorunregularexpressionsagainststrings.Recipes
enumerateregularexpressionmatches,breakupstrings
intotokens,find/replacecharacters,andverifythesyntax


ofaregularexpression.Arecipeisalsoincludedthat
containsmanycommonregularexpressionpatterns.

Chapter11,DataStructuresandAlgorithms
Thischaptergoesabitoutsideofwhatisprovidedforyou
inthe.NETFrameworkClassLibraryandimplements
certaindatastructuresandalgorithmsthatarenotinthe
FCL,orpossiblyarenotinexistenceexactlythewayyou
wouldliketousethem,butonesthatyouhaveusedto
solveproblemsbefore.Itemssuchasqueues,maps,trees,
andhashesareexplored.

Chapter12,FilesystemI/O
Thischapterdealswithfilesysteminteractionsinfour
distinctways.Thefirstwayistolookattypicalfile
interactions;thesecondwaylooksatdirectory-orfolderbasedinteractions;thethirdwaydealswithpathsand
temporaryfiles;andthefourthwaydealswithadvanced
filesystemI/Otopics.


Chapter13,Reflection
Thischaptershowswaystousethebuilt-inassembly
inspectionsystemprovidedbythe.NETFrameworkto
determinewhattypes,interfaces,andmethodsare
implementedwithinanassemblyandhowtoaccessthemin
alate-boundfashion.

Chapter14,Web


×