You are on page 1of 47

Introduction

to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 1

Introduction to Visual Studio 2010

Reset to Default Settings


Fromthemenu,selectTools>ImportandExportSettings.
SelecttheResetAllSettingsradiobutton,andthenclicktheNextbutton.
OntheSaveCurrentSettingspage,checkthatYes,savemycurrentsettingsisselected(to
saveabackupsothatyoumayrestoreyourcurrentsettingsaftercompletingthistutorial,if
required)andthenclicktheNextbutton.
OntheChooseaDefaultCollectionofSettingspage,SelectGeneralDevelopmentSettings
ClicktheFinishbutton
WhenyouseetheResetCompletescreen,clicktheClosebutton.

Selectingoneofthesepredefinedcollectionsofdefaultsettingscanmakemanychangestoyour
environment.Thingsthatarecommonlychangedincludemenuitems,menuitemshortcuts,toolbars,
andmore.

Creating a New Project


Oneofthefirstthingsyourelikelytowanttodoiscreateanewdevelopmentproject,soletsdothat
now.AswithmanythingsinVisualStudio,thereareoftenseveralwaystodosomething.Forexample,
tocreateanewdevelopmentprojectyoucan:

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.

Introduction to Visual Studio 2010 Page 2

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 3

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 4

Introduction to Visual Studio 2010

Visual Design Surfaces


ManythingsthatyouworkwithinVisualStudiohavevisualdesign
surfaces.Certainlyitiscommontoworkwithavisualdesignsurface
whenbuildingauserinterface,butseveralotherthingshavethem
also.Asthenamesuggests,avisualdesignsurfaceallowsyouto
designsomethingvisually,oftenbydraggingitemsfromapaletteof
availablethingsandarrangingthemonthedesignsurface.

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.

Introduction to Visual Studio 2010 Page 5

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 6

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 7

Introduction to Visual Studio 2010

Designer Source Files


Tohelpyoutounderstandwhatishappeningwhenyouinteractwithavisualdesignsurfaceorwiththe
propertieswindow,letsdigalittledeeperintooursimpleapplication.

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

Introduction to Visual Studio 2010 Page 8

Introduction to Visual Studio 2010

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.

The Properties Folder


EachprojectthatyoucreatewillincludeafoldercalledProperties,anddependingonthetypeof
project,thefolderwillcontainoneormorefiles.

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

Introduction to Visual Studio 2010 Page 9

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 10

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 11

Introduction to Visual Studio 2010

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.

The References Folder


InSolutionExplorer,expandtheReferencesfolder.

AllVisualStudiodevelopmentprojectswillincludeaspecialfoldercalledReferences.Thefolderdoesnt
containfiles,butrathercontainsalistofassembliesthatareaccessiblefromthecodewithinyour
application.Ifyouwanttoaccesstypesthatarestoredinaparticularassembly,youaddareferenceto
theassembly.Welllookathowtodothatshortly.

Whenyoucreateanewprojectfromaprojecttemplate,thetemplatewillprobablyincludeasetofpre
configuredreferences.Someofthesereferencesmayberequiredbecauseofexistingcodethathas
alreadybeenincludedintheprojectbythetemplate,whileothersmayhavebeenincludedsimply
becauseyouarelikelytoneedthemwhendevelopingaparticulartypeofapplication.

InSolutionExplorer,rightclickontheReferencesfolderandselectAddReference

Introduction to Visual Studio 2010 Page 12

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 13

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 14

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 15

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 16

Introduction to Visual Studio 2010

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:

Introduction to Visual Studio 2010 Page 17

Introduction to Visual Studio 2010

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

Introduction to Visual Studio 2010 Page 18

Introduction to Visual Studio 2010

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:

Macro TranslatesTo Example

$(Configuration) Thenameofthecurrent Debug


projectconfiguration.

$(OutDir) Pathtotheoutputfile bin\Debug\


directoryrelativetothe
projectdirectory.Thispath
shouldhaveatrailingslash.
Thisresolvestothevaluefor
theOutputDirectory
property.

$(ProjectDir) Thedirectoryoftheproject c:\temp\MyTestApp\


(definedasdrive+path);it

Introduction to Visual Studio 2010 Page 19

Introduction to Visual Studio 2010

includesthetrailing
backslash.

$(ProjectExt) Thefileextensionofthe .synproj


