Está en la página 1de 39

LightSwitch

HTML Client Tutorial


LightSwitch for Visual Studio 2012 HTML Client Preview

ThenewHTML5andJavaScriptbasedclientisanimportantcompaniontoourSilverlightbaseddesktop clientthataddressestheincreasingneedtobuildtouchorientedbusinessapplicationsthatrunwellon modernmobiledevices. Inthistutorial,wellbuildanapplicationthatconnectstoexistingdataservicesandprovidesatouch first,modernexperienceformobiledevices.Tohelpgroundthetutorial,wevecreatedafictional companyscenariothathasaneedforsuchanapplication.

Contents
TheMoveItApplication................................................................................................................................. 2 ImplementtheMoveItApp .......................................................................................................................... 6 Step1:AddaCompanionHTMLClienttoanExistingApplication ............................................................... 7 Step2:DefineCoreScreensandAppNavigation ......................................................................................... 9 Step3:CustomizetheUIwithCSSandJavaScript......................................................................................15 Step4:TesttheApplicationonaTabletDevice .........................................................................................20 Step5:CreateModalDialogs......................................................................................................................23 Step6:CustomizetheApplicationsTheme ...............................................................................................29 Step7:UsingaDevices BuiltinCameratoShootandUploadPhotos......................................................34 Step8:AddaBingMapCustomControl ....................................................................................................36 Step9:RepublishtheAppandTestiton aTabletDevice ..........................................................................38

Helpful resources
Asyouwalkthroughthistutorial,pleasebearinmindthatthereareusefulresourcesavailabletohelp youshouldyougetstuckorhaveaquestion [thefollowingareexternallinks]: x x LightSwitchHTMLClientforum topostfeedbackandaskquestions,andcheckbackforany correctionstothewalkthroughdocument. HTMLClientResourcesPageontheDeveloperCenter formorelearningresources. 1

The MoveIt Application


MoveItisanapplicationthatsusedbyContosoMovers,Inc totaketheinventoryofcustomers residencespriortomoving.ThedatacollectedviatheapplicationhelpsContosoMovers determinethe resourcesrequiredtomoveaparticularclientsbelongingshowmanytrucks,people,boxes,etc. need tobeallocated.Theapplicationiscomprisedoftwoclientsthatservedistinctbusinessfunctions: 1. Schedulersuseadesktopapplication toservicenewcustomerrequestsandcreate appointments.Thisapplicationisarichdesktopapplicationprimarilygearedtowardsheavy dataentrywiththekeyboardandmouse,sinceSchedulersareonthephonewithcustomersa lotandneedtoenterquiteabitofinformationintothesystemduringthecourseofaday. 2. PlanningSpecialistsuseatabletdevice toquicklytakeinventoryonlocationofeach residenceonthe specialistsschedulefortheday.Takinginventoryinvolvesdetailingeachroom intheresidence,itssizeandentryrequirements(ifany),andlistingitscontents.Picturesare oftentakenofeachroomsothemovershaveapointofreferencewhentheyarrive. Secondarily,PlanningSpecialistsmaymakenotesaboutparkingrestrictionsforthemoveteam (i.e.,wheretheycanparkthetruckduringthemove). ThistutorialwalksthroughbuildingoutthemobileclientusedbyContosoMovers planningspecialists. Beforewedothat,letsrunthroughacompleteversionoftheapplicationthatisalreadypublishedon thisVHDtogetabetterfeelforwhatwellbuild.

Run the Desktop Client for Schedulers


First,letslookattherichdesktopclientusedbySchedulers,sincethatishowmostofthedatainthe systemoriginates.ThedesktopclientcanberunbyenteringthefollowingURLinyourbrowser: http://localhost/ContosoMovingComplete/Client.Ifyoudliketoreachtheapplicationfromanother machine,theURLishttp://<machinename>/ContosoMovingComplete/Client,where<machinename> isthemachinenameyouspecifiedwhentheVHDwasfirstsetup. TheapplicationusesFormsAuthentication.Enterthefollowingcredentialsintheappsloginscreen, and thenchooseLogIn: x x UserName:admin Password:admin!!

Whentheapplicationisfirstlaunched,upcomingappointmentsaredisplayedinthehomescreen.Two keyentrypointsNewCustomer andNewAppointmentareprovidedforenteringthedetailsofa newcustomerandsettingupnewappointments.

ChoosetheNewAppointmentbuttontocreateanewappointment.TheCreateNewAppointment screenisusedtocaptureinformationaboutthe appointmentsuchaspreferreddate/time,address,and contactinformation.Typically,acustomerwillprovideenoughinformationoverthephonetocreatea roughprofileaboutthemove;forexample,isthemoveforaresidentialhome,apartment,oroffice building,theroomsinvolvedinthemove,andanyspecialinstructionsorquestionsthatthePlanning Specialistshouldfollowupwiththecustomerabout. Feelfreetoaddseveralofyourownappointmentsinthesystem,aswellasexploreotherscreens accessiblefromthemenubar.

Run the Mobile Client for Planning Specialists


