Tải bản đầy đủ (.pdf) (900 trang)

2004 ms c sharp programmers cookbook

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 (3.11 MB, 900 trang )

C#Programmer'sCookbook
ISBN:0735619301
byAllenJones
MicrosoftPress©2004
Thisbookoffers226coderecipesapplicableto
avarietyofdifficultiesthatmayariseinthe
processofapplicationdevelopment.Topics
coveredincludeXMLprocessing,Windows
forms,databaseaccess,networking,runtime
security,cryptographyandmore.
TableofContents
C#Programmer'sCookbook
Introduction
Chapter1 - ApplicationDevelopment
Chapter2 - WorkingwithData
ApplicationDomains,Reflection,and
Chapter3 Metadata
Chapter4 - Threads,Processes,andSynchronization
Chapter5 - XMLProcessing
Chapter6 - WindowsForms
Chapter7 - ASP.NETandWebForms
Chapter8 - Graphics,Multimedia,andPrinting
Chapter9 - Files,Directories,andI/O
Chapter10 - DatabaseAccess
Chapter11 - NetworkingandInternetworking
Chapter12 - XMLWebServicesandRemoting
Chapter13 - RuntimeSecurity
Chapter14 - Cryptography


Chapter15 - UnmanagedCodeInteroperability


Chapter16 - CommonlyUsedInterfacesandPatterns
Chapter17 - WindowsIntegration
Index
ListofFigures
ListofTables


BackCover
NexttimeyouhitthewallwithatoughC#
developmentproblem,getthecodebehindthesolution
—andsolveittherightway.TheC#Programmer’s
Cookbookprovidesat-a-glancereferencetohundreds
ofC#andMicrosoft.NETFrameworkprogramming
scenariosusingaconcise,problem/solutionformat.
Thebook’sorganizedsoyoucanquicklyzeroinonthe
topicsandanswersyouneed—withpracticalexamples,
codesnippets,bestpractices,andundocumented
secretstogetthejobdone.
Nohalf-bakedsolutions.Getexpertcodefromexpert
developers.
Gethundredsofrecipescoveringevery
applicationtype—fromMicrosoftWindowstoWeb
pages,Webservices,WindowsForms,and
Windowsservices.
DiscoverexpertwaystosolvecommonWeb
applicationandnetworkprogrammingchallenges.
Managefiles,directories,andstreamswiththe
.NETI/Oclasses.
AccessdatabasesusingMicrosoftADO.NET.
Tackleadvancedtechniquesformultithreading,

manipulatingXMLdata,.NETRemoting,and
reusingcommonpatterns.
Developrichmultimediaapplicationsusingthe


.NETFramework.
Helpprotectyourapplicationswithcodeaccess
security,role-basedsecurity,andcryptography.
InteroperatewithlegacyWin32APIandCOMbasedsolutions.
AbouttheAuthor
AllenJonesiscoauthorofthepopularC#forJava
Developers,Microsoft.NETXMLWebServicesStepby
Step,andProgramming.NETSecurity.A13-year
technologyveteran,heisknownforthedepthofhis
C#and.NETexpertise.Hespecializesindeveloping
andimplementingenterprisesolutions,includingecommerceandsecuritysystems.


C#Programmer'sCookbook
AllenJones
Microsoft
ForBrenda
PUBLISHEDBYMicrosoftPressADivisionofMicrosoftCorporationOne
MicrosoftWayRedmond,Washington98052-6399
Copyright©2004byAllenJonesandMatthewMacDonald
Allrightsreserved.Nopartofthecontentsofthisbookmaybe
reproducedortransmittedinanyformorbyanymeanswithoutthe
writtenpermissionofthepublisher.
LibraryofCongressCataloging-in-PublicationData[pending.]
PrintedandboundintheUnitedStatesofAmerica.