project.Itincludesthe'.'
beforethefileextension.

$(ProjectFileName) Thefilenameoftheproject MyTestApp.synproj


(definedasbasename+file
extension).

$(ProjectName) Thebasenameoftheproject. MyTestApp

$(ProjectPath) Theabsolutepathnameof c:\temp\MyTestApp\MyTestApp.synproj


theproject(definedasdrive
+path+basename+file
extension).

$(RootNameSpace) Thenamespace,ifany, MyTestApp


containingtheapplication.

$(SolutionDir) Thedirectoryofthesolution c:\temp\MyTestApp\


(definedasdrive+path);it
includesthetrailing
backslash.

$(SolutionExt) Thefileextensionofthe .sln


project.Itincludesthe'.'
beforethefileextension.

$(SolutionFileName) Thefilenameofthesolution MyTestApp.sln


(definedasbasename+file
extension).

$(SolutionName) Thebasenameofthe MyTestApp


solution.

$(SolutionPath) Theabsolutepathnameof c:\temp\MyTestApp\MyTestApp.sln


thesolution(definedasdrive
+path+basename+file
extension).

$(TargetDir) Thedirectoryoftheprimary c:\temp\MyTestApp\bin\Debug\


outputfileforthebuild
(definedasdrive+path);it

Introduction to Visual Studio 2010 Page 20

Introduction to Visual Studio 2010

includesthetrailing
backslash.

$(TargetExt) Thefileextensionofthe .exe


primaryoutputfileforthe
build.Itincludesthe'.'before
thefileextension.

$(TargetFileName) Thefilenameoftheprimary MyTestApp.exe


outputfileforthebuild
(definedasbasename+file
extension).

$(TargetName) Thebasenameofthe MyTestApp


primaryoutputfileforthe
build.

$(TargetPath) Theabsolutepathnameof c:\temp\MyTestApp\bin\Debug\MyTestApp.exe


theprimaryoutputfilefor
thebuild(definedasdrive+
path+basename+file
extension).

Bearinmindthattheenvironmentvariablesthatyouspecifythroughtheprojectpropertiesdialogsare
onlypresentinyourdevelopmentenvironment.Ifyouusethismechanismtospecifyvaluesfor
environmentvariablesthatarerequiredatapplicationruntime(outsideofVisualStudio)thenyoumust
providethoseenvironmentvariablesviasomeothermechanism.

Signing
SwitchtotheSigningtab

Introduction to Visual Studio 2010 Page 21

Introduction to Visual Studio 2010

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.)

Introduction to Visual Studio 2010 Page 22

Introduction to Visual Studio 2010

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:

Introduction to Visual Studio 2010 Page 23

Introduction to Visual Studio 2010

<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.

Introduction to Visual Studio 2010 Page 24

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 25

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 26

Introduction to Visual Studio 2010

Building the Project


VisualStudio2010utilizesanexternalbuildsystemcalledmsbuildtoperformbuildoperations.Almost
allprojectshavetheconceptofabuildwhichistheprocessofgeneratingwhatevertheoutputofthe
projectis,generallya.NETassembly,fromwhatevertheinputforthebuildis,generallysourcecode.

Youdontneedtodoanythingspecialtodefinewhathappensduringabuildotherthanconfiguringthe
contentoftheproject,whichinmostcasesinvolvesaddingsourcefilesandsourcecodetotheproject.
HoweverthereareothertypesofprojectthatVisualStudiosupports.Forexample,thereareproject
templatestoallowyoutocreateWindowsInstallerinstallationpackages(msifiles),aswellasvarious
otherthings.

Butmostprojectshaveabuildoption,andthatshowyoucausetheprojectoutputtobegenerated
(assumingthatyouhavenoerrorsofcourse!).Basedontheprojecttemplate,VisualStudioknowsHOW
tobuildthetargetoutput.InthecaseofaSynergy.NETproject,itknowstobuildadblnetcommand
lineusingthevariousoptionsspecifiedintheprojectpropertiesdialogsandusingalistofallthesource
filesandassemblyreferencesdefinedintheproject.Thenitexecutesthiscommandanddisplaysthe
resultingoutput.

The Output Window