TheVHDalsocontainsaprebuiltversionofthemobileclientthatPlanningSpecialistsuse thisisthe clientwellprimarilyfocusonthroughoutthistutorial.Youcanruntheprebuiltmobileclientby openingupabrowsertohttp://localhost/ContosoMovingComplete/MobileClient/.Ifaccessingthesite fromamobiledevice,substitute<machinename>forlocalhost.Note: Ifyourunintoproblemsloading themobileclientfromMetroInternetExplorer,youmayneedtoconfigureIEsIntranetsettings refer totheGettingStartedguidefortheLightSwitchHTMLClientPreviewVHD. Theapprequiresausernameandpassword.Youmayuseanyofthefollowing: Username ACarothers Dcarreras RCarroll JCastellucio Password pass@word1 pass@word1 pass@word1 pass@word1

Ifyoudontgetpromptedforlogincredentials,yourbrowsermaybecachingyourpreviouslogin tothe Silverlightclient.Ifso,pleasebesuretocloseallofyourbrowserwindows,and/orclearthecacheif necessary. 4

Onlaunchingthisclient,youllimmediatelynoticethattheexperienceispersonalizedonlythelogged inPlanningSpecialistsappointmentsaredisplayedandtheUIstyleisoptimizedfornavigatingthe applicationwithyourfinger.Also,verylittlechromeisdisplayedinorderforthecontenttobethe primaryfocuswithintheapplication.

TappinganappointmenttilewillopentheAppointmentDetails screen.Thisscreenisthenucleusofthe applicationitswhereInventorySpecialistswillspendmostoftheirtime.Assuch,thescreenhasbeen constructedtofacilitatethemostcommontasks:viewthecustomerinformationandtakinginventory. Youcanalwaysnavigatebacktothepreviousscreenbytappingthe<glyphtotheleftofthescreentitle, orbysimplyusingthebrowsersbacknavigationbutton.

Editingcustomerinformationisalsoaninfrequentbutnecessarytask.TappingtheEdit buttoninthe Summary sectiondisplaysamodaldialogwherethePlanningSpecialistcanmodifycustomer information. 5

Implement the MoveIt App


Nowthatweveseentheappinaction,letsbuildourownversion.Topicswellcoverthroughoutthe restofthetutorialarebrokeninto2mainparts: Part1: Step1:AddaCompanionHTMLClienttoanExistingApplication Step2:DefineCoreScreensandAppNavigation Step3:CustomizetheUIwithCSSandJavaScript Step4:TesttheApplicationonaTabletDevice Part2: Step5:CreateModalDialogs Step6:CustomizetheApplicationsTheme Step7:UsingaDevicesBuiltinCameratoShootandUploadPhotos Step8:AddaBingMapCustomControl Step9:RepublishtheAppandTestitonaTabletDevice

Letsgetstarted! 6

Step 1: Add a Companion HTML Client to an Existing Application


1. OpentheprojectlocatedatC:\Content\ContosoMovingStart ontheVHD.Ifwelookat SolutionExplorer weseethattheprojectalreadycontainsthecoredataservicelogicofthe application(locatedundertheServer node).TheSilverlightdesktopclientusedbyMoveIt Schedulershasalreadybeenbuilt(locatedundertheClient node),andthereisnomobileclient yet. PressF5toruntheSilverlightdesktopclientindebugmode.

2. NowletsaddanewHTMLclienttotheproject. Exitdebugmode,andinSolutionExplorer opentheshortcutmenufortheContosoMoving rootnodeandchooseAddClient.

3. IntheAddClient dialog,enterauniquename,forexampleMobileClient.

Note: IfadialogboxpopsupandpromptsyoutogetaDeveloperLicenseforWindows8, chooseCancel youdontneeditforthistutorial.

AfterchoosingOK intheAddClient dialogbox,thenewclientappearsinSolutionExplorer and isautomaticallydesignatedtobethestartupclient.Thestartupclientsettingsimplyspecifies whichclientlauncheswhenyoupressF5;thiscanbechangedatanytimebyopeningthe shortcutmenuforaclientnodeinSolutionExplorer andchoosingSetasStartupClient.

Step 2: Define Core Screens and App Navigation


Nowletsaddsomescreensforournewmobileclient.ForthosewhohaveusedLightSwitchbefore,the nextsetofstepsshouldfeelveryfamiliar.

Create the Home Screen


Letsmakeourhomescreendisplayalistofupcomingappointmentsforthecurrentlyloggedinuser. 4. InSolutionExplorer,opentheshortcutmenufortheMobileClient nodeandchooseAdd Screen. TheAddNewScreen dialogboxopens. 5. IntheAddNewScreen dialogbox,specifythefollowing: x ScreenTemplate:BrowseDataScreen x ScreenName:Home x ScreenData:UpcomingAppointments (thisqueryisalreadydefinedaspartofthe Serverproject itfiltersforupcomingappointmentsbasedonthecurrentlyloggedin user).

6. LetsmakesomesimplemodificationstohoweachAppointmentisdisplayedinthelist. a. First,changetheAppointment itemscontroltouseRowsLayout.

b. Secondly,letsopttodisplayonlytheStartDate andCustomer foreachappointment itembydeletingtheotherfields.ScreenDesignershouldnowlooklikethefollowing:

