LightSwitch HTML Client Tutorial
LightSwitch HTML Client Tutorial
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
Letsgetstarted! 6
3. IntheAddClient dialog,enterauniquename,forexampleMobileClient.
10
11
Create the Appointment Details Screen Theappointmentdetailscreenisthenucleusoftheapplicationitswheretheinventoryspecialists will spendmostoftheirtime. 9. Addanewscreenwiththefollowingsettings: x ScreenTemplate:ViewDetailsScreen x ScreenName:ViewAppointmentDetail x ScreenData:Appointment.Also,selectthecheckboxestoincludeallrelateddata.
12
ThisstatesthatwellnavigatetotheViewAppointmentDetailscreenwhenalistitemistapped. BecausetheViewAppointmentDetail screenwascreatedusingtheViewDetails screen template,ascreenparameternamedAppointment wasautomaticallydefinedtoallowusto passtheappointmentwewanttoviewinthat screen.Anyotherscreenparameterswouldalso beconfigurablehere. 14. LetshitF5andruntheapplication!YoullnowseethateachAppointmentnowhasaglyph indicatingthatyoucannavigatetoanotherscreen.
13
14
18. CustomizetheListcontrolintheHome screentoprogrammaticallyaddthetilelistCSSclassinits postRender() event.ThepostRender eventisausefulAPIentrypointbecauseitallowsyouto customizeascreenelementsHTMLusingstandardJavaScriptandjQuerysyntax. g. SwitchbacktoLogicalView andopentheHome screen. h. IntheScreenDesigner,selecttheUpcomingAppointments listcontrol.
16
i.
17
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
27. HitF5toruntheapp!
TheVHDcomespreconfiguredwithIIS8andSQLExpress,sowehaveeverythingweneedtopublishthe applicationtothelocalserverontheVHD aslongasyourmobiledeviceisconnectedtothesame networkyouwillbeableto runtheappfromyourdevice. 28. Beforepublishing,youmustexitandreopenVisualStudio2012asanadministrator.Fromthe WindowsStartscreen,rightclickontheVisualStudio2012tile,andselectRunasadministrator. 29. OnceyouhavestartedVisualStudio2012asanadministrator,loadtheLightSwitchprojectyou justcreatedbyselectingitfromtheRecent menusectionontheleft. 30. Onthemenubar,chooseBuild,ConfigurationManager.
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
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.
24
TheScreenContenttreeshouldnowlooksomethinglikethis:
27
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"); }; };
50. Aroundline26,youwillfindthefollowingline:
<link rel="stylesheet" type="text/css" href="Content/msls.theme.dark.css" />
30
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
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
70. SelectthenewlyaddedSelectedItemnode,andintheProperties windowchooseHeight.Clear theStretchtoContainer checkbox. 71. SwitchthedialogsPicturefieldfroman Image toaCustomControl.IntheProperties window, choosetheEditRenderCodehyperlinkandaddthefollowingcode:
createImageUploader(element,contentItem,"maxwidth:300px;maxheight:300px");
35
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.
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);}); };
38
39