123456789QWT876543
DistributedinCanadabyH.B.FennandCompanyLtd.
ACIPcataloguerecordforthisbookisavailablefromtheBritishLibrary.
MicrosoftPressbooksareavailablethroughbooksellersanddistributors
worldwide.Forfurtherinformationaboutinternationaleditions,contact
yourlocalMicrosoftCorporationofficeorcontactMicrosoftPress
Internationaldirectlyatfax(425)936-7329.VisitourWebsiteat
www.microsoft.com/mspress.Sendcommentsto

ActiveDirectory,ActiveMovie,ActiveX,Authenticode,DirectShow,
DirectX,Microsoft,MicrosoftPress,MSDN,VisualStudio,Win32,
Windows,theWindowslogo,WindowsMedia,andWindowsNTare
eitherregisteredtrademarksortrademarksofMicrosoftCorporationin
theUnitedStatesand/orothercountries.Otherproductandcompany
namesmentionedhereinmaybethetrademarksoftheirrespective


owners.
Theexamplecompanies,organizations,products,domainnames,e-mail
addresses,logos,people,places,andeventsdepictedhereinare
fictitious.Noassociationwithanyrealcompany,organization,product,
domainname,e-mailaddress,logo,person,place,oreventisintended
orshouldbeinferred.
AcquisitionsEditor:DanielleBirdVoeller
ProjectEditor:DickBrownandDeniseBankaitis
TechnicalEditor:EricDettinger
BodyPartNo.X10-08418
AllenJones
AllenJonesiscoauthorofthepopularC#forJavaDevelopersand
Microsoft.NETXMLWebServicesStepbyStep(MicrosoftPress).A13yeartechnologyveteran,heisknownforthedepthofhisC#and.NET

expertise.Allenspecializesindevelopingandimplementingenterprise
solutions,includinge-commerceandsecuritysystems.


Introduction


Overview
MasteringthedevelopmentofMicrosoft.NETFrameworkapplicationsin
C#islessaboutknowingtheC#languageandmoreaboutknowinghow
tousethefunctionalityofthe.NETFrameworkclasslibrarymost
effectively.TheC#Programmer'sCookbookexploresthebreadthofthe
.NETFrameworkclasslibraryandprovidesspecificsolutionstocommon
andinterestingprogrammingproblems.Eachsolution(orrecipe)is
presentedinasuccinctproblem/solutionformatandisaccompaniedby
workingcodesamples.
TheC#Programmer'sCookbookisnotintendedtoteachyouhowto
program,nortoteachyouC#.However,ifyouhaveeventhemost
rudimentaryexperienceprogrammingapplicationsbuiltonthe.NET
FrameworkusingC#,youwillfindthisbooktobeaninvaluableresource.
Ideally,whenyouarefacingaproblem,thisbookwillcontainarecipe
thatprovidesthesolution—oratleastitwillpointyouintheright
direction.Evenifyouaresimplylookingtobroadenyourknowledgeof
the.NETFrameworkclasslibrary,theC#Programmer'sCookbookisthe
perfectresourcetoassistyou.YoucannotbecomeproficientwithC#and
theclassesinthe.NETFrameworkclasslibrarymerelybyreadingabout
them;youmustusethemandexperimentwiththembywritingprograms,
programs,andmoreprograms.Thestructureandcontentofthisbook
andthereal-worldapplicabilityofthesolutionsitprovidesofferthe
perfectstartingpointfromwhichtokick-startyourownexperimentation.

Note Thecodeinthisbookhasbeenwrittenforandtestedon
version1.1ofthe.NETFramework.Inmanycases,youwill
findthatthesamplecodewillrunonversion1.0ofthe.NET
Framework,butthishasnotbeentestedandnoguarantees
aremade.