10

7. PressF5 toruntheapplication.Thedefaultbrowserwilllaunchandthehomescreenofthe MobileClientwilllooksomethinglikethescreenshotbelow.Thedateformattingisntideal,but thiswilldofornow lateron,wewillfurthercustomizethehomescreen. 8. Exitthedebugsessionbyclosingthebrowser.

11

Create the Appointment Details Screen Theappointmentdetailscreenisthenucleusoftheapplicationitswheretheinventoryspecialists will spendmostoftheirtime. 9. Addanewscreenwiththefollowingsettings: x ScreenTemplate:ViewDetailsScreen x ScreenName:ViewAppointmentDetail x ScreenData:Appointment.Also,selectthecheckboxestoincludeallrelateddata.

LookingattheScreenContenttree,youllnoticethatseveraltoplevelscreensectionshave beencreatedbydefaulttobettersegmentrelateddata.Layoutcaneasilybecustomized,but wellstickwiththedefaultsfornow.

Wire up Screen Navigation


Nowallweneedtodoiswireupourtwoscreenssuchthattheapplicationnavigatestothe ViewAppointmentDetailscreenwhenanappointmentistappedintheHome screen. 10. InSolutionExplorer,opentheHome screen. 11. IntheScreenContenttree,choosetheUpcomingAppointments Listcontrol. 12. InthePropertieswindow,choosetheActions,Item Tap hyperlinktoconfigurewhathappens whenalistitemistapped theEditItemTapActiondialog boxwillappear.

12

13. IntheEditItemTapAction dialogbox,configurethetapactionasfollows:

ThisstatesthatwellnavigatetotheViewAppointmentDetailscreenwhenalistitemistapped. BecausetheViewAppointmentDetail screenwascreatedusingtheViewDetails screen template,ascreenparameternamedAppointment wasautomaticallydefinedtoallowusto passtheappointmentwewanttoviewinthat screen.Anyotherscreenparameterswouldalso beconfigurablehere. 14. LetshitF5andruntheapplication!YoullnowseethateachAppointmentnowhasaglyph indicatingthatyoucannavigatetoanotherscreen.

13

14

15. TapanappointmenttoopenitsAppointmentDetails screen.

Step 3: Customize the UI with CSS and JavaScript


UpuntilnowwevemostlykeptdefaultUIandwehaveafunctionalapp,buttheUIcandefinitelybe improved.Letsstartaddressingsomeofthoseimprovementsheretolearnhowyourknowledgeof HTML,CSS,andJavaScriptcanbeappliedtocustomizeandextendyourapplicationsUI.

Tile Layout using CSS


AppointmentsintheHomescreencurrentlystretchoutacrossthepage.Thismaybeokfornarrow displays,butitsaveryinefficientuseofscreenrealestateifthescreeniswider(forexample,considera tabletdeviceinlandscapemode). Acommonvisualizationforlistsistouseatilebasedlayoutaswesawinthecompletedapp.Itturns outthisiseasytodowithcustomCSS,whichwellnowincorporateintoourHomescreen. 16. Adda.cssfiletotheMobileClient project: 15

a. SwitchfromLogicalView toFileView usingtheSolutionExplorer commandbar.

b. ExpandtheMobileClient project,opentheshortcutmenufortheContent folderand chooseAdd,ExistingItem. c. NavigatetotheC:\Content\Resourcesfolder,choosethefilenamedtilelist.css,and thenchooseAdd.Thetilelist.cssfileisaddedtotheContent folder. d. Ifyouopentilelist.cssyoullnoticethatitcontainsastraightforwarddefinitionofaCSS class.


ul.tilelist { width:100%; padding:10px; display:inlineblock !important; } ul.tilelist li { liststyletype:none; margin:6px; width:300px; height:100px; float:left !important; }

17. Includethenewlyadded.cssfileindefault.htm. e. Openthedefault.htm file intheMobileClient project. f. Insertthefollowingstatementjustafterthelast<link/> tag.


<link rel="stylesheet" type="text/css" href="Content/tilelist.css" charset="utf8" />

18. CustomizetheListcontrolintheHome screentoprogrammaticallyaddthetilelistCSSclassinits postRender() event.ThepostRender eventisausefulAPIentrypointbecauseitallowsyouto customizeascreenelementsHTMLusingstandardJavaScriptandjQuerysyntax. g. SwitchbacktoLogicalView andopentheHome screen. h. IntheScreenDesigner,selecttheUpcomingAppointments listcontrol.

16

i.

ChoosetheWriteCodedropdown listlocatedatthetoprightoftheScreenDesigner window,andchooseAppointment_postRender.ThiswillopentheJavaScriptcode editor.

ThegeneratedAppointment_postRender() functionstubhastwoparameters: element,whichrepresentstheHTMLdivelementofthescreenitem; contentItem,whichrepresentstheactualscreensdataobject. j. Insertthefollowinglineofcodeinthefunction.ThisisstandardjQuerysyntaxthat looksuptheunorderedlist(ul)containedwiththeelement,andaddsthetilelistCSS classtoit.