Generallytheoutputfromabuildisdisplayedinoneortwoplacesdependingonwhetherthebuildwas
successful.First,theactualtextualoutputisdisplayedintheOutputwindow,andthen,iftherewere
anyerrors,thoseerrorsaregenerallyparsedanddisplayedinamorestructuredwayintheErrors
window.

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.

Introduction to Visual Studio 2010 Page 27

Introduction to Visual Studio 2010

Error List Window


Todemonstratewhathappenswhenthereisanerror:

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!

Introduction to Visual Studio 2010 Page 28

Introduction to Visual Studio 2010

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).

Introduction to Visual Studio 2010 Page 29

Introduction to Visual Studio 2010

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:

Introduction to Visual Studio 2010 Page 30

Introduction to Visual Studio 2010


Intheproceduredivision,addthefollowingcode:

Thepointofthisexerciseisjusttogiveussomecodethatwecaninteractwithinthedebuggerlater.

Using the Debugger


InVisualStudiothedebuggeriscompletelyembeddedwithinthedevelopmentenvironment,makingit
mucheasiertostepthroughcodeandexaminedata.Thedebuggerhasmanyfeatures,sowelljusttake
abrieflookatsomeofthemorefundamentalthingsthatyoucando.

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.

Introduction to Visual Studio 2010 Page 31

Introduction to Visual Studio 2010

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:

Introduction to Visual Studio 2010 Page 32

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 33

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 34

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 35

Introduction to Visual Studio 2010

Working with Source Code


YouhaveseentheSynergy.NETsourcecodeeditorafewtimesnow,butsofarwehaventreally
exploreditscapabilities.Letsdothatnext.

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).

Introduction to Visual Studio 2010 Page 36

Introduction to Visual Studio 2010

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:

Introduction to Visual Studio 2010 Page 37

Introduction to Visual Studio 2010

Atanytimeduringthisprocessyoucanusethearrowkeysormousetoselectasuggestedvalue,and
thenpressenter,tab,orspacetoinsertthatvalueintoyourcode.Ifyoudontwanttheassistancethen
youcanhittheescapekeytoclosetheIntelliSensepromptsandofcourseyoucanjustignorewhat
itsdoingandkeeptyping.

IntelliSenseiscontextsensitive,sonomatterwhereyouareworkinginapieceofcodeyoumayfind
thatitjumpsinthereandoffersshortcutstowhatyouretyping.Itcanhelpyoucompletethenamesof
statements:

Andtypes:

Introduction to Visual Studio 2010 Page 38

Introduction to Visual Studio 2010

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:

Introduction to Visual Studio 2010 Page 39

Introduction to Visual Studio 2010

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

Introduction to Visual Studio 2010 Page 40

Introduction to Visual Studio 2010

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.

Adding new Items


WhenyoufirstcreatedtheprojectthatyouhavebeenworkingonyouusedaProjectTemplate,which
configuredanewprojectforaspecifictypeofdevelopmentproject.Whenitcomestimetoadd
additionalitemstoaproject,youcanuseanothertypeoftemplate,thistimecalledanItemTemplate.

Itemtemplatesprovideaneasywaytoaddvarioustypesoffilestoanexistingproject,andoften
providedefaultcontentinthefilesthatareadded.

Closeanyopenfilesbyclickingonthecloseicon(cross)inthetabforeachfile.Ifyouare
promptedtosavechangesthenclickYes.
InSolutionExplorer,rightclickontheIntroToVisualStudioproject(itstheoneinbold)and
thenselectAdd>NewItem,ortypeCtrl+Shift+A.

Introduction to Visual Studio 2010 Page 41

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 42

Introduction to Visual Studio 2010

Adding Existing Items


Aswellasaddingnewitemstoaproject,youcanaddexistingfiles.Infacttherearetwodifferentways
toaddexistingfilestoaproject,onewhichplacesaCOPYoftheoriginalfiledirectlyinyourproject
folder,andonewhichplacesaLINKtotheoriginalfileintoyourproject.

Tocopyanexistingfileintoyourproject,gotoSolutionExplorerandrightclickontheproject,then
selectAdd>ExistingItem.Usetheresultingfilebrowserdialogtolocateandselectthefileorfilesthat
youwishtoaddandclicktheAddbutton.Remember,thismechanismmakesaCOPYofthefilesdirectly
inyourprojectfolder.

