Visual Studio Study Material

Embed Size (px)

Citation preview

  • 7/28/2019 Visual Studio Study Material

    1/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page1

    IntroductionIfyouhaventusedMicrosoftVisualStudiobefore,thenthistutorialisforyou.Itwillwalkyouthrough

    themajorfeaturesofVisualStudio2010andgetyoustartedwithcreatingvarioustypesofSynergy.NET

    applications.You

    will

    also

    learn

    useful

    tips

    and

    techniques

    that

    can

    save

    you

    valuable

    time

    while

    programmingwithinVisualStudio.

    TutorialSetupNospecificpreparationisneededinordertocompletethistutorial.

    TutorialStepsStartingVisualStudioBeforewecangetstarted,ifitsnotalreadyrunning,weneedtostartMicrosoftVisualStudio2010.

    FromtheWindowsStartMenu,selectAllPrograms>MicrosoftVisualStudio2010>MicrosoftVisualStudio2010.

    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.

  • 7/28/2019 Visual Studio Study Material

    2/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page2

    ResettoDefaultSettingsFromthemenu,selectTools>ImportandExportSettings.SelecttheResetAllSettingsradiobutton,andthenclicktheNextbutton.OntheSaveCurrentSettingspage,checkthatYes,savemycurrentsettingsisselected(to

    saveabackupsothatyoumayrestoreyourcurrentsettingsaftercompletingthistutorial,if

    required)andthenclicktheNextbutton.

    OntheChooseaDefaultCollectionofSettingspage,SelectGeneralDevelopmentSettingsClicktheFinishbuttonWhenyouseetheResetCompletescreen,clicktheClosebutton.

    Selectingoneofthesepredefinedcollectionsofdefaultsettingscanmakemanychangestoyour

    environment.Thingsthatarecommonlychangedincludemenuitems,menuitemshortcuts,toolbars,

    andmore.

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

  • 7/28/2019 Visual Studio Study Material

    3/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page3

    Thenameofthefolderthattheprojectwillbecreatedin. Thenameofthemainassembly(programorlibrary)thatwillbecreatedbytheproject. Thenameofthedefaultnamespacethatwillbeusedwhensometypesofitemareaddedto

    theproject.

    Ofcourse,

    even

    after

    aproject

    has

    been

    created,

    all

    or

    any

    of

    these

    things

    can

    be

    changed,

    but

    some

    are

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

    is

    generally

    appropriate

    ifyou

    only

    plan

    on

    working

    with

    one

    project

    in

    the

    solution.

    IftheCreatedirectoryforsolutionboxischecked,thenVisualStudiowillcreateafolderforthe

    solution(belowthelocationthatyouspecify)andsavethesolutionfileinthatfolder.Thenasecond

    folder,fortheproject,willbecreatedbelowthesolutionfolder,andalloftheprojectfileswillbe

    createdinorbelowtheprojectfolder.Thisisappropriatewhenyouintendtoaddseveralprojectstoa

    solution,aseachprojectwillbestoredinitsownfolderbelowthemainsolutionfolder.Youllalsonotice

    thatinthiscaseyouareabletospecifyadifferentnameforthesolutionitself.

    ClickontheOKbuttontocreateyournewsolutionandproject.Becauseofthevirtualmachine,creating

    and

    opening

    the

    solution

    and

    project

    may

    take

    afew

    seconds.

    Differentprojecttemplatescausedifferentthingstohappenwhenanewprojectiscreated.Fora

    WindowsFormsproject,whatgenerallyhappensisthesolutionandproject,andvariousdefaultproject

    filesaredisplayedintheSolutionExplorertowardsthetoprightofthescreen,thevisualdesignsurface

    forthedefaultformthatwasaddedtotheprojectisdisplayedfillingmostofthescreen,andthe

    Propertieswindowisdisplayedtowardsthebottomrightofthescreen.

  • 7/28/2019 Visual Studio Study Material

    4/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page4

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

  • 7/28/2019 Visual Studio Study Material

    5/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page5

    VisualDesignSurfacesManythingsthatyouworkwithinVisualStudiohavevisualdesign

    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.

    TheToolboxTheToolboxmaynotbevisiblerightnow,butifnotlookdowntheleft

    handsideoftheVisualStudiowindowandyoumayseeaverticaltabthat

    saysToolbox.

    IfyoudontseetheToolboxWindowthenselectView>Toolboxfromthemenu(ortypeCtrl+Alt+X).

    WiththeToolboxvisible,clickonthesmall iconatthetoprightoftheToolboxwindowtopinthewindowinplace.

    Pinningawindowprovidesamechanismtoensurethatitremainsonthe

    screen.Mostwindows,whenunpinned,slideoutofsightbutleavebehind

    atabsothatyoucanaccessthewindowagain.Hoveringthemouseover

    theone

    of

    these

    tabs

    will

    make

    the

    window

    appear

    so

    that

    you

    can

    access

    it,orpinitinplace.

    MakesurethatthedesignviewofForm1.dblisvisible.IntheToolbox,gototheCommonControlsgroup,thenclickonce

    onanddragaButtoncontroltothedesignsurface.

  • 7/28/2019 Visual Studio Study Material

    6/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page6

    Youwillnoticethatwhenthebuttoniscreatedontheform,severalwhitehandlesappeararoundthe

    outsideofthebutton.Thesehandlesperformtwofunctions;theyindicatewhichitemiscurrently

    selectedtobeworkedwith,andtheycanbeusedtoresizetheselecteditem.

    Singleclickthebodyoftheform(notonthebutton)andyouwillseethatthehandlesmovetothe

    form,

    which

    is

    now

    selected

    to

    be

    worked

    on.

    Singleclickonthebuttonagain,thehandlesmovebacktothebutton.Asyouclickbetweenthesetwoitems,looktothelowerrightportionofthescreen.Youshouldseea

    windowcalledProperties,andyoushouldseethecontentofthewindowchangeasyouselectdifferent

    itemsonavisualdesignsurface.

    Ifyoucantseethepropertieswindow,selectView>PropertiesWindowfromthemenu,orusetheF4keyboardshortcut.

    Ifnecessary,pinthepropertieswindowinplace.PropertiesWindowThepropertieswindowisanotherkeypartofVisualStudiowhere,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.

  • 7/28/2019 Visual Studio Study Material

    7/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page7

    Noticehowtheselecteditemhandlesmovedfromthebuttontotheform,andhowthecontentofthe

    propertieswindowchangedtoreflectthepropertiesofthenewlyselecteditem.

    OnForm1sdesignview,selecttheform.

    In

    the

    properties

    window,

    Locate

    the

    Text

    property

    and

    set

    the

    value

    to

    My

    Form.

    AWindowsFormstextpropertyisusedtosetthetitleofthewindow;noticehowthetextthatyou

    typedisnowalsodisplayedinthetitleareaoftheformdesigner.Somechangesthatyoumakeinthe

    propertieswindowarereflectedvisuallyinthedesigner.

    Insomecases,theoppositeisalsotrue.Forexample:

    Withtheformselected,locatetheSizeproperty.Itmaybeeasiertoswitchtoalphabeticmode(toolbarattopofpropertieswindow).

    Noticethecurrentvalueofthesizeproperty;probablythedefault300,300Nowusethedesignerscurrentitemhandlestovisuallyresizetheform.ChecktheSizepropertyagain,itshouldhavechanged.

    So,makingchangesinthepropertieswindowoftenvisuallychangesthedesignerwindow,andmaking

    changesinthedesignerwindowalsochangesthepropertieswindow.

    Anotherthingtonoticewithrespecttothepropertieswindowishowpropertiesthathavenotbeen

    changed(i.e.,currentlyhaveadefaultvalue)aredisplayedinnormaltext,whereaspropertiesthathave

    hadtheirvaluechangedaredisplayedinboldtext.Thisvisualindicationofwhatpropertieshavebeen

    changedcan

    be

    very

    useful.

    So,wevediscoveredthatwecanchangethepropertiesofsomethingeithergraphicallyinadesignview,

    orviathepropertieswindow,butwhereisallofthatinformationstored?Theanswertothatdepends

    onwhattypeofprojectyouareworkingon.Somecommonexamplesare:

    ProjectType Designer/PropertiesChangesWrittenTo

    WindowsForms Adesignerprogramminglanguagesourcefile.

    WebForms(ASP.NET) Themainwebpagefile(.aspx)inHTMLformat.

    WindowsPresentation

    Foundation

    Themain

    form

    or

    control

    file

    (.xaml)

    in

    XAML

    format.

    Silverlight Themainformorcontrolfile(.xaml)inXAMLformat.

    Other Various,generallyaprogramminglanguagesourcefile.

  • 7/28/2019 Visual Studio Study Material

    8/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page8

    DesignerSourceFilesTohelpyoutounderstandwhatishappeningwhenyouinteractwithavisualdesignsurfaceorwiththe

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

    Rightnowthedesignersourcefileisfairlysimple,becauseallwehaveisaformandabutton.Notice

    howtheclassForm1extends(isa)System.Windows.Forms.Form,andhowtheclasscontainsan

    instancevariablecalledbutton1whichisoftypeSystem.Windows.Forms.Button.Thatvariablewas

    created,by

    the

    designer,

    when

    we

    dragged

    the

    button

    onto

    the

    form.

    LookdownalittleandyouwillseethatthereisamethodcalledInitializeComponent,andinthat

    methodtherearevariousassignmentstatementswhichsetvariouspropertiesofthebutton

    (this.button.something)andtheformitsself(this.something).Theselinesofcodeareinsertedwhenwe

    makechangestothepropertiesoftheform,orobjectsontheform,eitherviachangesthatwemake

    onthegraphicaldesignsurface,orchangesthatwemakeinthePropertieswindow.

    YoumayalsonoticethatthecodeinthisfiledefinestheclassaspublicpartialclassForm1.

    ClickonthetabatthetopoftheeditareacalledForm1.dbl.IfyouclosedthisviewtheninSolutionExplorer,rightclickonForm1.dblandselectViewCode.

    NoticethattheclassinthissourcefileisalsodefinedaspublicpartialclassForm1.Apartialclassisa

    classcomposedfrompartialclassdefinitionsinmultiplesourcefiles,sointhiscasetheclassForm1is

    madeupofsourcecodeinthefileForm1.dbl,whichthedevelopercontrols,andcodeinthefile

    Form1.designer.dbl,whichthedesignerandpropertieswindowcontrol.Ifyoulookatthedefaultcode

    inForm1.dblyouwillnoticethatthereisaconstructormethod(publicmethodForm1)whichcontains

  • 7/28/2019 Visual Studio Study Material

    9/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page9

    acalltotheInitializeComponentmethodwhichisinForm1.designer.dbl.So,whentheapplication

    createsaninstanceoftheForm1class,thedesignergeneratedcodeisexecutedtocreateandconfigure

    allofthecontrolsontheform.

    Program.dblProjects

    which

    target

    an

    assembly

    which

    is

    an

    executable

    program

    (i.e.,

    an

    .exe

    rather

    than

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

    ThePropertiesFolderEachprojectthatyoucreatewillincludeafoldercalledProperties,anddependingonthetypeof

    project,thefolderwillcontainoneormorefiles.

    InSolutionExplorer,expandthePropertiesfoldertoviewthefilesthatitcontains.IntheWindowsFormsprojectthatyourecurrentlyworkingin,therewillbevariousfilesinthe

    Propertiesfolder.

    These

    files

    are

    AssemblyInfo.dbl,

    Resources.resx

    and

    Settings.settings.

    Although

    you

    caneditsomeofthesefilesdirectly,andsomeofthesefiletypesalsohavevisualdesignersassociated

    withthem,thefilesinthePropertieswindowareusuallymaintainedviatheProjectPropertiesdialogs,

    asyouwillseeshortly.

    AssemblyInfo.dblInSolutionExplorer,doubleclick

    AssemblyInfo.dbl toopenitinacodeeditor.

    AssemblyInfo.dblcontainsvariousattributedefinitions

    usedto

    embed

    information

    into

    the

    compiled

    assembly.

    Youcanspecifyinformationaboutyourcompany,the

    nameoftheproduct,copyrightinformation,etc.

    Thefilecanalsobemaintainedviaadialogwindow

    whichcanbeaccessedbyopeningtheproject

  • 7/28/2019 Visual Studio Study Material

    10/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page10

    properties,selectingtheApplicationtabandclickingtheAssemblyInformationbutton.

    Resources.resxThisfileisaresourcefilewhichisaspecialtypeoffilethatcanbeusedtoembedvariousresources

    (strings,images,audiofiles,etc.)theapplicationmightneed,directlyintotheapplicationsassembly.

    Thebenefit

    of

    using

    resource

    files

    is

    that

    any

    resources

    that

    the

    application

    needs

    do

    not

    need

    to

    be

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

    IntheValuecolumnaddthetextWelcometomyapplication.IntheCommentcolumnaddthetextDisplayedatapplicationstartup.TypeCtrl+Stosaveyourchanges.

    Nowletstakealookatwhatweactuallydidwiththeresourcedesigner.

    InSolutionExplorer,rightclickonResources.resxandselectViewCode.

  • 7/28/2019 Visual Studio Study Material

    11/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page11

    TheXMLfilethatyouarelookingatistheactualresourcefile.Ifyouscrolltothebottomofthefileyou

    willseetheresourcethatyoujustaddedviathedesigner.

    ClosetheXMLviewoftheresourcefile.

    In

    Solution

    Explorer,

    expand

    the

    view

    of

    the

    file

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

  • 7/28/2019 Visual Studio Study Material

    12/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page12

    Settings.settingsConceptuallythesettingsfileissimilartoaresourcefile.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.TheReferencesFolderInSolutionExplorer,expandtheReferencesfolder.

    AllVisualStudiodevelopmentprojectswillincludeaspecialfoldercalledReferences.Thefolderdoesnt

    containfiles,butrathercontainsalistofassembliesthatareaccessiblefromthecodewithinyour

    application.Ifyouwanttoaccesstypesthatarestoredinaparticularassembly,youaddareferenceto

    theassembly.

    Well

    look

    at

    how

    to

    do

    that

    shortly.

    Whenyoucreateanewprojectfromaprojecttemplate,thetemplatewillprobablyincludeasetofpre

    configuredreferences.Someofthesereferencesmayberequiredbecauseofexistingcodethathas

    alreadybeenincludedintheprojectbythetemplate,whileothersmayhavebeenincludedsimply

    becauseyouarelikelytoneedthemwhendevelopingaparticulartypeofapplication.

    InSolutionExplorer,rightclickontheReferencesfolderandselectAddReference

  • 7/28/2019 Visual Studio Study Material

    13/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page13

    TheAddReferencedialogallowsyoutobrowseassembliesthatareavailabletobereferencedbyyour

    project.

    Therearefivetabsatthetopofthedialog,asfollows:

    .NET Listsall.NETFrameworkcomponentsavailableforreferencing,aswellasassemblies

    fromthirdpartiesthathavebeenregisteredonyoursystem.

    COM ListsallCOMcomponentsavailableforreferencingandusethrough.NETsCOMinterop

    capabilities.

    Projects ListsVisualStudioprojectsinthecurrentsolutionavailableforreferencing.Select

    assembliesfromthistabtocreateprojecttoprojectreferences.

    Browse Allowsyoubrowseadditionalfilestofindacomponentnotlistedinthecurrenttaband

    addittothelist.

    Recent

    Displaysrecently

    added

    references.

    Asanexampleofaddingareferencetoaproject,tomaketypes(classes,etc.)thatareavailableina

    particularassemblyavailableforuseintheproject,letsassumewewanttohavetheabilitytoexposea

    WCFservicefromourapplication.Todothatyouwouldneedtouseseveralclassesthatareprovidedby

    the.NETFrameworkintheSystem.ServiceModelnamespace.

    Inthe.NETtab,clicktheComponentNamecolumntitletosortthelistofassembliesinalphabeticalorder,andthenlocateandselecttheSystem.ServiceModelassembly.

    ClicktheOKbuttontoaddthereference.YoushouldnowseeSystem.ServiceModellistedundertheReferencesfolderinyourproject,meaning

    thatwhatevertypesaredefinedinthatassemblyarenowavailableforyoutouseinyourcode.

    ObjectBrowserVisualStudiosObjectBrowserwindowallowsyoutobrowseandviewthecontentofassemblies.

    InSolutionExplorer,doubleclickontheSystem.ServiceModelreferencethatyoujustadded.YoushouldseetheObjectExplorerwindowopen,andtheSystem.ServiceModelassemblyshouldbe

    selected

    in

    the

    list

    of

    assemblies

    to

    the

    left

    side

    of

    the

    screen.

    Similar

    to

    the

    .NET

    tab

    in

    the

    add

    referencedialog,thislistshowsassembliesthatareprovidedbythe.NETFrameworkaswellasother

    assembliesthatyoumayhavereferencedinyourproject.Atthetopofthedialogisatoolbarwitha

    dropdownlistwhichallowsyoutoapplyfilterstothelistofassembliesthataredisplayed.

    IntheBrowsedropdownlist,select.NETFramework4tofilterthelistofassembliestoonlythoseassembliesavailableinthatversionofthe.NETFramework.

  • 7/28/2019 Visual Studio Study Material

    14/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page14

    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.

  • 7/28/2019 Visual Studio Study Material

    15/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page15

    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.ActivationassemblyInObjectBrowsertoolbar,clicktheAddtoReferencesinSelectedProjectinSolutionExplorerbutton.

    ObjectBrowsercanbeveryuseful.Ifyouhaveanideaaboutwhatyouneedthenitcanallowyouto

    easilybrowsedetailedinformationaboutthings,and,havingconfirmedwhatyouneed,youcanadda

    referencetotherequiredassembly.

    Objectbrowserisalsoagreatwaytolearnaboutthecapabilitiesofthings,becauseitmakesiteasyto

    viewdetailedinformationaboutmethods,parameters,returnvalues,enumerations,andlotsofother

    things.

    CloseObjectBrowserbyclickingonthecrossiconinitsmaintab.

  • 7/28/2019 Visual Studio Study Material

    16/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page16

    ProjectPropertiesEachprojectthatyoucreateincludesmanyoptionswhichallowyoutodefinelotsofdifferentthings.

    Theseoptions,morecommonlyreferredtoasprojectproperties,allhavedefaultvaluesandcanbe

    customizedthroughtheProjectPropertiesdialogs.

    InSolutionExplorer,rightclickontheIntroToVisualStudioproject(itllbeshowninboldtextimmediatelybelowthesolution)andfromthecontextmenuselectProperties.

    Theprojectpropertiesdialoghasvarioustabsdownthelefthandside.

    CheckthattheApplicationtabisselected.Letstakealookthroughthevarioustabpagesandexplorewhatoptionsareavailabletoyou.Thereare

    lotsofoptions,sowelljustpickoutsomeofthemoreimportantones.

    ApplicationThetabsthataredisplayedwillvarybasedonthetypeofapplicationthatyouareworkingon.Were

    currentlyworkingonaWindowsFormsApplication,soyoushouldseetabsthatlooksomethinglikethis:

    Mostprojectscreateoneassembly,andthatassemblycaneitherbeanexecutableprogramoraclass

    library.Theassemblynameandoutputtypefieldsdeterminethenameoftheassemblythatiscreated

    bytheproject,withtheoutputtypebeingusedtodeterminethefileextension(.exeor.dll).

    Thedefaultnamespacedeterminesthenamespacethatisinsertedintoanynewsourcefilesthatare

    addedtotheproject.Whenusingmostprojecttemplates,theassemblynameanddefaultnamespace

    defaulttothenameoftheprojectthatyoucreate,andbythetimeanewprojecthasbeencreated,the

    defaultnamespacewillalreadyhavebeenusedinwhateversourcefilesareaddedtotheprojectbythe

    projecttemplate.So,ifyouchangethedefaultnamespaceyouwillusuallywanttoreviewanyexisting

    sourcefilesintheprojectandchangethenamespaceusedinthosefiles.

  • 7/28/2019 Visual Studio Study Material

    17/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page17

    Theassemblyinformationfile(AssemblyInfo.dbl)wasdiscussedearlier.YoullnoticetheAssembly

    Informationbuttonthatallowsyoutoeditthecontentofthefilethroughasimpleuserinterface.

    OneofthemostimportantsettingsforanapplicationistheTargetframework,whichdeterminesthe

    versionofthe.NETframeworkthattheassemblywillbebuiltfor.Synergy.NETprojectswilldefaultto

    eitherthe

    .NET

    Framework

    4.0,

    or

    the

    .NET

    Framework

    4.0

    Client

    Profile.

    The

    client

    profile

    is

    asmaller

    versionofthe.NETFramework4.0whichiscommonlyfoundondesktopPCsandlaptops;ithassomeof

    thefeaturesofthefullframeworkremoved.ThesefeaturesincludethingsliketheASP.NETweb

    componentswhicharetypicallyonlyrequiredonserversystems.Youcanchangethetargetframework

    toanearlierversionifyouwish,whichcouldforexamplehelpwithdeploymentbecausemostsystems

    willhaveV2.0oftheFrameworkalreadyinstalled,butmaynothave4.0.Howeverbydoingthisyoumay

    berestrictingthecapabilitiesofyourapplication,becausesomefeaturesofthecurrent.NETFramework

    willnotbeavailableforyoutouse.AbetterapproachistotargetthelatestversionoftheFramework,

    andsetupyourdeploymentpackagesorprocedurestoinstallthelatestFrameworkifrequired.

    The

    Output

    type

    setting

    allows

    you

    to

    specify

    the

    type

    of

    assembly

    being

    created;

    either

    a

    Windows

    Application,ConsoleApplicationorClassLibrary.Generallythissettingwillbesetcorrectlybythe

    projecttemplatethatyouuse,andwontneedtobechanged.

    Youcanalsosetanapplicationicononthistabpage.Doingsowillcausetheiconfiletobeaddedtothe

    project,andembeddedasaresourceinthetargetassembly.Selectinganapplicationicondoesnot

    causethaticontobedisplayedatthetopleftofanyformsthatyoumayaddtoaproject.Ifyouwantto

    usetheicononformsthenyoumustseteachformsIconpropertyalso.

    BuildEventsSwitchtotheBuildEventstab

    TheBuildEventstaballowsyoutospecifybuildconfigurationinstructions.Youcanalsospecifythe

    conditionsunderwhichanypostbuildeventsarerun.Notethefollowing:

  • 7/28/2019 Visual Studio Study Material

    18/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page18

    Buildevents(specifiedinthePrebuildeventcommandlineandPostbuildeventcommandlinefields)canincludeanycommandthatisvalidatacommandpromptorina.batfile.

    Ifyouspecifya.batfile,thenameofthefileshouldbeprecededby"call"(withoutquotes)toensurethatallsubsequentcommandsareexecuted.Forexample:callC:\MyFile.bat.

    The%characterisreservedforMSBuild,soifyouspecifyanenvironmentvariable,replaceeach%withthe%25escapesequence.Forexample,replace%MY_VAR%with%25MY_VAR%25.

    Ifyourprebuildorpostbuildeventdoesnotcompletesuccessfully,youcanterminatethebuildbyhavingyoureventactionexitwithacodeotherthanzero(whichindicatesasuccessful

    action).

    CompileSwitchtotheCompiletab

    OnthecompiletabyoucandeterminewhichSynergy.NETcompiler(dblnet)optionsareusedwhenthe

    projectisbuilt.TheCompilercommandlineboxtowardsthetopoftheformdisplaysasummaryofthe

    actualcommandlineoptionsthatwillbeused,andtheotherfieldsontheformallowyoutodetermine

    whatthoseoptionsshouldbe.Asyoucansee,therearesomecompileroptionsthatareusedbydefault.

    TherearespecificUIcontrolsontheformtoallowyoutosetorunsetsomeofthemorecommonlyused

    compileroptions,

    and

    the

    Other

    options

    field

    allows

    you

    to

    specify

    any

    other

    compiler

    options

    that

    are

    notspecificallysupportedbycontrolsontheform.

    EnvironmentVariablesSwitchtotheEnvironmentVariablestab

  • 7/28/2019 Visual Studio Study Material

    19/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page19

    Theenvironmentvariablestaballowsyoutospecifyenvironmentvariablesthataretobesetwhenthe

    projectisopened.TheseenvironmentvariableswillbeinplaceduringdevelopmentinVisualStudio,and

    alsowhenyouexecuteutilitiesoryourapplicationfromtheVisualStudioenvironment.

    Itis

    possible

    to

    refer

    to

    the

    translation

    of

    one

    environment

    in

    the

    value

    of

    another,

    using

    the

    syntax

    $(ENVVAR).Forexample,ifyouhadoneenvironmentvariablecalledROOTthattranslatedtoafolder

    path,andyouwantedtosetanothervariablecalledDATthattranslatedtoafoldercalledDATbelowthe

    ROOTfolder,youcouldexpressthevaluefortheDATenvironmentvariableas$(ROOT)DAT.Thiswould

    ofcourseassumethatthevalueoftheROOTvariablewasterminatedwithatrailingbackslashcharacter.

    TheenvironmentwithinVisualStudioincludesseveralpredefinedmacrosthatcanbeusedwhen

    settingenvironmentvariables.Forexamplethemacro$(SolutionDir)translatestothefolder

    specificationofthecurrentsolutionfile,and$(ProjectDir)translatestothelocationofthecurrent

    projectfile,whichmayormaynotbethesameasthesolutionfolder.Asyoucanseeinthescreenshot

    above,you

    can

    also

    refer

    to

    these

    macros

    when

    setting

    environment

    variables

    in

    your

    project.

    The

    table

    belowshowsalistofsomeoftheavailablemacros:

    Macro TranslatesTo Example

    $(Configuration) Thenameofthecurrent

    projectconfiguration.

    Debug

    $(OutDir) Pathtotheoutputfile

    directoryrelativetothe

    projectdirectory.Thispath

    shouldhave

    atrailing

    slash.

    Thisresolvestothevaluefor

    theOutputDirectory

    property.

    bin\Debug\

    $(ProjectDir) Thedirectoryoftheproject

    (definedasdrive+path);it

    c:\temp\MyTestApp\

  • 7/28/2019 Visual Studio Study Material

    20/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page20

    includesthetrailing

    backslash.

    $(ProjectExt) Thefileextensionofthe

    project.Itincludesthe'.'

    beforethe

    file

    extension.

    .synproj

    $(ProjectFileName) Thefilenameoftheproject

    (definedasbasename+file

    extension).

    MyTestApp.synproj

    $(ProjectName) Thebasenameoftheproject. MyTestApp

    $(ProjectPath) Theabsolutepathnameof

    theproject(definedasdrive

    +path+basename+file

    extension).

    c:\temp\MyTestApp\MyTestApp.synproj

    $(RootNameSpace) Thenamespace,ifany,

    containingtheapplication.

    MyTestApp

    $(SolutionDir) Thedirectoryofthesolution

    (definedasdrive+path);it

    includesthetrailing

    backslash.

    c:\temp\MyTestApp\

    $(SolutionExt) Thefileextensionofthe

    project.It

    includes

    the

    '.'

    beforethefileextension.

    .sln

    $(SolutionFileName) Thefilenameofthesolution

    (definedasbasename+file

    extension).

    MyTestApp.sln

    $(SolutionName) Thebasenameofthe

    solution.

    MyTestApp

    $(SolutionPath) Theabsolutepathnameof

    thesolution

    (defined

    as

    drive

    +path+basename+file

    extension).

    c:\temp\MyTestApp\MyTestApp.sln

    $(TargetDir) Thedirectoryoftheprimary

    outputfileforthebuild

    (definedasdrive+path);it

    c:\temp\MyTestApp\bin\Debug\

  • 7/28/2019 Visual Studio Study Material

    21/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page21

    includesthetrailing

    backslash.

    $(TargetExt) Thefileextensionofthe

    primaryoutputfileforthe

    build.It

    includes

    the

    '.'

    before

    thefileextension.

    .exe

    $(TargetFileName) Thefilenameoftheprimary

    outputfileforthebuild

    (definedasbasename+file

    extension).

    MyTestApp.exe

    $(TargetName) Thebasenameofthe

    primaryoutputfileforthe

    build.

    MyTestApp

    $(TargetPath) Theabsolutepathnameof

    theprimaryoutputfilefor

    thebuild(definedasdrive+

    path+basename+file

    extension).

    c:\temp\MyTestApp\bin\Debug\MyTestApp.exe

    Bearinmindthattheenvironmentvariablesthatyouspecifythroughtheprojectpropertiesdialogsare

    onlypresentinyourdevelopmentenvironment.Ifyouusethismechanismtospecifyvaluesfor

    environmentvariablesthatarerequiredatapplicationruntime(outsideofVisualStudio)thenyoumust

    provide

    those

    environment

    variables

    via

    some

    other

    mechanism.

    SigningSwitchtotheSigningtab

  • 7/28/2019 Visual Studio Study Material

    22/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page22

    Thesigningtaballowsyoutospecifythattheassemblycreatedbytheprojectshouldbedigitallysigned.

    Tosigntheassemblies,checktheSigntheAssemblycheckboxandthenselectthestrongnamekeyfile

    thatyouwishtousetosigntheassembly.

    Onceyouhaveenabledsigning,thereisanoptionintheChooseastrongnamekeyfiledropdownlist

    whichallows

    you

    to

    create

    anew

    key

    file.

    This

    is

    done

    using

    the

    .NET

    Frameworks

    strong

    name

    utility

    (sn.exe).

    Werenotgoingtogetintoassemblysigningherebecauseitsalargeandcomplexsubjectarea,butitis

    definitelysomethingthatyouneedtolearnaboutbeforeyourelease.NETapplicationstocustomers.

    ReferencePathsSwitchtotheReferencePathstab

    TheReferencePathstaballowsyoutospecifyfoldersthatwillbesearchedwhentheprojectsystem

    needstolocateareferencedassembly.Whentheprojectsystemfindsanassemblyreference,itresolves

    thereferencebylookinginthefollowinglocations,inthefollowingorder:

    Theprojectdirectory.TheprojectdirectoryfilesappearinSolutionExplorer. Directoriesspecifiedonthispage(ReferencePaths). DirectoriesdisplayingfilesintheAddReferencedialogbox. Theproject'sobjdirectory.(AssembliescreatedbyaddingCOMreferencestoyourprojectare

    addedtotheproject'sobjdirectory.)

  • 7/28/2019 Visual Studio Study Material

    23/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page23

    BuildSwitchtotheBuildtab

    Thebuildtaballowsyoutospecifyvarioussettingsrelatedtohowyourassemblyisbuilt.Eachproject

    thatyou

    create

    includes

    several

    configurations

    and,

    when

    working

    in

    the

    project,

    you

    always

    have

    one

    oftheseconfigurationsselected.Bydefaultthereisadropdownlistonthemaintoolbarwhichallows

    youtoeasilyswitchtoadifferentconfiguration.Mostprojectshavetwoinitialconfigurationsdefined,

    calledDebugandRelease,andthedefaultisusuallytheDebugconfiguration.

    AtthetopoftheformyouwillseeadropdownlistwhichallowsyoutoselecttheConfigurationto

    modify.Changesthatyoumakeinthelowerhalfoftheformareappliedtothatconfiguration.Youneed

    torememberthisbecauseifyouremakingachangetooneconfiguration,thenyoumaywanttomake

    correspondingchangestootherconfigurationsalso.Infact,ifthisisthecase,youcanselectAll

    Configurationsintheconfigurationdropdownlist,andthechangesthatyoumakewillthenbeapplied

    toall

    configurations.

    The

    Platform

    field

    is

    not

    used

    in

    Synergy

    .NET

    projects

    and

    should

    be

    ignored.

    Platformtargetallowsyoutospecifytheprocessortobetargetedbytheassembly.Selectx86totarget

    32bitplatforms,selectx64totarget64bitplatforms,orselectAnyCPUfortheassemblytobeplatform

    agnostic.

    Outputpathallowsyoutodeterminewheretheassemblycreatedbytheproject(ormorespecifically

    theprojectconfiguration)willbestored.Asyoucanseethedefaultlocationisinabin\Debug(or

    bin\Release)folderbelowtheprojectfolder.

    TheXMLdocumentationfileoptionallowsyoutoenablethecreationofanXMLfilewhichcontainsAPI

    documentationfor

    the

    code

    in

    your

    project.

    The

    information

    in

    the

    file

    is

    derived

    both

    from

    the

    actual

    codeintheproject,aswellasfromanydocumentationcommentsthatyoumayhaveincludedinthe

    code.OnceyouhavetheXMLdocumentationfilethereareseveralproductsonthemarketthatcan

    transformtheinformationinthefileintovarioustypesofdocumentation.

    TheDebug/Optimizecodeoptionallowsyoutospecifywhethertousejustintime(JIT)optimization,

    andspecifiesthelevelofdebugandstacktraceinformationthatwillbeavailable,whichaffects

    performance.Theoptioncanbesettothefollowingvalues:

  • 7/28/2019 Visual Studio Study Material

    24/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page24

    IncludeslessdebuginformationintheassemblythanisincludedbytheDebugsetting,

    andonlyincludeslimitedlinenumberlistingsfortracebacks,butincludesmore

    informationthantheOptimizesetting.ThisisthedefaultsettingforRelease

    configurations.

    Debug

    Fulldebugging

    information

    is

    included

    in

    the

    assembly.

    This

    is

    the

    default

    setting

    for

    Debugconfigurations.

    Optimize Includestheleastamountofdebugginginformationintheassembly,resultinginthe

    bestperformance.EnablesJIToptimization.Thisoptionisrecommendedforproduction

    code.

    TheGenerateserializationassemblyoptiondetermineswhetherthecompilerwillusetheXML

    SerializerGeneratorTool(sgen.exe)tocreateXMLserializationassemblies.Serializationassembliescan

    improvethestartupperformanceofXmlSerializerifyouhaveusedthatclasstoserializetypesinyour

    code.Theoptioncanbesettooneofthefollowingvalues:

    Auto

    (default)

    SerializationassemblieswillbegeneratedonlyifyouhaveusedXmlSerializertoencode

    typesinyourcodetoXML.

    Off Serializationassemblieswillneverbegenerated,regardlessofwhetheryourcodeuses

    XmlSerializer.

    On Serializationassemblieswillalwaysbegenerated.

    ItshouldbenotedthatduetoaVisualStudioissue,settingtheGenerateserializationassemblytoOn

    mightnotresultinaserializationassembly,evenifthereareserializabletypesintheproject.Thereisan

    articleon

    Microsoft

    Connect

    (bug

    id

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

  • 7/28/2019 Visual Studio Study Material

    25/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page25

    DebugSwitchtotheDebugtab

    TheoptionsontheDebugtabareusedtosetpropertiesforthebehavioroftheprojectwhenthe

    debuggerisstarted.Aswiththebuildoptions,itispossibletospecifydifferentdebuggersettingsbased

    onthecurrentlyselectedconfiguration,andagainthePlatformfieldisnotusedwithSynergy.NET

    projectsandshouldbeignored.

    TheoptionsunderStartActionareusedtosettheitemtobestartedwhenthedebuggingbegins,and

    canbesettooneofthefollowing:

    Startproject

    (default)

    Specifies

    that

    the

    executable

    for

    the

    project

    should

    be

    started

    when

    the

    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.

  • 7/28/2019 Visual Studio Study Material

    26/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page26

    TheUseremotemachine,Enableunmanagedcodedebugging,EnableSQLServerdebuggingand

    EnabletheVisualStudiohostingprocessoptionsarenotimplementedinSynergy.NETprojectsand

    shouldbeignored.

    SettingsSwitchtotheSettingstab

    Youvealreadyseenthesettingstabearlier,whenwewereintroducingtheSettings.settingsfile.When

    youclickedonthefileyouwerepresentedwiththevisualdesignerfortheprojectsettingsfile,andthat

    samedesignerisavailableviatheprojectpropertiesdialogsalso.

    ResourcesSwitchtotheResourcestab

    Andyouveseentheresourcestabbeforealso,whenwediscussedtheprojectsResources.resxfile

    earlier.Again,thedesignerforthefileisalsoavailableviatheprojectpropertiesdialogs.

    Closetheprojectpropertiesdialogbyclickingtheclose(cross)iconinthemaintabbar.Ifyouvemadeanychangesthenyoumaybepromptedtosaveyourchanges.

  • 7/28/2019 Visual Studio Study Material

    27/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page27

    BuildingtheProjectVisualStudio2010utilizesanexternalbuildsystemcalledmsbuildtoperformbuildoperations.Almost

    allprojectshavetheconceptofabuildwhichistheprocessofgeneratingwhatevertheoutputofthe

    projectis,generallya.NETassembly,fromwhatevertheinputforthebuildis,generallysourcecode.

    Youdont

    need

    to

    do

    anything

    special

    to

    define

    what

    happens

    during

    abuild

    other

    than

    configuring

    the

    contentoftheproject,whichinmostcasesinvolvesaddingsourcefilesandsourcecodetotheproject.

    HoweverthereareothertypesofprojectthatVisualStudiosupports.Forexample,thereareproject

    templatestoallowyoutocreateWindowsInstallerinstallationpackages(msifiles),aswellasvarious

    otherthings.

    Butmostprojectshaveabuildoption,andthatshowyoucausetheprojectoutputtobegenerated

    (assumingthatyouhavenoerrorsofcourse!).Basedontheprojecttemplate,VisualStudioknowsHOW

    tobuildthetargetoutput.InthecaseofaSynergy.NETproject,itknowstobuildadblnetcommand

    lineusingthevariousoptionsspecifiedintheprojectpropertiesdialogsandusingalistofallthesource

    filesand

    assembly

    references

    defined

    in

    the

    project.

    Then

    it

    executes

    this

    command

    and

    displays

    the

    resultingoutput.

    TheOutputWindowGenerallytheoutputfromabuildisdisplayedinoneortwoplacesdependingonwhetherthebuildwas

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

    should

    see

    the

    output

    window

    become

    focused,

    and

    output

    similar

    to

    this:

    Buildstarted:Project:IntroToVisualStudio,Configuration:DebugAnyCPU ==========Build:1succeededoruptodate,0failed,0skipped==========

    Thisoutputindicatesthattheprojectwasbuiltsuccessfully.

  • 7/28/2019 Visual Studio Study Material

    28/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page28

    ErrorListWindowTodemonstratewhathappenswhenthereisanerror:

    InSolutionExplorer,doubleclickonForm1.dbltodisplaytheformsgraphicaldesigner.DoubleclickinsidethebodyoftheformtoopenthecodeeditorwindowandpositionyourcursorintheForm1_Loadmethod.Somewhereintheproceduredivisionofthemethod,addsomeinvalidcodeanything.Adding

    thewordsjunkcodewouldworkquitenicely!

    TypeCtrl+Shift+Btobuildtheproject.Itisnotnecessarytomanuallysaveyourchanges,becauseVisualStudiowillautomaticallydothateach

    timeyoudoabuild,orexecute,ordebug.

    Againyoushouldinitiallyseethecompileroutputintheoutputwindow,butwhenthecompiler

    completeswith

    an

    error,

    the

    error

    list

    window

    should

    be

    displayed,

    and

    should

    contain

    the

    details

    of

    the

    errorsthatwerereportedbythecompiler.Youreprobablylookingatsomethinglikethis:

    Thewindowdisplaystheerrors,warnings,informationalmessagesemittedbythecompiler,aswellas

    informationaboutthefileinwhichtheerroroccurred,thelinenumber,andthenameoftheproject.

    If

    you

    only

    want

    to

    look

    at

    a

    certain

    type

    of

    message

    (errors

    vs.

    warnings

    for

    example)

    then

    you

    can

    filter

    thecontentofthelistbyclickingonthevariousbuttonsinthesmalltoolbarabovetheerrorlist.

    Thelistisalsoactive;inthatyoucandoubleclickonmessagesinthelisttotakeyoutothepointofthe

    problem.Todemonstratethis:

    ClosetheForm1.dblsourcefilebyclickingontheclose(cross)iconinitsmaintab.Doubleclickonthefirsterrorlineintheerrorlistwindow.

    Youshouldseethesourcefilebereopened,andyourcursorbepositionedatthelinewiththeproblem

    dontfixitjustyet!

  • 7/28/2019 Visual Studio Study Material

    29/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page29

    TaskListVisualStudiohasanotherusefulwindowcalledtheTaskList.Itsprobablyalreadydisplayedinthesame

    tabsetastheoutputanderrorlistwindows,but,ifnot,then:

    DisplaythetasklistbyselectingView>TaskListfromthemenu(orbytypingCtrl+\andthenT)Thetasklistwindowhastwomodesdeterminedbythedropdownlistinitssmalltoolbar.

    MakesurethatthedropdownlisthastheUserTasksoptionselected.WithUsertasksselected,adevelopercanmanuallycreateatodolistbyclickingontheCreateUser

    Taskbuttonandenteringthedetailsofthetaskinthelist.Taskscanthenbecheckedoffonce

    completed,ordeletedbyrightclickingonthetaskandselectingDelete.

    ClickontheCreateUserTaskbuttoninthetaskliststoolbar.TypeanewtaskperhapssomethinglikeMakethisapplicationactuallydosomething!andhitenter.Markthetaskascompletebyclickingitscheckbox.DeletetheusertaskbyrightclickingitandselectingDelete(orbyselectingthetaskand

    pressingDelete).

    Whilecreatingusertasksinaprojectcanbeuseful,whatismoreusefulistheoptiontocreatetodo

    commentsinyourcode.Thesearecomments,withaspecialformat,thatadevelopercanplaceintoa

    sourcefile,thatwillshowupinthetasklistwindow.

    IntheForm1.dblcodeeditor,addacommentlikethisafterthebadcode:;TODO:Thisneedsfixing!

    Inthetasklistwindow,changethedropdownlistfromUserTaskstoComments.

    Youshould

    see

    the

    comment

    that

    you

    entered

    displayed

    in

    the

    Task

    List.

    The

    TODO:

    prefix

    that

    you

    typediswhatdeterminesthatthecommentshouldbedisplayedinthisway.

    BackintheForm1.dblsourcecodeeditor,removetheTODOcomment,andthebadcode.Performabuildtoensurethattheapplicationisinagoodstate(Crtl+Shift+B).

  • 7/28/2019 Visual Studio Study Material

    30/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page30

    ExecutingaProjectDependingonthetypeofprojectthatyoureworkingon(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

    resourcefile

    string.

    Even

    clicking

    the

    button

    doesnt

    do

    anything!

    Lets

    change

    that:

    Closetheapplication. DisplaytheForm1designerwindow. Doubleclickonthebutton.

    WhenyoudoubleclickonacontrolVisualStudiotakesyoutothecodeforthedefaulteventforthat

    control.Ifthatcodedoesntexist,thenVisualStudiowillinsertanewemptyeventhandlermethodfor

    theevent.ThedefaulteventforabuttonistheClickevent,soyoushouldnowbelookingatthe

    button1_Clickmethod,whichlookslikethis:

    Inthedatadivision,addarecordandthreeintegerfields,likethis:

  • 7/28/2019 Visual Studio Study Material

    31/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page31

    Intheproceduredivision,addthefollowingcode:

    Thepointofthisexerciseisjusttogiveussomecodethatwecaninteractwithinthedebuggerlater.

    UsingtheDebuggerInVisualStudiothedebuggeriscompletelyembeddedwithinthedevelopmentenvironment,makingit

    mucheasiertostepthroughcodeandexaminedata.Thedebuggerhasmanyfeatures,sowelljusttake

    abrieflookatsomeofthemorefundamentalthingsthatyoucando.

    BreakpointsworkinmuchthesamewaythatyouwouldexpectintraditionalSynergy,butareeasierto

    workwithasaresultofthegraphicalnatureofthewaythattheyareset,clearedandvisualized.

    Codeeditorwindowsallhaveasmallregionattheleftmarginwherebreakpointscanbeset.Toseta

    breakpointatacertainpositionyousimplyclickinthisregion,andyouwillseeavisualrepresentation

    ofthebreakpoint,likethis:

    Thered

    circle

    indicator

    in

    the

    breakpoint

    region

    indicates

    that

    abreakpoint

    is

    set

    at

    that

    position.

    If

    you

    executetheapplicationindebugmodethenexecutionwillbeinterruptedatthatpoint.

    Itisalsopossibletohavebreakpointssetinyourproject,butdisableoneormoreofthosebreakpoints

    sothattheywillnotfirewhileyouaredebugging.Todisableabreakpointrightclickonthebreakpoint

    indicatorandselectDisableBreakpoint.Disabledbreakpointslooklikethis.

    ReenableadisabledbreakpointbyrightclickingthebreakpointindicatorandselectingEnable

    Breakpoint.Youcanalsotogglebetweenanenabledanddisabledstatebyplacingyourcursoronthe

    sourcelineandpressingCtrl+F9.

    ItisalsopossibletodisableorenableallbreakpointsviaitemsontheDebugmenu.

  • 7/28/2019 Visual Studio Study Material

    32/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page32

    Ifyouwishtoremovethebreakpoint,simplyclickonthebreakpointindicator,orrightclickitandselect

    DeleteBreakpoint.

    Intheconstructormethod,Form1,addabreakpointonthestatementthatcallstheInitializeComponentmethod,likethis:

    Alsoaddabreakpointonthebutton1_Clickmethod,likethis:

    Thereis

    also

    an

    easy

    way

    to

    examine

    all

    of

    your

    current

    breakpoints

    using

    adebugger

    tool

    window.

    Fromthemenu,selectDebugger>Windows>Breakpoints,orpressCtrl+Alt+B.

    YoushouldseetheBreakpointswindowwhichlistsallofthebreakpointsthatyoucurrentlyhaveset.

    Doubleclicking

    on

    abreakpoint

    in

    the

    list

    will

    take

    place

    your

    cursor

    on

    the

    associated

    line

    of

    code,

    and

    youcanalsoeasilyadd,remove,enableanddisablebreakpointsthroughthiswindow.

    ExecutetheapplicationbypressingF5(StartDebugging).Asanalternative,youcanalsousetheStartDebuggingtoolbarbutton,whichlookslikethis .

    WhenyoustartdebuggingyoumaynoticethatthelayoutoftheVisualStudiouserinterfacechanges.

    Visualstudiomaintainsdifferentwindowlayoutswhenindebuggingmode,andbydefaultshowsyou

    severalwindowswhichareusefulduringthedebuggingprocess.Youcancustomizethewindowlayouts

    likewedidearlier.

    Youwontseetheapplicationonthescreenyet,becausewesetabreakpointintheconstructor

    method,andtheformhasnotyetbeeninitialized.Whatyoushouldseeissomethinglikethis:

  • 7/28/2019 Visual Studio Study Material

    33/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page33

    Theyellowarrowiconoverthebreakpointindicatorandtheyellowhighlightonthecodeindicatesthat

    abreakpointwasencountered,andVisualStudiohashandedcontrolbacktoyou.Fromthispointon

    youcandeterminewhathappens,usingthesamesortoftechniquesthatyouwouldifyouwere

    debuggingintraditionalSynergy.

    Youcan

    control

    the

    flow

    of

    execution

    using

    commands

    like

    Step

    Into

    (F11),

    Step

    Over

    (F10),

    Step

    Out

    (Shift+F11)andContinue(F5).TheseoptionsareavailableontheDebugmenucolumn,andalsohave

    correspondingiconsontheDebugtoolbar,whichshowsupwhenyoustartthedebugger.Itlookslike

    this:

    StepINTOtheInitializeComponent()methodbypressingF11,orbyclickingthe toolbarbutton.

    StarttostepthroughthemethodbypressingF10afewtimes,orbyclickingthe toolbarbutton.

    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.

  • 7/28/2019 Visual Studio Study Material

    34/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page34

    PresstheF10keyagaintoexecutethefirstassignmentstatementandsteptothenextstatement.

    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.

  • 7/28/2019 Visual Studio Study Material

    35/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page35

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

    DefiningexpressionsintheWatchwindowcanbeaveryusefultechniquewhendebuggingcomplex

    problems.

    PressShift+F5tostopthedebugger. PressCtrl+Shift+F9andclicktheYesbuttontoremoveallbreakpoints.

    TheVisualStudiodebuggingenvironmentisverypowerful,andthishasonlybeenaVERYbrief

    introductiontoitsmostbasicfeatures.

  • 7/28/2019 Visual Studio Study Material

    36/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page36

    WorkingwithSourceCodeYouhaveseentheSynergy.NETsourcecodeeditorafewtimesnow,butsofarwehaventreally

    exploreditscapabilities.Letsdothatnext.

    Asyouwouldexpect,thesourcecodeeditorisalsoaverypowerfultool.Itisbothlanguageandcontext

    sensitive,and

    can

    help

    you

    write

    code

    correctly

    first

    time,

    layout

    that

    code

    in

    an

    appropriate

    way,

    and

    in

    manycasescanactuallywritesomeofthecodeforyou.

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

    wewould

    typically

    need

    to

    fully

    name

    each

    type

    that

    we

    wish

    to

    use,

    each

    time

    we

    reference

    it.

    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

    assemblyand

    we

    are

    going

    to

    use

    the

    types

    in

    that

    assembly

    frequently,

    we

    have

    the

    option

    of

    importingthenamespaceofthetypesthatwewishtouse.Importingthenamespacemakesthe

    compilerawareofthetypesinthenamespace,andmeansthatwedonthavetofullynamethetypes

    eachtimeweneedtorefertothem(unlessthereisaduplicatetypeintwoormorenamespacesthatwe

    haveimported).

  • 7/28/2019 Visual Studio Study Material

    37/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page37

    So,wecouldimportthenamespacebyaddingcodelikethisattheverytopofthesourcefile:

    importMyUtils

    Andthenwecouldwritethecodethatusesthosetypeswithoutmentioningthenamespace:

    paymentDue=DateUtils.AddDays(invoiceDate,30)

    InthecodeeditorforForm1.dbl,abovethenamespacedefinitionandwiththeexistingimportstatements,addanewimportfortheSystem.Diagnosticsnamespace,likethis:

    Scrolldownintothebutton1_ClickmethodandremovethenamespaceprefixfortheDebugclass,likethis:Importinganamespaceistotallyoptional,butcanmakethecodethatusesthetypesinthatnamespace

    muchlessverbose.

    IntelliSenseWhenyouweretypingtheimportstatementabove,youmayhavenoticedthatafteryoutyped

    importSystem.

    something

    happened.

    You

    probably

    saw

    something

    like

    this:

    WhathappenedwasaVisualStudiofeaturecalledIntelliSenserecognizedwhatyouweretyping,and

    steppedintohelp.Inthiscase,IntelliSenserecognizedthatyouwerenotcurrentlyinsideanamespace,

    andhad

    started

    to

    type

    an

    import

    statement.

    IntelliSense

    knows

    that

    ifyou

    have

    typed

    an

    import

    statement,thenyoualsoneedtoaddanamespace,soitpresentedyoualistofallofthenamespaces

    thatwerecurrentlyavailableinyourproject(basedontheprojectitself,andtheassembliesthatyou

    havereferenced).

    Whenthishappens,youcancontinuetotype,inwhichcasethelistofoptionswillgetgraduallyfiltered

    downtomatchthecharactersthatyouhavetypedsofar:

  • 7/28/2019 Visual Studio Study Material

    38/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page38

    Atany

    time

    during

    this

    process

    you

    can

    use

    the

    arrow

    keys

    or

    mouse

    to

    select

    asuggested

    value,

    and

    thenpressenter, tab,orspacetoinsertthatvalueintoyourcode.Ifyoudontwanttheassistancethen

    youcanhittheescapekeytoclosetheIntelliSensepromptsandofcourseyoucanjustignorewhat

    itsdoingandkeeptyping.

    IntelliSenseiscontextsensitive,sonomatterwhereyouareworkinginapieceofcodeyoumayfind

    thatitjumpsinthereandoffersshortcutstowhatyouretyping.Itcanhelpyoucompletethenamesof

    statements:

    Andtypes:

  • 7/28/2019 Visual Studio Study Material

    39/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page39

    Andvariables:

    Andparameters:

    IntelliSenseisverypowerful,butuntilyougetusedtoworkingwithit,canalsosometimesbealittle

    frustrating.Themainreasonforthisresultsfromthefactthatthespacekeyisoneofthewaysofasking

    IntelliSensetocompletewhatyoutyped.Forexampleifyouretypingsomething,andIntelliSenseis

    offeringyousomethingthatmatchesthecharactersthatyouhavetyped,youmightinstinctivelypress

    thespacebartoleavewhatyouhavetypedandmoveontothenextword,butIntelliSensestepsinand

    replaceswhatyouhavetypedwithwhatevermatchitwasdisplayingwhenyoupressedthespacebar.

    ThesolutiontothisistohittheescapekeytodismissIntelliSensebeforeyoupressthespacebar,butat

    firstthis

    can

    be

    alittle

    frustrating.

    However,

    it

    is

    well

    worth

    persevering

    and

    getting

    used

    to

    the

    way

    thatIntelliSenseworks,becauseonceyoumastertheartitcansaveyoualotoftyping.

    SnippetsAnotherfeaturethatcansaveyoualotoftyping,particularlywhenyouarewritingnewcode,isa

    featurecalledsnippets.AsnippetissimilarinconcepttoanaliasinWorkbench.Asnippetisapieceof

    predefinedandnamedcodethatisinsertedintotheeditbuffer,atthecurrentcursorposition,when

    thenameofthesnippetistypedfollowedbytwotabcharacters.Thefirsttabcharacterselectsthe

    snippet,andthesecondexpandsit.

    Visual

    Studio

    also

    presents

    snippets

    to

    you

    via

    IntelliSense,

    like

    this:

  • 7/28/2019 Visual Studio Study Material

    40/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page40

    Youcantellthatanitemisasnippetbecauseofits icon.

    Withasnippetselected,typeTABTABtoselectandexpandit.Forexample,theFORsnippetexpands

    likethis:

    Somesnippetsjustexpandtoapieceoffixedcode,butmostexpandtoapieceofcodethatincludes

    specialtokensthatareintendedtobereplacedwithsomeothervaluebytheprogrammer.Youcansee

    thesetokensintheexampleabove,theiwiththegreenbackgroundisthecurrentlyselectedtoken,and

    1,lengthand1withtheyellowbackgroundsareothertokenstobeselectedandreplaced.

    Withasnippettokenselected,simplytypethevaluethatyouwanttoinsert,thenpressTABtomoveon

    tothe

    next

    token

    or

    press

    ESCAPE

    to

    exit

    from

    token

    replacement

    completely.

    So,tofullyusetheFORsnippet,youcouldtype:

    forcount101 1

    Whichwouldresultinthefollowingcode:

    Whilethismayinitiallyseemcomplicated,whenyouactuallydoitintheeditoritisverynatural,andcan

    savetime.Anotherbenefitofusingsnippetsisthatyoureprettymuchguaranteedtoproducethe

    correctcodebecausethesnippetdoesalotoftheworkforyou.Tryitout:

    Placeyourcursorintheproceduredivisionofthebutton1_Clickmethod,aftertheDebug.Printstatement,onanewline

    Typeforandpresstabtwice. Typevar3andpresstabtwice(oncetodismissIntelliSense,oncetocompletethesnippet

    token).

    Typetabtoacceptthedefaultvalue1. Type10toinsertacustomvalue. Typetocompletethesnippetexpansion

  • 7/28/2019 Visual Studio Study Material

    41/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page41

    Noticehowwhenyoupressedtheescapekey,thecursormovedintothebeginendblock.Thatspartof

    thefunctionalityofthesnippetalso.

    RemovetheFORloopfromthecode.By

    the

    way,

    if

    you

    have

    blocks

    of

    code

    that

    you

    use

    frequently,

    then

    you

    can

    also

    create

    your

    own

    code

    snippetsandaddthemtoVisualStudio,butthatsalittlebeyondthescopeofourobjectivesforthis

    tutorial.

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

    Youcan

    also

    drag

    out

    aselection

    within

    the

    edit

    buffer

    and

    reformat

    just

    that

    selection

    using

    Format

    Selection,orCtrl+KthenCtrl+F.

    AddingnewItemsWhenyoufirstcreatedtheprojectthatyouhavebeenworkingonyouusedaProjectTemplate,which

    configuredanewprojectforaspecifictypeofdevelopmentproject.Whenitcomestimetoadd

    additionalitemstoaproject,youcanuseanothertypeoftemplate,thistimecalledanItemTemplate.

    Itemtemplatesprovideaneasywaytoaddvarioustypesoffilestoanexistingproject,andoften

    providedefaultcontentinthefilesthatareadded.

    Closeanyopenfilesbyclickingonthecloseicon(cross)inthetabforeachfile.IfyouarepromptedtosavechangesthenclickYes.

    InSolutionExplorer,rightclickontheIntroToVisualStudioproject(itstheoneinbold)andthenselectAdd>NewItem,ortypeCtrl+Shift+A.

  • 7/28/2019 Visual Studio Study Material

    42/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page42

    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.

  • 7/28/2019 Visual Studio Study Material

    43/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page43

    AddingExistingItemsAswellasaddingnewitemstoaproject,youcanaddexistingfiles.Infacttherearetwodifferentways

    toaddexistingfilestoaproject,onewhichplacesaCOPYoftheoriginalfiledirectlyinyourproject

    folder,andonewhichplacesaLINKtotheoriginalfileintoyourproject.

    Tocopy

    an

    existing

    file

    into

    your

    project,

    go

    to

    Solution

    Explorer

    and

    right

    click

    on

    the

    project,

    then

    selectAdd>ExistingItem.Usetheresultingfilebrowserdialogtolocateandselectthefileorfilesthat

    youwishtoaddandclicktheAddbutton.Remember,thismechanismmakesaCOPYofthefilesdirectly

    inyourprojectfolder.

    Analternativeistoaddlinkstotheexistingfiles,withoutcopyingthefilesintoyourproject.The

    procedureforthisissimilarexceptthatyouwillselectAdd>ReferenceExistingItem.Whenyouadd

    linkstoexistingitemsintoaproject,thefileisnotcopiedintoyourprojectfolder,butisincludedinthe

    compilationwhenyoubuildtheproject.

    OrganizingFiles

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

    ChangethefoldernametoModelsandpressenter. RightclickonthenewfolderandselectAdd>NewItem. EntertheinformationforanewClasscalledProduct.dblandclickAdd.

    Youshould

    see

    the

    new

    class

    added

    to

    Solution

    Explorer

    in

    the

    Models

    folder,

    and

    the

    new

    file

    should

    openinacodeeditorwindow.

    YouwillnoticethatthenamespaceusedforthenewitemisIntroToVisualStudio.Models.Youll

    rememberthatIntroToVisualStudiowasthedefaultnamespacefortheproject,andthatitemsthatyou

    addtotheprojectareplacedintothisnamespace.But,asyoucansee,whenanewitemisaddedtoa

    FOLDERintheproject,thedefaultbehavioristoaddtheitemtoanestednamespace,basedonthe

  • 7/28/2019 Visual Studio Study Material

    44/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page44

    nameoftheproject.Thisbehaviorisconsistentwithother.NETlanguagesandisgenerallyagoodidea.

    However,ifyoudontwanttomakeuseofnestednamespaces,thenyoujustneedtorememberto

    changethenamespacewhenyouaddnewitemsintoafolder.

    AddingProjectstotheSolutionSo

    far

    weve

    only

    considered

    developing

    with

    asolution

    containing

    asingle

    project.

    But

    very

    often

    when

    workinginVisualStudioyouwillworkwithsolutionscontainingseveralprojects,asyoustriveto

    organizeyourapplicationintologicalunitsthatcanbereusedfromotherplaces.

    Aswediscussedearlier,aprojectisusedtocreateasingleassembly(programorclasslibrary).

    Developerscommonlyorganizereusablecode(theequivalentoftraditionalSynergyssubroutine

    libraries)intoseparateassembliesandreferencethemfromtheprojectswhichusethetypesthatthey

    contain.

    Letslookatasimpleexample:

    InSolutionExplorer,rightclickontheIntroToVisualStudioSOLUTION(itstheoneattheverytop)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

    selectingSet

    As

    StartUp

    Project.

    Youhaveaddedaclasslibraryprojecttoyoursolution,anditcontainsasingledefaultclasscalled

    Class1.Werenotgoingtoworryaboutfunctionalityrightnow,becausethistutorialisabouthowtouse

    VisualStudiowithSynergy.NET,butwhatwedoneedtodoisshowhowtomodifytheapplication

    projecttohaveareferencetothenewclasslibraryproject,sothatitcanusethetypesinthelibrary.

  • 7/28/2019 Visual Studio Study Material

    45/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page45

    InSolutionExplorer,undertheIntroToVisualStudioproject,rightclickontheReferencesfolderandselectAddReference.

    IntheAddReferencedialog,selecttheProjectstab. SelectMyLibraryandclicktheOKbutton.

    YourIntroToVisualStudioprojectnowhasareferencetoyourMyLibraryclasslibraryassembly,andcan

    useanypublictypesinthatassembly.

    UsingtheCodeConverterSynergy.NETincludesacodeconverterutilitywhichiscapableoftranslatingC#syntaxtotheequivalent

    Synergy.NETsyntax.

    SelectTools>C#toSynergyCodeConverterfromthemenu.

    Tousethecodeconverter,eithertypeorpastetheC#codethatyouwishtoconvertintotheboxonthe

    left,andthenclickthetranslatebutton .Thetranslatedcodeisplacedintoyourclipboardsothatyou

    canpasteitintoasourcefile.

    ThecodeconvertercanbeveryusefulwhenlearninghowtoprogramsomethinginSynergy.NET

    becausetherearemanyC#codeexamplesintheVisualStudiodocumentationandontheInternet,

    generally.

    Thecodethatyouplaceintheleftboxmustbeacompletepieceofcodeinanamespace.Pastingsmall

    snippetsofcodeintotheconverterwillnotwork.

  • 7/28/2019 Visual Studio Study Material

    46/47

    IntroductiontoVisualStudio2010

    IntroductiontoVisualStudio2010 Page46

    ThecodeconverterhasbeensubstantiallyimprovedsincetheinitialreleaseofSynergy.NETandisnow

    capableofconvertingmostC#code,buttherearesomesyntaxconstructsavailableinC#thathaveno

    directequivalentinSynergy.NET,sooccasionallythecodeconvertermayreportFailedtoconvert.

    Also,occasionallythecodeconvertermayencounterC#syntaxwhichcanbeimplementedinSynergy

    .NET,but

    which

    is

    too

    complex

    to

    be

    converted

    automatically.

    In

    these

    cases,

    whenever

    possible,

    the

    codeconverterwillinsertaTODO:commentintotheresultingcodetoindicatethatyouneedtodo

    somemanualwork.

    Inmanycasesthecodeconverterisabletoproducecodewhichis100%correct,butifyouareusingit

    toproducecodethatyouactuallyintendtouse(ratherthanjusttolearnatechniquefrom)thenitis

    recommendedthatyoureviewthecodethatwasproduced.

    Closethecodeconverterwindow.BuildingWithMultipleProjectsWhenyouworkwithinasolutionthatincludesmultipleprojectsthenVisualStudiowillbuildany

    projectsthatareoutofdatewheneveryouexecuteordebugtheapplication.Also,typingCtrl+Shift+B

    (buildsolution)willalsobuildanyprojectswhichareoutofdate.Tryit:

    TypeCtrl+Shift+BChecktheoutputwindowandyoushouldseethatbothofyourprojectswerebuilt:

    YoualsohavetheoptionofbuildingtheprojectsindividuallyviamenuitemsontheBuildmenu.Youwill

    seeseparateoptionstobuildthesolutionorthecurrentproject.Th