lightSwitchApplication.Home.prototype.Appointment_postRender=function (element,contentItem){ $(element).find('ul').addClass("tilelist"); };

19. PressF5 thehomescreennowdisplaysupcomingappointmentsinatilebasedlayout.Try narrowingandwideningthewidthofthebrowserwindow noticehowthelayoutofthetiles dynamicallyadjuststomakegooduseofavailablehorizontalspace.Thisgivesusanideaofhow thelistlayoutwouldchangebasedonorientationofthemobiledevice,orhowthescreenwould berenderedonsmallorlargedevices.

17

Custom Formatting using Existing JavaScript Libraries


TheAppointmentitemsmakebetteruseofscreenrealestate,butthecontentwithineachtileclearly canbeimproved.Letsdotwothings:formattheappointmentdate/timetobemorelegible,and includethecustomersnameandphonenumber. Wecancustomizehoweachlistitemisrenderedbydefiningacustomcontrolforthelistitem. 20. ExitthedebugsessionandopentheHome screen. 21. SelecttheAppointment item,andchangeitscontrolfromRowsLayout toCustomControl.

22. ChoosetheWriteCodedropdown listandchooseRowTemplate_render.Thiswillopenthe JavaScriptcodeeditor.

18

23. InsertthefollowingcodeintheRowTemplate_render function.Again,thecodeinthisexample isstandardJavaScript itdefinesHTMLcontentandaddsittoanappointmentsdivelement.In thisfunction,contentItemrepresentstheAppointmentdataitem,sowecanrefertothe appointmentsStartDate andFirstName fieldsbycontentItem.value.startDate and contentItem.value.firstName respectively. IMPORTANT: NotethecamelCasingforthesefields JavaScriptiscasesensitivesoits importanttokeepthecasingexactlyasprovidedintheexamplebelow.
lightSwitchApplication.Home.prototype.RowTemplate_render=function (element, contentItem){ var itemTemplate=$("<div></div>"); var title=$("<h3>" +moment(contentItem.value.startDate).format("ddd,MMMDo, h:mm")+"" +moment(contentItem.value.endDate).format("h:mma")+"</h3>"); var subTitle=$("<span>" +contentItem.value.customer.firstName+"" + contentItem.value.customer.lastName+" " +contentItem.value.customer.phone+ "</span>"); title.appendTo($(itemTemplate)); subTitle.appendTo($(itemTemplate)); itemTemplate.appendTo($(element)); };

Weneedtodoonemorestep therearemanyJavaScriptlibrariesavailableonthewebthat helpparseandformatdates.ThecodeabovethatformatstheappointmentsstartDate usesa JavaScriptlibrarycalledMoment.jsthatwellneedtoincludeinourproject.Anyoftheavailable JavaScriptdatelibrariescouldbeusedforthisexample,butletsuseMoment.jsasitwillgiveus theopportunitytousetheNuGetmanagementfeaturesinsideVisualStudio2012. 24. InSolutionExplorer,switchtoFile View,opentheshortcutmenufortheMobileClient project andselectManageNuGetPackages. 25. IntheManageNuGetPackagesdialogbox,dothefollowing: a. ChoosetheOnline category(onthetopleft). b. Entermoment.jsintheSearchtextbox(topright).Searchresultswilldisplaythe NuGetpackageforMoment.js. c. ChoosetheInstall buttonforMoment.js.

19

26. Indefault.htm,referencemoment.jsusingthescripttag(youcaninsertitasthelastofthe scriptreferencetags).


<script type="text/javascript" src="Scripts/moment.js" charset="utf8"></script>

27. HitF5toruntheapp!

HopefullyyouwillhaveobservedintheseexampleshowstandardHTML,JavaScript,andCSS forwhich thereisavibrantcommunityprovidingmanyresources canbeusedtoeasilyextendLightSwitchUI.

Step 4: Test the Application on a Tablet Device


Sofarwehaveruntheapplicationindebugmodeandseenitinthedesktopbrowser.Itdbeniceto publishtheapplicationandreachitfromamobiledevicesbrowsersincethatswhatitsdesignedtobe usedon. 20

TheVHDcomespreconfiguredwithIIS8andSQLExpress,sowehaveeverythingweneedtopublishthe applicationtothelocalserverontheVHD aslongasyourmobiledeviceisconnectedtothesame networkyouwillbeableto runtheappfromyourdevice. 28. Beforepublishing,youmustexitandreopenVisualStudio2012asanadministrator.Fromthe WindowsStartscreen,rightclickontheVisualStudio2012tile,andselectRunasadministrator. 29. OnceyouhavestartedVisualStudio2012asanadministrator,loadtheLightSwitchprojectyou justcreatedbyselectingitfromtheRecent menusectionontheleft. 30. Onthemenubar,chooseBuild,ConfigurationManager.

31. IntheActivesolutionconfiguration dropdown,chooseRelease,andthenchoosetheClose button.

21