CodeSamples
ThecodeforallrecipesintheC#Programmer'sCookbookisavailable
onlineatTodownloadthe
samplefiles,clicktheCompanionContentlinkintheMoreInformation
menuontherightsideofthepage.ThisactionloadstheCompanion
Contentpage,whichincludesalinkfordownloadingthesamplefiles.To
installthesamplefiles,clicktheDownloadTheBook'sSampleFileslink
andfollowtheinstructionsinthesetupprogram.Alinktothesample
codewillbeaddedtoyourStartmenu.
ThecodeisprovidedasasetofVisualStudio.NET2003solutionsand
projectsorganizedbychapterandrecipenumber.Eachchapterisa
separatesolution,andeachrecipeisaseparateprojectwithinthe
chapter'ssolution.SomerecipesinChapter11andChapter12that
demonstratenetworkprogrammingincludeseparateprojectsthatcontain
theclientandserverelementsoftherecipe'ssolution.
AlthoughallsamplesareprovidedasVisualStudio.NETprojects,most
consistofasinglesourcefilethatyoucancompileandrunindependent
ofVisualStudio.NET.IfyouarenotusingVisualStudio.NET2003you
canlocatethecodeforaparticularrecipebynavigatingthroughthe
directorystructureofthesamplecode.Forexample,tofindthecodefor
recipe4.3,youwouldlookupthecodeinthedirectory
"Chapter04\Recipe04-03".Ifyouusethecommand-linecompiler,ensure
thatyouincludereferencestoallrequired.NETclasslibraryassemblies.

Someofthesampleapplicationsrequirecommand-linearguments.
Whererequired,therecipe'stextwilldescribethearguments.Ifyouare
usingVisualStudio.NET,youcanentertheseargumentsintheproject
properties(undertheDebuggingnodeoftheConfigurationProperties
item).Keepinmindthatifyouneedtoenterdirectoryorfilenamesthat
incorporatespaces,youwillneedtoplacethefullnameinquotation
marks.
Someadditionalstepsarerequiredtoinstallthetwovirtualdirectories
usedfortheexamplesthataccompanyChapter7,"ASP.NETandWeb
Forms,"andChapter12,"XMLWebServicesandRemoting."These


stepsaredescribedinareadme.txtfileprovidedwiththedownloaded
codeandonthecodedownloadpage.


SystemRequirements
Torunthesamplecodeaccompanyingthisbook,youwillneedthe
followingsoftware:
Microsoft.NETFrameworkSDKversion1.1
MicrosoftVisualStudio.NET2003(recommended)
MicrosoftWindows2000,WindowsXP,orMicrosoftWindows
Server2003
MicrosoftSQLServer2000orMSDEfortherecipesinChapter
10
MicrosoftInternetInformationServices(IIS)forsomerecipesin
Chapter7andChapter12
Theminimumhardwarespecificationfordevelopmentisa450-MHz
PentiumII-classprocessor,withaminimumof128MBofRAMifyou're
runningMicrosoftWindows2000and256MBofRAMifyou'rerunning

WindowsXP,Windows2000Server,orWindowsServer2003.You'll
needabout5GBoffreehard-diskspacetoinstallVisualStudio.NET
2003.Thesevaluesareminimums,andyourdevelopmentlifewillbe
mucheasieronasystemwithampleRAMandfreediskspace.
Note AlthoughMicrosoft'simplementationofthe.NETFrameworkfor
WindowsisthefocusoftheC#Programmer'sCookbook,an
importantgoalwastoprovideausefulresourcetoallC#
programmersregardlessoftheplatformonwhichtheyare
developingorthetoolstowhichtheyhaveaccess.Apartfrom
specifictopicsthatarenotsupportedonall.NETplatforms
(suchasWindowsForms,ADO.NET,andASP.NET)manyof
thesamplesinthisbookarevalidacrossall.NET
implementations.