Analternativeistoaddlinkstotheexistingfiles,withoutcopyingthefilesintoyourproject.The
procedureforthisissimilarexceptthatyouwillselectAdd>ReferenceExistingItem.Whenyouadd
linkstoexistingitemsintoaproject,thefileisnotcopiedintoyourprojectfolder,butisincludedinthe
compilationwhenyoubuildtheproject.

Organizing Files in Folders


Asyourdevelopmentprojectsgetlargeryoumayfinditnecessarytoorganizeyoursourcefilesinto
multiplefoldersbelowyourprojectfolder.Thisalsohastheadvantageoforganizingthefilesintofolders
withinSolutionExplorer,andcanmakeitmucheasiertoworkwithlargerprojectsinVisualStudio.

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

Introduction to Visual Studio 2010 Page 43

Introduction to Visual Studio 2010

nameoftheproject.Thisbehaviorisconsistentwithother.NETlanguagesandisgenerallyagoodidea.
However,ifyoudontwanttomakeuseofnestednamespaces,thenyoujustneedtorememberto
changethenamespacewhenyouaddnewitemsintoafolder.

Adding Projects to the Solution


Sofarweveonlyconsidereddevelopingwithasolutioncontainingasingleproject.Butveryoftenwhen
workinginVisualStudioyouwillworkwithsolutionscontainingseveralprojects,asyoustriveto
organizeyourapplicationintologicalunitsthatcanbereusedfromotherplaces.

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.

Introduction to Visual Studio 2010 Page 44

Introduction to Visual Studio 2010

InSolutionExplorer,undertheIntroToVisualStudioproject,rightclickontheReferences
folderandselectAddReference.
IntheAddReferencedialog,selecttheProjectstab.
SelectMyLibraryandclicktheOKbutton.

YourIntroToVisualStudioprojectnowhasareferencetoyourMyLibraryclasslibraryassembly,andcan
useanypublictypesinthatassembly.

Using the Code Converter


Synergy.NETincludesacodeconverterutilitywhichiscapableoftranslatingC#syntaxtotheequivalent
Synergy.NETsyntax.

SelectTools>C#toSynergyCodeConverterfromthemenu.

Tousethecodeconverter,eithertypeorpastetheC#codethatyouwishtoconvertintotheboxonthe
left,andthenclickthetranslatebutton .Thetranslatedcodeisplacedintoyourclipboardsothatyou
canpasteitintoasourcefile.

ThecodeconvertercanbeveryusefulwhenlearninghowtoprogramsomethinginSynergy.NET
becausetherearemanyC#codeexamplesintheVisualStudiodocumentationandontheInternet,
generally.

Thecodethatyouplaceintheleftboxmustbeacompletepieceofcodeinanamespace.Pastingsmall
snippetsofcodeintotheconverterwillnotwork.

Introduction to Visual Studio 2010 Page 45

Introduction to Visual Studio 2010

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.

Building With Multiple Projects


WhenyouworkwithinasolutionthatincludesmultipleprojectsthenVisualStudiowillbuildany
projectsthatareoutofdatewheneveryouexecuteordebugtheapplication.Also,typingCtrl+Shift+B
(buildsolution)willalsobuildanyprojectswhichareoutofdate.Tryit:

TypeCtrl+Shift+B

Checktheoutputwindowandyoushouldseethatbothofyourprojectswerebuilt:

YoualsohavetheoptionofbuildingtheprojectsindividuallyviamenuitemsontheBuildmenu.Youwill
seeseparateoptionstobuildthesolutionorthecurrentproject.Thecurrentprojectiswhichever
projectcontainstheselecteditemintheSolutionExplorertree.

Configuring Visual Studio


Aswithanymodernsoftwaredevelopmentenvironment,VisualStudioisVERYcustomizable.Youcan
changemanyaspectssuchaswhetherthingsarevisible,wherethingsappearonthescreen,what
keyboardshortcutsareused,etc.Youcanalsoperformextensivecustomizationofthingslikethe
behavioroftheeditorsandmanyotherthings.

Attemptingtocoverallofthisinatutoriallikethisisnotfeasible,soinsteadwelljustpointyouinthe
rightdirectionandhighlightafewoftheSynergy.NETspecificextensions.

Introduction to Visual Studio 2010 Page 46

Introduction to Visual Studio 2010

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.

Introduction to Visual Studio 2010 Page 47

You might also like