32. InSolutionExplorer,opentheshortcutmenufortheLightSwitchprojectsrootnodeand choosePublish. 33. IntheLightSwitchPublishApplicationWizard,setthefollowingvalues: a. ApplicationType:Web b. ApplicationServerConfiguration:keepdefaults. c. PublishOutput: i. ChooseRemotelypublishtoaservernow ii. ServiceURL:http://localhost iii. Site/Application:DefaultWebSite/ContosoMoving iv. Sinceyouarepublishingtolocalhost,theusernameandpasswordis unnecessary. Ifyouseeayellowexclamationmarknexttothegrayedout usernametextbox,youmaysafelyignoreit.

d. SecuritySettings:SetRequireSecureConnection(HTTPS) toOff. e. DatabaseConnections:Choosetheellipsis() buttonnexttotheSpecifytheuser connection textbox.IntheConnectionProperties dialogbox,specify: i. Servername:.\SQLExpress Notethedot(.)beforethebacklash. ii. UseSQLServerAuth: x Username:sa 22

x Password:passw)rd iii. Enteradatabasename:ChoosetheContosoMoving databasefromthe dropdownlist.Thisdatabaseisalreadyprepopulatedwithusers and appointments,soitwillsaveyoualotoftimetousethisoneratherthan creatinganewone. iv. ChoosetheOK button. v. InthewizardsDatabaseConnections page,makesurePublishdatabase schema ischecked,andthencopytheconnectionstringfromSpecifytheuser connection totheSpecifyadministratorconnection textbox,andthechoose theNext button. f. Authentication: Sincetheexistingdatabaseisalreadyprepopulatedwithdataand usersSelect No,anApplicationAdminstrator alreadyexists.(Theprepublishedadmin accountisusernameadmin,passwordadmin!!) g. SpecifyaCertificate:MakesuretheSpecifyacertificate checkbox isunchecked. h. Choose thePublish button. 34. Afterpublishsucceeds,theHTMLmobileclient willbeavailableattheURL: http://<machine name>/ContosoMoving/MobileClient,where<machinename> isthemachinenameyou specifiedwhentheVHDwasfirstset up.Youshouldbeabletoaccessitfromanysupported browseronyourPC(includingtheMetroIE10),andfromanysupportedmobiledevice, providedthatitisonthesamenetwork. a. Whenpromptedforlogincredentials,youcanuseanyofthefollowingusernameand passwordcombinationsintheapplicationssampleEmployeedata: Username ACarothers Dcarreras RCarroll JCastellucio Password pass@word1 pass@word1 pass@word1 pass@word1

b. Note:Tologoutandloginasanotheruser,besuretocloseallof yourbrowsers windows.Ifnecessary,youmayneedtoclearyourbrowserscache.

Step 5: Create Modal Dialogs


LetsnowdirectourattentiontotheViewAppointmentDetails screen,wherePlanningSpecialists spendmostoftheirtime.Becausereceptionistsoccasionallytranscribecustomerinformation incorrectly,PlanningSpecialistsoftenverifycontactinformationwhentheymeetacustomerandupdate itasneeded.Welladdsupporttodothisbydefiningasimpleeditdialog. 35. OpentheViewAppointment Details screen. 36. LetsbeginbycleaninguptheUIinthemainDetails section(welllateraddmorecontextual datainthescreentitle,sothisallowsustosimplifytheDetails section):

23

a. Removethesefields:StartDate,EndDate,Notes,MoveType,Employee (sinceits alwaysthecurrentuserinthisapplication),Customer, andSummary. b. SelecttheTabs node,andthenchooseAddTab. c. IntheProperties window,changetheName toNotes. d. IntheAdd dropdownfortheNotes tab,chooseOtherScreenData. e. IntheAddScreenData dialogbox,enterAppointment.Notes,andthenchooseOK. f. ChangethecontrolforNotes tobeaTextArea.Thiswillmakeitaneditablefieldby default. g. IntheDetails section,addtheCustomersphonenumberandemail: i. ChooseOtherScreenData fromtheAdd dropdown.

ii. Typeinthenameofthefieldtoadd:Customer.Phone.

iii. Repeatwith Customer.Email.

24

TheScreenContenttreeshouldnowlooksomethinglikethis:

h. Bonuspoints:Tomakebetteruseofscreenspace,breakthedataintotwocolumnsby usingtheColumnsLayout control.Also,turnoffattachedlabelsforfieldsbyselecting therootColumnsLayout (calledGroup inthescreenshotbelow)andsettingitsLabel Position propertytoCollapsed.

Nowitstimetocreateourmodaldialog.YoumayhavenoticedtheDialogs nodeinScreenDesigner asitsnameimplies,modaldialogsaredefinedwithinthissection.UIdefineddisplayswithinpopup visualswheninvoked,butdialogsalsohaveautomaticdatabindingwithOKandCancelbehaviorbuilt in. 25

37. UndertheDialogs node,addadialog,andnameitEditContactInformation. a. GesturetoaddOtherScreenData,andenterinAppointment.Customer.FirstNamein theresultingdialog.

b. Repeat theabove withAppointment.Customer.LastName. c. RepeattheabovewithAppointment.Customer.Phone and Appointment.Customer.Email,settingthetypesofthosefieldstoPhoneNumberEditor and EmailAddressEditor,respectively.