OtherBooks
Ifyouhavenoprogrammingexperience,thisbookwillnotteachyouhow
toprogram.Similarly,ifyouareaprogrammerbuthavelittleornoC#
experience,thisbookdoesnotprovidethestructurerequiredtoteach
youhowtoprogrameffectivelyinC#.Dependingonyourprogramming
backgroundandcurrentlevelofC#knowledge,thefollowingbookscan
teachyouenoughaboutC#andthe.NETFrameworktoenableyouto
getthemostfromthesolutionsprovidedinthisbook:
ProgrammingintheKeyofC#:APrimerforAspiring
Programmers(MicrosoftPress,2003)CharlesPetzold.
MicrosoftVisualC#.NETStepbyStepVersion2003(Microsoft
Press,2002)JohnSharpandJonJagger.
MicrosoftVisualC#.NET(CoreReference)(MicrosoftPress,
2002)MickeyWilliams.
Ifyouwanttoexploretopicsdiscussedinthisbookinmoredetail,oryou

wanttounderstandmoreabouttheinternaloperationofthe.NET
Framework,Irecommendthefollowingbooks:
InsideC#,SecondEdition(MicrosoftPress,2002)TomArcher
andAndrewWhitechapel.
AppliedMicrosoft.NETFrameworkProgramming(Microsoft
Press,2002)JeffreyRichter(Wintellect).
Essential.NET,Volume1:TheCommonLanguageRuntime
(Addison-Wesley,2002)DonBoxandChrisSells.
ProgrammingMicrosoftWindowswithC#(MicrosoftPress,2001)
CharlesPetzold.
Programming.NETSecurity(O'Reilly&Associates,2003)Adam
FreemanandAllenJones.
MicrosoftADO.NET(CoreReference)(MicrosoftPress,2002)


DavidSceppa.
Advanced.NETRemoting(Apress,2002)IngoRammer.


MicrosoftPressSupport
Everyefforthasbeenmadetoensuretheaccuracyofthebookandits
companioncontent.Microsoftalsoprovidescorrectionsforbooksthrough
theWorldWideWebatthefollowingaddress:
/>Ifyouhavecomments,questions,orideasregardingthepresentationor
useofthisbookorthecompanioncontent,youcansendthemto
Microsoftusingeitherofthefollowingmethods:
PostalMail:
MicrosoftPress
ATTN:C#Programmer'sCookbookEditor
OneMicrosoftWay

Redmond,WA98052-6399
E-Mail:
Pleasenotethatproductsupportisn'tofferedthroughtheabovemail
addresses.ForsupportinformationregardingVisualStudio.NET
2003,gotoYoucanalsocall
StandardSupportat(425)635-7011weekdaysbetween6A.M.and6
P.M.Pacifictime,oryoucansearchMicrosoftProductSupport
Servicesat />

Chapter1:ApplicationDevelopment


Overview
Thischaptercoverssomeofthefundamentalactivitiesyouwillneedto
performduringthedevelopmentofyourC#solutions.Therecipesinthis
chapterdescribehowto
BuildConsoleandWindowsFormsapplications(recipes1.1and
1.2).
Createandusecodemodulesandlibraries(recipes1.3and1.4).
Accesscommand-lineargumentsfromwithinyourapplications
(recipe1.5).
Usecompilerdirectivesandattributestoselectivelyincludecode
atbuildtime(recipe1.6).
Accessprogramelementsbuiltinotherlanguageswhosenames
conflictwithC#keywords(recipe1.7).
Giveassembliesstrongnamesandverifystrong-named
assemblies(recipes1.8,1.9,1.10,and1.11).
SignanassemblywithaMicrosoftAuthenticodedigitalsignature
(recipes1.12and1.13).
Managethesharedassembliesthatarestoredintheglobal

assemblycache(recipe1.14).
Preventpeoplefromdecompilingyourassembly(recipe1.15).
Note Allofthetoolsdiscussedinthischaptershipwiththe
Microsoft.NETFrameworkorthe.NETFramework
SDK.ThosetoolsthatarepartoftheFrameworkarein
themaindirectoryfortheversionoftheFrameworkthat
youarerunning.Forexample,theyareinthedirectory
C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322if
youinstallversion1.1ofthe.NETFrameworktothe


defaultlocation.The.NETinstallationprocess
automaticallyaddsthisdirectorytoyourenvironment
path.
ThetoolsprovidedwiththeSDKareintheBin
subdirectoryofthedirectoryinwhichyouinstallthe
SDK.Thisdirectoryisnotaddedtoyourpath
automatically,soyoumustmanuallyedityourpathin
ordertohaveeasyaccesstothesetools.
Mostofthetoolssupportshortandlongformsofthe
command-lineswitchesthatcontroltheirfunctionality.
Thischapteralwaysshowsthelongform,whichis
moreinformativebutrequiresadditionaltyping.Forthe
shortenedformofeachswitch,seethetool's
documentationinthe.NETFrameworkSDK.


1.1CreateaConsoleApplication
Problem
Youneedtobuildanapplicationthatdoesn'trequireaWindowsgraphical

userinterface(GUI)butinsteaddisplaysoutputto,orreadsinputfrom,
theWindowscommandprompt(console).

Solution
EnsureyouimplementastaticmethodnamedMainwithoneofthe
followingsignaturesinatleastoneofyoursourcecodefiles.
publicstaticvoidMain();
publicstaticvoidMain(string[]args);
publicstaticintMain();
publicstaticintMain(string[]args);
Usethe/target:exeswitchontheC#compiler(csc.exe)whenyou
compileyourassembly.

Discussion
Bydefault,theC#compilerwillbuildaConsoleapplicationunlessyou
specifyotherwise.Forthisreason,it'snotnecessarytospecifythe
/target:exeswitch,butdoingsomakesyourintentionclearer,whichis
usefulifyouarecreatingbuildscriptsthatwillbeusedbyothersorwillbe
usedrepeatedlyoveraperiodoftime.Thefollowingexamplelistsaclass
namedConsoleUtilsthatisdefinedinafilenamedConsoleUtils.cs:
usingSystem;

publicclassConsoleUtils{

//Amethodtodisplayapromptandreadaresponsefromth
publicstaticstringReadString(stringmsg){

Console.Write(msg);



returnSystem.Console.ReadLine();
}

//Amethodtodisplayamessagetotheconsole
publicstaticvoidWriteString(stringmsg){

System.Console.WriteLine(msg);
}

//MainmethodusedfortestingConsoleUtilitymethods
publicstaticvoidMain(){

//Promptthereadertoentertheirname
stringname=ReadString("Pleaseenteryourname:");

//WelcomethereadertotheC#Cookbook
WriteString("WelcometotheC#Programmer'sCookbook,"
}
}
TobuildtheConsoleUtilsclassintoaConsoleapplicationnamed
ConsoleUtils.exe,usethecommandcsc/target:exeConsoleUtils.cs.
Youcanruntheresultingexecutableassemblydirectlyfromthe
commandline.Whenrun,theMainmethodoftheConsoleUtils.exe
applicationpromptsyouforyournameandthenwelcomesyoutotheC#
Programmer'sCookbook,asshownhere.
Pleaseenteryourname:Rupert
WelcometotheC#Programmer'sCookbook,Rupert
Inreality,applicationsrarelyconsistofasinglesourcefile.Asan
example,theHelloWorldclasslistedhereusestheConsoleUtilsclassto
displaythemessage"Hello,world"totheconsole.(HelloWorldis

containedintheHelloWorld.csfile.)
publicclassHelloWorld{
publicstaticvoidMain(){



ConsoleUtils.WriteString("Hello,world");
}
}
TobuildaConsoleapplicationconsistingofmorethanonesourcecode
file,youmustspecifyallthesourcefilesasargumentstothecompiler.
Forexample,thefollowingcommandbuildsanapplicationnamed
MyFirstApp.exefromtheHelloWorld.csandConsoleUtils.cssourcefiles.
csc/target:exe/main:HelloWorld
/out:MyFirstApp.exeHelloWorld.csConsoleUtils.cs
The/outswitchallowsyoutospecifythenameofthecompiledassembly.
Otherwise,theassemblyisnamedafterthefirstsourcefilelisted—
HelloWorld.csintheexample.BecauseboththeHelloWorldand
ConsoleUtilsclassescontainMainmethods,thecompilercan't
automaticallydeterminewhichmethodrepresentsthecorrectentrypoint
fortheassembly.Youmustusethecompiler's/mainswitchtoidentifythe
nameoftheclassthatcontainsthecorrectentrypointforyour
application.


1.2CreateaWindows-BasedApplication
Problem
YouneedtobuildanapplicationthatprovidesaWindowsForms–based
GUI.


Solution
EnsureyouimplementastaticmethodnamedMaininatleastoneof
yoursourcecodefiles.IntheMainmethod,createaninstanceofaclass
thatextendstheSystem.Windows.Forms.Formclass.(Thisisyour
application'smainform.)Passyourmainformobjecttothestaticmethod
RunoftheSystem.Windows.Forms.Applicationclass.Usethe
/target:winexeswitchontheC#compiler(csc.exe)whenyoucompile
yourassembly.

Discussion
BuildinganapplicationthatprovidesasimpleWindowsGUIisaworld
awayfromthedevelopmentofafull-fledgedWindows-basedapplication.
However,therearethingsyoumustdoregardlessofwhetheryouare
writingtheWindowsequivalentofHelloWorldorthenextversionof
MicrosoftWord,includingthefollowing:
Foreachformyouneedinyourapplication,createaclassthat
extendstheSystem.Windows.Forms.Formclass.
Ineachofyourformclasses,declaremembersthatrepresentthe
controlsthatwillbeonthatform,forexamplebuttons,labels,
lists,andtextboxes.Thesemembersshouldbedeclaredprivate
oratleastprotectedsothatotherprogramelementscan'taccess
themdirectly.Ifyouneedtoexposethemethodsorpropertiesof
thesecontrols,implementthenecessarymembersinyourform
class,providingindirectandcontrolledaccesstothecontained
controls.


Declaremethodsinyourformclassthatwillhandleeventsraised
bythecontrolscontainedbytheform,suchasbuttonclicksor
keypresseswhenatextboxistheactivecontrol.Thesemethods

shouldbeprivateorprotectedandfollowthestandard.NET
eventpattern(describedinrecipe16.10).It'sinthesemethods
(ormethodscalledbythesemethods)whereyouwilldefinethe
bulkofyourapplication'sfunctionality.
Declareaconstructorforyourformclassthatinstantiateseachof
theform'scontrolsandconfigurestheirinitialstate(size,color,
position,content,andsoon).Theconstructorshouldalsowireup
theappropriateeventhandlermethodsofyourclasstothe
eventsofeachcontrol.
DeclareastaticmethodnamedMain—usuallyasamemberof
yourapplication'smainformclass.Thismethodistheentrypoint
foryourapplication,anditcanhavethesamesignaturesas
thosementionedinrecipe1.1.IntheMainmethod,createan
instanceofyourapplication'smainformandpassitasan
argumenttothestaticApplication.Runmethod.TheRunmethod
makesyourmainformvisibleandstartsastandardWindows
messagelooponthecurrentthread,whichpassestheuserinput
(keypresses,mouseclicks,etc.)toyourapplicationasevents.
TheWelcomeFormclassshowninthefollowingcodelistingisasimple
WindowsFormsapplicationthatdemonstratesthetechniquesjustlisted.
Whenrun,itpromptsausertoenteranameandthendisplaysa
messageboxwelcomingtheusertotheC#Programmer'sCookbook.
usingSystem.Windows.Forms;
publicclassWelcomeForm:Form{

//Privatememberstoholdreferencestotheform'scontrol
privateLabellabel1;
privateTextBoxtextBox1;
privateButtonbutton1;



//Constructorusedtocreateaninstanceoftheformandc
//theform'scontrols.
publicWelcomeForm(){
//Instantiatethecontrolsusedontheform.
this.label1=newLabel();
this.textBox1=newTextBox();
this.button1=newButton();

//Suspendthelayoutlogicoftheformwhileweconfig
//positionthecontrols.
this.SuspendLayout();

//Configurelabel1,whichdisplaystheuserprompt.
this.label1.Location=newSystem.Drawing.Point(16,36)
this.label1.Name="label1";
this.label1.Size=newSystem.Drawing.Size(128,16);
this.label1.TabIndex=0;
this.label1.Text="Pleaseenteryourname:";

//ConfiguretextBox1,whichacceptstheuserinput.
this.textBox1.Location=newSystem.Drawing.Point(152,
this.textBox1.Name="textBox1";
this.textBox1.TabIndex=1;
this.textBox1.Text="";

//Configurebutton1,whichtheuserpressestoentert
this.button1.Location=newSystem.Drawing.Point(109,8
this.button1.Name="button1";
this.button1.TabIndex=2;

this.button1.Text="Enter";
this.button1.Click+=newSystem.EventHandler(this.butt
//ConfigureWelcomeFormandaddcontrols.
this.ClientSize=newSystem.Drawing.Size(292,126);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);


this.Controls.Add(this.label1);
this.Name="form1";
this.Text="C#Programmer'sCookbook";

//Resumethelayoutlogicoftheformnowthatallcon
//configured.
this.ResumeLayout(false);
}

//Applicationentrypoint,createsaninstanceoftheform
//runningastandardmessagelooponthecurrentthread.T
//loopfeedstheapplicationwithinputfromtheuserase
publicstaticvoidMain(){
Application.Run(newWelcomeForm());
}

//EventhandlercalledwhentheuserclickstheEnterbutt
privatevoidbutton1_Click(objectsender,System.EventArgs

//Writedebugmessagetotheconsole
System.Console.WriteLine("Userentered:"+textBox1.Te


//Displaywelcomeasamessagebox
MessageBox.Show("WelcometotheC#Programmer'sCookboo
+textBox1.Text,"C#Programmer'sCookbook");
}
}
TobuildtheWelcomeFormclass(containedinafilenamed
WelcomeForm.cs)intoanapplication,usethecommandcsc
/target:winexeWelcomeForm.cs.The/target:winexeswitchtellsthe
compilerthatyouarebuildingaWindows-basedapplication.Asaresult,
thecompilerbuildstheexecutableinsuchawaythatnoconsoleis
createdwhenyourunyourapplication.Ifyouusethe/target:exeswitch
tobuildaWindowsFormsapplicationinsteadof/target:winexe,your
applicationwillstillworkcorrectly,butyouwillhaveaConsolewindow


visiblewhiletheapplicationisrunning.Althoughthisisundesirablefor
productionqualitysoftware,theConsolewindowisusefulifyouwantto
writedebugandlogginginformationwhileyou'redevelopingandtesting
yourWindowsFormsapplication.Youcanwritetothisconsoleusingthe
WriteandWriteLinemethodsoftheSystem.Consoleclass.
Figure1.1showstheWelcomeForm.exeapplicationinoperationgreeting
ausernamedRupert.Thisversionoftheapplicationisbuiltusingthe
/target:execompilerswitch,resultinginthevisibleConsolewindowin
whichyoucanseetheoutputfromtheConsole.WriteLinestatementin
thebutton1_Clickeventhandler.


Figure1.1:AsimpleWindowsFormsapplication.
Note BuildinglargeGUI-basedapplicationsisatimeconsuming
undertakingthatinvolvesthecorrectinstantiation,

configuration,andwiringupofmanyformsandcontrols.
MicrosoftVisualStudio.NETautomatesmuchofthework
associatedwithbuildinggraphicalapplications.Tryingtobuilda
largegraphicalapplicationwithouttheaidoftoolslikeVisual
Studio.NETwilltakeyoumuchlonger,beextremelytedious,
andresultinagreaterchanceofbugsinyourcode.


×