214

Microsoft® SharePoint® 2013 App Development - … SHAREPOINT … · Microsoft® SharePoint® 2013 App Development Scot Hillier Ted Pattison Published by Microsoft Press

Embed Size (px)

Citation preview

  • MicrosoftSharePoint2013AppDevelopment

    ScotHillier

    TedPattison

    PublishedbyMicrosoftPress

  • SpecialUpgradeOffer

    Ifyoupurchasedthisebookdirectlyfromoreilly.com,youhavethefollowingbenefits:

    DRM-freeebooksuseyourebooksacrossdeviceswithoutrestrictionsorlimitations

    Multipleformatsuseonyourlaptop,tablet,orphone

    Lifetimeaccess,withfreeupdates

    Dropboxsyncingyourfiles,anywhere

    Ifyoupurchasedthisebookfromanotherretailer,youcanupgradeyourebooktotakeadvantageofallthesebenefitsforjust$4.99.Clickheretoaccessyourebookupgrade.Pleasenotethatupgradeoffersarenotavailablefromsamplecontent.

    http://oreilly.com

  • ANoteRegardingSupplementalFiles

    Supplementalfilesandexamplesforthisbookcanbefoundathttp://examples.oreilly.com/9780735674981-files/.Pleaseuseastandarddesktopwebbrowsertoaccessthesefiles,astheymaynotbeaccessiblefromallereaderdevices.

    Allcodefilesorexamplesreferencedinthebookwillbeavailableonline.Forphysicalbooksthatshipwithanaccompanyingdisc,wheneverpossible,wevepostedallCD/DVDcontent.Notethatwhileweprovideasmuchofthemediacontentasweareableviafreedownload,wearesometimeslimitedbylicensingrestrictions.Pleasedirectanyquestionsorconcernstobooktech@oreilly.com.

    http://examples.oreilly.com/9780735674981-files/mailto:[email protected]

  • Introduction

    WiththereleaseofSharePoint2013,MicrosofthasdramaticallychangedtherulesforSharePointdevelopers.Theintroductionofthenewappdevelopmentmodelisintendedtoessentiallyeliminatethedevelopmentoffull-trustandsandboxedsolutionsforSharePoint.AlthoughbothofthesesolutiontypesarestillavailableinSharePoint2013,themessagefromMicrosoftisclear:allnewSharePointdevelopmentshouldbedonebyusingtheappmodel.

    WecoverthereasonsforthisseismicshiftindetailinChapter1,sowewontrepeatthemhere.However,theSharePointcommunitywillprobablybeleftwithmanyquestionsaboutthefutureevenafterunderstandingMicrosoftslogic.Certainly,themostimportantquestionsrevolvearoundwhetherorganizationswillactuallyaccepttheprimacyoftheappmodel.MostSharePointinstallationsareon-premisesfarmswithsignificantinvestmentincustomfull-trustsolutions.ThesesolutionstaketheformofWebParts,workflows,applicationpages,eventhandlers,andsoonthatperformsignificantcustomprocessing.Clearly,organizationscannotabandontheseinvestmentsovernight.Ontheotherhand,noonecandenythemomentumpressuringorganizationstomovemorefunctionalityintothecloudwherethefull-trustmodelsimplydoesnotworkeffectively.

    Fordevelopers,thesituationisbothintriguingandconcerning.ManySharePointdeveloperstheauthorsofthisbookincludedhavespentadecademasteringtheintricaciesofthefull-trustmodel.Now,wefindourselvesfacedwiththerealitythataportionofthisknowledgemightbeinjeopardy.EventhoughalltheexpertisesurroundingSharePointinfrastructure,architecture,anddeclarativeprocessingisstilluseful,theappmodelforbidstheuseoftheserver-sideobjectmodel,whichhasbeenthebreadandbutterofSharePointdevelopersformorethantenyears.

    Onthepositiveside,theappmodelopensupnewandexcitingpossibilitiesfordevelopment.Cloud-basedappsallowforscenariosthatweredifficultorimpossibletocreateinpreviousversionsofSharePoint.Developersnowhaveclient-sideaccesstoeverymajorworkloadinSharePointthroughtheclient-sideobjectmodelandREST,whichmeansthatSharePoint2013fitsperfectlyintocloud-basedandcross-platformdevelopmentmodels.Additionally,SharePointdevelopersnowhaveaccesstoamarketplacetoselltheirapplicationstoMicrosoftOffice365users.

    Althoughthisbookcantansweralloftheadoptionquestionsthecommunitywillface,itcancertainlyhelpyoutogetstartedinappdevelopment.TherearemanynewskillsforyoutolearnincludingadvancedJavaScriptpatterns,OAuthsecurity,andcloud-baseddevelopmentmodels.IfyouarelikethehundredsofMicrosoftemployeesandpartnerswehavealreadytaught,youllfindyourselfreactingwithamixofexcitement,joy,denial,andfrustration.WelookforwardtoworkingthroughitwithyouandtherestoftheSharePointcommunity.

  • WhothisbookisforThisbookiswrittenforexperiencedSharePointdeveloperswhoareproficientwithMicrosoftVisualStudio2012,theMicrosoft.NET4.0framework,andwhounderstandthefundamentalsoftheSharePointobjectmodel.ThecodesamplesinthisbookarewritteninJavaScriptandC#andareintendedtorepresentthespectrumofpossibleappsolutions.TheprimaryaudienceforthebookisSharePointarchitectsanddeveloperswhoarelookingtomasterthenewappmodelinSharePoint2013.

    OrganizationofthisbookThisbookisorganizedintofourchapters:

    Chapter1,coversthenewappmodelindetail.Thischapterpresentsthehistoricalcontextthatjustifiestheappmodelandthefundamentaldevelopmentprocess.

    Chapter2,firstprovidesaJavaScriptandjQueryprimerforSharePointdeveloperswithanemphasisonprofessionalpatterns.Thesecondhalfofthechapterpresentsthefundamentalsoftheclient-sideobjectmodelandRESTAPIsforSharePoint2013.

    Chapter3,presentsthesecurityconceptsnecessarytosuccessfullydevelopapps.ThischapterexplainstheconceptoftheappprincipalandpresentsthedetailsbehindtheOAuthsecuritymodel.

    Chapter4,presentsprofessionalpatternsforappdevelopmentsuchasModel-View-ViewModel(MVVM)andModel-View-Controller(MVC).Withinthesepatterns,thechaptershowsthebasicsofcreatingappswithvariousworkloads,suchassearch,BusinessConnectivityServices(BCS),andthesocialcapabilities.

    PrereleasesoftwareTohelpyoubecomefamiliarwithSharePoint2013asearlyaspossible,thisbookwaswrittenbyusingexamplesthatworkwithSharePoint2013Preview.Consequently,thefinalversionmightincludenewfeatures,andfeaturesdiscussedinthisbookmightchangeordisappearaltogether.YoucanrefertotheCapabilitiesandfeaturesinSharePoint2013topiconTechNetattechnet.microsoft.com/en-us/sharepoint/fp142374.aspxforthemostup-to-datelistofchangestotheproduct.Beaware,however,thatyoumightalsonoticesomedifferencesbetweentheReleasetoManufacture(RTM)versionoftheproductandthedescriptionsandscreenshotsthatareprovidedinthisbook.

    NOTEMoreInfoYoucanfindinformationabouttheExchangeServer2013Previewattechnet.microsoft.com/en-us/library/bb124558(v=exchg.150).aspx.YoucanfindmoreinformationabouttheLync2013Previewatlync.microsoft.com/en-us/Pages/Lync-2013-Preview.aspx.

    Codesamples

  • Youcandownloadthecompanioncodesamplesfromthebookscatalogpageat:http://go.microsoft.com/FWLink/?Linkid=274914

    CopyandunzipthefilesintherootoftheC:drive.Ifyoucopyandunzipthefilesinanotherfolder,youmightgetanerrormessagebecausethetotalfilepathsaretoolong.

    Support&feedbackThefollowingsectionsprovideinformationonerrata,booksupport,feedback,andcontactinformation.

    ErrataWevemadeeveryefforttoensuretheaccuracyofthisbookanditscompanioncontent.AnyerrorsthathavebeenreportedsincethisbookwaspublishedarelistedonourMicrosoftPresssiteatoreilly.com:http://go.microsoft.com/FWLink/?Linkid=274913

    Ifyoufindanerrorthatisnotalreadylisted,youcanreportittousthroughthesamepage.

    Ifyouneedadditionalsupport,[email protected].

    PleasenotethatproductsupportforMicrosoftsoftwareisnotofferedthroughtheaddressesabove.

    WewanttohearfromyouAtMicrosoftPress,yoursatisfactionisourtoppriority,andyourfeedbackourmostvaluableasset.Pleasetelluswhatyouthinkofthisbookat:http://www.microsoft.com/learning/booksurvey

    Thesurveyisshort,andwereadeveryoneofyourcommentsandideas.Thanksinadvanceforyourinput!

    StayintouchLetskeeptheconversationgoing!WereonTwitter:http://twitter.com/MicrosoftPress.

    http://go.microsoft.com/FWLink/?Linkid=274914http://go.microsoft.com/FWLink/?Linkid=274913mailto:[email protected]://www.microsoft.com/learning/booksurveyhttp://twitter.com/MicrosoftPress

  • Chapter1.IntroducingSharePointApps

    LetsbeginwithabitofhistorysothatyoucanunderstandwhyandhowtheMicrosoftSharePointappmodelcameabout.ItwasbackwithSharePoint2007thatMicrosoftfirstinvestedtotransformSharePointtechnologiesintoatruedevelopmentplatformbyintroducingfeaturesandfarmsolutions.WiththereleaseofSharePoint2010,Microsoftextendedtheoptionsavailabletodevelopersbyintroducingsandboxed-solutiondeploymentasanalternativetofarm-solutiondeployment.WithSharePoint2013,MicrosofthasnowaddedathirdoptionforSharePointdeveloperwiththeintroductionofSharePointapps.

    WhendevelopingforSharePoint2013,youmustlearnhowtodecidebetweenusingafarmsolution,asandboxedsolution,oraSharePointapp.Tomakethisdecisioninaninformedmanner,youmustlearnwhatsdifferentaboutdevelopingSharePointapps.Asyouwillseeinthischapter,SharePointappdevelopmenthasseveralimportantstrengthsandafewnoteworthyconstraintswhencomparedtotheoldschoolapproachofdevelopingSharePointsolutionsforSharePoint2010.

    AsyoubegintogetyourheadaroundwhatthenewSharePointappmodelisallabout,itshelpfultounderstandoneofMicrosoftskeymotivationsbehindit.SharePoint2007andSharePoint2010havegainedlarge-scaleadoptionworldwideandhavegeneratedbillionsofdollarsinrevenueprimarilyduetocompaniesandorganizationsthathaveinstalledSharePointontheirownhardwareinanon-premisesfarm.And,whereaspreviousversionsofSharePointhavebeenverysuccessfulproductswithrespecttoalltheseon-premisesfarms,MicrosoftssuccessandadoptionrateinhostedenvironmentssuchasMicrosoftOffice365havebeenfarmoremodest.

    ThereleaseofSharePoint2013representsasignificantshiftinMicrosoftsstrategyforevolvingtheproduct.MicrosoftsfocusisnowconcernedwithimprovinghowSharePointworksinthecloud,especiallywithOffice365.MicrosoftsprimaryinvestmentinSharePoint2013hasbeentoaddfeaturesandfunctionalitythatworkequallywellinthecloudastheydoinon-premisesfarms.

    UnderstandingthenewSharePointappmodelThemovefromSharePointsolutionsdevelopmenttoSharePointappdevelopmentrepresentsasignificantchangeindevelopmenttechniqueandperspective.However,Microsoftisnotmakingthischangejustforthesakeofmakingachange;thereareveryvalidtechnicalreasonsthatwarrantsuchadrasticshiftinthefutureoftheSharePointdevelopmentplatform.

    TofullyunderstandMicrosoftsmotivationforbeginningtotransitionawayfromSharePointsolutionstothenewSharePointappmodel,youmustfirstunderstandtheproblemsandpainpointsofSharePointsolutionsdevelopment.Therefore,thissectionwillbeginbydescribingthelimitationsandconstraintsimposedbySharePointsolutiondevelopment.Afterthat,thediscussionturnstothedesigngoalsandarchitectureofthenewSharePointappmodelandaddresseshowthisarchitectureimprovesuponthelimitationsandconstraintsimposedbySharePointsolutiondevelopment.

  • UnderstandingSharePointsolutionchallengesThefirstproblemwithSharePointsolutionsdevelopmentisthatmostofthecustomcodewrittenbydevelopersrunswithintheSharePointhostenvironment.Forexample,managedcodedeployedinafarmsolutionrunswithinthemainSharePointworkerprocess(w3wp.exe).ManagedcodedeployedbyusingasandboxedsolutionrunswithintheSharePointsandboxedworkerprocess(SPUCWorkerProcess.exe).

    TherearetwoprimaryreasonswhyMicrosoftwantstogetridofcustomcodethatrunswithintheSharePointenvironment.ThefirstreasonhastodowithincreasingthestabilityofSharePointfarms.Thisoneshouldbeprettyobvious.EliminatinganytypeofcustomcodethatrunswithintheSharePointenvironmentresultsinlowerrisk,fewerproblems,andgreaterstabilityforthehostingfarm.

    Thesecondreasonhastodowiththeabilitytoupgradeanon-premisesfarmtonewerversionsofSharePoint.SharePointsolutionsareoftendevelopedwithfulltrustandperformcomplexoperations.Thesesolutionsareoftentightlyboundtoaparticularfeatureset,whichmeansthattheymightnotmovegracefullytothenextversionofSharePoint.Fearingacompleterewriteofdozensofsolutions,manycustomersdelayupgradingtheirSharePointfarms.

    MicrosofthaswitnessedmanyoftheirbiggestSharePointcustomerspostponingtheupgradeoftheirproductionon-premisesfarmsformonthsandsometimesyearsuntiltheyhavehadtimetoupdatetheirSharePointsolutioncodeandtestitagainstthenewversionofMicrosoft.SharePoint.dll.BecausethisisaproblemthatnegativelyaffectsSharePointsalesrevenue,youcanbetitwasprettyhighontheprioritylistofproblemstofixwhenMicrosoftbegantodesignSharePoint2013.

    AnothersignificantproblemwithSharePointsolutiondevelopmenthastodowithsecurityandpermissions.Therootproblemisthatcodealwaysrunsundertheidentityandwiththepermissionsofaspecificuser.Asanexample,thinkaboutthecommonscenarioinwhichasiteadministratoractivatesafeaturefromaSharePointsolutionthathasafeaturereceiver.ThereisasecurityissueinthataSharePointsolutionwithafeaturereceiverisabletoexecutecodethatcandoanythingthatthesiteadministratorcando.TherereallyisntapracticalwaytoconstraintheSharePointsolutioncodesothatitrunswithalessersetofpermissionsthantheuserthathasactivatedthefeature.

    MostSharePointprofessionalsareundertheimpressionthatcodeinsideasandboxedsolutionisconstrainedfrombeingabletoperformattacks.Thisisonlypartiallytrue.Thesandboxprotectsthefarmandothersitecollectionswithinthefarm,butitdoesnotreallyprotectthecontentofthesitecollectionsinwhichasandboxedsolutionisactivated.Forexample,thereisntanytypeofenforcementtoprohibitthefeatureactivationcodeinasandboxedsolutionfromdeletingeveryitemandeverydocumentinthecurrentsitecollection.

    Anotherissuewithsandboxedsolutionsisthattheresnoabilitytoperformimpersonation.Therefore,customcodeinasandboxedsolutionalwaysrunsasthecurrentuser.Thiscanbeverylimitingwhenthecurrentuserisalow-privilegedusersuchasacontributororavisitor.Thereisnowaytoelevateprivilegessothatyourcodecandomorethanthecurrentuser.

    Farmsolutions,ontheotherhand,allowforimpersonation.Thismeansadevelopercanelevateprivilegessothatfarmsolutioncodecanperformactionsevenwhenthecurrentuserdoesnotpossesstherequiredpermissions.However,thissimplyreplacesoneproblemwithanother.

    AfarmsolutiondevelopercancallSPSecurity.RunWithElevatedPrivileges,whichallowscustomcodeto

  • impersonatetheall-powerfulSHAREPOINT\SYSTEMaccount.Whencoderunsunderthisidentity,itexecuteswithnosecurityconstraintswhatsoever.Thecodecanthenessentiallydowhateveritwantsonafarm-widebasis.ThistypeofimpersonationrepresentsthePandorasBoxoftheSharePointdevelopmentplatformbecauseafarmsolutioncouldperformanattackonanypartofafarminwhichitsdeployed,anditmustbetrustednottodoso.Asyoucanimagine,thiscancauseanxietywithSharePointfarmadministratorswhoaremuchfonderofsecurityenforcementthantheyareoftrust.

    Inanutshell,thesecurityproblemswithSharePointsolutionsstemfromthefactthatyoucannoteffectivelyconfigurepermissionsforaspecificSharePointsolution.Thislimitationcannotbeovercome,becausetheSharePointsolutiondevelopmentmodelprovidesnowaytoestablishtheidentityofSharePointsolutioncodeindependentofuseridentity.BecausethereisnoabilitytoestablishtheidentityofcodefromaSharePointsolution,thereisnowaytoconfigurepermissionsforit.

    ThelastimportantpainpointofSharePointsolutiondevelopmentcentersaroundinstallationandupgrade.Theinstallationoffarmsolutionsisproblematicbecauseitrequiresafarmadministrator,anditoftenrequiresrestartingInternetInformationServices(IIS)onallthefront-endwebservers,causinganinterruptioninservice.AlthoughthedeploymentofaSharePointsolutiondoesntinvolvetheseproblems,itraisesotherconcerns.Businessusersoftenhavetroublewiththeprocessoffindinganduploadingsandboxedsolutionsinordertoactivatethem.Furthermore,abusinessuserhasverylittletoindicatewhetherornottotrustasandboxedsolutionbeforeactivatingitandgivingitscodeaccesstoallthecontentwithinthecurrentsitecollection.

    OfalltheissuessurroundingSharePointsolutiondevelopment,nothingismorepronetoerrorandlessunderstoodthanthesupportforupgradingcodefromoneversionofaSharePointsolutiontoanother.EventhoughMicrosoftaddedsupportforfeatureupgradeandassemblyversionredirectioninSharePoint2010,almostnooneisusingit.Therequiredstepsandtheunderlyingsemanticsofthefeatureupgradeprocesshaveprovedtobetootrickyformostdeveloperstodealwith.Furthermore,thevastmajorityofprofessionalSharePointdevelopershavemadethedecisionnevertochangetheassemblyversionnumberoftheassemblydynamic-linklibrary(DLL)deployedwithaSharePointsolution.Thatsbecausecreatingandmanagingtherequiredassemblyredirectionentriesacrossagrowingsetofweb.configfilesisjusttoopainfulanderrorprone.

    YouhavejustreadaboutthemostsignificantpainpointswithrespecttoSharePointsolutiondevelopment.Hereisasummaryofthesepoints.

    CustomcoderunninginsidetheSharePointhostenvironmentposesrisksandcompromisesscalability.

    Customcodewithdependenciesonin-processDLLscausesproblemswhenmigratingfromoneversionofSharePointtothenext.

    Apermissionsmodelforcustomcodebasedentirelyontheidentityofthecurrentuserisinflexible.

    Userimpersonationsolvesthetoo-little-permissionsproblembutreplacesitwiththetoo-many-permissionsproblem,whichisevenworse.

    SharePointsolutionslackeffectivesupportandeasilyunderstoodsemanticsfordistribution,installation,andupgrade.

  • UnderstandingSharePointappmodeldesigngoalsTheSharePointappmodelwasdesignedfromthegrounduptoremedytheproblemswithSharePointsolutionsthatwerediscussedintheprevioussection.ThismeansthatthearchitectureoftheSharePointappmodelisverydifferentfromthatofSharePointsolutions,whichrepresentSharePointsoriginaldevelopmentplatform.Thisnewarchitecturewasbuiltbasedonthefollowingdesigngoals.

    AppsmustbesupportedinOffice365andinon-premisesfarms.

    AppcodeneverrunswithintheSharePointhostenvironment.

    AppcodeprogramsagainstSharePointsitesbyusingwebserviceentrypointstominimizeversion-specificdependencies.

    Appcodeisauthenticatedandrunsunderadistinctidentity.

    Apppermissionscanbeconfiguredindependentlyofuserpermissions.

    Appsaredeployedbyusingapublishingschemebasedonappcatalogs.

    Appsthatarepublishedinacatalogareeasiertodiscover,install,andupgrade.

    YouhavenowseenthedesigngoalsforthenewSharePointappmodel,andyouunderstandthemotivatingfactorsbehindthem.ThisshouldprovideyouwithgreaterinsightandabetterappreciationastowhyMicrosoftdesignedtheSharePointappmodelthewayitdid.Now,itstimetodiveintothedetailsoftheSharePointappmodelanditsunderlyingarchitecture.

    UnderstandingSharePointappmodelarchitectureMicrosoftdesignedtheSharePointappmodeltoworkintheOffice365environmentaswellaswithinon-premisesfarms.However,developingforOffice365introducesafewimportantnewconceptsthatwillbeunfamiliartomanyexperiencedSharePointdevelopers.OneofthenewconceptsthatisessentialtothedevelopmentofSharePointappsisaSharePointtenancy.

    ASharePointtenancyisasetofsitecollectionsthatareconfiguredandadministratedasaunit.WhenanewcustomerestablishesanOffice365accounttohostitsSharePointsites,theOffice365environmentcreatesanewtenancy.Thecustomersbusinessusersthataccessthetenancyareknown(notsurprisingly)astenants.

    WhentheOffice365environmentcreatesanewtenancyforacustomer,itcreatesanadministrativesitecollectionwhichisaccessibletouserswhohavebeenconfiguredtoplaytheroleofatenantadministrator.Atenantadministratorcancreateadditionalsitecollectionsandconfigurethesetofservicesthatareavailabletoallthesitesrunningwithinthetenancy.

    TheconceptoftenancieswasfirstintroducedinSharePoint2010tosupporthostingenvironmentssuchasOffice365.AlthoughthecreationanduseoftenanciesisessentialtotheOffice365environment,theirusehasnotbeenwidelyadoptedinon-premisesfarms.ThisisprimarilyduetothefactthatSharePointfarmadministratorscancreatesitecollectionsandconfiguretheservicesavailabletouserswithinthescopeof

  • awebapplication.

    ThearchitectureoftheSharePointappmodelrequiresthatappsarealwaysinstalledandrunwithinthecontextofaspecifictenancy.ThiscanbeabitconfusingforscenariosinwhichyouwanttoinstallSharePointappsinanon-premisesfarmthatdoesntinvolvetheexplicitcreationoftenancies.However,SharePoint2013isabletosupportinstallingandrunningSharePointappsinon-premisesfarmsbytransparentlycreatingafarm-widetenancybehindthescenesthatisknownasthedefaulttenancy.

    WorkingwithappserviceapplicationsSharePoint2013reliesontwoserviceapplicationstomanagetheenvironmentthatsupportsSharePointapps.ThefirstserviceapplicationistheAppManagementService,whichisnewtoSharePoint2013.ThesecondserviceapplicationistheSiteSubscriptionsSettingsService,whichwasintroducedinSharePoint2010.Ahigh-levelviewofaSharePoint2013farmrunningthesetwoserviceapplicationsisshowninFigure1-1.

    Figure1-1.ASharePointFarmthatsupportsappsrequiresaninstanceoftheAppManagementServiceandtheSiteSubscriptionservicetoberunning.

    TheAppManagementServicehasitsowndatabasethatisusedtostoretheconfigurationdetailsforappsastheyareinstalledandconfigured.TheAppManagementServiceisalsoresponsiblefortrackingothertypesofapp-specificconfigurationdatathatdealswithappsecurityprincipals,apppermissions,andapplicensing.

    TheSiteSubscriptionSettingsServicetakesontheresponsibilityofmanagingtenancies.Eachtimeanewtenancyiscreated,thisserviceaddsconfigurationdataforitinitsowndatabase.TheSiteSubscriptionSettingsServiceisparticularlyimportanttotheSharePointappmodelduetotherequirementthatSharePointappsmustalwaysbeinstalledandrunwithinthecontextofaspecifictenancy.

    WhenyouareworkingwithintheOffice365environment,youneverhavetoworryaboutcreatingorconfiguringthesetwoserviceapplications,becausetheyareentirelymanagedbehindthescenes.However,thingsaredifferentwhenyouwanttoconfiguresupportforSharePointappsinanon-premisesfarm.Inparticular,youmustexplicitlycreateaninstanceofboththeAppManagementServiceandthe

  • SiteSubscriptionSettingsService.

    CreatinganinstanceofAppManagementServiceiseasierbecauseitcanbedonebyhandviatheCentralAdministrationorbyusingtheFarmCreationWizard.CreatinganinstanceofSiteSubscriptionSettingsServiceisabittrickierbecauseitmustbedonebyusingWindowsPowerShell.However,whenyoucreateaninstanceoftheSiteSubscriptionSettingsServicebyusingWindowsPowerShell,itautomaticallycreatesthedefaulttenancywhichthenmakesitpossibletoinstallSharePointappsinsitesthroughoutthefarm.

    BUILDINGANENVIRONMENTFORSHAREPOINTAPPDEVELOPMENTIfyouplanondevelopingSharePointappsthatwillbeusedwithinprivatenetworkssuchasacorporateLAN,itmakessensetobuildoutadevelopmentenvironmentwithalocalSharePoint2013farm.CriticalPathTrainingprovidesafreedownloadinPDFformatcalledtheSharePointServer2013VirtualMachineSetupGuide,whichprovidesyouwithstep-by-stepinstructionstoinstallallthesoftwareyouneedtocreateadevelopmentenvironmentwithalocalSharePoint2013farm.Youcandownloadtheguidefromhttp://criticalpathtraining.com/Members.

    UnderstandingappinstallationscopesASharePointappmustbeinstalledbeforeitcanbemadeavailabletousers.WhenyouinstallaSharePointapp,youmustinstallitwithinthecontextofatargetweb.Oncetheapphasbeeninstalled,userscanthenlaunchtheappandbegintouseit.Thesitefromwhichanapphasbeenlaunchedisknownasthehostweb.

    TherearetwodifferentscopesinwhichyoucaninstallandconfigureaSharePointapp.Thescenariothatiseasiertounderstandiswhenanappisinstalledatsitescope.Inthisscenario,theappisinstalledandlaunchedwithinthescopeofthesameSharePointsite.Inthisscenario,thehostwebwillalwaysbethesamesitewheretheapphasbeeninstalled.

    SharePointappscanalsobeinstalledandconfiguredattenancyscope.Inthisscenario,anappisinstalledinaspecialtypeofSharePointsiteknownasanappcatalogsite.Oncetheapphasbeeninstalledinanappcatalogsite,theappcanthenbeconfiguredsothatuserscanlaunchitfromothersites.Inthisscenario,thehostwebwillnotbethesamesitewheretheapphasbeeninstalled.

    TheabilitytoinstallandconfigureappsattenancyscopeisespeciallyvaluableforscenariosinwhichasingleappisgoingtobeusedbymanydifferentusersacrossmultiplesiteswithinanOffice365tenancyoranon-premisesfarm.Asingleadministrativeusercanconfigureapppermissionsandmanagelicensinginoneplace,whichpreventstheneedtoinstallandconfiguretheapponasite-by-sitebasis.Thetopicofinstallingappswillberevisitedingreaterdetailattheendofthischapter.

    ThisbookdiscussesmanydifferentscenariosinwhichSharePointappsbehavethesameway,regardlessofwhethertheyhavebeeninstalledinanOffice365tenancyorinanon-premisesfarm.Therefore,thebookfrequentlyusesthegenerictermSharePointhostenvironmentwhentalkingaboutscenariosthatworkthesameacrosseitherenvironment.

    UnderstandingappcodeisolationWhenyoudevelopaSharePointapp,youobviouslyneedtowritecustomcodetoimplementyour

    http://criticalpathtraining.com/Members

  • businesslogic,andthatcodemustrunsomeplaceotherthanonthewebserversinthehostingSharePointfarm.TheSharePointappmodelprovidesyouwithtwoplacestorunyourcustomcode.First,aSharePointappcancontainclient-sidecodethatrunsinsidethebrowserontheuserscomputer.Second,aSharePointappcancontainserver-sidecodethatrunsinanexternalwebsitethatisimplementedanddeployedaspartoftheappitself.

    TherearemanydifferentwaysinwhichyoucandesignandimplementaSharePointapp.Forexample,youcouldcreateaSharePointappthatcontainsonlyclient-sideresourcessuchaswebpagesandclient-sideJavaScriptcodethatareservedupbytheSharePointhostenvironment.ThistypeofappisknownasaSharePoint-hostedappbecauseitiscontainedentirelywithintheappweb.YoucouldwriteaSharePoint-hostedappthatusesMicrosoftSilverlight,MicrosoftVBScript,Flash,orwhateverclient-sidetechnologyyouprefer.

    Now,imaginethatyouwanttocreateasecondSharePointappinwhichyouwanttowriteserver-sidecodeinalanguagesuchasC#.ThistypeofSharePointappwillrequireitsownexternalwebsitesothatyourserver-sidecodehasaplacetoexecuteoutsideoftheSharePointhostenvironment.InSharePoint2013terminology,aSharePointappwithitsownexternalwebsiteisknownasacloud-hostedapp,andtheexternalwebsiteisknownastheremoteweb.ThediagraminFigure1-2showsthekeyarchitecturaldifferencebetweenaSharePoint-hostedappandacloud-hostedapp.

    FromthediagraminFigure1-2,youcanseethatbothSharePoint-hostedappsandcloud-hostedappshaveastartpagethatrepresentstheappsprimaryentrypoint.WithaSharePoint-hostedapp,theappsstartpageisservedupbytheSharePointhost;however,withacloud-hostedapp,thestartpageisservedupfromtheremoteweb.Therefore,theSharePointhostenvironmentmusttracktheremotewebURLforeachcloud-hostedappthathasbeeninstalledsothatitcanredirectuserstotheappsstartpage.

    ThereisinfrastructureintheSharePointhostenvironmentthatcreatesaclient-sideJavaScriptcomponentknownasanapplauncherthatisusedtoredirecttheuserfromapageservedupbytheSharePointhostenvironmentovertotheremoteweb.

    Whenyoudecidetodevelopacloud-hostedSharePointapp,youmustoftentakeontheresponsibilityofhostingtheappsremoteweb.However,thisresponsibilityofcreatinganddeployingaremotewebalongwithaSharePointappalsocomeswithadegreeofflexibility.YoucanimplementtheremotewebassociatedwithaSharePointappbyusinganyexistingweb-baseddevelopmentplatform.

    Forexample,theremotewebforacloud-hostedSharePointappcouldbeimplementedbyusinganon-MicrosoftplatformsuchasJava,LAMP,orPHP.However,theeasiestandthemostcommonapproachforSharePointdevelopersistodesignandimplementtheremotewebforcloud-hostedappsbyusingASP.NETwebformsorMVC4.Chapter4,discussesseveralpatternsthatusethesetechnologies.

  • Figure1-2.Acloud-hostedappdiffersfromaSharePoint-hostedappinthatithasanassociatedremoteweb,whichmustbedeployedonaseparateinfrastructurefromtheSharePointfarm.

    UnderstandingapphostingmodelsThusfar,thischapterhasdiscussedhowaSharePointappcanbecategorizedaseitheraSharePoint-hostedapporacloud-hostedapp.However,theSharePointappmodelactuallydefinesthreeapphostingmodels,notjusttwo.AnytimeyoucreateanewSharePointappprojectinMicrosoftVisualStudio2012youmustpickfromoneofthefollowingthreeapphostingmodels.

    SharePoint-hosted

    Provider-hosted

    Autohosted

    ThischapterhasalreadyexplainedSharePoint-hostedapps.Asyourecall,aSharePoint-hostedappissimplyanappthataddsitsstartpageandallitsotherresourcesintotheSharePointhostenvironmentduringinstallation.Now,itstimetoexplainthedifferencesbetweentheothertwoapphostingmodels.

    Aprovider-hostedappandanautohostedapparejusttwovariationsofthehostingmodelforacloud-

  • hostedapp.Bothtypesofappshaveanassociatedremotewebthatiscapableofhostingtheappsstartpageandanyotherresourcestheapprequires.Furthermore,bothprovider-hostedappsandautohostedappscanandoftenwillhosttheirowncustomdatabasestostoreapp-specificdata.Thedifferencebetweenthesetwodifferentapphostingmodelsinvolveshowtheremotewebanditsassociateddatabasearecreatedwhenanappisdeployedandinstalled.

    Itmakessensetobeginbyfirstexaminingthehostingmodelforaprovider-hostedapp.Imagineascenarioinwhichadeveloperhasjustfinishedtestinganddebuggingaprovider-hostedappthathasaremotewebwithitsowncustomdatabase.BeforetheappcanbeinstalledinaSharePointhostenvironment,thedeveloperorsomeotherpartymustfirstdeploythewebsitefortheremotewebtomakeitaccessibleacrosstheInternetoronaprivatenetwork.

    Thecustomdatabaseusedbytheremotewebmustalsobecreatedonadatabaseserverandmadeaccessibletotheremotewebaspartofthedeploymentprocess.Oncetheremotewebanditscustomdatabaseareupandrunning,theprovider-hostedappcanthenbeinstalledinaSharePointtenancyandmadeavailabletothecustomersusers,asdemonstratedinFigure1-3.

    Figure1-3.Provider-hostedappsaredeployedintheirowninfrastructureincludinganyrequireddatabases.

    Onceaprovider-hostedapphasbeendeployed,thecompanythatdevelopedtheappusuallyassumestheresponsibilityforitsongoingmaintenance.Forexample,ifacompanydevelopsaprovider-hostedappanddeploysitsremotewebononeormoreofitslocalwebservers,itmustensurethatthosewebserversremainhealthyandaccessible.Ifitdeploystheremoteappforitsprovider-hostedinahostingenvironmentsuchasWindowsAzure,itmustpayamonthlyfeeforthehostingservices.Furthermore,itwillberesponsibleforbackinguptheappsdatabaseandthenrestoringitifdatabecomeslostorcorrupt.

    Keepinmindthataprovider-hostedappcanbeinstalledinmorethanoneSharePointsite.Furthermore,aprovider-hostedappcanbeinstalledinmanydifferentSharePointsitesthatspanacrossmultiplecustomersandmultipleSharePointhostenvironments.Thisisacommonscenariowhichisknownasmultitenancy.Whatiscriticaltoacknowledgeisthatmultitenancyintroducesseveralnoteworthydesignissuesanddeploymentconcerns.Letslookatanexample.

  • Thinkaboutascenarioinvolvingmultitenancyinwhichaprovider-hostedapphasbeeninstalledbymanydifferentcustomersandthenumberofusersiscontinuallygrowinglarger.Alltheseuserswillbeaccessingthesameremotewebthroughasingleentrypoint,whichistheappsstartpage,asshowninFigure1-4.

    Figure1-4.Aprovider-hostedappinamultitenantenvironmentmustbedesignedtoscaleandtoisolatedataonacustomer-by-customerbasis.

    Asyoucanimagine,aprovider-hostedappinthistypeofmultitenantscenariomusthaveawaytoscaleupasthenumberofusersincreases.Furthermore,thistypeofappshouldgenerallybedesignedtoisolatethedataforeachcustomertokeepitseparatefromthedatabelongingtoothercustomersyouwouldneverwantonecustomeraccessinganothercustomersdata.Dependingonthecustomersindustry,therecouldevenbegovernmentregulationsorprivacyconcernsthatpreventtheappfromstoringdatafordifferentcustomerswithinthesamesetoftablesorevenwithinthesamedatabase.

    Theimportanttakeawayisthatmultitenancyintroducescomplexity.Thedevelopmentofaprovider-hostedappthatwillbeusedinamultitenantscenariotypicallyrequiresadesignthatisolatesdataonacustomer-by-customerbasis.Asyoucanimagine,thisincreasesboththetimeandthecostassociatedwithdevelopingaprovider-hostedapp.

    Nowthatyouhaveseensomeoftheinheritdesignissuesthatariseduetomultitenancy,youwillbeabletomorefullyappreciatethebenefitsofthehostingmodelforautohostedapps.Autohostedappsoffervaluebecausetheypreventthedeveloperfromhavingtoworryaboutmanyoftheissuesinvolvedwithappdeployment,scalability,anddataisolation.

  • ThefirstthingtounderstandaboutautohostedappsisthattheyareonlysupportedintheOffice365environment.Althoughthisconstraintmightchangeinfuturereleases,withSharePoint2013youcannotinstallanautohostedappinanon-premisesfarm.ThereasonforthisisthatthehostingmodelforautohostedappsisbasedonaprivateinfrastructurethatintegratestheOffice365environmentwithWindowsAzureanditsabilitytoprovisionwebsitesanddatabasesondemand.

    ThecentralideabehindthehostingmodelforautohostedappsisthattheOffice365environmentcandeploytheremotewebondemandwhenanappisinstalled.Youcanalsoconfigureanautohostedappsothatitcreatesitsownprivatedatabaseduringappinstallation.Onceagain,theOffice365environmentanditsintegrationwithWindowsAzureisabletocreateaSQLAzuredatabaseondemandandthenmakeitaccessibletotheremoteweb.

    Autohostedappsoffervalueoverprovider-hostedappsbecausetheOffice365environmenttransparentlyhandlesthedeploymentoftheremotewebandpotentiallythecreationofacustomdatabase,aswell.AutohostedappsalsotransfertheongoingcostofownershipoftheremotewebanditsdatabasefromthedeveloperovertothecustomerwhoownstheOffice365tenancywheretheapphasbeeninstalled.Therefore,theappdeveloperdoesnthavetoworryaboutbabysittingwebservers,backingupdatabases,orcomingupwithastrategyscalinguptheremotewebasthenumberofusersincreases.

    Thebenefitsofanautohostedappoveraprovider-hostedappalsoextendintoappdesign,whichcanservetolowerdevelopmentcosts.Thatsbecauseeachcustomerreceivesitsownprivatedatabasewheneverinstallinganautohostedapp,asillustratedinFigure1-5.Thebenefitisthatthedeveloperisntrequiredtoaddcomplexitytotheappsdesignandimplementationtoprovideisolationbecauseeachcustomersdataisisolatedautomatically.

    Figure1-5.Anautohostedappcreatestherequiredremotewebandanydatabasesautomaticallyduringdeployment.

    ReviewingtheappmanifestEverySharePointapprequiresanXMLfilecalledAppManifest.xml,whichisknownastheapp

  • manifest.TheappmanifestcontainsessentialmetadatafortheappthatisreadandtrackedbytheSharePointhostenvironmentwhenanappisinstalled.Example1-1presentsasimpleexampleofwhattheappmanifestlookslikeforaSharePoint-hostedapp.

    Example1-1.Anappmanifest

    My SharePoint App

    ~appWebUrl/Pages/Default.aspx?{StandardTokens}

    Theappmanifestcontainsatop-levelelementwhichrequiresasetofattributessuchasName,ProductID,andVersion.Withintheelementthereisaninnerelementthatcontainsimportantchildelementssuchasand.Theelementcontainshuman-readabletextthatisdisplayedtotheuserintheapplauncher.TheelementcontainstheURLthattheSharePointhostenvironmentusesintheapplaunchertoredirecttheusertotheappsstartpage.

    Example1-1showstheminimalamountofmetadatarequiredinanappmanifest;however,theappmanifestformostreal-worldappswillcontainagooddealmore.Theappmanifestoftencontainsadditionmetadatatoconfigureotheressentialaspectsofanapp,suchasapp-levelevents,authentication,permissions,andtheSharePointservicesthatanapprequiresfromtheSharePointhostenvironment.Table1-1liststhemostcommonelementsyoumightberequiredtoaddtoanappmanifest.

  • Table1-1.TheelementsusedintheAppManifestfile

    Element Purpose

    Name CreatestheURLtotheappweb.

    ProductID Identifiestheapp.

    Version Indicatesthespecificversionoftheapp.

    SharePointMinVersion IndicatestheversionofSharePoint.

    Properties\Title Providestextfortheapplauncher.

    Properties\StartPage Redirectstheusertotheappsstartpage.

    Properties\SupportedLanguages Indicateswhichlanguagesaresupported.

    Properties\WebTemplate Suppliesacustomsitetemplatefortheappweb.

    Properties\InstalledEventEndpoint Executescustomcodeduringinstallation.

    Properties\UpgradedEventEndpoint Executescustomcodeduringupgrade.

    Properties\UninstallingEventEndpoint Executescustomcodeduringuninstallation.

    AppPrincipal\Internal Indicatesthereisnoneedforexternalauthentication.ThisiswhatisalwaysusedforSharePoint-hostedapps.

    AppPrincipal\RemoteWebApplication Indicatesthattheappisprovider-hostedandrequiresexternalauthentication.

    AppPrincipal\AutoDeployedWebApplication Indicatesthattheappisautohostedandrequiresexternalauthentication.

    AppPermissionRequests\AppPermissionRequest Addpermissionrequeststhatmustbegrantedduringappinstallation

    AppPrerequisites\AppPrerequisite IndicateswhatSharePointservicesmustbeenabledintheSharePointhostenvironmentfortheapptoworkproperly.

    RemoteEndpoints\RemoteEndpoint Configuresallowabledomainsforcross-domaincallsusingthewebproxy.

    UsingtheappmanifestdesignerinVisualStudio2012WhenyouareworkingwiththeappmanifestinaSharePointappproject,VisualStudio2012providesthevisualdesignershowninFigure1-6.ThisvisualdesignereliminatestheneedtoedittheXMLintheAppManifest.xmlfilebyhand.Thedesignerprovidesdrop-downliststhatmakeseditingmoreconvenientandaddsavaluabledegreeofvalidationasyouareselectingtheappstartpageorconfiguringpermissionrequests,featureprerequisites,andcapabilityperquisites.

    Althoughyoushouldtakeadvantageofthevisualdesignerwheneveryoucantoedittheappmanifest,itisimportanttounderstandthatitcannotmakecertaintypesofmodificationsthatyoumightrequire.Therefore,youshouldalsobecomeaccustomedtoopeningtheAppManifest.xmlfileincodeviewandmakingchangestotheXMLwithinbyhand.Fortunately,intimeswhenyouneedtomanuallyedittheAppManifest.xmlfile,VisualStudio2012isabletoprovideIntelliSense,basedontheXMLschemabehindtheappmanifest.

  • Figure1-6.VisualStudio2012providesavisualeditortoedittheappmanifest.

    SettingthestartpageURLEveryapphasastartpagewhoseURLmustbeconfiguredbyusingtheelementwithintheappmanifest.TheSharePointhostenvironmentusesthisURLwhencreatingapplaunchersthatredirecttheusertotheappsstartpage.ForaSharePoint-hostedapp,thestartpagemustbelocatedinachildsiteknownastheappwebthatwillbediscussedinmoredetaillaterinthischapter.Foracloud-hostedapp,thestartpagewillusuallybelocatedintheremoteweb.

    WhenyouareconfiguringtheURLwithintheelementforaSharePoint-hostedappyoumustuseadynamictokennamed~appWebUrl,asdemonstratedinthefollowing:

    ~appWebUrl/Pages/Default.aspx

    Thisuseofthe~appWebUrltokenisrequiredbecausetheactualURLtotheappsstartpagewillnotbeknownuntiltheapphasbeeninstalled.TheSharePointhostenvironmentisabletorecognizethe~appWebUrltokenduringappinstallationanditreplacesitwiththeabsoluteURLtotheappweb.

    Inthecaseofaprovider-hostedappwhosestartpageexistswithintheremoteweb,theelementcanbeconfiguredwiththeactualURLthatisusedtoaccessthestartpagewheretheremotewebhasbeendeployed,suchasinthefollowing:

    https://RemoteWebServer.wingtip.com/MyAppsRemoteWeb/Pages/Default.aspx

    Whenyouaredebuggingprovider-hostedappsandautohostedapps,youcanuseaconvenientdynamictokennamed~remoteAppUrlthateliminatestheneedtohardcodethepathtotheremotewebduringthedevelopmentphase.Forexample,youcanconfiguretheelementwiththefollowingvalue:

  • ~remoteAppUrl/Pages/Default.aspx

    ThereasonthisworksduringdebuggingisduetosomeextrasupportinVisualStudio2012.WhenyoucreateanewSharePointappprojectandselecttheoptionforaprovider-hostedapporanautohostedapp,VisualStudio2012automaticallycreatesasecondprojectfortheremotewebthatisconfiguredastheWebProject.WheneveryoudebugtheVisualStudiosolutioncontainingthesetwoprojects,VisualStudio2012performsasubstitutiontoreplace~remoteAppUrlwiththecurrentURLoftheWebProject.Afterthesubstitution,theappmanifestcontainsastartpageURLthatlookslikethis:

    https://localhost:44300/Pages/Default.aspx

    ThekeypointisthatVisualStudio2012replacesthe~remoteAppUrltokenduringadebuggingsessionbeforetheappmanifestisinstalledintotheSharePointhostenvironment.ThisprovidesyouwithaconvenienceinthedebuggingphaseofaSharePointappproject.

    Now,thinkaboutwhathappensafteryouhavefinishedtestinganddebugginganappanditsremoteweb.VisualStudio2012providesaPublishcommandwithwhichyoucanbuildafinalversionoftheAppManifest.xmlfilethatwillbedistributedalongwithyourapp.Inthiscase,whatwillVisualStudio2012dowiththe~remoteAppUrltoken?Theanswerisdifferentdependingonwhethertheappisanautohostedapporaprovider-hostedapp.

    WhenyouusethePublishcommandwithanautohostedapp,VisualStudio2012buildsafinalversionoftheAppManifest.xmlinwhichthe~remoteAppUrltokenremainswithintheelement.ThisisdonebecausetheactualURLtotheremotewebofanautohostedappwillnotbeknownuntiltheappinstallationprocesshasstartedandtheOffice365environmenthascreatedtheremoteweb.Youcanseethatthe~remoteAppUrltokenisreplacedbyVisualStudio2012insomescenariosandbytheOffice365environmentinotherscenarios.

    WhenyouusethePublishcommandwithaprovider-hostedapp,thefinalversionoftheAppManifest.xmlcannotcontainthe~remoteAppUrltoken.YoumustknowtheURLtotheremotewebaheadoftime.Therefore,whenitisusedwithaprovider-hostedapp,thePublishcommandpromptsyouforseveralpiecesofinformationincludingtheactualURLwheretheremotewebwillbedeployed.

    WhencreatingtheURLfortheelement,itisastandardpracticetoincludeaquerystringthatcontainsanotherdynamictokennamed{StandardTokens},asdemonstratedinthefollowingexample:

    ~remoteAppUrl/Pages/Default.aspx?{StandardTokens}

    The{StandardTokens}tokenisneverreplacedbyVisualStudio2012.Instead,thisdynamictokenremainsinsidethefinalversionoftheappmanifestthatisinstalledintheSharePointhostenvironment.TheSharePointhostenvironmentperformsasubstitutionon{StandardTokens}tokenwheneveritcreatestheURLforanapplauncher.Thissubstitutioninvolvesreplacingthe{StandardTokens}tokenwithastandardsetofquerystringparametersthatarefrequentlyusedinSharePointappdevelopmentsuchastheSPHostUrlparameterandtheSPLangaugeparameter,asshowninthefollowing:

    default.aspx?SPHostUrl=http%3A%2F%2Fwingtipserver&SPLanguage=en%2DUS

  • WhenyouimplementthecodebehindthestartpageofaSharePointapp,youcangenerallyexpectthatthepagewillbepassedthetwoquerystringparametersnamedSPLanguageandSPHostUrl,whichareusedtodeterminethelanguageinuseandtheURLthatpointsbacktothehostweb.Insomescenarios,theSharePointhostenvironmentwilladdadditionalquerystringparameters.

    UnderstandingtheappwebEachtimeyouinstallaSharePointapp,youmustinstallitonaspecifictargetsite.ASharePointapphastheabilitytoadditsownfilestotheSharePointhostenvironmentduringinstallation.Forexample,aSharePoint-hostedappmustaddastartpageandwilltypicallyaddotherresources,aswell,suchasaCSSfileandaJavaScriptfiletoimplementtheappsuserexperience.TheSharePointhostenvironmentstoresthesefilesinthestandardfashionbyaddingthemtothecontentdatabaseassociatedwiththesiteinwhichtheappisbeinginstalled.

    BeyondaddingbasicfilessuchasastartpageandaJavaScriptfile,aSharePointappalsohastheabilitytocreateotherSharePoint-specificsiteelementsintheSharePointhostduringinstallationsuchaslistsanddocumentlibraries.Letslookatanexample.

    ImaginethatyouwanttocreateasimpleSharePointapptomanagecustomers.Duringinstallation,theappcanbedesignedtocreateacustomerlistusingthestandardContactslisttypealongwithasetofpagesdesignedtoprovideasnazzyuserexperienceforaddingandfindingcustomers.YourappcouldadditionallybedesignedtocreateadocumentlibraryuponinstallationsothattheappcanstorecustomercontractsasMicrosoftWorddocuments,wherebyeachWorddocumentwouldreferenceaspecificcustomeriteminthecustomerslist.

    So,wheredoestheSharePointhostenvironmentstorethecontentaddedbyanappduringinstallation?TheanswerisinsideaspecialchildsitethattheSharePointhostenvironmentcreatesunderthesitewheretheapphasbeeninstalled.Thischildsiteisknownastheappweb.

    TheappwebisanessentialpartoftheSharePointappmodelbecauseitrepresentstheisolatedstoragethatisownedbyaninstalledinstanceofaSharePointapp.Theappwebprovidesascopefortheappsprivateimplementationdetails.Notethatanappbydefaulthasfullpermissionstoreadandwritecontentwithinitsownappweb.However,SharePointapphasnootherdefaultpermissionstoaccesscontentfromanyotherlocationintheSharePointhostenvironment.Theappwebistheonlyplacewhereanappcanaccesscontentwithoutrequestingpermissionsthatthenmustbegrantedbyauser.

    ThereisavaluableaspectoftheSharePointappmodelthatdealswithuninstallinganappandensuringthatalltheapp-specificstorageisdeletedautomatically.Inparticular,theSharePointhostenvironmentwillautomaticallydeletetheappwebforanappwhenevertheappisuninstalled.ThisprovidesasetofcleanupsemanticsforSharePointappsthatisentirelymissingfromthedevelopmentmodelforSharePointsolutions;whenanappisuninstalled,itdoesntleaveabunchofjunkbehind.

    Understandingtheappweb-hostingdomainNow,itstimetofocusonthestartpageforaSharePoint-hostedapp.Asyouhaveseen,thestartpageforaSharePoint-hostedappisaddedtotheappwebduringinstallation.ConsiderascenarioinwhichyouhaveinstalledaSharePointappwiththenameofMyFirstAppinaSharePointteamsite,whichisaccessiblethroughthefollowingURL:

  • https://intranet.wingtip.com.

    Duringappinstallation,theSharePointhostenvironmentcreatestheappwebasachildsiteunderthesitewheretheappisbeinginstalled.TheSharePointhostenvironmentcreatesarelativeURLfortheappwebbasedontheappsNameproperty.Therefore,inthisexample,theappwebiscreatedwitharelativepathofMyFirstApp.Iftheappsstartpagenameddefault.aspxislocatedintheappwebwithinthePagesfolder,therelativepathtothestartpageisMyFirstApp/Pages/default.aspx.YourintuitionmighttellyouthattheappsstartpagewillbeaccessiblethroughaURLthatcombinestheURLofthehostwebtogetherwiththerelativepathtotheappsstartpage,asinthefollowing:

    https://intranet.wingtip.com/MyFirstApp/Pages/default.aspx

    However,thisisnotthecase.TheSharePointhostenvironmentdoesnotmaketheappweboranyofitspagesaccessiblethroughthesamedomainasthehostwebthatisusedtolaunchtheapp.Instead,theSharePointhostenvironmentcreatesanewuniquedomainontheflyeachtimeitcreatesanewappwebaspartoftheappinstallationprocess.Bydoingso,theSharePointhostenvironmentcanisolateallthepagesfromanappwebinitsownprivatedomain.ThestartpageforaSharePoint-hostedappismadeaccessiblethroughaURLthatlookslikethis:

    https://wingtiptenant-ee060af276f95a.apps.wingtip.com/MyFirstApp/Pages/Default.aspx

    Atthispoint,itshouldbeclearwhyyouarerequiredtoconfiguretheelementforaSharePoint-hostedappbyusingthe~appWebUrltoken.TheURLtotheappwebisnotknownuntiltheSharePointhostenvironmentcreatesthenewdomainfortheappwebduringinstallation.Aftercreatingthedomainforanappweb,theSharePointhostenvironmentcanreplacethe~appWebUrltokenwithanactualURL.

    LetsexaminetheURLthatisusedtoaccesstheappwebingreaterdetail.ConsiderthefollowingURL,whichisusedtoaccessanappwebinanon-premisesfarm:

    wingtiptenant-ee060af276f95a.apps.wingtip.com/MyFirstApp

    ThefirstpartoftheappwebURL(wingtiptenant)isbasedonthenameofthetenancywheretheapphasbeeninstalled.Thisvalueisconfigurableinanon-premisesfarm.IntheOffice365environment,thetenancynameisestablishedwhenthecustomercreatesanewaccount,anditcannotbechangedafterward.

    ThesecondpartoftheappwebURL(ee060af276f95a)isknownasanAPPUID.Thisisaunique14-characteridentifiercreatedbytheSharePointhostenvironmentwhentheappisinstalled.RememberthattheAPPUIDisreallyanidentifierforaninstalledinstanceofanapp,asopposedtoanidentifierfortheappitself.

    ThethirdpartoftheappwebURL(apps.wingtip.com)istheappwebhostingdomain.Youhavetheabilitytoconfigurethisinanon-premisesfarmtowhatevervalueyouwouldlike.JustensurethatyouhavealsoconfiguredtheproperDNSsettingforthisdomainsothatitresolvestoanIPaddresspointingtothewebserver(s)ofyouron-premisesfarms.InOffice365theappweb-hostingdomainisalways

  • sharepoint.com.

    Now,askyourselfthisfundamentalquestion:whydoesnttheSharePointhostenvironmentserveuppagesfromtheappwebbyusingthesamedomainasthehostwebfromwhichtheapphasbeenlaunched?ThereasonswhytheSharePointhostenvironmentservesuppagesfromtheappwebintheirownisolateddomainmightnotbeobvious.TherearetwoprimaryreasonswhytheSharePointappmodeldoesthis.Bothofthesereasonsarerelatedtosecurityandtheenforcementofpermissionsgrantedtoanapp.

    ThefirstreasonforisolatinganappwebinitsownprivatedomainhastodowithpreventingdirectJavaScriptcallsfrompagesintheappwebbacktothehostweb.ThissecurityprotectionoftheSharePointappmodelbuildsonthebrowsersbuilt-insupportforprohibitingcross-sitescripting(XSS).BecauseJavaScriptcoderunningonpagesfromanappweboriginatesfromadifferentdomain,thiscodecannotdirectlycallbacktothehostweb.Morespecifically,callsfromJavaScriptrunningonappwebpagesdonotrunwiththesameestablisheduseridentityasJavaScriptcode-behindpagesinthehostweb.Therefore,theJavaScriptcoderunningonappwebpagesdoesntautomaticallyreceivethesamesetofpermissionsasJavaScriptcoderunningonpagesfromthehostweb.

    ThesecondreasonforcreatinganisolateddomainforeachappwebhastodowithprocessingofJavaScriptcallbacksthatoccuronthewebserveroftheSharePointhostenvironment.BecausetheSharePointhostenvironmentcreatesanewuniquedomainforeachappweb,itcandetermineexactlywhichappiscallingwhenitseesaJavaScriptcallbackoriginatingfromapageinanappweb.

    ThekeypointisthattheSharePointhostenvironmentisabletouseaninternalmechanismtoauthenticateanappthatusesJavaScriptcallbacksoriginatingfromitsappweb.Asaresult,theSharePointhostenvironmentcanenforceasecuritypolicybasedonthepermissionsthathavebeengrantedtotheapp.

    RememberthataSharePointapphasadefaultsetofpermissionsbywhichitcanaccessitsappwebbuthasnootherpermissionsbydefaulttoaccessanyothersite.TheabilityoftheSharePointhostenvironmenttoauthenticateanappbyinspectingtheURLofincomingcallsoriginatingfromtheappwebhostingdomainisessentialtoenforcingthisdefaultpermissionsscheme.

    Workingwithappuser-interfaceentrypointsEverySharePointapprequiresastartpage.Asyouknow,theURLtothestartpagesisusedwithinanapplaunchertoredirecttheuserfromthehostwebtothestartpage.Thistypeofentryintotheuserinterfaceoftheappisknownasafullimmersionexperiencebecausetheapptakesovertheuserinterfaceofthebrowserwithafull-pageview.

    TheuserinterfaceguidelinesofSharePointappdevelopmentrequiretheappstartpagetoprovidealinkbacktothehostweb.Thisrequirementexistssothatausercanalwaysreturntothehostwebfromwhichtheapphasbeenlaunched.WhenyouaredevelopingaSharePoint-hostedapp,thereisastandardmasterpageusedinappwebsnamedapp.masterthatautomaticallyaddstherequiredlinkbacktothehostwebforyou.

    Whendevelopingacloud-basedappwiththestartpageintheremoteweb,youcannotrelyonaSharePointmasterpagetoautomaticallyprovidethelinkonthestartpagewhichredirectstheuserbacktothehostweb.Instead,youmustuseatechniquethatinvolvesreadingtheSPHostUrlparameterwhichispassedtothestartpageinthequerystring.Thisisoneofthekeyreasonswhyyoualwayswanttofollow

  • thepracticeofaddingthe{StandardTokens}tokentothestartpageURLofacloud-hostedapp.

    ThereareseveraldifferenttechniquesthatyoucanuseinthecodebehindastartpageintheremotewebtoreadtheSPHostUrlparametervaluefromthequerystringanduseittoconfiguretherequiredlinkbacktothehostweb.Forexample,youcanaccomplishthistaskwithserver-sideC#codeorwithclient-sideJavaScriptcode.InChapter4,youcanseehowtoaccomplishthistaskbyusingaclient-sideJavaScriptcomponentknownasthechromecontrol.

    Inadditiontotherequiredstartpage,aSharePointappcanoptionallyprovidetwoothertypesofentrypointsknownasapppartsandUIcustomactions.Unlikethestartpage,youuseapppartsandUIcustomactionstoextendtheuserinterfaceofthehostweb.

    BuildingapppartsAnapppartisauserinterfaceelementthatissurfacedonpagesinthehostwebbyusinganIFrame.Onceanappwithanappparthasbeeninstalled,ausercanthenaddanappparttopagesinthehostwebbyusingthesameuserinterfaceexperiencethatisusedtoaddstandardwebparts.

    YouimplementanapppartinVisualStudio2012byusingaclientwebpart.Thismakesmostdevelopersask,Whatsthedifferentbetweenanapppartandaclientwebpart?ThebestwaytothinkaboutthisisthatthetermapppartismeantforSharePointusers,whereasthetermclientwebpartisusedbydeveloperstodescribetheimplementationofanapppart.

    Despitehavingsimilarnames,clientwebpartsareverydifferentfromthestandardwebpartsthatarefamiliartomostSharePointdevelopers.Inparticular,aclientwebpartcannothaveanyserver-sidecodethatrunswithintheSharePointhostenvironment.TheimplementationofaclientwebpartmustfollowtherulesofSharePointappdevelopment.

    Clientwebpartsaresupportedundereachofthethreeapphostingmodels.YouimplementaclientwebpartinaSharePoint-hostedappbyusingHTML,CSS,andJavaScript.Inacloud-hostedapp,youalsohavetheoptionofimplementingthebehaviorforaclientwebpartbyusingserver-sidecodeintheremoteweb.

    Atfirst,manydevelopersassumethataclientwebpartisnothingmorethananIFramewrapperaroundanexternalwebpage.However,theclientwebpartprovidessignificantvaluebeyondthat.WhenyouconfiguretheURLwithinaclientwebpart,youcanusethesametokensaswiththestartpage,suchas~appWebUrl,~remoteAppUrl,and{StandardTokens}.Clientwebpartsalsosupportaddingcustomproperties,aswell.Furthermore,thepagebehindaclientwebpartisoftenpassedcontextualsecurityinformationthatallowsittocallbackintotheSharePointhostenvironmentwithanestablishedappidentity.YoucanthinkoftheclientwebpartasanIFrameonsteroids.

    WhenyouwanttoaddanewclientwebparttoaSharePointappproject,youusetheAddNewItemcommand.TheAddNewItemdialogboxinVisualStudio2012providesaClientWebPartitemtemplate,asshowninFigure1-7.

    Whenyouaddanewprojectitemforaclientwebpart,VisualStudio2012addsanelements.xmlfiletotheSharePointappprojectthatcontainsaClientWebPartelement.ThefollowingcodeisasimpleexampleoftheXMLdefinitionforaclientwebpartinaSharePoint-hostedappprojectthatisimplementedbyusingapageinsidetheappweb:

  • Figure1-7.TheAddNewItemdialogprovidestemplatesforaddingclientwebpartsandUIcustomactionstoappprojects.

    Asyoucanseefromthisexample,thecontentdisplayedinaclientwebpartisconfiguredbyassigningaURLtotheSrcattributeoftheelement.ThewebpagethatisreferencedbythisURLisusuallyaddedtoeithertheappwebortotheremoteweb.However,youcanevenreferenceawebpageontheInternetthatisneitherinanappwebnorinaremoteweb.TheonlyimportantrestrictionisthatthewebpagecannotbereturnedwiththeX-Frame-OptionsheaderintheHTTPresponse.ThisisaheaderusedbysomewebsitestopreventitspagesfrombeingusedinsideanIFramewithatypeofattackknownasclickjacking.

    HereissomethingthatcancatchyouoffguardwhencreatingaclientwebpartinaSharePoint-hostedapp:thedefaultbehaviorofSharePoint2013istoaddtheX-Frame-OptionsheaderwithavalueofSAMEORIGINintheHTTPresponsewhenitservesuppagesfromaSharePointsite.Theresultofthisisthatapageservedupfromtheappwebwillnotworkwhenyouattempttouseitasthepagebehindaclientwebpart.ThewaytodealwiththisproblemistoaddthefollowingdirectivetothetopofanypageintheappwebreferencedbyaclientwebparttosuppressthedefaultbehaviorofaddingtheX-Frame-Optionsheader:

  • Whenyoudevelopclientwebparts,youcanaddcustomproperties.Therealvalueofcustompropertiesisthattheycanbetailoredbytheuserinthebrowserinthesamefashionasausercustomizesthepropertiesofstandardwebparts.Youdefineacustompropertybyaddingaelementintotheelementandthenaddingaelementwithinthat,asillustratedinExample1-2.

    Example1-2.ClientWebPartproperties

    Onceyouhaveaddedacustomproperty,youmustthenmodifythequerystringattheendoftheURLthatisassignedtotheSrcattributeintheelement.Youdothisbyaddingaquerystringparameterandassigningavaluebasedonapatternbywhichthepropertynameisgivenanunderscorebeforeitandafterit.Thus,forapropertynamedMyProperty,youshouldcreateaquerystringparameterandassignitavalueofMyProperty.ThiswouldresultinXMLwithintheelementthatlookslikethefollowing:

    Notethatyoucanuseanynameyouwantforthequerystringparameteritself.Itswhenyouassignavaluetotheparameterthatyouhavetouseactualpropertynameandfollowthepatternofaddingtheunderscoresbothbeforeandafter.

    BuildingUIcustomactionsAUIcustomactionisadeveloperextensionintheSharePointappmodelwithwhichyoucanaddcustomcommandstothehostsite.ThecommandforaUIcustomactionissurfacedintheuserinterfaceofthehostsitebyusingeitherabuttonontheribbonoramenucommandinthemenuassociatedwithitemsinalistordocumentsinadocumentlibrarythatisknownastheEditControlBlock(ECB)menu.ItistheactofinstallinganappwithUIcustomactionsthatautomaticallyextendstheuserinterfaceofthehostsitewithribbonbuttonsandECBmenucommands.

    Asinthecaseoftheclientwebpart,UIcustomactionsaresupportedineachofthethreeapphostingmodels.However,aUIcustomactionisdifferentthantheclientwebpartbecauseitspurposeisnottodisplaycontentinthehostweb.Instead,itprovidesanexecutablecommandforbusinessuserswithwhichtheycandisplayapagesuppliedbytheapp.ThepagethatisreferencedbyaUIcustomactioncanbeineithertheappwebortheremoteweb.

  • Asadeveloper,youhavecontroloverwhatispassedinthequerystringforaUIcustomaction.Thismakesitpossibletopasscontextualinformationabouttheitemorthedocumentonwhichthecommandwasexecuted.ThisinturnmakesitpossibleforcodeinsidetheapptodiscoverinformationsuchastheURLthatcanbeusedtoaccesstheitemordocumentbyusingeithertheClient-SideObjectModel(CSOM)orthenewRepresentationalStateTransfer(REST)API,whichisdiscussedinChapter2.

    Keepinmindthatanappwillrequireadditionalpermissionsbeyondthedefaultpermissionsetinordertoaccesscontentinthehostweb.ThistopicisdiscussedinChapter3.ThiscurrentchapterwillonlydiscusshowtocreateaUIcustomactionthatpassescontextualinformationtoapagesuppliedbytheapp.Chapter3alsocoverswhatsrequiredtoactuallyusethisinformationtocallbackintotheSharePointhostenvironment.

    InthedialogboxshownearlierinFigure1-6,youcanseethatVisualStudio2012providesaprojectitemtemplatenamedUICustomAction.WhenyouusethisitemtemplatetocreateanewUIcustomaction,VisualStudio2012addsanewelements.xmlfiletoyourSharePointappproject.Whenyoulookinsidetheelements.xmlfileyoufindaelementthatyoucanmodifytodefineeitheranECBmenuitemorabuttonontheribbon.

    ManySharePointdevelopersalreadyhaveexperienceworkingwithcustomactionsinSharePoint2007andSharePoint2010.ThegoodnewsisthatthemannerinwhichyouedittheXMLwithintheelementforaSharePointappprojectworksthesamewayasitdoesforaSharePointsolutionproject.ThebadnewsisthatmanyofthecustomactionsavailablewhendevelopingfarmsolutionsarenotavailablewhendevelopingaSharePointapp.

    Inparticular,aSharePointapponlyallowsforUIcustomactionsthatcreateECBmenucommandsandribbonbuttons.TheSharePointappmodelimposesthisrestrictiontoprovideabalancebetweenfunctionalityandsecurityconcerns.Furthermore,youareprohibitedfromaddinganycustomJavaScriptcodewhenyouconfiguretheURLforaUIcustomactioninaSharePointapp.Ifthisrestrictionwerenotenforced,JavaScriptcodefromtheappcouldcallintothehostsitewithoutbeinggrantedtheproperpermissions.

    SupposethatyouwanttocreateaUIcustomactiontoaddacustomECBmenuitemtoalltheitemsineveryContactslistwithinthehostsite.YoucanstructuretheelementtolooklikethatpresentedinExample1-3.

    Example1-3.ACustomActiondefinition

    OnceyouinstallanappwiththisUIcustomaction,itregistersanECBmenucommandforeveryiteminliststhathavealisttypeIDof105.ThisistheIDfortheContactslisttype.Oncetheappisinstalled,the

  • hostwebwillprovideacustommenuitemontheECBmenuforeachiteminanyContactslist.AnexampleofwhattheECMmenucommandlookslikeisshowninFigure1-8.

    Figure1-8.AcustomUIactionisusedtoaddanitemtotheedit-controlblockorribbon.

    ThedefaultactionofaUIcustomactionistoredirecttheusertothepagereferencedbytheURLconfiguredwithintheelement.Thismakessenseforascenarioinwhichyouwanttomovetheuserfromthehostwebintothefullimmersionexperienceoftheappinordertodosomework.However,thisdefaultbehaviorwillprovideadistractinguserinterfaceexperienceforascenarioinwhichauserwishestoreturntothehostwebimmediatelyafterseeingthepagedisplayedbytheapp.Forthesescenarios,youcanmodifytheUIcustomactiontodisplaythepagefromtheappasadialogboxinthecontextofthehostweb.Theuserinterfaceexperienceismuchbetterbecausetheusercanseeapagefromtheappwithouteverleavingthehostweb.

    Example1-4demonstratesthetechniquetodisplaythepagereferencedbyaUIcustomactionasadialogbox,whichinvolvesaddingthreeattributestotheelement.First,youaddtheHostWebDialogattributeandassignitavalueoftrue.Next,youaddtheHostWebDialogWidthattributeandtheHostWebDialogHeightattributeandassignthemvaluestosetthewidthandheightofthedialogbox.

    Example1-4.Displayingareferencedpage

  • Now,letsgointomoredetailaboutconfiguringtheUrlattributeoftheelement.WhenyouconfiguretheURLyoucanusethesamefamiliartokensthatyouusewiththestartpageandwithclientwebpartssuchas~appWebUrl,~remoteAppUrl,and{StandardTokens},asshowninthefollowingcode:

    However,UIcustomactionssupportseveraladditionaltokensbeyondwhatisavailableforstartpagesandclientwebparts.Thesearethetokensthatmakeitpossibletopasscontextualinformationabouttheitemordocumentonwhichthecommandwasexecuted.Forexample,youcanpassthesite-relativeURLtotheitemordocumentbyusingthe{ItemURL}token.

    Inmostscenarios,youwillalsoneedtheabsoluteURLtotherootofthehostweb,whichcanbepassedbyusingthe{HostUrl}token.NotethattheUrlisconfiguredbyusinganXMLattribute,soyoucannotusethe&characterwhencombiningtwoormoreparameterstogether.Instead,youmustusetheXMLencodedvalue,whichis&amp,asshowninthefollowingexample:

    NotethattheSharePointhostenvironmentsubstitutesvaluesintothesetokensbyusingstandardURLencoding.ThismeansthatyoumustwritecodeintheapptouseaURLdecodingtechniquebeforeyoucanusethesevaluestoconstructaURLthatcanbeusedtoaccesstheitemordocument.

    Table1-2liststhetokensthatcanbeusedinUIcustomactions,beyondthosethatarealsosupportedinstartpagesandclientwebparts.NotethatsomeofthetokensworkequallywellregardlessofwhethertheUIcustomactionisusedtocreateanECBmenuitemorabuttonintheribbon.However,the{ListID}tokenandthe{ItemID}tokenworkwithECBmenuitemsbutnotwithbuttonsontheribbon.Conversely,the{SelectedListId}tokenandthe{SelectedItemId}tokenworkwithbuttonsontheribbonbutnotwithECBmenuitems.

  • Table1-2.TheextratokensavailablewhenconfiguringtheURLforaUIcustomaction

    Token Purpose

    {HostUrl} ProvidesanabsoluteURLtotherootofthehostsite

    {SiteUrl} ProvidesanabsoluteURLtotherootofthecurrentsitecollection

    {Source} ProvidesarelativeURLtothepagethathoststhecustomaction

    {ListURLDir} Providesasite-relativeURLtotherootfolderofthecurrentlist

    {ListID} ProvidesaGUID-basedIDofthecurrentlist(ECBonly)

    {ItemURL} Providesasite-relativeURLtotheitemordocument

    {ItemID} Providesaninteger-basedIDoftheitemordocument(ECBonly)

    {SelectedListId} ProvidesaGUID-basedIDoftheselectedlist(ribbononly)

    {SelectedItemId} Providesaninteger-basedIDoftheselecteditemordocument(ribbononly)

    PackaginganddistributingappsThefinalsectionofthischapterexamineshowSharePointappsaredistributedanddeployedintoproductionaswellashowappsaremanagedovertime.First,youwilllearnaboutthedetailsofhowappsarepackagedintoredistributablefiles.Afterthat,youwillseehowthesefilesarepublishedandinstalledtomakeSharePointappsavailabletousers.Asyouwillsee,theSharePointappmodelprovidesvaluablesupportformanagingappsinaproductionenvironmentandupgradingtonewerversions.

    PackagingappsASharePointappispackagedupfordeploymentbyusingadistributablefileknownasanapppackage.Anapppackageisafilebuiltbyusingtheziparchivefileformatanditrequiresanextensionof.app.Forexample,ifyoucreateanewSharePoint-hostedappprojectnamedMySharePointApp,theprojectwillgenerateanapppackagenamedMySharePointApp.appasitsoutput.

    NotethatthezipfileformatforcreatinganapppackageisbasedontheOpenPackageConvention(OPC).ThisisthesamefileformatthatMicrosoftOfficebeganusingwiththereleaseofOffice2007forcreatingWorddocuments(.docx)andMicrosoftExcelworkbooks(.xslx).

    Theprimaryrequirementforanapppackageisthatitcontainstheappmanifestasatop-levelfilenamedAppManifest.xml.Asdiscussedearlierinthischapter,theSharePointhostenvironmentreliesonmetadatacontainedintheappmanifestsothatitcanproperlyconfigureanappduringtheinstallationprocess.

    AnapppackagewillusuallycontainanappiconfilenamedAppIcon.png.TheAppIcon.pngfile,likemanyoftheotherfilesinanapppackage,ispairedwithanXMLfilenamedAppIcon.png.config.xml.ThepurposeofthisXMLfileistoassigntheAppIcon.pngfileanidentifyingGUID.

    UnderstandingtheappwebsolutionpackageInadditiontotheAppManifest.xmlfile,theapppackageoftencontainsadditionalfilesthatareusedas

  • partoftheappsimplementation.Forexample,theapppackageforaSharePoint-hostedappcontainsafilefortheappsstartpagealongwithotherresourcesusedbythestartpagesuchasaCSSfileandaJavaScriptfile.Theseareexamplesoffilesthatareaddedtotheappwebaspartoftheappinstallationprocess.

    ThedistributionmechanismusedbyaSharePointapptoaddpagesandliststotheappwebduringinstallationisastandardsolutionpackage,whichisaCABfilewitha.wspextension.Ifthissoundsfamiliar,thatsbecausethesolutionpackagefileembeddedwithinanapppackagehastheexactsamefileformatasthesolutionpackagefilesthatdevelopershavebeenusingtodeploySharePointsolutionsinSharePoint2007andSharePoint2010.TheonekeydifferenceisthatthesolutionpackageusedbytheSharePointappmodeltoaddfilestoanappwebisnotastand-alonefile.Instead,itisembeddedasa.wspfilewithintheapppackage,asshowninFigure1-9.

    Figure1-9.Apppackagesthatcontainartifactsfordeploymentcontainaseparatesolutionpackagewithintheapppackage.

    WhenauserinstallsaSharePointapp,theSharePointhostenvironmentexaminestheapppackagetoseeifitcontainsaninnersolutionpackage.ItisthepresenceofaninnersolutionpackagewithintheapppackagefilethatspecifiestotheSharePointhostenvironmentwhetheritneedstocreateanappwebduringinstallation.Iftheapppackagedoesnotcontainaninnersolutionpackage,theSharePointhostenvironmentinstallstheappwithoutcreatinganappweb.

    Theappwebsolutionpackagecontainsasingleweb-scopedfeature.TheSharePointhostenvironmentactivatesthisfeatureautomaticallyontheappwebimmediatelyaftertheappwebiscreated.Thisfeatureiswhatmakesitpossibletoadddeclarativeelementssuchaspagesandliststotheappwebastheappisinstalled.

    Anappwebsolutionpackagecannotcontaina.NETassemblyDLLwithserver-sidecode.Therefore,you

  • cansaythattheappwebsolutionpackageembeddedinsideanapppackageisconstrainedbecauseitmustbeafullydeclarativesolutionpackage.Thisisdifferentfromthesolutionpackagesforfarmsolutionsandsandboxedsolutions,whichcancontainassemblyDLLswithcustom.NETcodewrittenineitherC#orVB.NET.

    KeepinmindthattheinstallationofaSharePointappdoesntalwaysresultinthecreationofanappweb.Someappsaredesignedtocreateanappwebduringinstallationandsomearenot.ASharePoint-hostedappisthetypeofappthatwillalwayscreateanappwebduringinstallation.ThisisarequirementbecauseaSharePoint-hostedapprequiresastartpagethatmustbeaddedtotheappweb.

    However,thingsaredifferentwithacloud-hostedapp.Becauseacloud-hostedappusuallyhasastartpagethatisservedupfromaremoteweb,itdoesnotrequirethecreationofanappwebduringinstallation.Therefore,theuseofanappwebinthedesignofaprovider-hostedapporanautohostedappisreallyjustanavailableoptionasopposedtoarequirementasitiswithaSharePoint-hostedapp.

    Whenyoudesignaprovider-hostedapporanautohostedapp,youhaveachoiceofwhetheryouwanttocreateanappwebduringinstallationtostoreprivateappimplementationdetailsinsidetheSharePointhost.Somecloud-hostedappswillstoreallthecontenttheyneedwithintheirownexternaldatabaseandwillnotneedtocreateanappwebduringinstallation.Othercloud-hostedappscanbedesignedtocreateanappwebduringinstallationforscenariosinwhichitmakessensetostorecontentwithintheSharePointhostenvironmentforeachinstalledinstanceoftheapp.

    PackaginghostwebfeaturesThischapterhasalreadydiscussedclientwebpartsandUIcustomactions.Asyourecall,thesetwotypesoffeaturesareusedtoextendtheuserinterfaceofthehostweb,asopposedtomanyoftheothertypesofelementsinanappthatareaddedtotheappweb.Forthisreason,theXMLfilescontainingthedefinitionsofclientwebpartsandUIcustomactionsarenotdeployedwithinasolutionpackageembeddedwithintheapppackage.Instead,theXMLfilesthatdefineclientwebpartsandUIcustomactionsareaddedtotheapppackageastop-levelfiles.

    ConsideranexampleSharePointappnamedMyAppPartsthatcontainstwoclientwebparts.Thecontentsoftheapppackageforthisappwillcontainatop-levelelements.xmlfileforeachoftheclientwebpartsandatop-levelfeature.xmlfileforthefeaturethathoststhem.WhenVisualStudio2012createstheseXMLfilesandbuildsthemintotheoutputapppackagefile,itaddsauniqueGUIDtoeachfilenametoavoidnamingconflicts,asillustratedinFigure1-10.

    ThefeaturethathostsclientwebpartsandUIcustomactionsisaweb-scopedfeatureknownasahostwebfeature.TheSharePointhostenvironmentisabletodetectahostwebfeatureinsideanapppackageduringappinstallationandactivateitinthehostweb.Whenanappwithawebhostfeatureisinstalledattenancyscope,thatfeaturewillbeactivatedinmorethanonesite.

  • Figure1-10.TheXMLfilesthatdefineclientwebpartsandUIcustomactionsarepackagedastop-levelfileswithintheapppackage.

    PackagingforautohostedappsWhenitcomestopackagingaSharePointappfordistribution,autohostedappsaremorecomplicatedanddeservealittleextraattention.TheextracomplexityisrequiredbecausetheapppackageforanautohostedappmustcontaintheresourcesrequiredtocreateanASP.NETapplicationondemandtodeploytheremoteweb.AnautohostedappcanalsobedesignedtocreateaSQLAzuredatabase,aswell,duringtheappinstallationprocess.

    Whenyoucreateanewautohostedapp,VisualStudio2012createstwoprojects.ThereisoneprojectfortheappitselfandasecondwebprojectforanASP.NETapplicationtoimplementtheremoteweb.Forexample,ifyoucreateanewautohostedappusingthenameMyAutoHostedApp,VisualStudio2012createsanappprojectnamedMyAutoHostedAppandanASP.NETprojectnamedMyAutoHostedAppWeb,andaddsthemtoasingleVisualStudiosolution.

    WhatisimportanttounderstandisthattheapppackagebuiltfortheMyAutoHostedAppprojectmustcontainallthenecessaryfilestodeploytheASP.NETprojectnamedMyAutoHostedAppWeb.ThisisarequirementbecausetheinstallationofthisapppackagemustprovidetheOffice365environmentwiththemeanstoprovisiontheremotewebasaWindowsAzureapplication.Thisiswhatmakesitpossibleforanautohostedapptocreateitsownremotewebduringtheinstallationprocess.

    VisualStudio2012reliesonapackagingformatthatMicrosoftcreatedespeciallyfortheWindowsAzureenvironmentbywhichallthefilesandmetadatarequiredtodeployanASP.NETapplicationarebuiltintoasinglezipfilefordistribution.Thiszipfileisknownasawebdeploypackage.WhenusedwithintheSharePointappmodel,thewebdeploypackageisembeddedwithintheapppackageofanautohostedappfordistribution.

    WhenVisualStudio2012buildsthewebdeploypackageforanautohostedapp,itcreatesthefilebycombiningtheapppackagenametogetherwithaweb.zipextension.Forexample,anapppackagednamedMyAutohostedApp.appwillhaveanembeddedwebdeploypackagenamedMyAutohostedApp.web.zip.

    Now,considerthescenarioinwhichanautohostedapphasanassociatedSQLAzuredatabase.The

  • Office365environmentmustcreatethisdatabaseondemandduringappinstallation.Therefore,theapppackagemustcontaintheresourcesrequiredtocreateaSQLAzuredatabasecontainingstandarddatabaseobjects,suchastables,indexes,storedprocedures,andtriggers.

    TheSharePointapppackagingmodeltakesadvantageofasecondpackagingformatthatMicrosoftcreatedforWindowsAzureknownasaDataTierApplicationpackage.Inthispackagingformat,themetadatarequiredtoautomatethecreationofaSQLAzuredatabaseisdefinedinXMLfilesthatarebuiltintoazipfilewithanextensionof.dacpac.ThenameoftheDataTierApplicationpackageistypicallybasedonthenameofthedatabase.Forexample,aSQLAzuredatabasenamedMySqlDatabasewillhaveanassociatedDataTierApplicationpackagenamedMySqlDatabase.dacpac.IfyoulookinsideaDataTierApplicationpackage,youcanlocateafilenamedmodel.xml,whichdefinesthedatabaseobjectsthatneedtobecreated.

    Figure1-11showsthelayoutofanapppackageforanautohostedappthatwilltriggertheOffice365environmenttocreatearemoteandaSQLAzuredatabaseaspartoftheappinstallationprocess.Rememberthatthewebdeploypackageisrequiredinanautohostedapppackage,whereasthedatatierapplicationpackageisoptional.

    Figure1-11.AnautohostedapppackagecontainsawebdeploymentpackagetocreatetheremotewebandadataapplicationpackagetocreateaSQLAzuredatabase.

    Whenyoucreateanautohostedapp,VisualStudio2012automaticallycreatesthewebprojectandtakescareofsettingupallthatsrequiredtobuildthewebdeploypackageintotheapppackage.However,youhavetotakeafewextrastepstocreateaSQLdatabaseprojectandconfigureittoproperlybuildtheDataTierApplicationpackageintotheapppackage.

    ThefirststepistocreateanewSQLdatabaseprojectinVisualStudio2012andaddittothesamesolutionthatcontainstheautohostedproject.Next,onthePropertiespageoftheSQLDatabaseproject,gototheProjectSettingstabandchangethetargetplatformsettingtoSQLAzure.ThisisthestepthatchangestheprojectoutputtoaDataTierApplicationpackage.Afterthis,youmustbuildtheSQLdatabaseprojectatleastoncetobuildtheDataTierApplicationpackage.

    ThefinalstepistoconfiguretheappprojecttoreferencetheDataTierApplicationpackage.Youcanaccomplishthisbyusingthepropertysheetfortheautohostedappproject.Youwillfindthatthereisa

  • projectpropertynamedSQLPackage.OnceyouconfiguretheSQLPackagepropertytopointtotheDataTierApplicationpackage(.dacpac)file,youhavemadethenecessarychangessothatVisualStudio2012willbeginbuildingtheDataTierApplicationpackageintoapppackagefile.

    PublishingappsTheapppackageisadistributablefilethatsusedtopublishSharePointapps.Oncetheapppackagehasbeenpublished,itisavailableforuserstoinstall.InthecaseofSharePoint-hostedappsandautohostedapps,theapppackagecontainsalltheresourcesrequiredtodeploytheappduringtheinstallationprocess.However,provider-hostedappsrequirethedevelopertodeploytheremotewebindependentlyofthepublicationprocessandtheinstallationprocess.

    YoupublishaSharePointappbyuploadingitsapppackagefiletooneoftwodifferentplaces.First,youcanpublishanappbyuploadingitsapppackagetothepublicOfficeStore.Thisistherightchoicetomakeyourappavailabletothegeneralpublic,includinguserswithSharePointtenanciesinOffice365.

    ThesecondwaytopublishaSharePointappisbyuploadingtheapppackagetoaspecialtypeofsiteknownasanappcatalogsite.ThisistheoptiontousewhenyouwanttomaketheappavailableonlytouserswithinaspecificOffice365tenancyorwithinaspecificon-premisesfarm.

    PublishingSharePointappstotheOfficeStoreTopublishanapptothepublicOfficeStore,thedevelopermustfirstcreateadashboardselleraccount.Youcancreatethistypeofaccountbynavigatingtohttps://sellerdashboard.microsoft.cominthebrowserandloggingonwithavalidWindowsAccount.Onceyouhaveloggedon,youcancreateanewdashboardselleraccountthatiseitheranindividualaccountoracompanyaccount.

    AveryappealingaspectofpublishingappstotheOfficeStorewithadashboardselleraccountisthatitprovidesassistancewiththemanagementoflicensingaswellascollectingmoneyfromcustomersthroughcreditcardtransactions.Whenyoucreateadashboardselleraccount,youareabletocreateasecondpayoutaccountfromwhichyousupplyMicrosoftwiththenecessarydetailssowhenitcollectsmoneyfromcustomerspurchasingyourapps,itcantransferthefundsyouhaveearnedtoeitherabankaccountoraPayPalaccount.

    Onceyouhavegonethroughtheprocessofcreatingadashboardselleraccount,ittakesadayortwoforthisnewaccounttobeapproved.Onceyouraccounthasbeenapproved,youcanthenbegintopublishyourappsintheOfficeStore.TheOfficeStoresupportspublishingthreetypesofapps:youcanpublishSharePointapps,AppsforOffice,andWindowsAzureCatalogApps.

    YoupublishaSharePointappbyuploadingitsapppackagefileandfillinginthedetailsassociatedwiththeapp.Forexample,thepublishingprocessfortheOfficeStorerequiresyoutoprovideatitle,versionnumber,description,category,logo,andatleastonescreenshotthatshowspotentialcustomerswhatyourapplookslike.

    WhenyoupublishaSharePointapp,youcanalsoindicateviathesellerdashboardwhetheryourappisfreeormustbepurchased.Ifyoupublishanappforpurchase,youcanspecifythelicensingfeeforeachuserorforagivennumberofusers.Thereisevenanoptiontoconfigureafreetrialperiodforanappthathasanassociatedlicensingfee.

    https://sellerdashboard.microsoft.com

  • Onceyouhaveuploadedanappandprovidedtherequiredinformation,theappmustthengothroughanapprovalprocess.Theapprovalprocessinvolvescheckingtheapppackagetoensurethatitonlycontainsvalidresources.Therearealsocheckstovalidatethattheappmeetstheminimumrequirementsoftheuserexperienceguidelines.Forexample,thereisachecktoensurethatthestartpagefortheappcontainstherequiredlinkbacktothehostweb.

    Oncetheapphasbeenapproved,itisthenreadyforuseandaddedtothepublicOfficeStorewhereitcanbediscoveredandinstalledbySharePointusers.

    PublishingappstoanappcatalogWhatshouldyoudoifyouwanttopublishanappbutyoudontwanttopublishittotheOfficeStore?Forexample,imagineascenarioinwhichyoudontwanttomakeanappavailabletothegeneralpublic.Instead,youwanttopublishtheapptomakeitavailabletoasmalleraudiencesuchasahandfulofcompaniesthatarewillingtopayyouforyourdevelopmenteffort.Theansweristopublishtheapptoanappcatalogsite.

    Anappcatalogsitecontainsaspecialtypeofdocumentlibrarythatisusedtouploadandstoreapppackagefiles.Alongwithstoringtheapppackagefile,thisdocumentlibraryalsotracksvarioustypesofmetadataforeachapp.Someofthismetadataisrequired,whereasothermetadataisoptional.

    IntheOffice365environment,theappcatalogsiteisautomaticallyaddedwhenatenancyiscreatedforanewcustomer.However,thisisnotthecaseinanon-premisesfarm.Instead,youmustexplicitlycreatetheappcatalogsitebyusingtheCentralAdministrationsiteorbyusingWindowsPowerShell.Furthermore,theappcatalogiscreatedatwebapplicationscope,soyoumustcreateaseparateappcatalogsiteforeachwebapplication.

    Youmusthavefarmadministratorpermissionswithinanon-premisesfarmtocreateanappcatalogsite.YoubeginbynavigatingtothehomepageofCentralAdministration.Onthehomepage,thereisatop-levellinkforApps.WhenyouclicktheAppslink,youwillberedirectedtoapagewithagroupoflinksundertheheadingofAppManagement.Withinthisgroupoflinks,locateandclickthelinktitledManageAppCatalog.

    ThefirsttimeyouclicktheManageAppCataloglink,youareredirectedtotheCreateAppCatalogpage,whichyoucanusetocreateanewappcatalogsite,asshowninFigure1-12.Notethattheappcatalogsitemustbecreatedasatop-levelsitewithinanewsitecollection.OntheCreateAppCatalogpage,youcanselectthetargetwebappthatwillhostthenewappcatalogsite.

  • Figure1-12.TheappcatalogcanbecreatedthroughCentralAdministrationwithinaspecificwebappofyourchoice.

    NotethatyoucanalsousetheCreateAppCatalogpage(shownalittlelaterinFigure1-14)toconfigureuseraccesspermissionstotheappcatalogsite.Rememberthatprovidinguserswithaccesstotheappcatalogsiteiswhatmakesitpossibleforthemtodiscoverandinstallappsoftheirown.Youmustprovidereadaccesstousersifyouwantthemtohavetheabilitytodiscoverappsandinstallthematsitescope.However,youmightdecideagainstconfiguringuseraccesstotheappcatalogsiteifyouplanoninstallingappsattenancyscope.

    Onceyouhavecreatedtheappcatalogsitewithinanon-premisesfarm,youshouldnavigatetoitandinspectwhatsinside.YouwillfindthatthereisadocumentlibrarywithatitleofAppsforSharePointwhichisusedtopublishSharePointapps.ThereisaseconddocumentlibrarywithatitleofAppsforOfficethatisusedtopublishappscreatedforOfficeapplicationssuchasWordandExcel.

    YoupublishaSharePointappbyuploadingitsapppackagetotheAppsforSharePointdocumentlibrary.TheSharePointhostenvironmentisabletoautomaticallyfillinsomeoftherequiredappmetadatasuchastheTitle,Version,andProductIDbyreadingtheappmanifestastheapppackageisuploaded.However,thereisadditionalmetadatathatmustbefilledinbyhandorbysomeothermeans.AviewofappsthathavebeenpublishedintheAppsforSharePointdocumentlibraryispresentedinFigure1-13.

    Figure1-13.TheAppsforSharePointdocumentlibrarycontainsapppackagefilesandassociatedmetadataforpublishedapps.

    Youwillalsonoticethattheappcatalogsitesupportsthemanagementofapprequestsfromusers.TheideabeingthatauserwithinasitecanrequestanappfromtheOfficeStore.Theappcatalog

  • administratorcanseethisrequestanddecidewhethertopurchasetheappornot.Iftheapprequestseemsappropriate,theappcatalogadministratorcanpurchasetheappandmakeitavailableforsite-scopeinstallation.Alternatively,theappcatalogadministratorcanmaketheappavailabletotherequesterbyusingatenancy-scopedinstallation.

    InstallingappsOnceanapphasbeenpublished,itcanbediscoveredandinstalledbyauserwhohasadministratorpermissionsinthecurrentsite.IfyounavigatetotheSiteContentpagewithinasiteandclickthetilewiththecaptionaddanapp,youwillberedirectedtothemainpageforinstallingappsnamedaddanapp.aspx.Thispagedisplaysappsthathavebeenpublishedtotheappcatalogsite.RememberthatanOffice365tenancyhasasingleappcatalogsite,buton-premisesfarmshaveanappcatalogsiteperwebapplication.Therefore,youwillnotseeappsthathavebeenpublishedtoanappcatalogsiteinadifferentwebapplication.

    Auserrequiresadministratorpermissionswithinasitetoinstallanapp.Ifyouareloggedonwithauseraccountthatdoesnothaveadministratorpermissionswithinthecurrentsite,youwillnotbeabletoseeappsthathavebeenpublishedintheappcatalogsite.Thisistrueevenwhenyouruseraccounthasbeengrantedpermissionsontheappcatalogsiteitself.

    Onceyoulocateanappthatyouwanttoinstall,youcansimplyclickitstiletoinstallit.Theappinstallationprocesstypicallypromptsyoutoverifywhetheryoutrusttheapp.Apageappearsthatdisplaysalistofthepermissionsthattheappisrequestingalongwithabuttontograntordenytheappspermissionrequest.Youmustgrantallpermissionsthattheapphasrequestedtocontinuewiththeinstallationprocess.Thereisnoabilitytograntonerequestedpermissiontoanappwhiledenyinganother;grantingpermissionstoanappduringinstallationisalwaysanall-or-nothingproposition.

    Aftertheapphasbeeninstalled,youwillseeatileforitontheSiteContentpage.Thistilerepresentstheapplauncherthatausercanclicktoberedirectedtotheappsstartpage.Theapptitlealsodisplaysanellipsetoaccessafly-outmenuforappmanagement,asillustratedinFigure1-14.

    Figure1-14.Onceanapphasbeeninstalled,itcanbelaunchedusinganassociatedtile,whichisdisplayedonthesitecontentpage.

    Recallfromearlierinthechapterwhathappensduringappinstallation.Someappsrequireanappweb.Whenthisisthecase,theappwebiscreatedasachildsiteunderthecurrentsitewheretheapphasbeeninstalled.IftheappcontainshostfeatureelementssuchasclientwebpartsandUIcustomactions,theseuserinterfaceextensionswillbemadeavailableinthehostsite,aswell.

  • InstallingappsattenancyscopeYouhaveseenthattheappcatalogsiteprovidesaplacewhereyoucanuploadappsinordertopublishthem.Onceanapphasbeenpublishedintheappcatalogsite,auserwithinthesameOffice365tenancyorwithinthesameon-premiseswebapplicationcandiscovertheappandinstallitatsitescope.However,thefunctionalityofanappcatalogsitegoesonestepfurther:itplaysacentralroleininstallingappsattenancylevel.

    Youinstallanappattenancyscopebyinstallingitinanappcatalogsite.Justaswithasite-scopedinstallation,youmustfirstpublishtheappbyuploadingittotheAppsforSharePointdocumentlibraryintheappcatalogsite.Afterpublishingtheapp,youshouldbeabletolocateitontheAddAnApppageoftheappcatalogsiteandinstallitjustasyouwouldinstallanappinanyothertypeofsite.However,thingsareabitdifferentaftertheapphasbeeninstalledinanappcatalogsite.Morespecifically,theappprovidesdifferentoptionsinthefly-outmenuthatisavailableontheSiteContentpage,asshowninFigure1-15.

    AsyoucanseeinFigure1-15,anappthathasbeeninstalledinanappcatalogsitehasaDeploymentmenucommandthatisnotavailableinanyothertypeofsite.WhenyouclicktheDeploymentmenucommand,youareredirectedtoapageonwhichyoucanconfiguretheappsothatyoucanmakeitavailabletousersinothersites.

    Figure1-15.Onceanapphasbeeninstalled,theassociateddeploymentmenucanbeusedtomaketheappavailabletoothersites.

    Youhaveseveraloptionswhenyouconfigureanappinanappcatalogsitetomakeitavailableinothersites.Oneoptionistomaketheappavailabletoallsiteswithinthescopeoftheappcatalogsite.Or,youcanbemoreselectiveandjustmaketheappavailableinsitesthatwerecreatedbyusingaspecificsitetemplateorsitescreatedunderaspecificmanagedpath.ThereisevenanoptiontoaddtheURLsofsitecollectionsone-by-oneifyouneedfine-grainedcontrol.

    Afteryouconfigurethecriteriaforatenancy-scopedappinstallationtoindicatethesitesinwhichitcanbeused,youwillfindthattheappdoesnotappearinthosesitesinstantly.ThatsbecausetheSharePointhostenvironmentreliesonatimerjobtopushtherequiredappmetadatafromtheappcatalogsitetoalltheothersites.Bydefault,thistimerjobisconfiguredtorunonceeveryfiveminutes.DuringyourtestingyoucanspeedthingsupbynavigatingtotheCentralAdministrationsiteandlocatingthetimerjobdefinitionnamedAppInstallationService.ThepageforthistimerjobdefinitionprovidesaRunNowbuttonthatyoucanclicktorunitondemand.

  • UpgradingappsTheupgradeprocessdesignedbytheSharePointappmodelprovidesamuchbetterexperiencecomparedtotheupgradeprocessusedwithSharePointsolutions.Whenappsarepublished,theOfficeStoreandappcatalogsitesalwaystracktheirversionnumber.Whenanappisinstalled,theSharePointhostenvironmentseesthisversionnumberandrecordsitfortheinstalledappinstance.

    Takeasimpleexample.Imagineyouhaveuploadedversion1.0.0.0ofanapp.Afterthat,theappisinstalledinseveralsitesviasite-scopedinstallation.TheSharePointhostenvironmentremembersthateachofthesesiteshasinstalledversion1.0.0.0oftheapp.

    Now,imaginethatyouwanttofurtherdevelopyourapp.Maybeyouneedtofixabug,improveitsperformance,orextendtheappsfunctionality.Afteryouhavefinishedyourtesting,youdecidetoupdatetheversionnumberto2.0.0.0andpublishthenewversioninthesameappcatalogsitewhereyouinstalledtheoriginalversion.

    OneimportantaspectoftheupgradeprocessoftheSharePointappmodelisthatanupdatedversionofanappisneverforcedupontheuserthatinstalledtheapp.Instead,theuserisnotifiedthatanewversionoftheappisavailable.Thisusercanthendecidetodonothingortoupdatetheapptothenewversion.Figure1-16showsthenotificationthattheSharePointhostenvironmentaddstotheapptileontheSiteContentspage.

    Figure1-16.ThetileforanappdisplaysanotificationwhenanupdatedversionisavailablefromtheSharePointStoreorappcatalog.

    ThenotificationdepictedinFigure1-16containsanupdatelinkthatausercanclicktoberedirectedtoapagewithabuttonthatactivatestheupgradeprocess.Whatactuallyoccursduringtheupgradeprocessisdifferent,dependingonwhethertheappisaSharePoint-hostedapporacloud-hostedapp.

    WhenyouareworkingonanupdatedversionofaSharePoint-hostedapp,youhavetheabilitytochangesomeofthemetadataintheappmanifestandtoaddnewelementsintotheappweb.Forexample,youcouldaddanewpagetotheappwebnamedstartv2.aspxandthenmodifytheappmanifesttousethisstartpageinsteadofthestartpagethatwasusedintheoriginalversionoftheapp.Youcouldalsoaddother,newappwebelementssuchasJavaScriptfiles,lists,anddocumentlibraries.ManyofthetechniquesusedtoupgradeelementsintheappwebarebasedonthesametechniquesdevelopershavebeenusingwithfeatureupgradeinSharePointsolutions.

    Whenitcomestoupdatingacloud-hostedapp,thingsaredifferent.ThatsbecausemostoftheimportantchangestotheappsimplementationaremadetotheremotewebandnottoanythinginsidetheSharePointhostenvironment.Ifyouareworkingwithaprovider-hostedapp,youmustrolloutthesechangestotheremotewebbeforeyoupublishthenewversionoftheapptotheOfficeStoreoranyappcatalogsite.

    Itsequallyimportantthattheupdatedversionoftheremotewebmustcontinuetosupportcustomersthatwillcontinuetousetheoriginalversionoftheapp.Remember;thereisnothingthatforcestheuserto

  • acceptanupdate.Youshouldexpectthatsomecustomerswillbehappywiththeoriginalversionandwillbeopposedtoupgradingtoanewversionofanapp.

    Onceyouhavepushedoutmorethanoneormoreupdatestoaprovider-hostedapp,youmustbegintotrackwhatversioneachcustomerisusing.Onetechniquetoaccomplishthistaskistoprovideadifferentstartpageforeachversionoftheapp.Manyprovider-hostedappswillgoastepfurtherandstorethecurrentversionofappinacustomerprofilethatistrackedinacustomdatabasebehindtheremoteweb.

    TrappingapplifecycleeventsOnefavorableaspectoftheSharePointappmodelfordevelopersistheabilitytodesignacloud-hostedappwithcustomserver-sidecodethatisautomaticallyexecutedwhenanappisinstalled,upgraded,oruninstalled.Bytakingadvantageoftheabilitytoaddcodebehindthesethreeapplifecycleevents,youcanprogramagainstthehostwebandtheappwebwithlogictoinitialize,update,andcleanupsiteelementsintheSharePointenvironment.Theseapplifecycleeventsalsoprovidethenecessarytriggersforupdatingthecustomdatabaseusedbyprovider-hostedappsandautohostedapps.

    ThearchitectureofappeventsisbasedonregisteringappeventhandlersintheappmanifestthatcausetheSharePointhostenvironmenttocallouttoawebserviceentrypointintheremoteweb.Duetothearchitecturesrelianceonaserver-sideentrypoint,appeventsarenotsupportedinSharePoint-hostedapps.Therefore,youcanonlyusetheappeventsinautohostedappsandprovider-hostedapps.

    Itsrelativelysimpletoaddsupportforappeventstotheprojectforanautohostedapporaprovider-hostedapp.ThepropertysheetfortheappprojectcontainsthreepropertiesnamedHandleAppInstalled,HandleAppUninstalling,andHandleAppUpgrade,asshowninFigure1-17.

    Figure1-17.ThepropertysheetforanappprojectprovidesBooleanpropertiesforenablinglifecycleevents.

    Thedefaultvalueforeachoftheseappeventpropertiesisfalse.Thefirsttimeyouchangeoneofthesepropertiestoavalueoftrue,VisualStudio2012addsawebserviceentrypointintothewebprojectwithanameofAppEventReceiver.svc.VisualStudio2012alsoaddstherequiredconfigurationinformationintotheappmanifestfile,aswell.Ifyouenableallthreeevents,theelementwithinelementoftheappmanifestwillbeupdatedwiththefollowingthreeelements:

  • ~remoteAppUrl/AppEventReceiver.svc

    ~remoteAppUrl/AppEventReceiver.svc

    ~remoteAppUrl/AppEventReceiver.svc

    Afteryouhaveenabledoneormoreoftheappevents,youcanthenbegintowritethecodethatwillexecutewhentheeventsoccur.Youwritethiscodeinthecode-behindfilenamedAppEventReceiver.svc.cs.Ifyouexaminethisfile,youwillseethatVisualStudio2012hascreatedaclassshowninthefollowingcodethatimplementsaspecialinterfacethattheSharePointteamcreatedforremoteeventhandlingnamedIRemoteEventService:

    public class AppEventReceiver : IRemoteEventService {

    public SPRemoteEventResult ProcessEvent(RemoteEventProperties properties) {}

    public void ProcessOneWayEvent(RemoteEventProperties properties) { }

    }

    TheIRemoteEventServiceinterfaceisusedwithappeventsandalsowithothertypesofremoteeventhandlers,aswell.TherearetwomethodsnamedProcessEventandProcessOneWayEvent.TheSharePointhostenvironmentmakesawebservicecallwhichexecutestheProcessEventmethodwhenitneedstoinspecttheresponsereturnedfromtheremoteweb.TheProcessOneWayEventmethodiscalledforcasesinwhichtheSharePointhostenvironmentneedstotriggertheexecutionofcodeintheremotewebbutdoesntneedtoinspecttheresponse.AppeventsalwaystriggertotheProcessEventmethod,soyoucanleavetheProcessOneWayEventmethodemptyintheAppEventReceiver.svc.csfile.

    IfyouhaveregisteredfortheAppInstalledevent,theProcessEventmethodwillexecutewheneverauserisinstallingtheapp.ItiscriticaltosupplyrobusterrorhandlingbecauseanunhandledexceptionwillbereturnedtotheSharePointhostenvironmentandcauseanerrorintheappinstallationprocess.

    WhenyouimplementtheProcessEventmethod,youmustreturnanobjectcreatedfromtheSPRemoteEventResultclass,asdemonstratedinthefollowing:

    public SPRemoteEventResult ProcessEvent(RemoteEventProperties properties) {

    // return an SPRemoteEventResult object

    SPRemoteEventResult result = new SPRemoteEventResult();

    return result;

    }

    TheSPRemoteEventResultclasswasdesignedtomakeitpossibleforcodeintheremotewebtorelaycontextualinformationbacktotheSharePointhostenvironment.Forexample,imaginethatyouhavedetectedthattheinstallersIPaddressislocatedinacountryth