d. Add Street, City, State,and PostalCode bydraggingthemfromthe Appointment sidebarintothedialog,orbyaddingthemasabove.Theresultingdialogshouldlook likethis: 26

Nowthatwehaveadialog,letsaddabuttonthatinvokesthedialog. 38. AddaNewButton intheDetails section.

39. ConfiguretheAddButton dialogasfollows;thisconfigurationshowstheShowDialog method referencingtheEditContactInformation dialogwejustdefined.

27

40. IntheProperties window,namethebuttonEdit. 41. PressF5andruntheapplication.IntheAppointmentDetail screen,taptheEdit buttonto invokethedialog notehowOKandCancelbehaviorisprovidedasabuiltincapability.

Update the Appointment Screen to have a Dynamic Screen Title


LetsplacecontextualinformationinthescreentitlesinceweremovedtheStartDate andCustomer Name fieldsfromtheDetails tab. 42. 43. 44. 45. OpentheViewAppointmentDetail screen. ChoosetheDetails tabintheScreenContenttree. OpentheWriteCode menuandchooseDetails_postRender. Addthecodebelow:

lightSwitchApplication.ViewAppointmentDetail.prototype.Details_postRender=function (element,contentItem){ msls.bind(contentItem,"value.customer.firstName",function (){ formatAppointmentScreenTitle(contentItem); }); msls.bind(contentItem,"value.customer.lastName",function (){ formatAppointmentScreenTitle(contentItem); }); function formatAppointmentScreenTitle(contentItem){ contentItem.screen.details.displayName=contentItem.value.customer.firstName+" " + contentItem.value.customer.lastName+"" + moment(contentItem.value.startDate).format("h:mma")+" " + moment(contentItem.value.endDate).format("h:mma"); }; };

ThisexamplemakesuseofaLightSwitchAPIhelperwehaventseenbefore:msls.bind(). ThisAPI providesa simple,yetpowerful,meanstodatabindscreencontenttofunctions.Inthecodesample above,thismeansthatwheneverthedataforfirstName orlastName changes,thefunction formatAppointmentScreenTitle() willbereevaluated,therebyupdatingthescreentitle. 28

WecanseethisinactionifweruntheappandchangethecustomersnameintheEditAppointment dialog noticehowthescreentitleupdates dynamically.

Step 6: Customize the Applications Theme


Add an icon in the header
Onewaytocustomize yourapplicationistointroduceacustomiconintheheader:

46. IntheSolutionExplorer,switchtoFileView.UndertheMobileClient node,expandtheContent andImages nodes.Youwillseeandefault logo.pngfile.

47. Deletelogo.png. 48. OpentheshortcutmenufortheImages folderandchooseAdd, ExistingItem.Navigatetothe c:\Content\Resourcesfolderandchooselogo.png.Note: YoumaychooseanyotherPNGfileto serveasalogo,butyouwillneedtorenameittologo.pngonceyouaddittotheproject.

Switch between Dark and Light themes


Outofthebox,LightSwitchcomeswithtwothemes:adark (default)andalight theme.Toswitch betweenthethemes: 49. IntheSolutionExplorer,switchtoFileView.UndertheMobileClient node,opendefault.htm. 29

50. Aroundline26,youwillfindthefollowingline:
<link rel="stylesheet" type="text/css" href="Content/msls.theme.dark.css" />

51. Toswitchbetweenthedarkandlightthemes,simplysubstitutedark orlight intothehref portionoftheline:href="Content/msls.theme.___.css".

Integrate ThemeRoller themes


TheappearanceofaLightSwitchMobileappcanbecustomizedviaThemeRollerforJQueryMobile. SomeaspectsofThemeRollermightnotintegratequiteperfectlyyet,butrestassuredthatthiswillbe addressedinafuturerelease. 52. LaunchThemeRollerbynavigatingtohttp://jquerymobile.com/themeroller/. Youwillbepresentedwithataskpaneontheleft,andalivepreviewofaJQueryMobileapp on theright. 53. ModifytheThemeRollersettingstosuityourneeds.Notethatthesidebarontheleftcontains severaltabs;thesettingsyouwillwanttomodifywillbeunderGlobal andSwatchA.Allother swatchesandtheirrespectivepreviewswillbeignored(andshouldprobablybedeleted,forthe sakeofkeepingdowntheCSSsize).

30

a. Notethatforsomesettings,youcanjustdragcolorsfromthetopbartotheapplication elements.Forothersettings(e.g.,fontcolor),youwillneedtoopenuptherespective settingsinthetaskpane. b. Tip:Ifyouwanttouseaprebuiltthemeratherthancreatingyourown,clickImport andthenchooseImportDefaultTheme atthetopofthewindow.Thiswillpopulate5 swatches.Chooseanythatyoulikeanddeletetherest,sothatyourchosenswatch becomesSwatchA.

54. Onceyouredonecustomizingtheappearanceofyourtheme,clickDownload.SpecifyaTheme Name (forexample,customtheme),andclickDownloadZip.

31

