Professional Documents
Culture Documents
Introduction To Visual Studio 2010: Tutorial Setup
Introduction To Visual Studio 2010: Tutorial Setup
Introduction
IfyouhaventusedMicrosoftVisualStudiobefore,thenthistutorialisforyou.Itwillwalkyouthrough
themajorfeaturesofVisualStudio2010andgetyoustartedwithcreatingvarioustypesofSynergy.NET
applications.Youwillalsolearnusefultipsandtechniquesthatcansaveyouvaluabletimewhile
programmingwithinVisualStudio.
Tutorial Setup
Nospecificpreparationisneededinordertocompletethistutorial.
Tutorial Steps
Starting Visual Studio
Beforewecangetstarted,ifitsnotalreadyrunning,weneedtostartMicrosoftVisualStudio2010.
FromtheWindowsStartMenu,selectAllPrograms>MicrosoftVisualStudio2010>Microsoft
VisualStudio2010.
OnceVisualStudiohasfinishedloading,youshouldbelookingatascreencalledtheStartPage.This
screenallowsyoutoeasilycreateanewdevelopmentproject,oropenanexistingone,andopen
recentlyusedprojects.OntherightsideoftheStartPageVisualStudiopresentsallkindsofinformation,
thecontentofwhichisalsocustomizedtothetypeofenvironmentthatyouselect(welltalkaboutthis
moreinamoment).Thisinformationcanincludenewsandannouncements,technicalinformation,and
lotsofothertypesofcontent.TheStartPageisoftenoverlookedbydevelopers,butwhenyouare
learningVisualStudioand.NETdevelopmentitcanbeavaluablesourceofinformation.
TheStartPagecloseswhenyoucreateoropenadevelopmentproject,butyoucanreturntoitatany
timebyselectingView>StartPagefromthemenu.
ManythingsinVisualStudioarecustomizable,sotohelptoensurethatyouareabletocompletethis
tutorial,weregoingtoresetallVisualStudiosettingstodefaultvalues.Infact,therearemultiplesetsof
defaultvalues,asyouwillseeshortly.Therearedefaultsettingsbasedonthesomeoftheavailable
programminglanguages,defaultsfortypesofdevelopment(e.g.,webdevelopment)andvariousother
scenarios.
ThefirsttimeyoustartVisualStudioafterinstallingit,youwillbeaskedtoselectwhichdefault
configurationyouwishtouse.ManypeopleselectGeneralDevelopmentSettingsforaninitial
configurationwellsuitedtomultiplelanguagesandvarioustypesofdevelopmentprojects.
ItisalsopossibletoswitchVisualStudiotoadifferentcollectionofsettingsatanytime,andalsotosave
andrestorecustomsettings.
Selectingoneofthesepredefinedcollectionsofdefaultsettingscanmakemanychangestoyour
environment.Thingsthatarecommonlychangedincludemenuitems,menuitemshortcuts,toolbars,
andmore.
OntheStartPage,clicktheNewProjectlink.
SelectFile>New>Projectfromthemenu.
ClicktheNewProjectbuttononthetoolbar.
TypeCtrl+Shift+N.
OntheStartPage,clickontheNewProjectlink.
YouwillnoticethattheNewProjectdialogisdividedintoseveralmainparts.Ontheleftisatreeview
whereyoucanselectfromvariousprojectcategoriesandsubcategories,manyofthembasedonthe
programminglanguagethatyouwishtouse.Whenyouselectacategory,thecenterpartofthedialog
displaysalistofprojecttemplatesthatbelongtothecategorythatyouhaveselected.Whenyouselect
aprojecttemplate,abriefdescriptionoftheprojectcreatedbythetemplateisdisplayedattherightof
thedialog.Finallythelowerportionofthedialogallowsyoutopickthelocationwhereyouwouldlike
theprojecttobecreated,andspecifyanameforyournewproject.
Theprojectnamethatyoupickisusedinmanyways,dependingonthetypeofprojectyouarecreating.
Generallytheprojectnamewillbeusedtodeterminethingslike:
ThenameoftheSolutionthatiscreated(moreaboutthisinamoment).
Thenameoftheprojectthatiscreated.
Thenameofthefolderthattheprojectwillbecreatedin.
Thenameofthemainassembly(programorlibrary)thatwillbecreatedbytheproject.
Thenameofthedefaultnamespacethatwillbeusedwhensometypesofitemareaddedto
theproject.
Ofcourse,evenafteraprojecthasbeencreated,alloranyofthesethingscanbechanged,butsomeare
hardertochangethanothers.Itsbesttoputsomethoughtintothenameofyourprojectbeforeyou
createit.
Inthetemplatestree(left)expandtheSynergy/DEcategory,andthenselectWindows.
Intheprojecttemplateslist(center)selectWindowsFormsApplication.
IntheNamefield,enterIntroToVisualStudio.
Decideonafoldertocreateyourprojectin,andenteritsnameintheLocationfield.
EnsurethattheCreatedirectoryforsolutioncheckboxISchecked.
InVisualStudio,oneormoreprojectsmayexistwithinaSolution.Everyprojectwillhavesometypeof
output,usuallyanassembly,eitheraprogram(.exe)orlibrary(.dll).Projectsmakeupthevariousparts
ofanapplication.ASolutionismerelyacollectionofprojects,providingawayfordeveloperstomove
aroundthevariouspartsoftheirapplicationeasily.Everyprojectmustexistwithinasolution,anda
solutioncancontainmultipleprojects.
WhenyoucreateanewprojectinVisualStudiobyoneofthemechanismsthatwediscussedearlier,
VisualStudiowillalsocreateaSolution.IftheCreatedirectoryforsolutionboxisnotchecked,then
thesolutionfileisnamedthesameastheprojectbeingcreated,andiscreatedinthesamefolderasthe
project.Thisisgenerallyappropriateifyouonlyplanonworkingwithoneprojectinthesolution.
IftheCreatedirectoryforsolutionboxischecked,thenVisualStudiowillcreateafolderforthe
solution(belowthelocationthatyouspecify)andsavethesolutionfileinthatfolder.Thenasecond
folder,fortheproject,willbecreatedbelowthesolutionfolder,andalloftheprojectfileswillbe
createdinorbelowtheprojectfolder.Thisisappropriatewhenyouintendtoaddseveralprojectstoa
solution,aseachprojectwillbestoredinitsownfolderbelowthemainsolutionfolder.Youllalsonotice
thatinthiscaseyouareabletospecifyadifferentnameforthesolutionitself.
ClickontheOKbuttontocreateyournewsolutionandproject.Becauseofthevirtualmachine,
creatingandopeningthesolutionandprojectmaytakeafewseconds.
Differentprojecttemplatescausedifferentthingstohappenwhenanewprojectiscreated.Fora
WindowsFormsproject,whatgenerallyhappensisthesolutionandproject,andvariousdefaultproject
filesaredisplayedintheSolutionExplorertowardsthetoprightofthescreen,thevisualdesignsurface
forthedefaultformthatwasaddedtotheprojectisdisplayedfillingmostofthescreen,andthe
Propertieswindowisdisplayedtowardsthebottomrightofthescreen.
Solution Explorer
TheSolutionExplorerwindowisakeypartofVisualStudio,andis
frequentlyusedbydevelopers.Itallowsyoutonavigatearoundthevarious
filesandotheritemsthatmakeupyourprojectsandyoursolution.
Generally,doubleclickingonafilewillopenthatfile,eitherinatexteditor
orperhapssomekindofvisualdesignsurface.Somefilescanbeeditedin
variousways.Forexample,youwillnoticethatwhentheprojectwas
created,thefileForm1.dblwasautomaticallycreated,addedtotheproject,
andopenedindesignview.Butthereisanotherwayofworkingwith
Form1.dbl,inasourcecodeeditor.Toseethisinaction:
InSolutionExplorer,rightclickForm1.dblandselectViewCode.
WhenworkingwithpiecesofaUIitiscommontoworkwiththesetwo
viewsofagivensourcefile,thedesignviewandthecodeview.
RightclickForm1.dblagainandthistimeselectViewDesigner.
Youmayhavenoticedthatonceafile(oraviewofafile)isopened,itremainsopenuntilyouspecifically
closeit.Eachfileisassignedatabtowardsthetopofthemainworkarea,whichlookslikethis:
Youcanusethesetabstoswitchbetweentheviewsofafile,orbetweenmultiplefilesthatyouhave
opened.YoullalsonoticeanXtotherightofeachtab,whichcanbeusedtoclosethatfileorview.
Youmaysometimesseereddotsnextthefilenameonatab.Thisisanindicationthatthefilehasbeen
modifiedandneedstobesaved.VisualStudiowillautomaticallysavefileswhenyoubuildorrun,and
therearealsovariouswaystomanuallysaveoneormorefiles.Theeasiestwaytomanuallysavefilesis
tousetheCtrl+Sshortcuttosavethecurrentfile,ortheCtrl+Shift+Sshortcuttosaveallchangedfiles.
ItiseasytochangethelayoutoftheUIinVisualStudio,wheremostthingscanberepositioned,docked,
stackedintabsets,andhiddenawayatwill.IfatanytimeyoucantfindSolutionExploreryoucan
alwaysmakeitvisiblebyselectingView>SolutionExplorerfromthemenu,orbyusingthekeyboard
shortcutCtrl+Alt+L.
RightnowwearecreatingaWindowsFormsapplication,sowe
haveaccesstoawidevarietyofcomponentsthatcanbeusedto
buildaWindowsuserinterface.Thesecomponentsincludethings
liketheTextBox,CheckBoxandButtoncontrolsthatyoure
probablyfamiliarwith.ThesecontrolsarelocatedintheToolbox
(moreinamoment)andcanbedraggedtothevisualdesign
surfaceasneeded.
Bytheway,thesameconceptalsoapplieswhenworkingwithothertypesofapplication.Aswellaswith
traditionalWindowsFormsapplications,developerscommonlyworkwithvisualdesignsurfacesand
toolboxeswhendevelopingWindowsPresentationFoundation(WPF)applications,ASP.NETWeb
applications,Silverlightapplications,andothers.
The Toolbox
TheToolboxmaynotbevisiblerightnow,butifnotlookdowntheleft
handsideoftheVisualStudiowindowandyoumayseeaverticaltabthat
saysToolbox.
IfyoudontseetheToolboxWindowthenselectView>Toolbox
fromthemenu(ortypeCtrl+Alt+X).
WiththeToolboxvisible,clickonthesmall iconatthetopright
oftheToolboxwindowtopinthewindowinplace.
Pinningawindowprovidesamechanismtoensurethatitremainsonthe
screen.Mostwindows,whenunpinned,slideoutofsightbutleavebehind
atabsothatyoucanaccessthewindowagain.Hoveringthemouseover
theoneofthesetabswillmakethewindowappearsothatyoucanaccess
it,orpinitinplace.
MakesurethatthedesignviewofForm1.dblisvisible.
IntheToolbox,gototheCommonControlsgroup,thenclickonce
onanddragaButtoncontroltothedesignsurface.
Youwillnoticethatwhenthebuttoniscreatedontheform,severalwhitehandlesappeararoundthe
outsideofthebutton.Thesehandlesperformtwofunctions;theyindicatewhichitemiscurrently
selectedtobeworkedwith,andtheycanbeusedtoresizetheselecteditem.
Singleclickthebodyoftheform(notonthebutton)andyouwillseethatthehandlesmoveto
theform,whichisnowselectedtobeworkedon.
Singleclickonthebuttonagain,thehandlesmovebacktothebutton.
Asyouclickbetweenthesetwoitems,looktothelowerrightportionofthescreen.Youshouldseea
windowcalledProperties,andyoushouldseethecontentofthewindowchangeasyouselectdifferent
itemsonavisualdesignsurface.
Ifyoucantseethepropertieswindow,selectView>PropertiesWindowfromthemenu,oruse
theF4keyboardshortcut.
Ifnecessary,pinthepropertieswindowinplace.
Properties Window
ThepropertieswindowisanotherkeypartofVisualStudiowhere,ifyouredevelopingauserinterface
atleast,youarelikelytospendalotoftime.
Essentiallyeachitemthatyouworkwith(buttons,textboxes,
checkboxes,etc.)haveproperties,sometimeshundredsofthem,
andthepropertieswindowallowsyoutoinspectandchangethe
valuesoftheseproperties,inordertoachievethedesired
functionalitywithinyourapplication.
Noticetheminitoolbaratthetopofthepropertieswindow;infact
manyofVisualStudioswindowshaveasimilartoolbar,which
generallyallowsyoutoviewtheinformationinthewindowin
variousways.Forexample,thepropertieswindowiscurrently
groupingthevariouspropertiesoftheselectedbuttoncontrolby
type(Accessibility,Appearance,etc.)becausethefirstbutton( )
onthetoolbarisselected.
Clickonthesecondicon( )toorderthepropertiesalphabetically.
Noticethatthepropertieswindowalsohasadropdownlist(atthetop)whichshowsyouwhichitemis
currentlyselected.Anotherwayofchangingtheselecteditemistodropdownthislistandselecta
differentitem.
DropdownthelistatthetopofthepropertieswindowandselectForm1.
Noticehowtheselecteditemhandlesmovedfromthebuttontotheform,andhowthecontentofthe
propertieswindowchangedtoreflectthepropertiesofthenewlyselecteditem.
OnForm1sdesignview,selecttheform.
Inthepropertieswindow,LocatetheTextpropertyandsetthevaluetoMyForm.
AWindowsFormstextpropertyisusedtosetthetitleofthewindow;noticehowthetextthatyou
typedisnowalsodisplayedinthetitleareaoftheformdesigner.Somechangesthatyoumakeinthe
propertieswindowarereflectedvisuallyinthedesigner.
Insomecases,theoppositeisalsotrue.Forexample:
Withtheformselected,locatetheSizeproperty.Itmaybeeasiertoswitchtoalphabeticmode
(toolbarattopofpropertieswindow).
Noticethecurrentvalueofthesizeproperty;probablythedefault300,300
Nowusethedesignerscurrentitemhandlestovisuallyresizetheform.
ChecktheSizepropertyagain,itshouldhavechanged.
So,makingchangesinthepropertieswindowoftenvisuallychangesthedesignerwindow,andmaking
changesinthedesignerwindowalsochangesthepropertieswindow.
Anotherthingtonoticewithrespecttothepropertieswindowishowpropertiesthathavenotbeen
changed(i.e.,currentlyhaveadefaultvalue)aredisplayedinnormaltext,whereaspropertiesthathave
hadtheirvaluechangedaredisplayedinboldtext.Thisvisualindicationofwhatpropertieshavebeen
changedcanbeveryuseful.
So,wevediscoveredthatwecanchangethepropertiesofsomethingeithergraphicallyinadesignview,
orviathepropertieswindow,butwhereisallofthatinformationstored?Theanswertothatdepends
onwhattypeofprojectyouareworkingon.Somecommonexamplesare:
ProjectType Designer/PropertiesChangesWrittenTo
WindowsForms Adesignerprogramminglanguagesourcefile.
WebForms(ASP.NET) Themainwebpagefile(.aspx)inHTMLformat.
WindowsPresentation Themainformorcontrolfile(.xaml)inXAMLformat.
Foundation
Silverlight Themainformorcontrolfile(.xaml)inXAMLformat.
Other Various,generallyaprogramminglanguagesourcefile.
InSolutionExplorer,expandtheForm1.dblitem.
YouwillnoticethatbelowForm1.dblaretwootherfiles,calledForm1.designer.dblandForm1.resx.By
theway,theseparticularfilesarespecifictoaWindowsForm,butthegeneralprincipleofwhatwere
lookingathereappliesinanumberofdifferentscenarios.
Fornow,thefilethatwearemostconcernedwithistheForm1.desidner.dblfile.Thisisaspecialsource
filethatisalteredwheneveryoumakechangestoaWindowsFormsvisualdesignsurfaceorProperties
window.
WARNING:Asageneralrule,youshouldnotedit.designerfiles.Theyarecreatedandmaintainedby
VisualStudiovisualdesignersandthePropertieswindow.Itisrelativelyeasytobreakyourapplication
bymakinginappropriatechangestothesefiles,anditcanbedifficulttoresolveproblemslikethis.
Withthewarningoutofthewayletseditthefile!
InSolutionExplorer,doubleclickonForm1.designer.dbltoopenitincodeview(youcouldalso
rightclickthefileandselecteitherOpenorViewCode).
Rightnowthedesignersourcefileisfairlysimple,becauseallwehaveisaformandabutton.Notice
howtheclassForm1extends(isa)System.Windows.Forms.Form,andhowtheclasscontainsan
instancevariablecalledbutton1whichisoftypeSystem.Windows.Forms.Button.Thatvariablewas
created,bythedesigner,whenwedraggedthebuttonontotheform.
LookdownalittleandyouwillseethatthereisamethodcalledInitializeComponent,andinthat
methodtherearevariousassignmentstatementswhichsetvariouspropertiesofthebutton
(this.button.something)andtheformitsself(this.something).Theselinesofcodeareinsertedwhenwe
makechangestothepropertiesoftheform,orobjectsontheform,eitherviachangesthatwemake
onthegraphicaldesignsurface,orchangesthatwemakeinthePropertieswindow.
YoumayalsonoticethatthecodeinthisfiledefinestheclassaspublicpartialclassForm1.
ClickonthetabatthetopoftheeditareacalledForm1.dbl.Ifyouclosedthisviewthenin
SolutionExplorer,rightclickonForm1.dblandselectViewCode.
NoticethattheclassinthissourcefileisalsodefinedaspublicpartialclassForm1.Apartialclassisa
classcomposedfrompartialclassdefinitionsinmultiplesourcefiles,sointhiscasetheclassForm1is
madeupofsourcecodeinthefileForm1.dbl,whichthedevelopercontrols,andcodeinthefile
Form1.designer.dbl,whichthedesignerandpropertieswindowcontrol.Ifyoulookatthedefaultcode
inForm1.dblyouwillnoticethatthereisaconstructormethod(publicmethodForm1)whichcontains
acalltotheInitializeComponentmethodwhichisinForm1.designer.dbl.So,whentheapplication
createsaninstanceoftheForm1class,thedesignergeneratedcodeisexecutedtocreateandconfigure
allofthecontrolsontheform.
Program.dbl
Projectswhichtargetanassemblywhichisanexecutableprogram(i.e.,an.exeratherthana.dll)
includeanothersourcefile,calledProgram.dbl.Thisisthemainlineortheentrypointtothe
application.
InSolutionExplorer,doubleclickonthefileProgram.dbltoopenitinthecodeeditor.
ThedefaultcodeintheProgram.dblfilewillvary,dependingonthetypeofapplication,buttendstobe
verysimpleinnature.InthecaseofaWindowsFormsapplication,asyoucansee,thefilecontainsa
mainlineprogramwhichessentiallyjustlaunchesanewinstanceofthedefaultform,Form1.
IfyouweretorenametheclassinForm1.dbl(andofcoursethematchingpartialclassin
Form1.designer.dbl)toadifferentname,orifyouwantedtolaunchsomeotherformatapplication
startup,thenyouwouldneedtoeditthecodeinProgram.dblasappropriate.
InSolutionExplorer,expandthePropertiesfoldertoviewthefilesthatitcontains.
IntheWindowsFormsprojectthatyourecurrentlyworkingin,therewillbevariousfilesinthe
Propertiesfolder.ThesefilesareAssemblyInfo.dbl,Resources.resxandSettings.settings.Althoughyou
caneditsomeofthesefilesdirectly,andsomeofthesefiletypesalsohavevisualdesignersassociated
withthem,thefilesinthePropertieswindowareusuallymaintainedviatheProjectPropertiesdialogs,
asyouwillseeshortly.
AssemblyInfo.dbl
InSolutionExplorer,doubleclick
AssemblyInfo.dbltoopenitinacodeeditor.
AssemblyInfo.dblcontainsvariousattributedefinitions
usedtoembedinformationintothecompiledassembly.
Youcanspecifyinformationaboutyourcompany,the
nameoftheproduct,copyrightinformation,etc.
Thefilecanalsobemaintainedviaadialogwindow
whichcanbeaccessedbyopeningtheproject
properties,selectingtheApplicationtabandclickingtheAssemblyInformationbutton.
Resources.resx
Thisfileisaresourcefilewhichisaspecialtypeoffilethatcanbeusedtoembedvariousresources
(strings,images,audiofiles,etc.)theapplicationmightneed,directlyintotheapplicationsassembly.
Thebenefitofusingresourcefilesisthatanyresourcesthattheapplicationneedsdonotneedtobe
providedasindividualfilesondisk,whichinturncansignificantlysimplifyapplicationdeployment.
ResourcefilesareactuallyXMLfiles.Theresourcesaddedtothefileareserialized(ifnecessary)and
storedwithintheXMLfile.Thatbeingsaid,youwillprobablyneverdealwitharesourcefileasanXML
file,becauseVisualStudioprovidesagraphicaldesignerthatletsyouworkwiththecontentsofresource
files.
Resourcesinresourcefilesarealsoveryeasytousewithintheapplication,becausetheresourcefile
designerdynamicallygeneratesaclasswhichrepresentsthecontentsoftheresourcefile.Accessinga
resourceisaseasyasreferringtoastaticpropertyinthisclass.
InSolutionExplorer,doubleclicktheResources.resxfiletoopentheresourcefiledesigner.
BydefaulttheresourcefiledesigneropensinStringsmode,butyoucanswitchtoworkingwithImages,
Icons,Audio,FilesorOtherItemsusingthedropdownfieldinthetopleftcorneroftheresource
designer.Youwillalsonoticethattherearebuttonsonthetoolbarwhichallowyoutoaddandremove
itemsfromtheresourcefile.
Letsworkthroughasimpleexampleofaddingastringresourcetoaproject:
IntheNamecolumn,whereitdefaultstoString1,changetheresourcenameto
WelcomeMessage.
IntheValuecolumnaddthetextWelcometomyapplication.
IntheCommentcolumnaddthetextDisplayedatapplicationstartup.
TypeCtrl+Stosaveyourchanges.
Nowletstakealookatwhatweactuallydidwiththeresourcedesigner.
InSolutionExplorer,rightclickonResources.resxandselectViewCode.
TheXMLfilethatyouarelookingatistheactualresourcefile.Ifyouscrolltothebottomofthefileyou
willseetheresourcethatyoujustaddedviathedesigner.
ClosetheXMLviewoftheresourcefile.
InSolutionExplorer,expandtheviewofthefileResources.resx
Likeformsthatwediscussedearlier,resourcefilesalsohaveadesignersourcefile,inthiscase
Resources.designer.dbl
DoubleclickonResources.designer.dbltoopenitinthesourcecodeeditor.
Asyouinteractwitharesourcefilethroughthedesigner,VisualStudiogeneratesthecodeinthe
designersourcefile.Asyoucansee,thesourcefilecontainsasubnamespacecalledProperties(the
nameofthefolder)containingaclassnamedResources(thenameoftheresourcefile).
Scrolldowntothebottomofthesourcefile.
Asyoucansee,thestringresourcethatyouaddedhasbeenexposedasaninternalstaticproperty.This
meansthatwecanrefertothevalueofthestringresourcefromanywhereintheproject(assembly)like
this:
Properties.Resources.WelcomeMessage
Closethesourcefilebyclickingontheclose(cross)iconinitsmaintab.
Letsaddsomecodetotheapplicationtomakeuseoftheresourcestringthatwejustadded:
InSolutionExplorer,doubleclickonthefileForm1.dbltoopenitsvisualdesigner.
Doubleclicksomewhereinthebodyoftheformtoopenthecodeeditorwindow.
PlaceyourcursorintheproceduredivisionoftheForm1_Loadmethodandaddthefollowing
code:
this.Text=Properties.Resources.WelcomeMessage
TypeCtrl+F5tosaveyourchanges,andtobuildandruntheapplication.
Youshouldseethetextthatyouenteredintheresourcefilenowdisplayedintheapplicationdragbar.
Closetheapplication.
ClosetheResources.resxfilebyclickingontheXiconinitsmaintab.
Settings.settings
Conceptuallythesettingsfileissimilartoaresourcefile.However,wherearesourcefileisintendedto
storeresourceslikeimages,soundsandstringsthatareusedbyanapplication,thesettingsfileis
intendedtostoreapplicationorusersettings.Asettingisaname/valuepair,andyoucanspecifythe
datatypeofthevalue.
InSolutionExplorer,doubleclickontheSettings.settingsfiletoopenthesettingsfiledesigner.
Settingsfilesalsohavea.designer.dblfile,andjustlikewithresourcefilesthesettingsdesigner
dynamicallygeneratesaclasscalledSettings,withpublicpropertiestorepresentthesettingsthatyou
havedefinedinthedesigner.Thismeansthatyoucanprogrammaticallyaccessthesettingswithcode
likethis:
Properties.Settings.Default.AutoLogin
Defaultvaluesforthesettingsthatyoudefinearestoredinthe.settings(XML)file.
ClosetheSettings.settingsdesignerbyclickingontheXiconinitsmaintab.
AllVisualStudiodevelopmentprojectswillincludeaspecialfoldercalledReferences.Thefolderdoesnt
containfiles,butrathercontainsalistofassembliesthatareaccessiblefromthecodewithinyour
application.Ifyouwanttoaccesstypesthatarestoredinaparticularassembly,youaddareferenceto
theassembly.Welllookathowtodothatshortly.
Whenyoucreateanewprojectfromaprojecttemplate,thetemplatewillprobablyincludeasetofpre
configuredreferences.Someofthesereferencesmayberequiredbecauseofexistingcodethathas
alreadybeenincludedintheprojectbythetemplate,whileothersmayhavebeenincludedsimply
becauseyouarelikelytoneedthemwhendevelopingaparticulartypeofapplication.
InSolutionExplorer,rightclickontheReferencesfolderandselectAddReference
TheAddReferencedialogallowsyoutobrowseassembliesthatareavailabletobereferencedbyyour
project.
Therearefivetabsatthetopofthedialog,asfollows:
.NET Listsall.NETFrameworkcomponentsavailableforreferencing,aswellasassemblies
fromthirdpartiesthathavebeenregisteredonyoursystem.
COM ListsallCOMcomponentsavailableforreferencingandusethrough.NETsCOMinterop
capabilities.
Projects ListsVisualStudioprojectsinthecurrentsolutionavailableforreferencing.Select
assembliesfromthistabtocreateprojecttoprojectreferences.
Browse Allowsyoubrowseadditionalfilestofindacomponentnotlistedinthecurrenttaband
addittothelist.
Recent Displaysrecentlyaddedreferences.
Asanexampleofaddingareferencetoaproject,tomaketypes(classes,etc.)thatareavailableina
particularassemblyavailableforuseintheproject,letsassumewewanttohavetheabilitytoexposea
WCFservicefromourapplication.Todothatyouwouldneedtouseseveralclassesthatareprovidedby
the.NETFrameworkintheSystem.ServiceModelnamespace.
Inthe.NETtab,clicktheComponentNamecolumntitletosortthelistofassembliesin
alphabeticalorder,andthenlocateandselecttheSystem.ServiceModelassembly.
ClicktheOKbuttontoaddthereference.
YoushouldnowseeSystem.ServiceModellistedundertheReferencesfolderinyourproject,meaning
thatwhatevertypesaredefinedinthatassemblyarenowavailableforyoutouseinyourcode.
Object Browser
VisualStudiosObjectBrowserwindowallowsyoutobrowseandviewthecontentofassemblies.
InSolutionExplorer,doubleclickontheSystem.ServiceModelreferencethatyoujustadded.
YoushouldseetheObjectExplorerwindowopen,andtheSystem.ServiceModelassemblyshouldbe
selectedinthelistofassembliestotheleftsideofthescreen.Similartothe.NETtabintheadd
referencedialog,thislistshowsassembliesthatareprovidedbythe.NETFrameworkaswellasother
assembliesthatyoumayhavereferencedinyourproject.Atthetopofthedialogisatoolbarwitha
dropdownlistwhichallowsyoutoapplyfilterstothelistofassembliesthataredisplayed.
IntheBrowsedropdownlist,select.NETFramework4tofilterthelistofassembliestoonly
thoseassembliesavailableinthatversionofthe.NETFramework.
ClickthesmalltriangleiconnexttotheSystem.ServiceModelassembly.
Assembliescancontaintypes(classes,etc.)fromoneormorenamespaces.Whenyoudrillintoan
assemblyinObjectBrowser,thefirstthingyouseeisthenamespacesthatarepresentintheassembly:
AboveyoucanseethattheSystem.ServiceModelassemblycontainstypesfrommultiplenamespaces.
Notethatthetypesinanamespacedonthavetobealldefinedinoneassembly.Forexample,youcan
seethatthisnamespacecontainssometypesfromtheSystemnamespace,buttherewillbetypesfrom
thesamenamespaceinotherassembliestoo.
ClickthetriangleiconnexttotheSystem.ServiceModelnamespacetodrillintoit.
Drillingintoanamespacedisplaysthetypesthatarepresentinthatnamespace.Thenatureofthetype
isindicatedbytheicondisplayednexttoit.Forexample,inthediagramabove,
ActionNotSupportedExceptionisaclasswhileAuditLevelisanenumeration.
SingleclickontheclassBasicHttpBindingtoselectit.
IntheupperrightsectionoftheObjectBrowserwindowyoucanseemoredetailaboutthetypethat
youhaveselected,andagaintheiconnexttoeachitemindicatesthenatureoftheitem.Inthecaseof
theBasicHttpBindingclass,youwillseethattheclasshasseveralmethods,oneofwhichiscalled
CreateBindingElements(),andalsoseveralproperties,includingBypassProxyOnLocal.
SingleclickontheCreateBindingElementsmethodtoselectit.
InthelowerrightportionoftheObjectBrowserwindowyoucanseeevenmoreinformationaboutthe
thingthatyouhaveselectedabove.
Inthiscasetheinformationistellingusaboutthemethodthatweselected.Wecanseethatitisapublic
method,soitsavailableforustocall,itdoesnothaveanyparameters(nothingislistedbetweenthe
parenthesesfollowingthemethodname)anditreturnsaBindingElementCollection.Thereisalsouseful
descriptiveinformationaboutwhatthemethoddoes,anyparametersitmightaccept,andthereturn
value.
Youmayalsonoticethatothertypesthatarementionedhereappeartobehyperlinks,andsureenough
clickingononeofthemwilltakeyoutothedocumentationforthattypeinObjectBrowser.Thereare
alsoforwardandbackbuttonsonthetoolbartomakenavigatingaroundeasy,justlikeinaweb
browser.
YoucanalsouseObjectBrowsertoaddreferencestoyourproject.Forexample,letssupposethatby
browsingaroundinObjectBrowserwedeterminedthatweneedareferencetothe
System.ServiceModel.Activationassembly.
InObjectBrowserselecttheSystem.ServiceModel.Activationassembly
InObjectBrowsertoolbar,clicktheAddtoReferencesinSelectedProjectinSolutionExplorer
button.
ObjectBrowsercanbeveryuseful.Ifyouhaveanideaaboutwhatyouneedthenitcanallowyouto
easilybrowsedetailedinformationaboutthings,and,havingconfirmedwhatyouneed,youcanadda
referencetotherequiredassembly.
Objectbrowserisalsoagreatwaytolearnaboutthecapabilitiesofthings,becauseitmakesiteasyto
viewdetailedinformationaboutmethods,parameters,returnvalues,enumerations,andlotsofother
things.
CloseObjectBrowserbyclickingonthecrossiconinitsmaintab.
Project Properties
Eachprojectthatyoucreateincludesmanyoptionswhichallowyoutodefinelotsofdifferentthings.
Theseoptions,morecommonlyreferredtoasprojectproperties,allhavedefaultvaluesandcanbe
customizedthroughtheProjectPropertiesdialogs.
InSolutionExplorer,rightclickontheIntroToVisualStudioproject(itllbeshowninboldtext
immediatelybelowthesolution)andfromthecontextmenuselectProperties.
Theprojectpropertiesdialoghasvarioustabsdownthelefthandside.
CheckthattheApplicationtabisselected.
Letstakealookthroughthevarioustabpagesandexplorewhatoptionsareavailabletoyou.Thereare
lotsofoptions,sowelljustpickoutsomeofthemoreimportantones.
Application
Thetabsthataredisplayedwillvarybasedonthetypeofapplicationthatyouareworkingon.Were
currentlyworkingonaWindowsFormsApplication,soyoushouldseetabsthatlooksomethinglikethis:
Mostprojectscreateoneassembly,andthatassemblycaneitherbeanexecutableprogramoraclass
library.Theassemblynameandoutputtypefieldsdeterminethenameoftheassemblythatiscreated
bytheproject,withtheoutputtypebeingusedtodeterminethefileextension(.exeor.dll).
Thedefaultnamespacedeterminesthenamespacethatisinsertedintoanynewsourcefilesthatare
addedtotheproject.Whenusingmostprojecttemplates,theassemblynameanddefaultnamespace
defaulttothenameoftheprojectthatyoucreate,andbythetimeanewprojecthasbeencreated,the
defaultnamespacewillalreadyhavebeenusedinwhateversourcefilesareaddedtotheprojectbythe
projecttemplate.So,ifyouchangethedefaultnamespaceyouwillusuallywanttoreviewanyexisting
sourcefilesintheprojectandchangethenamespaceusedinthosefiles.
Theassemblyinformationfile(AssemblyInfo.dbl)wasdiscussedearlier.YoullnoticetheAssembly
Informationbuttonthatallowsyoutoeditthecontentofthefilethroughasimpleuserinterface.
OneofthemostimportantsettingsforanapplicationistheTargetframework,whichdeterminesthe
versionofthe.NETframeworkthattheassemblywillbebuiltfor.Synergy.NETprojectswilldefaultto
eitherthe.NETFramework4.0,orthe.NETFramework4.0ClientProfile.Theclientprofileisasmaller
versionofthe.NETFramework4.0whichiscommonlyfoundondesktopPCsandlaptops;ithassomeof
thefeaturesofthefullframeworkremoved.ThesefeaturesincludethingsliketheASP.NETweb
componentswhicharetypicallyonlyrequiredonserversystems.Youcanchangethetargetframework
toanearlierversionifyouwish,whichcouldforexamplehelpwithdeploymentbecausemostsystems
willhaveV2.0oftheFrameworkalreadyinstalled,butmaynothave4.0.Howeverbydoingthisyoumay
berestrictingthecapabilitiesofyourapplication,becausesomefeaturesofthecurrent.NETFramework
willnotbeavailableforyoutouse.AbetterapproachistotargetthelatestversionoftheFramework,
andsetupyourdeploymentpackagesorprocedurestoinstallthelatestFrameworkifrequired.
TheOutputtypesettingallowsyoutospecifythetypeofassemblybeingcreated;eitheraWindows
Application,ConsoleApplicationorClassLibrary.Generallythissettingwillbesetcorrectlybythe
projecttemplatethatyouuse,andwontneedtobechanged.
Youcanalsosetanapplicationicononthistabpage.Doingsowillcausetheiconfiletobeaddedtothe
project,andembeddedasaresourceinthetargetassembly.Selectinganapplicationicondoesnot
causethaticontobedisplayedatthetopleftofanyformsthatyoumayaddtoaproject.Ifyouwantto
usetheicononformsthenyoumustseteachformsIconpropertyalso.
Build Events
SwitchtotheBuildEventstab
TheBuildEventstaballowsyoutospecifybuildconfigurationinstructions.Youcanalsospecifythe
conditionsunderwhichanypostbuildeventsarerun.Notethefollowing:
Buildevents(specifiedinthePrebuildeventcommandlineandPostbuildeventcommandline
fields)canincludeanycommandthatisvalidatacommandpromptorina.batfile.
Ifyouspecifya.batfile,thenameofthefileshouldbeprecededby"call"(withoutquotes)to
ensurethatallsubsequentcommandsareexecuted.Forexample:callC:\MyFile.bat.
The%characterisreservedforMSBuild,soifyouspecifyanenvironmentvariable,replaceeach
%withthe%25escapesequence.Forexample,replace%MY_VAR%with%25MY_VAR%25.
Ifyourprebuildorpostbuildeventdoesnotcompletesuccessfully,youcanterminatethebuild
byhavingyoureventactionexitwithacodeotherthanzero(whichindicatesasuccessful
action).
Compile
SwitchtotheCompiletab
OnthecompiletabyoucandeterminewhichSynergy.NETcompiler(dblnet)optionsareusedwhenthe
projectisbuilt.TheCompilercommandlineboxtowardsthetopoftheformdisplaysasummaryofthe
actualcommandlineoptionsthatwillbeused,andtheotherfieldsontheformallowyoutodetermine
whatthoseoptionsshouldbe.Asyoucansee,therearesomecompileroptionsthatareusedbydefault.
TherearespecificUIcontrolsontheformtoallowyoutosetorunsetsomeofthemorecommonlyused
compileroptions,andtheOtheroptionsfieldallowsyoutospecifyanyothercompileroptionsthatare
notspecificallysupportedbycontrolsontheform.
Environment Variables
SwitchtotheEnvironmentVariablestab
Theenvironmentvariablestaballowsyoutospecifyenvironmentvariablesthataretobesetwhenthe
projectisopened.TheseenvironmentvariableswillbeinplaceduringdevelopmentinVisualStudio,and
alsowhenyouexecuteutilitiesoryourapplicationfromtheVisualStudioenvironment.
Itispossibletorefertothetranslationofoneenvironmentinthevalueofanother,usingthesyntax
$(ENVVAR).Forexample,ifyouhadoneenvironmentvariablecalledROOTthattranslatedtoafolder
path,andyouwantedtosetanothervariablecalledDATthattranslatedtoafoldercalledDATbelowthe
ROOTfolder,youcouldexpressthevaluefortheDATenvironmentvariableas$(ROOT)DAT.Thiswould
ofcourseassumethatthevalueoftheROOTvariablewasterminatedwithatrailingbackslashcharacter.
TheenvironmentwithinVisualStudioincludesseveralpredefinedmacrosthatcanbeusedwhen
settingenvironmentvariables.Forexamplethemacro$(SolutionDir)translatestothefolder
specificationofthecurrentsolutionfile,and$(ProjectDir)translatestothelocationofthecurrent
projectfile,whichmayormaynotbethesameasthesolutionfolder.Asyoucanseeinthescreenshot
above,youcanalsorefertothesemacroswhensettingenvironmentvariablesinyourproject.Thetable
belowshowsalistofsomeoftheavailablemacros:
includesthetrailing
backslash.
includesthetrailing
backslash.
Bearinmindthattheenvironmentvariablesthatyouspecifythroughtheprojectpropertiesdialogsare
onlypresentinyourdevelopmentenvironment.Ifyouusethismechanismtospecifyvaluesfor
environmentvariablesthatarerequiredatapplicationruntime(outsideofVisualStudio)thenyoumust
providethoseenvironmentvariablesviasomeothermechanism.
Signing
SwitchtotheSigningtab
Thesigningtaballowsyoutospecifythattheassemblycreatedbytheprojectshouldbedigitallysigned.
Tosigntheassemblies,checktheSigntheAssemblycheckboxandthenselectthestrongnamekeyfile
thatyouwishtousetosigntheassembly.
Onceyouhaveenabledsigning,thereisanoptionintheChooseastrongnamekeyfiledropdownlist
whichallowsyoutocreateanewkeyfile.Thisisdoneusingthe.NETFrameworksstrongnameutility
(sn.exe).
Werenotgoingtogetintoassemblysigningherebecauseitsalargeandcomplexsubjectarea,butitis
definitelysomethingthatyouneedtolearnaboutbeforeyourelease.NETapplicationstocustomers.
Reference Paths
SwitchtotheReferencePathstab
TheReferencePathstaballowsyoutospecifyfoldersthatwillbesearchedwhentheprojectsystem
needstolocateareferencedassembly.Whentheprojectsystemfindsanassemblyreference,itresolves
thereferencebylookinginthefollowinglocations,inthefollowingorder:
Theprojectdirectory.TheprojectdirectoryfilesappearinSolutionExplorer.
Directoriesspecifiedonthispage(ReferencePaths).
DirectoriesdisplayingfilesintheAddReferencedialogbox.
Theproject'sobjdirectory.(AssembliescreatedbyaddingCOMreferencestoyourprojectare
addedtotheproject'sobjdirectory.)
Build
SwitchtotheBuildtab
Thebuildtaballowsyoutospecifyvarioussettingsrelatedtohowyourassemblyisbuilt.Eachproject
thatyoucreateincludesseveralconfigurationsand,whenworkingintheproject,youalwayshaveone
oftheseconfigurationsselected.Bydefaultthereisadropdownlistonthemaintoolbarwhichallows
youtoeasilyswitchtoadifferentconfiguration.Mostprojectshavetwoinitialconfigurationsdefined,
calledDebugandRelease,andthedefaultisusuallytheDebugconfiguration.
AtthetopoftheformyouwillseeadropdownlistwhichallowsyoutoselecttheConfigurationto
modify.Changesthatyoumakeinthelowerhalfoftheformareappliedtothatconfiguration.Youneed
torememberthisbecauseifyouremakingachangetooneconfiguration,thenyoumaywanttomake
correspondingchangestootherconfigurationsalso.Infact,ifthisisthecase,youcanselectAll
Configurationsintheconfigurationdropdownlist,andthechangesthatyoumakewillthenbeapplied
toallconfigurations.ThePlatformfieldisnotusedinSynergy.NETprojectsandshouldbeignored.
Platformtargetallowsyoutospecifytheprocessortobetargetedbytheassembly.Selectx86totarget
32bitplatforms,selectx64totarget64bitplatforms,orselectAnyCPUfortheassemblytobeplatform
agnostic.
Outputpathallowsyoutodeterminewheretheassemblycreatedbytheproject(ormorespecifically
theprojectconfiguration)willbestored.Asyoucanseethedefaultlocationisinabin\Debug(or
bin\Release)folderbelowtheprojectfolder.
TheXMLdocumentationfileoptionallowsyoutoenablethecreationofanXMLfilewhichcontainsAPI
documentationforthecodeinyourproject.Theinformationinthefileisderivedbothfromtheactual
codeintheproject,aswellasfromanydocumentationcommentsthatyoumayhaveincludedinthe
code.OnceyouhavetheXMLdocumentationfilethereareseveralproductsonthemarketthatcan
transformtheinformationinthefileintovarioustypesofdocumentation.
TheDebug/Optimizecodeoptionallowsyoutospecifywhethertousejustintime(JIT)optimization,
andspecifiesthelevelofdebugandstacktraceinformationthatwillbeavailable,whichaffects
performance.Theoptioncanbesettothefollowingvalues:
<blank> IncludeslessdebuginformationintheassemblythanisincludedbytheDebugsetting,
andonlyincludeslimitedlinenumberlistingsfortracebacks,butincludesmore
informationthantheOptimizesetting.ThisisthedefaultsettingforRelease
configurations.
Debug Fulldebugginginformationisincludedintheassembly.Thisisthedefaultsettingfor
Debugconfigurations.
Optimize Includestheleastamountofdebugginginformationintheassembly,resultinginthe
bestperformance.EnablesJIToptimization.Thisoptionisrecommendedforproduction
code.
TheGenerateserializationassemblyoptiondetermineswhetherthecompilerwillusetheXML
SerializerGeneratorTool(sgen.exe)tocreateXMLserializationassemblies.Serializationassembliescan
improvethestartupperformanceofXmlSerializerifyouhaveusedthatclasstoserializetypesinyour
code.Theoptioncanbesettooneofthefollowingvalues:
Auto SerializationassemblieswillbegeneratedonlyifyouhaveusedXmlSerializertoencode
(default) typesinyourcodetoXML.
Off Serializationassemblieswillneverbegenerated,regardlessofwhetheryourcodeuses
XmlSerializer.
On Serializationassemblieswillalwaysbegenerated.
ItshouldbenotedthatduetoaVisualStudioissue,settingtheGenerateserializationassemblytoOn
mightnotresultinaserializationassembly,evenifthereareserializabletypesintheproject.Thereisan
articleonMicrosoftConnect(bugid123088) which discusses this issue. You can locate the
article via an internet search for "ProjectDoesNotGenerateSerializationAssemblyEvenWhen
SpecificallyToldToDoSo".
TheDLLbaseaddressspecifiesthepreferredbaseaddressatwhichtoloadtheassembly.Thiscanbe
specifiedindecimalorhexadecimalformat,anditmustbe0x10000aligned.Thedefaultbaseaddress
foraDLLissetbythe.NETFrameworkcommonlanguageruntime.SettingaDLLbaseaddressisan
advancedsubjectandisbeyondthescopeofthisintroductorytutorial.
Debug
SwitchtotheDebugtab
TheoptionsontheDebugtabareusedtosetpropertiesforthebehavioroftheprojectwhenthe
debuggerisstarted.Aswiththebuildoptions,itispossibletospecifydifferentdebuggersettingsbased
onthecurrentlyselectedconfiguration,andagainthePlatformfieldisnotusedwithSynergy.NET
projectsandshouldbeignored.
TheoptionsunderStartActionareusedtosettheitemtobestartedwhenthedebuggingbegins,and
canbesettooneofthefollowing:
Startproject(default) Specifiesthattheexecutablefortheprojectshouldbestartedwhenthe
applicationisdebugged.
Startexternalprogram Specifiesthatsomeotherexecutableislaunchedwhentheapplicationis
debugged.Specifythefullpathtotheexecutabletobestartedinthefield
totheright,whichisenabledwhenthisoptionisselected.
StartbrowserwithURL SpecifiesthataURLshouldbeaccessedwhentheapplicationisdebugged.
SpecifytheURLinthefieldtotheright,whichbecomesenabledwhenthis
optionisselected.Ifyouselectthisoptionwithoutenteringanythingin
thetextfield,thedebuggerwillworkasif"Startproject"wereselected.
TheCommandlineargumentsfieldallowsyoutospecifyanycommandlineargumentsthatshouldbe
passedtotheprogramwhenstartinganexecutable.TheoptionisnotapplicableifstartingaURL.
TheWorkingdirectoryoptionallowsyoutospecifythedirectoryfromwhichtheprojectwillbe
launchedfordebugging.ThisappliesonlywhenStartprojectisselected.Thedefaultistheoutputpath
folderspecifiedinthebuildtabsDebugconfiguration.
TheUseremotemachine,Enableunmanagedcodedebugging,EnableSQLServerdebuggingand
EnabletheVisualStudiohostingprocessoptionsarenotimplementedinSynergy.NETprojectsand
shouldbeignored.
Settings
SwitchtotheSettingstab
Youvealreadyseenthesettingstabearlier,whenwewereintroducingtheSettings.settingsfile.When
youclickedonthefileyouwerepresentedwiththevisualdesignerfortheprojectsettingsfile,andthat
samedesignerisavailableviatheprojectpropertiesdialogsalso.
Resources
SwitchtotheResourcestab
Andyouveseentheresourcestabbeforealso,whenwediscussedtheprojectsResources.resxfile
earlier.Again,thedesignerforthefileisalsoavailableviatheprojectpropertiesdialogs.
Closetheprojectpropertiesdialogbyclickingtheclose(cross)iconinthemaintabbar.If
youvemadeanychangesthenyoumaybepromptedtosaveyourchanges.
Youdontneedtodoanythingspecialtodefinewhathappensduringabuildotherthanconfiguringthe
contentoftheproject,whichinmostcasesinvolvesaddingsourcefilesandsourcecodetotheproject.
HoweverthereareothertypesofprojectthatVisualStudiosupports.Forexample,thereareproject
templatestoallowyoutocreateWindowsInstallerinstallationpackages(msifiles),aswellasvarious
otherthings.
Butmostprojectshaveabuildoption,andthatshowyoucausetheprojectoutputtobegenerated
(assumingthatyouhavenoerrorsofcourse!).Basedontheprojecttemplate,VisualStudioknowsHOW
tobuildthetargetoutput.InthecaseofaSynergy.NETproject,itknowstobuildadblnetcommand
lineusingthevariousoptionsspecifiedintheprojectpropertiesdialogsandusingalistofallthesource
filesandassemblyreferencesdefinedintheproject.Thenitexecutesthiscommandanddisplaysthe
resultingoutput.
Followthesestepstoensurethattheoutputanderrorswindowsarevisible.
Fromthemenu,selectView>Output(ortypeCtrl+Alt+O)
Iftheerrorwindowisnotpinnedinplace,thenpinitinplacebyclickingthesmallpushpinicon
atthetoprightcornerofthewindow.
Fromthemenu,selectView>ErrorList(ortypeCtrl+\andthenE)
Nowtobuildtheproject:
Fromthemenu,selectBuild>BuildSolution(ortypeCtrl+Shift+B)
Youshouldseetheoutputwindowbecomefocused,andoutputsimilartothis:
Buildstarted:Project:IntroToVisualStudio,Configuration:DebugAnyCPU
==========Build:1succeededoruptodate,0failed,0skipped==========
Thisoutputindicatesthattheprojectwasbuiltsuccessfully.
InSolutionExplorer,doubleclickonForm1.dbltodisplaytheformsgraphicaldesigner.
Doubleclickinsidethebodyoftheformtoopenthecodeeditorwindowandpositionyour
cursorintheForm1_Loadmethod.
Somewhereintheproceduredivisionofthemethod,addsomeinvalidcodeanything.Adding
thewordsjunkcodewouldworkquitenicely!
TypeCtrl+Shift+Btobuildtheproject.
Itisnotnecessarytomanuallysaveyourchanges,becauseVisualStudiowillautomaticallydothateach
timeyoudoabuild,orexecute,ordebug.
Againyoushouldinitiallyseethecompileroutputintheoutputwindow,butwhenthecompiler
completeswithanerror,theerrorlistwindowshouldbedisplayed,andshouldcontainthedetailsofthe
errorsthatwerereportedbythecompiler.Youreprobablylookingatsomethinglikethis:
Thewindowdisplaystheerrors,warnings,informationalmessagesemittedbythecompiler,aswellas
informationaboutthefileinwhichtheerroroccurred,thelinenumber,andthenameoftheproject.
Ifyouonlywanttolookatacertaintypeofmessage(errorsvs.warningsforexample)thenyoucanfilter
thecontentofthelistbyclickingonthevariousbuttonsinthesmalltoolbarabovetheerrorlist.
Thelistisalsoactive;inthatyoucandoubleclickonmessagesinthelisttotakeyoutothepointofthe
problem.Todemonstratethis:
ClosetheForm1.dblsourcefilebyclickingontheclose(cross)iconinitsmaintab.
Doubleclickonthefirsterrorlineintheerrorlistwindow.
Youshouldseethesourcefilebereopened,andyourcursorbepositionedatthelinewiththeproblem
dontfixitjustyet!
Task List
VisualStudiohasanotherusefulwindowcalledtheTaskList.Itsprobablyalreadydisplayedinthesame
tabsetastheoutputanderrorlistwindows,but,ifnot,then:
DisplaythetasklistbyselectingView>TaskListfromthemenu(orbytypingCtrl+\andthenT)
Thetasklistwindowhastwomodesdeterminedbythedropdownlistinitssmalltoolbar.
MakesurethatthedropdownlisthastheUserTasksoptionselected.
WithUsertasksselected,adevelopercanmanuallycreateatodolistbyclickingontheCreateUser
Taskbuttonandenteringthedetailsofthetaskinthelist.Taskscanthenbecheckedoffonce
completed,ordeletedbyrightclickingonthetaskandselectingDelete.
ClickontheCreateUserTaskbuttoninthetaskliststoolbar.
TypeanewtaskperhapssomethinglikeMakethisapplicationactuallydosomething!and
hitenter.
Markthetaskascompletebyclickingitscheckbox.
DeletetheusertaskbyrightclickingitandselectingDelete(orbyselectingthetaskand
pressingDelete).
Whilecreatingusertasksinaprojectcanbeuseful,whatismoreusefulistheoptiontocreatetodo
commentsinyourcode.Thesearecomments,withaspecialformat,thatadevelopercanplaceintoa
sourcefile,thatwillshowupinthetasklistwindow.
IntheForm1.dblcodeeditor,addacommentlikethisafterthebadcode:
;TODO:Thisneedsfixing!
Inthetasklistwindow,changethedropdownlistfromUserTaskstoComments.
YoushouldseethecommentthatyouentereddisplayedintheTaskList.TheTODO:prefixthatyou
typediswhatdeterminesthatthecommentshouldbedisplayedinthisway.
BackintheForm1.dblsourcecodeeditor,removetheTODOcomment,andthebadcode.
Performabuildtoensurethattheapplicationisinagoodstate(Crtl+Shift+B).
Executing a Project
Dependingonthetypeofprojectthatyoureworkingon(youcantdirectlyexecuteaclasslibrary
project),onceyouhavesuccessfullyperformedabuild,thenextthingyourelikelytowanttodoisrun
theapplication.VisualStudiomakesthisveryeasy.Therearetwomainwaystobeginexecutinga
project,oneistoselectDebug>StartDebugging(orpressF5),andtheotheristoselectDebug>Start
WithoutDebugging(orpressCtrl+F5).
Asyouhaveprobablyalreadydeduced,thedifferencebetweenthesetwooptionsisthatwiththefirst,if
anythingslikebreakpointsorwatchpointsareactivated,thencontrolwillpasstothedebugger.With
thesecondmethodthedebuggerwillnotbeused,evenifbreakpointsandwatchpointsarepresent.
ExecutetheapplicationbypressingF5(orbyselectingDebug>StartDebugging).
YoushouldseetheWindowsFormsprogramstart.Ofcourseitsnotveryinteresting,becauseallthe
applicationcurrentlydoesischangethemainformstitletothestringstoredintheWelcomeMessage
resourcefilestring.Evenclickingthebuttondoesntdoanything!Letschangethat:
Closetheapplication.
DisplaytheForm1designerwindow.
Doubleclickonthebutton.
WhenyoudoubleclickonacontrolVisualStudiotakesyoutothecodeforthedefaulteventforthat
control.Ifthatcodedoesntexist,thenVisualStudiowillinsertanewemptyeventhandlermethodfor
theevent.ThedefaulteventforabuttonistheClickevent,soyoushouldnowbelookingatthe
button1_Clickmethod,whichlookslikethis:
Inthedatadivision,addarecordandthreeintegerfields,likethis:
Intheproceduredivision,addthefollowingcode:
Thepointofthisexerciseisjusttogiveussomecodethatwecaninteractwithinthedebuggerlater.
BreakpointsworkinmuchthesamewaythatyouwouldexpectintraditionalSynergy,butareeasierto
workwithasaresultofthegraphicalnatureofthewaythattheyareset,clearedandvisualized.
Codeeditorwindowsallhaveasmallregionattheleftmarginwherebreakpointscanbeset.Toseta
breakpointatacertainpositionyousimplyclickinthisregion,andyouwillseeavisualrepresentation
ofthebreakpoint,likethis:
Theredcircleindicatorinthebreakpointregionindicatesthatabreakpointissetatthatposition.Ifyou
executetheapplicationindebugmodethenexecutionwillbeinterruptedatthatpoint.
Itisalsopossibletohavebreakpointssetinyourproject,butdisableoneormoreofthosebreakpoints
sothattheywillnotfirewhileyouaredebugging.Todisableabreakpointrightclickonthebreakpoint
indicatorandselectDisableBreakpoint.Disabledbreakpointslooklikethis.
ReenableadisabledbreakpointbyrightclickingthebreakpointindicatorandselectingEnable
Breakpoint.Youcanalsotogglebetweenanenabledanddisabledstatebyplacingyourcursoronthe
sourcelineandpressingCtrl+F9.
ItisalsopossibletodisableorenableallbreakpointsviaitemsontheDebugmenu.
Ifyouwishtoremovethebreakpoint,simplyclickonthebreakpointindicator,orrightclickitandselect
DeleteBreakpoint.
Intheconstructormethod,Form1,addabreakpointonthestatementthatcallsthe
InitializeComponentmethod,likethis:
Alsoaddabreakpointonthebutton1_Clickmethod,likethis:
Thereisalsoaneasywaytoexamineallofyourcurrentbreakpointsusingadebuggertoolwindow.
Fromthemenu,selectDebugger>Windows>Breakpoints,orpressCtrl+Alt+B.
YoushouldseetheBreakpointswindowwhichlistsallofthebreakpointsthatyoucurrentlyhaveset.
Doubleclickingonabreakpointinthelistwilltakeplaceyourcursorontheassociatedlineofcode,and
youcanalsoeasilyadd,remove,enableanddisablebreakpointsthroughthiswindow.
ExecutetheapplicationbypressingF5(StartDebugging).Asanalternative,youcanalsouse
theStartDebuggingtoolbarbutton,whichlookslikethis .
WhenyoustartdebuggingyoumaynoticethatthelayoutoftheVisualStudiouserinterfacechanges.
Visualstudiomaintainsdifferentwindowlayoutswhenindebuggingmode,andbydefaultshowsyou
severalwindowswhichareusefulduringthedebuggingprocess.Youcancustomizethewindowlayouts
likewedidearlier.
Youwontseetheapplicationonthescreenyet,becausewesetabreakpointintheconstructor
method,andtheformhasnotyetbeeninitialized.Whatyoushouldseeissomethinglikethis:
Theyellowarrowiconoverthebreakpointindicatorandtheyellowhighlightonthecodeindicatesthat
abreakpointwasencountered,andVisualStudiohashandedcontrolbacktoyou.Fromthispointon
youcandeterminewhathappens,usingthesamesortoftechniquesthatyouwouldifyouwere
debuggingintraditionalSynergy.
YoucancontroltheflowofexecutionusingcommandslikeStepInto(F11),StepOver(F10),StepOut
(Shift+F11)andContinue(F5).TheseoptionsareavailableontheDebugmenucolumn,andalsohave
correspondingiconsontheDebugtoolbar,whichshowsupwhenyoustartthedebugger.Itlookslike
this:
StepINTOtheInitializeComponent()methodbypressingF11,orbyclickingthe toolbar
button.
StarttostepthroughthemethodbypressingF10afewtimes,orbyclickingthe toolbar
button.
StepoutofthemethodbypressingShift+F11,orbyclickingthe toolbarbutton.
ContinueexecutionbypressingF5,orbyclickingthe toolbarbutton.
Youshouldnowseetheapplicationappearonthescreen,anditshouldoperatenormallyuntila
breakpointisencountered.YousetabreakpointontheeventhandlerforthebuttonsClickmethod,so:
Clickthebuttonontheform.
Thedebuggershouldnowbreakontheprocstatementofthebutton1_Clickmethod.Inthelowerpart
ofthescreenyoushouldseeawindowcalledLocals;youmayneedtoclickonitstabtobringittothe
front.
Ifyoucantseethelocalswindow,selectDebug>Windows>Localsfromthemenu.
Thelocalswindowisveryuseful,itdisplaysinformationaboutthelocalvariablesinthecurrentscope.In
thiscase,thebutton1_Clickmethod.Youcanusethewindowtoviewthecontentoflocalvariables,and
youcanalsochangethevalueofthelocalvariables,atleastforvaluetypes.
PresstheF10keytostepintotheproceduredivision.
DoubleclickintheValuecellforthevar3localvariable,thentypeanewnumericvalueand
pressenter.
Inthelocalswindow,clickononeoftheotherlocalvariables.
Youwillseethatwhenthevalueofavariablechanges,thelocalswindowtemporarilydisplaysthevalue
inredtoindicatethatitrecentlychanged.
PresstheF10keyagaintoexecutethefirstassignmentstatementandsteptothenext
statement.
Youwillnoticethatthevariablethatyoupreviouslychangedisnolongerdisplayedinred,butthatthe
var1variableisnowinred,becausethestatementthatwasjustexecutedchangedthevalueofthe
variable.
PressF10againtoexecutethesecondassignmentstatement.
PressF10againtoexecutetheadditionexpressionandcalculation.
Theyellowarrowindicator(nextstatementtoexecute)shouldnowbepointingtotheDebug.Print
statementwhichcanbeusedtoaddtracinginformationtotheoutputwindowinVisualStudio.Thiscan
alsobeausefuldebuggingtechnique.Iftheapplicationisexecutednormally(withoutdebugging)then
thisstatementwontdoanything.
Makesurethattheoutputwindowisvisible.
PressF10toexecutetheDebug.Printstatement
Youshouldseethetextvar1+var2=3printedintheoutputwindow.
AnotherusefulwindowistheImmediateWindow,whichshouldbeoneofthetabstowardsthebottom
ofthescreen.
IfyoucantseetheImmediateWindowthenmakeitvisiblebyselectingDebug>Windows>
Immediatefromthemenu,orbypressingCtrl+Alt+I.
CheckthattheImmediatewindowisshownbyclickingonitstab.
TheImmediatewindowallowsyoutotypeanexpressionintothewindowandhaveVisualStudio
evaluatetheexpressionanddisplaytheresultingvalue.
ClickintheImmediateWindowandtype?var1andpressenter.
Thedebuggershoulddisplaythevalueoftheexpressionvar1,inthiscasethevalue1.
IntheImmediateWindow,type?var3var1andpressenter.
Again,thedebuggershoulddisplaythevalueoftheexpression,2.
AnotherwaytointeractwithdataisviatheWatchwindow,whichmaynotbedisplayedbydefault.This
windowallowsyoutodefineexpressionsthatyouareinterestedinlookingatonanongoingbasis.
Theseexpressionscouldbesimplevariablenames,ormorecomplexexpressions.
StoptheprogrambyselectingDebug>StopDebugging,orbypressingShift+F5.
PressCtrl+Shift+F9andclicktheYesbuttontoremoveallbreakpoints.
Addanewbreakpointonthevar1=1statement.
PressF5tostartanewdebuggingsession.
Onceyourapplicationstarts,inVisualStudiodisplaytheWatchwindowbyselectingDebug>
Windows>Watch>Watch1fromthemenu.
Gobacktoyourapplicationandclickthebutton.
IntheWatch1window,clickintheemptycellbelowtheNamecolumn,typevar1andpress
enter.
Repeatthis,butthistimefortheexpressionvar2.
Addanotherwatch,thistimefortheexpressionvar1+var2.
YourWatchwindowshouldnowlooksomethinglikethis:
PressF10tostepintotheproceduredivision,thencontinuepressingF10tostepthroughthe
assignmentstatementsandnoticewhathappensintheWatchwindow.
DefiningexpressionsintheWatchwindowcanbeaveryusefultechniquewhendebuggingcomplex
problems.
PressShift+F5tostopthedebugger.
PressCtrl+Shift+F9andclicktheYesbuttontoremoveallbreakpoints.
TheVisualStudiodebuggingenvironmentisverypowerful,andthishasonlybeenaVERYbrief
introductiontoitsmostbasicfeatures.
Asyouwouldexpect,thesourcecodeeditorisalsoaverypowerfultool.Itisbothlanguageandcontext
sensitive,andcanhelpyouwritecodecorrectlyfirsttime,layoutthatcodeinanappropriateway,andin
manycasescanactuallywritesomeofthecodeforyou.
Imports
TheconceptofimportingnamespaceswasfirstintroducedinSynergyLanguage9.1,whensupportfor
objectoriented(OO)developmentwasintroduced.IntraditionalSynergy,writingOOcodeisoptional,
butinSynergy.NETeverythingisOOwhetheryourealizeitornot.Yes,youcanstillusesubroutines
andfunctions,butunderthehoodtheenvironmentismakingthosethingsmethodsonaclass.In.NET
everythingisOO!
InOOprogramming,types(classes,interfaces,enumerations,structures,etc.)areorganizedinto
namespaces.Ifthesetypesaredefinedwithinaprojectthentheyareusuallyallpartofthesame
namespaceandbecomepartoftheassemblybeingdeveloped.Thismeansthat(subjecttoaccessibility
rulesdefinedinthecode)theycanbeusedwithintheassemblybysimplynamingthetype.
However,iftypesaredefinedinadifferentassembly(project)thentheyarenotautomaticallyavailable
foruse,andaregenerallygoingtobepartofadifferentnamespace.Inthiscase,ifwewanttobeableto
usethetypesinanexternalassemblythenweaddareferencetothatassembly,aswasdiscussedand
demonstratedearlier.
Havingaddedareferencetoanassembly,wecanaccessthepublictypesintheassembly,buttodoso
wewouldtypicallyneedtofullynameeachtypethatwewishtouse,eachtimewereferenceit.For
example,imaginethatwehaveaddedareferencetoanassemblycalledMyUtils.dll.Intheassemblyisa
classcalledDateUtils,andthatclassispartoftheMyUtilsnamespace.Theclasshasthreepublicstatic
methodscalledDaysBetween(),AddDays()andSubtractDays().
Ifwewantedtorefertooneofthosemethodsincodeinourproject,wewouldneedtofullyname
them,includingtheirnamespace.Ourcodemightlooksomethinglikethis:
paymentDue=MyUtils.DateUtils.AddDays(invoiceDate,30)
Whilethereisnothingwrongwiththiscode,itcouldbesimplified.Ifwehavereferencedanother
assemblyandwearegoingtousethetypesinthatassemblyfrequently,wehavetheoptionof
importingthenamespaceofthetypesthatwewishtouse.Importingthenamespacemakesthe
compilerawareofthetypesinthenamespace,andmeansthatwedonthavetofullynamethetypes
eachtimeweneedtorefertothem(unlessthereisaduplicatetypeintwoormorenamespacesthatwe
haveimported).
So,wecouldimportthenamespacebyaddingcodelikethisattheverytopofthesourcefile:
importMyUtils
Andthenwecouldwritethecodethatusesthosetypeswithoutmentioningthenamespace:
paymentDue=DateUtils.AddDays(invoiceDate,30)
InthecodeeditorforForm1.dbl,abovethenamespacedefinitionandwiththeexistingimport
statements,addanewimportfortheSystem.Diagnosticsnamespace,likethis:
Scrolldownintothebutton1_ClickmethodandremovethenamespaceprefixfortheDebug
class,likethis:
Importinganamespaceistotallyoptional,butcanmakethecodethatusesthetypesinthatnamespace
muchlessverbose.
IntelliSense
Whenyouweretypingtheimportstatementabove,youmayhavenoticedthatafteryoutyped
importSystem.somethinghappened.Youprobablysawsomethinglikethis:
WhathappenedwasaVisualStudiofeaturecalledIntelliSenserecognizedwhatyouweretyping,and
steppedintohelp.Inthiscase,IntelliSenserecognizedthatyouwerenotcurrentlyinsideanamespace,
andhadstartedtotypeanimportstatement.IntelliSenseknowsthatifyouhavetypedanimport
statement,thenyoualsoneedtoaddanamespace,soitpresentedyoualistofallofthenamespaces
thatwerecurrentlyavailableinyourproject(basedontheprojectitself,andtheassembliesthatyou
havereferenced).
Whenthishappens,youcancontinuetotype,inwhichcasethelistofoptionswillgetgraduallyfiltered
downtomatchthecharactersthatyouhavetypedsofar:
Atanytimeduringthisprocessyoucanusethearrowkeysormousetoselectasuggestedvalue,and
thenpressenter,tab,orspacetoinsertthatvalueintoyourcode.Ifyoudontwanttheassistancethen
youcanhittheescapekeytoclosetheIntelliSensepromptsandofcourseyoucanjustignorewhat
itsdoingandkeeptyping.
IntelliSenseiscontextsensitive,sonomatterwhereyouareworkinginapieceofcodeyoumayfind
thatitjumpsinthereandoffersshortcutstowhatyouretyping.Itcanhelpyoucompletethenamesof
statements:
Andtypes:
Andvariables:
Andparameters:
IntelliSenseisverypowerful,butuntilyougetusedtoworkingwithit,canalsosometimesbealittle
frustrating.Themainreasonforthisresultsfromthefactthatthespacekeyisoneofthewaysofasking
IntelliSensetocompletewhatyoutyped.Forexampleifyouretypingsomething,andIntelliSenseis
offeringyousomethingthatmatchesthecharactersthatyouhavetyped,youmightinstinctivelypress
thespacebartoleavewhatyouhavetypedandmoveontothenextword,butIntelliSensestepsinand
replaceswhatyouhavetypedwithwhatevermatchitwasdisplayingwhenyoupressedthespacebar.
ThesolutiontothisistohittheescapekeytodismissIntelliSensebeforeyoupressthespacebar,butat
firstthiscanbealittlefrustrating.However,itiswellworthperseveringandgettingusedtotheway
thatIntelliSenseworks,becauseonceyoumastertheartitcansaveyoualotoftyping.
Snippets
Anotherfeaturethatcansaveyoualotoftyping,particularlywhenyouarewritingnewcode,isa
featurecalledsnippets.AsnippetissimilarinconcepttoanaliasinWorkbench.Asnippetisapieceof
predefinedandnamedcodethatisinsertedintotheeditbuffer,atthecurrentcursorposition,when
thenameofthesnippetistypedfollowedbytwotabcharacters.Thefirsttabcharacterselectsthe
snippet,andthesecondexpandsit.
VisualStudioalsopresentssnippetstoyouviaIntelliSense,likethis:
Youcantellthatanitemisasnippetbecauseofits icon.
Withasnippetselected,typeTABTABtoselectandexpandit.Forexample,theFORsnippetexpands
likethis:
Somesnippetsjustexpandtoapieceoffixedcode,butmostexpandtoapieceofcodethatincludes
specialtokensthatareintendedtobereplacedwithsomeothervaluebytheprogrammer.Youcansee
thesetokensintheexampleabove,theiwiththegreenbackgroundisthecurrentlyselectedtoken,and
1,lengthand1withtheyellowbackgroundsareothertokenstobeselectedandreplaced.
Withasnippettokenselected,simplytypethevaluethatyouwanttoinsert,thenpressTABtomoveon
tothenexttokenorpressESCAPEtoexitfromtokenreplacementcompletely.
So,tofullyusetheFORsnippet,youcouldtype:
for<tab><tab>count<tab>10<tab>1<tab>1<escape>
Whichwouldresultinthefollowingcode:
Whilethismayinitiallyseemcomplicated,whenyouactuallydoitintheeditoritisverynatural,andcan
savetime.Anotherbenefitofusingsnippetsisthatyoureprettymuchguaranteedtoproducethe
correctcodebecausethesnippetdoesalotoftheworkforyou.Tryitout:
Placeyourcursorintheproceduredivisionofthebutton1_Clickmethod,afterthe
Debug.Printstatement,onanewline
Typeforandpresstabtwice.
Typevar3andpresstabtwice(oncetodismissIntelliSense,oncetocompletethesnippet
token).
Typetabtoacceptthedefaultvalue1.
Type10toinsertacustomvalue.
Type<Escape>tocompletethesnippetexpansion
Noticehowwhenyoupressedtheescapekey,thecursormovedintothebeginendblock.Thatspartof
thefunctionalityofthesnippetalso.
RemovetheFORloopfromthecode.
Bytheway,ifyouhaveblocksofcodethatyouusefrequently,thenyoucanalsocreateyourowncode
snippetsandaddthemtoVisualStudio,butthatsalittlebeyondthescopeofourobjectivesforthis
tutorial.
Code Beautifier
Synergy.NETincludesacodebeautifier,whichcanhelpyoureformatthesourcecodeinanedit
window.ThebeautifierfollowsthestylerulesthatyouhaveconfiguredinyourVisualStudio
environmentwelllookathowtodothatshortly.
Usingthecodebeautifiercouldntbeeasier;simplyopenasourcefilethatneedscleaningupand
activatethebeautifierbyselectingEdit>Advanced>FormatDocumentfromthemenu,orbytyping
thekeysequenceCtrl+KthenCtrl+D.Tryitout:
PlaceyourcursoranywhereintheForm1.dblsourcefile.
TypeCtrl+Atoselectthewholemethod.
TypeShift+Tabseveraltimestocauseallofthecodetobeunindentedtotheleftmargin.
Clickanywhereinthefiletodeselectthecode.
TypeCtrl+KfollowedbyCtrl+Dtoactivatethecodebeautifier.
YoucanalsodragoutaselectionwithintheeditbufferandreformatjustthatselectionusingFormat
Selection,orCtrl+KthenCtrl+F.
Itemtemplatesprovideaneasywaytoaddvarioustypesoffilestoanexistingproject,andoften
providedefaultcontentinthefilesthatareadded.
Closeanyopenfilesbyclickingonthecloseicon(cross)inthetabforeachfile.Ifyouare
promptedtosavechangesthenclickYes.
InSolutionExplorer,rightclickontheIntroToVisualStudioproject(itstheoneinbold)and
thenselectAdd>NewItem,ortypeCtrl+Shift+A.
YouwillseetheAddNewItemdialogappear.Itlookslikethis:
Asyoucansee,thedialogcontentisfilteredtofiletypesappropriateforaddingtoaSynergy/DEproject,
andorganizedintoseveralcategories.IfyouselecttheSynergycategorythenyouwillseeallofthe
availableitemtemplatesandclickingononeofthemorespecificcategories,suchasCode,resultsinthe
templatelistbeingfilteredtoonlyitemsthatmatchthatcategory.
SelecttheCodecategory.
SelecttheClasstemplate.
ChangethenameoftheclasstoCustomer.dbl
ClicktheAddbutton.
YoushouldseeanewfileaddedtoSolutionExplorer,andthenewfileshouldopenintheeditor;it
shouldcontaindefaultcontentforanewclass.
Noticethatthenameoftheclasshasbeensettothenameofthefilethatyouentered,andalsothat
thenamespacethathasbeeninsertedisthedefaultnamespaceforyourprojectasspecifiedinproject
properties.Filesinsertedbyitemtemplatesarenotnecessarilyproducedfromstaticcontent;rather
theycanbegeneratedasappropriate.
Tocopyanexistingfileintoyourproject,gotoSolutionExplorerandrightclickontheproject,then
selectAdd>ExistingItem.Usetheresultingfilebrowserdialogtolocateandselectthefileorfilesthat
youwishtoaddandclicktheAddbutton.Remember,thismechanismmakesaCOPYofthefilesdirectly
inyourprojectfolder.
Analternativeistoaddlinkstotheexistingfiles,withoutcopyingthefilesintoyourproject.The
procedureforthisissimilarexceptthatyouwillselectAdd>ReferenceExistingItem.Whenyouadd
linkstoexistingitemsintoaproject,thefileisnotcopiedintoyourprojectfolder,butisincludedinthe
compilationwhenyoubuildtheproject.
Theapproachusuallytakenistogroupsimilarroutinesintofolders.Forexample,ifyouaredeveloping
anapplicationusingtheMVVMdesignpattern,youmightchoosetoplaceallofyourviewsourcecode
intoaViewsfolder,allthemodelcodeinaModelsfolder,andalloftheviewmodelsintoaViewModels
folder.Bytheway,thisisntaspecificrecommendation,itmaybebettertoorganizethosethingsinto
entirelyseparateprojectsandassemblies.Itreallydependsonthescaleoftheapplicationandseveral
otherfactors.
Tocreateanewfolderinyourproject:
InSolutionExplorer,rightclickontheIntroToVisualStudioproject(itstheoneinbold)and
selectAdd>NewFolder.
ChangethefoldernametoModelsandpressenter.
RightclickonthenewfolderandselectAdd>NewItem.
EntertheinformationforanewClasscalledProduct.dblandclickAdd.
YoushouldseethenewclassaddedtoSolutionExplorerintheModelsfolder,andthenewfileshould
openinacodeeditorwindow.
YouwillnoticethatthenamespaceusedforthenewitemisIntroToVisualStudio.Models.Youll
rememberthatIntroToVisualStudiowasthedefaultnamespacefortheproject,andthatitemsthatyou
addtotheprojectareplacedintothisnamespace.But,asyoucansee,whenanewitemisaddedtoa
FOLDERintheproject,thedefaultbehavioristoaddtheitemtoanestednamespace,basedonthe
nameoftheproject.Thisbehaviorisconsistentwithother.NETlanguagesandisgenerallyagoodidea.
However,ifyoudontwanttomakeuseofnestednamespaces,thenyoujustneedtorememberto
changethenamespacewhenyouaddnewitemsintoafolder.
Aswediscussedearlier,aprojectisusedtocreateasingleassembly(programorclasslibrary).
Developerscommonlyorganizereusablecode(theequivalentoftraditionalSynergyssubroutine
libraries)intoseparateassembliesandreferencethemfromtheprojectswhichusethetypesthatthey
contain.
Letslookatasimpleexample:
InSolutionExplorer,rightclickontheIntroToVisualStudioSOLUTION(itstheoneatthevery
top)andselectAdd>NewProject.
IntheAddNewProjectdialog,selectSynergy/DEandClassLibrary.
SettheNameoftheclasslibrarytoMyLibrary.
PresstheOKbuttontoaddthenewlibrary.
YoushouldnowhavetwoprojectsshowinginSolutionExplorer.You
willnoticethattheIntroToVisualStudioisstilldisplayedinbold.That
isbecauseitissetasthesolutionsStartupProject,meaningthat
whenyouexecuteordebugthesolutionthatistheprojectwhose
executablewillbestarted.
Veryoften,solutionscontainingmultipleprojectswillcontainone
applicationandoneormoreclasslibraries,whichcantbestarted
directly,soitisusuallyclearwhichprojectshouldbethestartup
project.Howeverinsomesituationsyoumaydecidetohavemultiple
applicationprojectsinasolution,andinthatcaseyoucandetermine
whichprojectisthestartupprojectbyrightclickingtheprojectand
selectingSetAsStartUpProject.
Youhaveaddedaclasslibraryprojecttoyoursolution,anditcontainsasingledefaultclasscalled
Class1.Werenotgoingtoworryaboutfunctionalityrightnow,becausethistutorialisabouthowtouse
VisualStudiowithSynergy.NET,butwhatwedoneedtodoisshowhowtomodifytheapplication
projecttohaveareferencetothenewclasslibraryproject,sothatitcanusethetypesinthelibrary.
InSolutionExplorer,undertheIntroToVisualStudioproject,rightclickontheReferences
folderandselectAddReference.
IntheAddReferencedialog,selecttheProjectstab.
SelectMyLibraryandclicktheOKbutton.
YourIntroToVisualStudioprojectnowhasareferencetoyourMyLibraryclasslibraryassembly,andcan
useanypublictypesinthatassembly.
SelectTools>C#toSynergyCodeConverterfromthemenu.
Tousethecodeconverter,eithertypeorpastetheC#codethatyouwishtoconvertintotheboxonthe
left,andthenclickthetranslatebutton .Thetranslatedcodeisplacedintoyourclipboardsothatyou
canpasteitintoasourcefile.
ThecodeconvertercanbeveryusefulwhenlearninghowtoprogramsomethinginSynergy.NET
becausetherearemanyC#codeexamplesintheVisualStudiodocumentationandontheInternet,
generally.
Thecodethatyouplaceintheleftboxmustbeacompletepieceofcodeinanamespace.Pastingsmall
snippetsofcodeintotheconverterwillnotwork.
ThecodeconverterhasbeensubstantiallyimprovedsincetheinitialreleaseofSynergy.NETandisnow
capableofconvertingmostC#code,buttherearesomesyntaxconstructsavailableinC#thathaveno
directequivalentinSynergy.NET,sooccasionallythecodeconvertermayreportFailedtoconvert.
Also,occasionallythecodeconvertermayencounterC#syntaxwhichcanbeimplementedinSynergy
.NET,butwhichistoocomplextobeconvertedautomatically.Inthesecases,wheneverpossible,the
codeconverterwillinsertaTODO:commentintotheresultingcodetoindicatethatyouneedtodo
somemanualwork.
Inmanycasesthecodeconverterisabletoproducecodewhichis100%correct,butifyouareusingit
toproducecodethatyouactuallyintendtouse(ratherthanjusttolearnatechniquefrom)thenitis
recommendedthatyoureviewthecodethatwasproduced.
Closethecodeconverterwindow.
TypeCtrl+Shift+B
Checktheoutputwindowandyoushouldseethatbothofyourprojectswerebuilt:
YoualsohavetheoptionofbuildingtheprojectsindividuallyviamenuitemsontheBuildmenu.Youwill
seeseparateoptionstobuildthesolutionorthecurrentproject.Thecurrentprojectiswhichever
projectcontainstheselecteditemintheSolutionExplorertree.
Attemptingtocoverallofthisinatutoriallikethisisnotfeasible,soinsteadwelljustpointyouinthe
rightdirectionandhighlightafewoftheSynergy.NETspecificextensions.
Fromthemenu,SelectTools>Options
TheOptionsdialogcontainsliterallythousandsofconfigurablesettingswhichallowyoutocontrol
virtuallyanyaspectofVisualStudio.
Inthetreecontrol,selectTextEditor,thenexpandandselectSynergy/DE
BelowSynergy/DEyouwillfindseveralpagesofsettingsrelatedspecificallytoworkingwithSynergy
.NET.Atsomepointyoushouldtakethetimetofamiliarizeyourselfwiththevarioussettingsavailable.
SelecttheFormattingitem
Theformattingpageallowsyoutospecify,indetail,howyouwantVisualStudiotoformatthecodethat
youtype.Thesesamerulesarealsofollowedbythecodebeautifiertool.
PressCanceltoclosetheoptionsdialog.
Review
DuringthisworkshopwehaveattemptedtointroduceyoutothebasicfunctionalityprovidedbyVisual
Studio2010,butthereisalotmoretolearn.VisualStudioisanextensiveapplication,withmanyoptions
andmanywaysofworking,andisextremelycustomizable.