55. Downloadthezipfiletoatemporarylocation andunzipit.Intheresultingfolder,navigateto thethemes folderwithin. 56. BackinVisualStudio,opentheSolutionExplorertoFileView,andnavigatetotheMobileClient project.Open theshortcutmenufor theContentfolder andchoose Add, ExistingItem,and thenchoosethe <themename>.css fileinthethemes folderinsidetheunzippedthemefolder.

57. WhilestillinFileView,opendefault.htm fromtherootoftheHTMLclient. a. Movethelinewiththebasetheme(msls.theme.dark.cssor msls.theme.light.css)just below thestartofthelinkssection.Thatis,itshouldnowbepositionedrightbelowthe Content/jquery.mobile1.0.css reference. Seeimagebelow(wherebytheredline arrowrepresentsthemove).

32

b. AddareferencetoyourThemeRollercustomthemeimmediatelybelowthenewly repositionedbasetheme reference(customthemeoutlinedingreenintheimage above):


<link rel="stylesheet" type="text/css" href="Content/customtheme.css" charset="text/css" />

c. Notethatsomesettings,likethecoloroflistitemsandsomeoftheheaders,are determinedbythebasethemeratherthanThemeRoller.Therefore,thechoiceofthe darkversus lightthemewillprobablystillberelevantforyou. 58. Press F5; theappshouldincludeyournewstyle.Pleasebewarethattherearesomeknown issues withthemes,and wereworkinghardtoresolvethembythenextrelease.

59. If,havingcreatedtheThemeRollerfile,youwanttomodifyit: a. OpentheThemeRollerwebsiteandclickImport atthetopofthewindow.Copypaste thecontentsofyourcurrentcustomthemeandclickImport. b. Whenyouaredonemakingchanges,pressDownload,unzipthefile,navigatetothe themes folder,andopenyour<themename>.css file.Copypastethecontentsofthat updatedfileintoyourformerthemefile.

33

c. Undersomecircumstances(e.g.,whenyoureplacethethemefileratherthanits contents),thebrowsermightbeusingacachedCSSandnotloadingyournewchanges. Ifthisisthecase,andyouarenotseeingthechangesthatyoudjustmade,besureto clearyourbrowserscache.

Add an application title


ThedefaulttitleforaLightSwitchHTMLclientisinitiallyblank whichmeansthatbrowserswilltypically renderthenameoftheserverorthewebaddressasthetitle(typically shownnexttothetabthat representsthepage).Tocustomizeit: 60. IntheSolutionExplorer,switchtoFileView.UndertheMobileClient node,opendefault.htm. 61. Modify<title></title> nearthetopofthefiletoincludeatitleforyourapp.Forexample, <title>MoveIt</title>.

Step 7: Using a Devices Built-in Camera to Shoot and Upload Photos


Letsgiveplanningspecialiststheoptiontouseusetheirmobiledevicetouploadpicturesofthehome. Theintentisthattheinventoryspecialistwilltakeapicturewiththedevice,saveitlocally,andthen uploaditviatheMoveItapp. NOTE: DuetoApplespolicyofdisablingthefileuploadbrowsebutton,uploadingviaiOSs Safaribrowserisnotsupportedatthistime. 62. OpenSolutionExplorerandswitchtoFileView,andthenchoosetheMobileClient,Scripts folder. 63. OpentheshortcutmenufortheScripts folderandchooseAdd,Existing Item. 64. Fromwithinthedialog,navigatetoC:\Content\Resources,andselecttoaddthefollowingtwo file: a. imageuploader.js b. imageuploaderbase64encoder.aspx 65. Opendefault.htm toaddareferencetoimageuploader.js (theaspxpagedoesnotneeda reference).Thescriptreferenceshouldgoattheendofthescriptreferencesblock. 34

<scripttype="text/javascript"src="Scripts/Generated/usercode.js"></script> <script type="text/javascript" src="Scripts/imageuploader.js" charset="utf 8"></script>

66. SwitchbacktoLogicalView andopen theViewAppointmentDetail screen.IntheScreen Designer,selecttheAppointmentPhotos tab.

67. ChangetheAppointmentPhoto summaryfieldtoaRowsLayout.

68. ChoosetheDialogs node,andthenchooseAddDialog.NamethedialogImageUploader. 69. FromtheleftScreenDesignerpane,dragtheSelectedItemnodeof AppointmentPhotos into thenewdialog.DeletetheAppointment item.

70. SelectthenewlyaddedSelectedItemnode,andintheProperties windowchooseHeight.Clear theStretchtoContainer checkbox. 71. SwitchthedialogsPicturefieldfroman Image toaCustomControl.IntheProperties window, choosetheEditRenderCodehyperlinkandaddthefollowingcode:
createImageUploader(element,contentItem,"maxwidth:300px;maxheight:300px");

Thecallredirectsalloftheheavyliftingtotheimageuploader.jsfile.Thecustomizablestyling statement("maxwidth:300px;maxheight:300px")specifiestheimagepreviewsize. 72. IntheScreenDesigner,choosetheAppointmentPhotos sectionandthenchooseAdd,New Button.IntheAddButton dialogbox,choosetheAppointmentPhotos.AddAndEditNew method,andImageUploader astheNavigateTodesignation.

35

73. Oncethebuttoniscreated,dragitabovetheAppointmentPhotos list. 74. PressF5toruntheapp.SelectanappointmentandswitchtotheAppointmentPhotos tab. ClickAddAppointmentPhoto andsee theimageuploaderinaction.

Step 8: Add a Bing Map Custom Control


NowletsmodifytheViewAppointmentDetail screentodisplayamapforthecurrentappointments address.Weneedtobeginbyaddingsomefilestoourproject,andreferencingthemfromthe default.htmfile. 75. InSolutionExplorer,switch to File View andchoosetheScripts folderoftheMobileClient project. 76. OpentheshortcutmenufortheScripts folderandchooseAdd,ExistingItem. 77. NavigatetotheC:\Content\Resourcesfolderandaddlightswitch.bingmaps.js. 78. Openthedefault.htm fileandaddscriptreferencesforthelightswitch.bingmaps.js file,anda CDNreferencetotheBingMapscontrol(takenoteofthewherethefilereferenceswereadded inthecodebelowbecauseordermatters):
<linkrel="stylesheet"type="text/css"href="Content/msls.theme.font.css"/> <linkrel="stylesheet"type="text/css"href="Content/msls.theme.dark.css"/> <script type="text/javascript" charset="utf8" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script> <scripttype="text/javascript"src="Scripts/winjS/winjs1.0.RC.js"></script> <scripttype="text/javascript"src="Scripts/JQuery/jquery1.6.4.js" charset="utf8"></script>

36

<scripttype="text/javascript"src="Scripts/JQuery/jquery.mobile1.0.js" charset="utf8"></script> <scripttype="text/javascript"src="Scripts/JQuery/datajs1.0.0.js" charset="utf8"></script> <scripttype="text/javascript"src="Content/Resources/msls.prerequisite.resources.js"></script> <scripttype="text/javascript" src="Content/Resources/msls.defaultprerequisite.resources.js"></script> <scripttype="text/javascript"src="Scripts/msls1.0.0.js"></script> <script type="text/javascript" src="Scripts/lightswitch.bingmaps.js" charset="utf8"></script> <scripttype="text/javascript"src="Scripts/Generated/data.js"></script>

79. OpentheViewAppointmentDetail screeninthedesigner. 80. IntheDetails section,clickAddTab aftertheRooms tab,andnameitMap,andthenchoose Add,NewCustomControl. 81. IntheAddCustomControl dialogbox,specifyAppointment asthedataforthecustomcontrol.

82. UsetheWriteCode menutoedittheAppointment_render logicforthecontrol. 83. Addthefollowingutilitymethods abovetherenderfunction:


var mapLastUpdated; var mapControl; function rebindMap(element,contentItem){ //Checktomakesurewearen'tupdatingthemapcontinuouslyduetomultipleboundvalues changing. var now=new Date(); if (now.getTime() mapLastUpdated.getTime()>15){ setTimeout(function (){ updateMap(element,contentItem); mapLastUpdated=new Date(); },20); } }; function updateMap(element,contentItem){ var mapDiv=$("#appointmentMap"); //Ifwe'vepreviouslycreatedthemap,makesuretocleanupthedivitwascontainedin; //otherwisethebingmapcontrolfailstocreateproperly. if (mapDiv.length>0){ $(mapDiv).remove(); } mapDiv=$("<divid='appointmentMap'class='mslshautomslsvauto'></div>"); $(mapDiv).appendTo($(element)); mapControl=mapDiv.lightswitchBingMapsControl({ street:contentItem.value.street, city:contentItem.value.city, state:contentItem.value.state.name, zipcode:contentItem.value.postalCode, mapTypeId:Microsoft.Maps.MapTypeId.road, width:"600", height:"400" }); };

84. Nowbindthemapcontroltheaddressfieldsontheappointmentbyaddingthecodeto the Appointment_render method: 37

lightSwitchApplication.ViewAppointmentDetail.prototype.Appointment_render=function (element, contentItem){ updateMap(element,contentItem); mapLastUpdated=new Date(); msls.bind(contentItem,"value.street",function (){rebindMap(element,contentItem);}); msls.bind(contentItem,"value.city",function (){rebindMap(element,contentItem);}); msls.bind(contentItem,"value.zip",function (){rebindMap(element,contentItem);}); msls.bind(contentItem,"value.postalCode",function (){rebindMap(element,contentItem);}); };

85. PressF5.Aftertheapplicationloads,taponanappointment,andthentaptheMap section.

Step 9: Republish the App and Test it on a Tablet Device


86. Beforerepublishing,ifyouarenotalreadyrunningVisualStudioasanadmin,exitandreopen VisualStudio2012asanadministrator.ThisisdonebyrightclickingontheVisualStudio2012 tileintheWindowsstartscreen,andselectingRunasadministrator. 87. InSolutionExplorer,opentheshortcutmenufortheContosoMoving projectandchoose Publish. 88. Thepublishwizardremembersyourexistingconfigurationandautomaticallyshowsthe Summarypage.ChoosethePublish button.Asbefore,theMobileClient appwillbeavailableat theURL: http://<machinename>/ContosoMoving/MobileClient/.

38

39