An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft...

Preview:

Citation preview

AnIntroductiontotheMicrosoftBotFramework

CreateFacebookandSkypeChatbotsusingMicrosoftVisualStudioandC#

(ThisbookcoverstheMicrosoftBotFrameworkPreviewEdition)

Copyright2016

PublishedBy

TheAiHelpWebsite

http://AiHelpWebsite.com

Copyright

Copyright©2016byMichaelWashington

Coverandinternaldesign©MichaelWashington

EditingbyAndreaDickinson(www.QualityBookServices.com)

Allrightsreserved.Nopartofthisbookmaybereproducedinanyformorbyanyelectronicormechanicalmeansincludinginformationstorageandretrievalsystems–exceptinthecaseofbriefquotationsinarticlesorreviews–withoutthepermissioninwritingfromitspublisher,AiHelpWebsite.com.

Allbrandnamesandproductnamesusedinthisbookaretrademarks,registeredtrademarks,ortradenamesoftheirrespectiveholders.Wearenotassociatedwithanyproductorvendorinthisbook.

MicrosoftVisualStudioisaregisteredtrademarkofMicrosoftCorporation.

SkypeisaregisteredtrademarkofMicrosoftCorporation.

FacebookisaregisteredtrademarkofFacebookInc.

TableofContents

Copyright

TableofContents

Dedication

MichaelWashington

ThankYou

Microsoft

Community

Preface

Requirements

Chapter1:UnderstandingtheMicrosoftBotFramework

WhatIstheMicrosoftBotFramework?

Chapter2:CreateaHelloWorld!Bot

CreatingAHelloWorld!Bot

UsingTheBotEmulator

SavingUserData

PublishingTheBot

RegisteringTheBotWithTheMicrosoftBotFrameworkDeveloperPortal

Chapter3:UsingFormFlow

AWalkThrough

CreatingTheProject

TestTheApplication

SavingTheData

Chapter4:UsingDialogs

WalkThrough

CreatingTheApplication

TestTheApplication

DialogPrompts

Chapter5:UsingImages,Cards,Carousels,andButtons

HeroCard

Carousel

RichCardAttachmentsInDialogs

CreateTheHeroCardInTheDialogClass

CreatingARe-UsableHeroCard

Chapter6:ImplementingASQLServerDatabaseWithYourBot

CreateTheSQLServerDatabase

CreateAnADO.NETEntityDataModel

LogToTheDatabase

LogMessagesInTheDialogClass

TestTheDatabaseLoggingCode

ViewTheData

LoggingHighScores

UpdateADO.NETEntityDataModel

AlterCodeToLogHighScores

DisplayTheHighScores

TestTheCode

PublishingAMicrosoftBotFrameworkApplicationThatUsesaDatabase

Chapter7:ImplementingLanguageUnderstandingIntelligentService(LUIS)

CreateTheLUISApplication

UpdateTheBotApplication

ImplementHighScores

Chapter8:CallingTheMicrosoftBotFrameworkUsingTheDirectLineAPI

ConfiguringTheDirectLineConnector

CreateTheWebApplication

CompleteTheWebApplication

RunTheApplication

Chapter9:UsingApplicationInsightsToMonitorYourBot

EnableApplicationInsights

DebugTheApplication

UsingTheBotEmulator

CustomTelemetry

ApplicationInsightsAPIsummary

ApplicationInsightsPortal

MonitoringAPublishedApplication

Chapter10:CreatingaSkypeBot

PublishingTheBot

RegisteringTheBotWithTheBotConnector

ConfigureSkype

Chapter11:CreatingAFacebookMessengerBot

Set-UpFacebook

CreateAFacebookDeveloperAccount

CreateAFacebookApp

ConfigureTheCallbackURLandVerifyToken

GetPageToken

ConfigureTheMicrosoftBotConnector

TalkingToYourBot

AboutTheAuthor

Dedication

MichaelWashington

Asalways,forValerieandZachary

ThankYouMicrosoft

DanDriscoll

JimLewallen

SimonMichael

AnnaRoth

RebeccaDuffy

DanielEgan

Community

EzequielJadib

JoeMayo

RobinOsborne

GaryPretty

MaheshChand

JohnathanLightfoot

Preface

Requirements

YoumusthaveacomputerrunningMicrosoftWindowswithMicrosoftVisualStudio2015(orhigher)withUpdate3(orhigher)tocreatetheapplicationsdescribedinthisbook.

YoucandownloadthefreeVisualStudioCommunityEditionfromhttps://www.visualstudio.com/vs/community/

YouwillalsoneedtodownloadandinstalltheVisualStudio2015Bottemplatefromhttp://aka.ms/bf-bc-vstemplate

Chapter1:UnderstandingtheMicrosoftBotFramework

ThisbookcoversusingVisualStudio2015tocreateChatbotsusingtheMicrosoftBotFramework.Thepurposeofthisbookistodemonstrate,provideexamplesof,andtoexplainimportantconceptsofthetechnology.

WhatIstheMicrosoftBotFramework?

TheMicrosoftBotFrameworkallowsyoutoeasilycreateBots.

Youcancreatebotsthatinteractwithyourusersnaturallywherevertheyare,includingFacebook,text,Skype,Office365email,andotherpopularservices.

TheMicrosoftBotFrameworkcontainsthefollowingcomponents:

BotFrameworkDeveloperPortal–AservicethatconnectsyourBottocommunicationchannelssuchasFacebook,Skype,andemail.BotBuilderSDK–AC#andNode.jslibrarythatprovidesapowerfulframeworkforconstructingbotsthatcanhandlefreeformandguidedinteractions.BotDirectory–AdirectoryofBotsthatyoucanconnectto.

TheBotFrameworkDeveloperPortalhelpsyouconnectyourBottocommunicationchannels.YoucanwriteaBotandexposetheMicrosoftBotFramework-compatibleAPIontheInternet.TheBotFrameworkDeveloperPortalwillforwardmessagestousers,andwillsendtheusermessagesbacktoyourBot.

TheBotBuilderSDKisanopensourceSDKhostedonGitHub(https://github.com/Microsoft/BotBuilder-Samples)thatprovideseverythingyouneedtobuilddialogs.BotdevelopersatMicrosoftcreatedthislibrarytoencapsulatefunctionalityrequiredforconversationalbots.

TheBotDirectory(locatedathttps://bots.botframework.com/)featuresBotsthatyoucancommunicatewiththroughchannelsexposedthroughtheBotConnector.

Chapter2:CreateaHelloWorld!Bot

Thesamplecodeforthischaptercanbeobtainedatthelink“CreatingaHelloWorld!BotUsingTheMicrosoftBotFramework”athttp://AiHelpWebsite.com/Downloads

ThepurposeofthischapteristodemonstratehowtogetstartedusingtheMicrosoftBotFramework,howtocreateasimpleBot,andhowtopublishittotheMicrosoftBotFrameworkDeveloperPortal.

CreatingAHelloWorld!Bot

DownloadtheVisualStudio2015templatefromhttp://aka.ms/bf-bc-vstemplate

Savethe.zipfileinthetemplatesdirectoryofyourwindowscomputerlocatedat%USERPROFILE%\Documents\VisualStudio2015\Templates\

ProjectTemplates\VisualC#

ThiscreatesatemplatethatyoucanuseinVisualStudiotocreateBotprojects.

OpenVisualStudio.

CreateanewProject.

SelecttheBotApplicationtemplateandnametheprojectHelloWorldBot.

OpentheMessagesController.csfileintheControllersfolder.

ChangethePostmethodtothefollowing:

HitF5toruntheproject.

Notethewebaddress.Youwillneeditinthenextstep.

UsingTheBotEmulator

Download,install,andruntheBotFrameworkEmulatorfromhttps://aka.ms/bf-bc-emulator

Whentheemulatorstarts,connecttotheBotbysettingtheaddresstotheaddressindicatedinthewebbrowser.However,add/api/messagestotheend.

IntheBotEmulator,enterHellointhetextboxandclickthesendkey(orpressenter).

YouwillseetheresponseintheChatwindowandtheJSONcontentsoftheresponseintheJSONwindow.

SavingUserData

Animportantpartofanyconversationisrememberingwhatauserhaspreviouslysaid.

WecandothisusingGetPrivateConversationDataandSetPrivateConversationData.

Todemonstratehowthisishandled,addthefollowingtothetopoftheMessagesController.csfileintheControllersfolder:

Next,changethePostmethodintheMessagesController.csfiletothefollowing:

Finally,alterthefollowingsectionintheHandleSystemMessagemethod(intheMessagesController.csfile)tothefollowing:

NowwhenwechatwiththeBot,itcanrememberourname.

IfwetellittoDeleteUserData…

Itwillrespectourwishes.

PublishingTheBot

ToconnectyourBotthroughchannelssuchasSkypeandFacebookMessenger,youneedtoconfigureitontheMicrosoftBotFrameworkDeveloperPortal.Todothat,youwillfirstneedtopublishitinapubliclyaccessiblelocation.

Thiscanbeanyserver;however,publishingtoAzureisrecommendedbecausepublishingtoithasbuilt-insupportinVisualStudio.

First,gotohttps://azure.microsoft.comandcreateanaccountandasubscriptionifyoudon’talreadyhaveone.

Next,Right-clickontheProjectnode(nottheSolutionnode)inVisualStudioandselectPublish.

SelectMicrosoftAzureWebApps.

SignintoyourAzureaccount.

Selectasubscription.

ThenclicktheNewbutton.

EnterauniqueWebAppname.

Selectyoursubscription.

Selectorcreateaserviceplan,resourcegroupandregion.

ThenclicktheCreatebutton.

Afterthewebapphasbeencreated,clickthePublishbutton.

Thewebappwillopeninthewebbrowser.

Notethewebaddress.Youwillneeditinalaterstep.

RegisteringTheBotWithTheMicrosoftBotFrameworkDeveloperPortal

GototheMicrosoftBotFrameworkDeveloperPortalathttps://www.botframework.comandsigninwithyourMicrosoftAccount.

SelectRegisterabot.

Fillinallofthefields.

Note:Theendpointwebaddressiswhatyousawwhenthewebbrowseropenedinthepreviousstep.However,rememberyouhavetoadd“/api/messages”totheendoftheaddressandusehttps://ratherthanhttp://.

Duringtheprocess,youwillbepromptedtoclickalinktogotohttps://apps.dev.microsoft.com.

ItistherethatyouwillgetanApplicationIDandapassword.

MakeanoteofthembecauseyouwillneedtousethemtoupdatetheVisualStudioprojectinlaterstep.

ClicktheRegisterbutton.

TheBotregistrationwillbecreated.

CopytheBotID,MicrosoftAppId,andMicrosoftAppPasswordfromthehttps://apps.dev.microsoft.comsitetotheweb.configoftheBotinVisualStudio.

Note:IfyouforgottonotetheMicrosoftAppPasswordintheearlierstep,youcanclicktheGenerateNewPasswordbuttontocreateanotherone.

PublishtheBotagain.

YouaredoingthisbecausetheBotFrameworkwillpasstheBotID,MicrosoftAppId,andMicrosoftAppPasswordwhenitcommunicateswithit.

YoucannowtestyourBotusingtheBotFrameworkDeveloperPortalwebpage.

Ifyoudesire,youcanclickthePublishbuttontosubmityourBottotheBotDirectory.

YoucanalsoconfigurechannelsforyourBot.

EvenifyoudonotpublishyourBottotheBotDirectory,youcanstillcallitfromyourownapplicationsandthroughanychannelsyouconfigure.

Note:Chapters10and11coverhowtousetheBotFrameworkDeveloperPortaltoconfiguretheSkypeandFacebookMessengerchannelstodeployyourBotonthosenetworks.

Chapter3:UsingFormFlow

Thesamplecodeforthischaptercanbeobtainedatthelink“IntroductionToFormFlowWithTheMicrosoftBotFramework”athttp://AiHelpWebsite.com/Downloads

UsingFormFlowwiththeMicrosoftBotFrameworkallowsyoutoquicklycreateaguidedconversationtogatherinformationfromauserwiththeleastamountofcode.WhileitislessflexiblethanusingDialogs(Dialogsarecoveredinthenextchapter),itcanbecombinedwithDialogstoincreaseitsfunctionality.

AWalkThrough

WhenauserbeginsaconversationwiththeBot,itintroducesitselfandaskstheuser’sname.

TheBotproceedstoaskquestionsandgathertheresponses.

AfeatureofFormFlowisthattheusercantypehelpatanytimetoobtainassistancewithanyquestionortheFormFlowitself.

Asadeveloper,yougetthisfunctionalitywithouttheneedtowriteanyadditionalcode.

TheFormFlowcontinuesuntiltheformiscomplete.

CreatingTheProject

OpenVisualStudio.

CreateanewProject.

SelecttheBotApplicationtemplateandnametheprojectHelloFormFlowBot.

Theprojectwillbecreated.

Right-clickontheproject.SelectAddandthenNewItem.

WewillnowcreatetheclassthatwillcontainthelogicforourFormFlow.

AddanewC#classcalledProfileForm.cs.

Replaceallthecodewiththefollowingcode:

ThiscodeindicatesthefieldswewillgatherwithourFormFlow.

Noticethattheclass,aswellastheGenderenumthatitconsumes,ismarked[Serializable].

TheMicrosoftBotFrameworkrequiresthattheclassesmustbeserializable,sotheBotcanbestateless.

Savethefile.

OpentheMessagesController.csfile.

Addthefollowingusingstatementsatthetopofthefile(tosupporttheFormFlowcode):

AddthefollowingMakeRootDialogmethodtotheMessagesControllerclasstocalltheBuildFormmethodintheProfileFormclasswecreatedearlier:

Finally,alterthePostmethodintheMessagesControllerclasstothefollowing:

Savethefile.

TestTheApplication

HitF5toruntheapplication.

Thewebbrowserwillopen.

Notetheportnumberandthewebaddress.

OpenandruntheMicrosoftBotFrameworkEmulator.

Whentheemulatorstarts,connecttotheBotbysettingtheaddresstotheoneindictedinthewebbrowser;however,add/api/messagestotheend.

EnsurethattheBotURLisconnectingtothecorrectaddress.

Typeamessageandclickthesendkey(orpressEnter).

YoucannowconversewiththeBotandfillouttheFormFlow.

SavingTheData

Currentlytheapplicationdoesnotsavetheresponsesfromtheuser.Infact,afteryoufilltheFormFlowout,itwillsimplyaskyoutofillitoutagain.

WecanusetheBotStateServicetosaveandretrievethevalues.

AltertheBuildFormmethodintheProfileForm.csfiletothefollowingtosavethevaluesenteredintotheform:

Wearenotonlystoringthevaluesprovidedbytheuser,butwearealsosettingaflag(ProfileComplete),sowedon’tasktheusertofillouttheformagain.

Finally,alterthePostmethodintheMessagesControllerclasstothefollowing:

NowtheapplicationwillonlyasktheusertofillintheformonetimeanddisplaythevaluesreceivedusingtheBotStateService.

ThevalueswillbepersistedbytheMicrosoftBotFrameworkkeyedtothatuserinthatconversation.

Inourexample,weusedPrivateConversationData,buttheBotStateServiceexposesthefollowingmethods,eachwithadifferentscope:

Method Scoped Description

SetUserData() User Rememberingcontextobjectwithauser

SetConversationData() Conversation Rememberingcontextobjectwithaconversation

SetPrivateConversationData() User&Conversation

Rememberingcontextobjectwithapersoninaconversation

Chapter4:UsingDialogs

Thesamplecodeforthischaptercanbeobtainedatthelink“IntroductionToUsingDialogsWithTheMicrosoftBotFramework”athttp://AiHelpWebsite.com/Downloads

UsingDialogswiththeMicrosoftBotFrameworkallowsyoutomodelaconversationwithauser.WhiletheyaremoreflexiblethanusingaFormFlow(coveredintheprecedingchapter),Dialogsrequiremorecode.

ADialogisaclassthatimplementstheIDialoginterface.Dialogscanbecomposedwithotherdialogstomaximizereuse.

ADialoghasacontextthatcontainsastackofdialogsactiveinaconversationandwillmaintainthestateoftheconversation.ADialogsendsmessagestoauserandissuspendedwhenitiswaitingforaresponsefromauser.

ADialogusesastatestoredinitscontexttoresumeaconversation.ThisstateisstoredinthestateserviceprovidedbytheMicrosoftBotFrameworkservice.

WalkThrough

TheconversationstartswhentheUsertypesinamessage.

TheBotrespondswithagreetingandthedirectionsofthegame,whichistoguessanumberfrom1to10(chosenatrandom).

TheUserguessesanumber,andtheBotinformstheUseriftheyarecorrectornot.

WhentheUserguessesthenumbercorrectly,theyareofferedachancetoplaythegameagain.

IftheUserchoosesnottoplaythegameagain,theBottellsthemgoodbye.

CreatingTheApplication

OpenVisualStudio.

CreateanewProject.

SelecttheBotApplicationtemplateandnametheprojectAiNumberGuesserBot.

Theprojectwillbecreated.

Right-clickontheproject.SelectAddandthenNewItem.

WewillnowcreatetheclassthatwillcontainthelogicfortheDialog.

AddanewC#classcalledNumberGuesserDialog.cs.

Replaceallthecodewiththefollowingcode:

ADialogisaclassthatinheritsfromIDialog.

Notethatwemustdecoratethisclassas[Serializable].

ThisrequiresyoutoimplementaStartAsyncmethod.

Toimplementthis,hoverthemouseoverIDialog<object>,waitafewseconds,andtheinterfaceoptionwindowwillappear.

ClicktheblackarrownexttothelightbulbandselectImplementinterface.

TheStartAsyncmethodwillbecreated.

ThiswillbecalledwhentheDialogisfirstinstantiated.

Wewantthecodetorunasynchronously,soaddasynctothemethodsignature.

Now,changethecodeinsidethemethod,sothecompletemethodiscodedasfollows:

Thelastlineinthemethodiscontext.Wait.ThissuspendsthecurrentDialoguntiltheuserhassentamessagetotheBot.

TheWaitmethodtakesamethodasaparameter(inthiscaseMessageReceivedAsync)tobecalledtoresumetheconversationwhentheresponsehasbeenreceived.

Toimplementit,hoverthemouseoverMessageReceivedAsync,waitafewseconds,andtheinterfaceoptionwindowwillappear.

ClicktheblackarrownexttothelightbulbandselectGeneratemethod‘NumberGuesserDialog.MessageReceivedAsync.

TheMessageReceivedAsyncmethodwillbecreated.

NoticeittakesthecontextoftheDialogandanargument(result).

ChangethetypeoftheargumentfromobjecttoIMessageActivityandchangethenameofthevariablefromresulttoargument.

Again,wewantthecodetorunasynchronously,soaddasynctothemethodsignatureandmarkitasvirtual.

Alterthecodeinthemethod,sothecompletemethodiscodedasfollows:

Noticethelastline(context.Wait(MessageReceivedAsync))simplycallsthemethodthecodeiscontainedinagainandagain.

Weareonlydoingthistomakethisexampleassimpleaspossible.WewillexploreamorerealisticexampleinthenextsectionwhenweaddaPromptDialog.

Next,opentheMessagesController.csfileat…\AiNumberGuesserBot\AiNumberGuesserBot\Controllers\

MessagesController.cs

Replacethedefaultcodeinthecodeblockthatbegins:

Withthecode:

ThistellstheBottodirectanymessagestotheNumberGuesserDialogclass.

Finally,addthefollowingusingstatementtothetopofthecodefile:

TestTheApplication

HitF5toruntheapplication.

Thewebbrowserwillopen.Notetheportnumberandthewebaddress.

OpenandruntheMicrosoftBotFrameworkEmulator.

Whentheemulatorstarts,connecttotheBotbysettingtheaddresstotheoneindictedinthewebbrowser;however,add/api/messagestotheend.

EnsurethattheBotURLisconnectingtothecorrectaddress.

Typeamessageandclickthesendkey(orpressEnter).

TheBotwillrespond.

ThisisalltheBotwilldoatthispoint;however,thisexampleshowstheminimalcodetocreateandconsumeaDialogclass.

DialogPrompts

APromptDialogisessentiallyaDialogfactoryforcreatingsimpleprompts.ItallowsyoutoasktheUserforaresponseandindicatewhatcodewillrunwhentheresponseisgiven.APromptDialogspawnsasub-dialogthathasitsownprivatestate.Thissub-dialogissuspendedbytheMicrosoftBotFrameworkservicewhileitwaitsforaresponse.Whenitgetsaresponse,itresumesatthepointinthecodeitwasatwhenitwassuspended.

ThisistheprimarymeansofcontrollingprogramflowwithinaDialogclass.

APromptDialogcanbeoneofthefollowingtypes:

PromptforanattachmentPromptforoneofasetofchoicesAskayes/noquestionPromptforalongPromptforadoublePromptforastring

WewillenhanceourapplicationtoimplementaPromptDialogthatasksayes/noquestion.

First,addthefollowingcodetotheMessageReceivedAsyncmethod:

Thiscodewillsimplykeeploopingandcountingtheguessingattemptsiftheuserdoesnotguesstherandomnumber.

Iftheuserdoesguessthenumber,thecodeintheelseblockwillbecalled.

Rightnow,thecodeisnotcomplete.WeneedtoaddaPromptDialogundertheline//PutPromptDialoghere.

TypePromptDialogandpresstheperiod(.)key.TheautocompleteoptionswillshowandwewillseetheoptiontoimplementthevarioustypesofPromptDialogs.

ChoosetheConfirmoption.

Wecanlookintheofficialdocumentationathttps://docs.botframework.com/en-us/csharp/builder/sdkreference/andseethemethodsignaturerequiresustopassthecurrentcontext,indicatethemethodtobecalledwhenwegetaresponse(resumehandler),provideamessagetoshowtheuser(prompt),andprovideamessagetodisplayiftheresponsetypeisnotcorrect(retry).Theotherparametersareoptional.

Thefollowingshowsthecompletecodeforourimplementation:

Wenowneedtoimplementtheresumehandlermethodtohandletheresponse(PlayAgainAsync).

Toimplementit,hoverthemouseoverPlayAgainAsync,waitafewseconds,andtheinterfaceoptionwindowwillappear.

ClicktheblackarrownexttothelightbulbandselectGeneratemethod‘NumberGuesserDialog.PlayAgainAsync’.

Themethodwillbecreated.

Addasynctothemethodsignature.

Alterthemethod,sothecompletecodeisasfollows:

HitF5toruntheprogramandconnecttoit,usingtheBotFrameworkEmulator…

Whenweguessthecorrectnumber,thePromptDialogwillappear.Whenweprovideananswer,thePlayAgainAsyncmethodwillimmediatelyruntoprocessouranswer.

WecanspawnanotherPromptDialoginsidethePlayAgainAsyncmethodifwechoose,effectivelycreatinganendlesschainofPromptDialogstocreatebranchesofcodeforaconversation.

Chapter5:UsingImages,Cards,Carousels,andButtons

Thesamplecodeforthischaptercanbeobtainedatthelink“UsingImages,Cards,Carousels,andButtonsInTheMicrosoftBotFramework”athttp://AiHelpWebsite.com/Downloads

Note:TheimageaboveshowstheBotinSkype.DeployingaBottoSkypeiscoveredinChapterTen.

ImplementingimagesinyourMicrosoftBotFrameworkapplicationaddsavisualelementtotheinteractionwithyourusers.

Youcaneasilypassamediaattachment(image/audio/video/file)toamessageusingcodesuchasthis:

Dependingonthechannelusedandthemediatype,animagewillbedisplayedoralinkwillbedisplayedfortheusertodownloadthemediaelement.

However,realpowerisprovidedwhenyouuserichcardattachments.

Therearefourcardtypes:

CardType Description SingleorCarousel/List

(MultipleCards)

HeroCard Abigimagewithtext SingleorCarousel/List

ThumbnailCard

Asmallimagewithtext SingleorCarousel/List

ReceiptCard Aninvoiceorreceipt Single

Sign-InCard Ausersign-inform Single

HeroCard

Inthischapter,wewillcoverHeroCard.

AHeroCardandaThumbnailCarddifferonlyinthesizeoftheirimageandcard.

Eachconsistsofthefollowingproperties:

Property Description

Title Titleofthecard

Text Texttodisplayonthecard

Subtitle Alinkforthetitle

Images Actually,onlyasingleimage

Buttons Oneormorebuttons(InSkype,only5buttonswilldisplayonacard.Ifyouhavemorebuttons,itwillcreatetwocards.)

Tap Anactionthatistriggeredwhenausertapsonthecard(ThisdoesnotworkinsomeSkypeclients,soforSkype,useahyperlinkfortheSubtitleproperty.)

TodemonstrateimplementingaHeroCard,wewillstartwiththecodefromthepreviouschapter.

Note:First,youwillhavetouseManageNuGetPackagesinVisualStudiotoupdateMicrosoft.Bot.Buildertothelateststableversionbeforeyoucontinue.

Also,wewillmakesomesmallchanges,suchasmakingthenumbertoguessfrom1to5ratherthan1to10,soitshowsupwellinSkypebecauseSkypewillonlydisplay5buttonsonasinglecard.

OpentheprojectinVisualStudio.

AddanewfolderandcallitImages.

AddtheNumberGuesserOpeningCard.pngfile(youcangetthecodeontheDownloadspageoftheAiHelpWebsite.com)totheImagesfolder.

OpentheMessagesController.csfile(intheControllersdirectory),andaddthefollowingusingstatementtothetopofthefile:

Next,locatetheelseif(message.Type==ActivityTypes.ContactRelationUpdate)sectionintheHandleSystemMessagemethod.

ThismethodfireswhentheBotisaddedtotheContactlistofauser.

Replaceallthecodeinthesectionwiththefollowingcode:

SavethefileandhitF5toruntheapplication.

OpenandruntheBotusingtheMicrosoftBotFrameworkEmulator.

IntheEmulator,invoketheContactRelationUpdate-addevent.

TheHeroCardwilldisplay.

ClickingonthecardwilltakeyoutotheAiHelpWebsite.comwebsite.

Carousel

Acarouseldisplaysmultiplecards(eitherHeroCardsorThumbnailCards)horizontally.

AList(thedefaultlayoutformultiplecards)displaysthecardsvertically.

TheimageaboveshowswhatacarouseloftwoHeroCardslookslikeintheSkypeclient.

Toimplementthis,firstaddtheAiLogo_smallSquare.pngfile(youcangetthecodeontheDownloadspageoftheAiHelpWebsite.com)totheImagesfolder.

Next,addthefollowingcodetotheHandleSystemMessagemethod(abovethevarconnector=newConnectorClient(newUri(message.ServiceUrl));line):

Savethefile,runtheapplication,andconnecttoitintheEmulator.

IntheEmulator,invoketheContactRelationUpdate-addevent.

Thefirstcardwillshow,butyouwillnowseeaslider.

Slideittotheright.

YouwillthenseethesecondHeroCard.

InSkype,theSubtitlepropertywilldisplayasahyperlinkandbeclickable.

RichCardAttachmentsInDialogs

ThereareadditionalchallengeswhenimplementingrichcardattachmentsinDialogs.

Primarily,thebiggestchallengeisthat,insidetheDialogclass,youdonothaveaccesstothebaseURLoftheapplicationtodeterminewhereyourimagesare.

WecanaddressthisbyusingtheBotStateService.

OpentheMessagesController.csfile:

AddthefollowingcodetothetopofthePostmethod:

ThiswillstoretheCurrentBaseURLandtheRecipientusingtheBotStateService,sothevaluescanlaterberetrievedintheDialogclass.

OpentheNumberGuesserDialog.csfile.

Addthefollowingcodeabovethenamespace:

Addthistothetopoftheclass:

ThiswillprovideaglobalvariablethatwillbeautomaticallyserializedandpersistedbetweencallstostoretheBaseURL.

AddthefollowingcodetothetopoftheMessageReceivedAsyncmethod:

ThiswillretrievethevalueofCurrentBaseURLthatwasstoredinBotStateServiceintheMessagesControllerclassandstoreitinthestrBaseURLglobalvariable.

AddthefollowingUtilitymethodtotheclass.Thismethodwillcreate5CardActionbuttonsthatwillbeattachedtotheHeroCard(thatwewillcreateinalaterstep):

ThebuttonsaresettotheType“imBack”,whichmakesthebutton(CardAction)simplypostthevalue(inthiscase,thebuttonnumber)backtotheBot.

CreateTheHeroCardInTheDialogClass

WewillnowdisplayaHeroCardwith5buttonsintheDialogclass.

First,addtheNumberGuesserCard.pngfile(youcangetthecodeontheDownloadspageoftheAiHelpWebsite.com)totheImagesfolder.

Next,findthefollowingcodeintheMessageReceivedAsyncmethod:

Replaceitwiththefollowingcode:

Savethefile,hitF5toruntheproject,andconnecttoitintheEmulator.

TheBotwillnowdisplayanimageandbuttons.

Wecaneitherclickoneofthebuttonsorenteranumbertoplaythegame.

ThefollowingimageshowswhatitlookslikeinSkype:

CreatingARe-UsableHeroCard

IfthereareafewmoreplacesweneedtodisplaytheHeroCardwiththebuttons,

wewillwanttocreateare-usableHeroCard.

ThisHeroCardwillnothaveanimage,onlybuttons.

First,addthefollowingutilitymethodtotheDialogclass:

NotethatitcallstheCreateButtonsutilitymethodthatwecreatedearlier.

Now,locatethefollowingcode:

Replaceitwith:

ThecodewillnowcalltheShowButtonsmethodthatwillreturntheHeroCard.

Finally,findthefollowingcode:

Replaceitwith:

TheBotwillnowdisplaytheHeroCard,withonlythebuttons,ineachsituationwherewecalledtheutilitymethod.

Chapter6:ImplementingASQLServerDatabaseWithYourBot

Thesamplecodeforthischaptercanbeobtainedatthelink“ImplementingASQLServerDatabaseWithTheMicrosoftBotFramework”athttp://AiHelpWebsite.com/Downloads

MicrosoftBotFrameworkChatbotapplicationsthatrequireinformationtobestored,queried,andsharedwithmultipleuserswillrequireacentralstoragerepository.

UsingMicrosoftSQLServerandMicrosoftAzurewillallowyoutoeasilyimplementthisfeature.

TodemonstrateimplementingadatabasewithaMicrosoftBotFrameworkapplication,wewillstartwiththecodefromthepreviouschapter.

CreateTheSQLServerDatabase

WewillstartbycreatingadatabaseandloggingthemessagessenttoandfromtheBot.

OpentheprojectinVisualStudio.

IntheSolutionExplorerinVisualStudio,right-clickontheProject(nottheSolution),andselectAdd,thenAddASP.NETFolder,thenApp_Data.

Note:App_Dataisaspecialfolderthatwillcontainthedatabasewewillcreate.Weusethisfolderbecausewewillhaveanoptiontonotdeploythisfolder(andthedatabasethatitwillcontain)whenwepublishtheapplicationtoAzure.Thiswillbecoveredlater.

Right-clickontheApp_Datafolder.SelectAddandthenNewItem.

AddaSQLServerDatabase.

NameitBotData.mdf.

Wewillnowcreateatableinthedatabasetoholdourdata.

Right-clickonthedatabaseandselectOpen.

Expandthedatabaseelementsinthetree.

Right-clickonTablesandselectAddNewTable.

PastethefollowingscriptinandclicktheUpdatebutton:

ClickUpdateDatabase.

Thetablewillbecreated.

Right-clickontheTablesnodeandselectRefresh.

Thetablewillshow.

CreateAnADO.NETEntityDataModel

WewillnowcreateanEntityDataModeltoallowprogrammaticaccesstothedatabase.

SwitchtoSolutionExplorerview.

CreateafoldercalledModels.

Right-clickontheModelsfolder.SelectAddandthenNewItem.

AddanADO.NETEntityDataModelandcallitBotData.

WhentheEntityDataModelWizardopens,selectEFDesignerfromdatabase.

ClickNext.

SelectBotData.mdfinthedatabasedropdown(ifitisnotalreadyselected).

ChecktheboxnexttoSaveconnectionsettingsinWeb.Config.

ClickNext.

SelectEntityFramework6.x.

ClickNext.

ExpandthetreetorevealtheUserLogtableandclickthecheckboxnexttoit.

Accepttheotherdefaultvalues.

ClickFinish.

TheBotData.edmxanEntityDataModelwillbecreated.

YoucanclosetheBotData.edmxfornow.

LogToTheDatabase

Wewillnowcreatecodethatwilllog(mostof)themessagestoandfromtheBottothedatabase.

First,createafilecalledUtility.csandusethefollowingcode:

Thiscreatesautilitymethodtoallowustotrimanytextwestoreinthedatabase.Thisensuresthatnomessageistoolongtobestoredinthedatabase.Thiswouldcauseanerror.

Next,findthefollowingcodeinMessagesController.cs:

Replaceitwith:

ThiscodelogsthemessagesbeingsentfromtheusertotheBot.

LogMessagesInTheDialogClass

TheDialogclasscreatesaresponsetotheuser.

FindallcodeintheNumberGuessserDialog.csfile(therewillbemultipleplaces)thatsendatextresponsetotheuser,whichcontaintheselines:

Addthefollowingcodeabovetheexistinglinesofcode(again,therewillbemultipleplacesyouwilldothis):

WhenwehaveaPromptDialog,wedon’thaveareplyActivity.Inthiscase,weneedtomakeone,sowehavethevaluesweneedtologtothedatabase.

FindthefollowingcodeintheDialogclass:

Addthefollowingcodeabovetheexistinglinesofcode:

Note:TheCongratulationsStringPromptissetbytheexistingcodetoindicatethattheuserhaswonthegame.

TestTheDatabaseLoggingCode

HitF5toruntheapplication.

Thewebbrowserwillopen.

Notetheportnumberandthewebaddress.

OpenandruntheMicrosoftBotFrameworkEmulator.

Whentheemulatorstarts,connecttotheBotbysettingtheaddresstotheoneindictedinthewebbrowser;however,add/api/messagestotheend.

EnsurethattheBotURLisconnectingtothecorrectaddress.

EnterHelloandclickthesendbuttontostartaconversationwiththeBot.

PlaythegamewiththeBot.

ClosethewebbrowsertostoptheapplicationandreturntoVisualStudio.

ViewTheData

Wewillnowviewthedatathatwasloggedtothedatabase.

IntheSolutionExplorerinVisualStudio,right-clickonBotData.mdfandselectOpen.

ThiswillopentheServerExplorer.

Right-clickontheUserLogtableandselectShowTableData.

Theloggeddatawillbedisplayed.

LoggingHighScores

WewillnowaddcodetologanddisplayHighScores.

Wehavetoalterthedatabasefirsttostorethenumberofturnsrequiredtowinandthenameofthewinner.

IntheServerExplorer,right-clickontheUserLogtableandselectOpenTableDefinition.

Note:Ifyoudon’thavethisoption,installthelatestSQLServerDataTools(SSDT)fromhttps://msdn.microsoft.com/library/mt204009.aspx

Addthefollowingfields:

CountOfTurnsToWin[int]WinnerUserName[nvarchar(150)]

ClicktheUpdatebutton.

WhenthePreviewDatabaseUpdatesboxshows,clickUpdateDatabase.

TheDataToolsOperationswindowwillindicatewhentheupdateiscomplete.

UpdateADO.NETEntityDataModel

WehavetoupdatetheADO.NETEntityDataModeltohaveprogrammaticaccesstothenewlyaddedfields.

IntheSolutionExplorer,clickonBotData.edmxtoopenitinthedesigner.

Inthedesigner,right-clickontheUserLogtableandselectUpdateModelfromDatabase.

WhentheUpdateWizardshows,selecttheRefreshtabandthenselecttheUserLogtable.ClickFinish.

AlterCodeToLogHighScores

WewillnowalterthecodeintheDialogclasstologthewinninguserandthenumberofturnstheyrequiredtowin.

IntheNumberGuesserDialog.csfile,locatethefollowingcode:

Addthefollowinglinesofcodebelowthecodeabove:

DisplayTheHighScores

WewillnowaddcodetodisplaytheHighScoreswhenevertheusertypesHighScores.

OpentheMessagesController.csfileandaddthefollowingmethodtotheclass:

WewillnowaddthecodethatwillcalltheShowHighScoresmethodwejustadded.

IntheMessagesController.csfile,locatethefollowingcode:

Replaceitwiththefollowingcode:

Finally,tolettheuserknowtheycantypeHighScorestoseethehighscores,findthefollowingcodeintheDialogclass:

Changeitto:

TestTheCode

NowwhenwetypeHighScores,wecanseethehighscoresforthepastday.

TheimageaboveshowswhatthehighscoreslooklikewhentheBotispublishedandviewedthroughtheSkypeclient.

PublishingAMicrosoftBotFrameworkApplicationThatUsesaDatabase

TopublishtheBot,wecanfollowthedirectionsinChapter2:CreateaHelloWorld!Bot.

However,unlikethischapter,thatchapterdoesnotcoverpublishingaBotthatusesadatabase.

IfyoudonothaveaMicrosoftAzureaccount,gotohttps://azure.microsoft.comandcreateanaccountandasubscription.

LogintotheAzurewebportalandselectSQLdatabases.

Addanewdatabase.

Fillintheformtocreateanewdatabase.

Note:Ifyoudonotalreadyhaveaservertoputthedatabaseon,youwillbepromptedtocreateone.Atthattime,youwillcreateausernameandpassword.ThisistheusernameandpasswordyouwilluseintheconnectionstringtoconnecttothedatabasewhenyouusethedeploymentwizardinVisualStudio(coveredlater).

Afteryoucreatethedatabase,youcanviewtheADO.NET(SQLauthentication)connectionstringforthedatabaseintheOverviewsection.

Note:Theconnectionstringwillnothavetheusernameandpassword.YouwillusetheusernameandpasswordoftheAzureserverthatcontainsthedatabase.

IntheSolutionExplorerinVisualStudio,right-clickontheprojectnodeandselectPublish.

InthePublishwizard,filloutthefieldstopublishyourBottoAzure.

OntheSettingstab:

1. SelectExcludefilesfromtheApp_Datafolder.ThiswillpreventtheBotData.mdfdatabasefilefrombeingpublishedtoAzure.Youaredoingthisbecausethe.mdffilecannotbeusedonAzure.

2. Entertheconnectionstringtothedatabase(runningonAzure)inBotDataEntities.YoucangettheADO.NET(SQLauthentication)connectionstringforthedatabaseintheOverviewsectionforthedatabaseintheAzureportal.Usethe“…”buttontohelpyouconnecttothedatabaseandconstructtheconnectionstring.

3. CheckUsethisconnectionstringatruntime.Thiswillupdatetheweb.configofthepublishedapplication,sothepublishedapplicationwillconnecttothedatabaseonAzure.

4. ClickthePublishbutton.

IntheServerExplorerinVisualStudio,right-clickonthedatabaseandselectOpeninSQLServerObjectExplorer.

Note:Ifyoudon’thavethisoption,installthelatestSQLServerDataTools(SSDT)fromhttps://msdn.microsoft.com/library/mt204009.aspx

ThiswillopentheSQLServerObjectExplorer.

Right-clickontheTablesnodeunderthedatabaseandselectAddNewTable.

UsethefollowingscripttocreatetherequiredtableandclicktheUpdatebutton:

WhenthePreviewDatabaseUpdatesboxshows,clickUpdateDatabase.

Note:YoucanalsousetheCloudExplorerforVisualStudio2015extensiontomanageyourAzuredatabasesinsideVisualStudio.

Chapter7:ImplementingLanguageUnderstandingIntelligentService(LUIS)

Thesamplecodeforthischaptercanbeobtainedatthelink“ImplementingLanguageUnderstandingIntelligentService(LUIS)InMicrosoftBotFramework”athttp://AiHelpWebsite.com/Downloads

UsingLanguageUnderstandingIntelligentService(LUIS)inyourMicrosoftBotFrameworkapplicationallowsyoutocreatechatbotsthatareeasierforyourend-userstointeractwith.

Forthisexample,wewillstartwiththecodecreatedinthepreviouschapter.

Thischaptercovershowtocreateanumberguessinggameandstoringanddisplayingthehighscores.Inthepreviouschapter,theuserisrequiredtotypeintheexactwordsHighScores,andtheycouldonlyseethehighscoresforthepastday.

Inthischapter,wewillalterthecodetoallowtheusertoseethehighscoresforthepastweek,thepastmonth,orthepastdaystheyspecify(upto30days).

Mostimportantly,wewillallowtheusertotypetheirrequestusingnormallanguageandthendetecttheintentoftheuserandtheimportantrelatedentities(suchasthenumberofdays).

WewilldothisbycreatinganapplicationusingtheLanguageUnderstandingIntelligentService(LUIS)andtheninterfacingthatapplicationwithourexistingBot.

CreateTheLUISApplication

Thefirststepistogotohttps://www.luis.ai/andcreateanaccountontheLanguageUnderstandingIntelligentService(LUIS)siteandlogin.

CreateaNewApplication.

WewillcallitHighScores,andafterfillingouttheotherfields,weclickAddApp.

NowweneedtocreateEntities.Theseareelementswewillneedtoidentifyandgather,soourBotcanperformoperationsbasedontheirvalue.Inourexample,wewanttocreatetwoEntities:

PeriodOfTime–Detectiftheuserenteredaworddescribingtheamountofdays(butnottheactualdays),forexample,weekormonthDays–Detectiftheuserenteredtheactualdayssuchas3orthree

ClicktheplusbuttonnexttotheEntitieslabel(ontheleft-handsideoftheeditor)toopenaboxthatwillallowyoutoaddeachEntity(oneatatime).

Whenyou’redone,theEntitieswillbedisplayed.

Next,wewilladdanIntent.

Note:The“None”Intent,tobetriggeredwhenanutterancebytheuserdoesnotmatchaprogrammedintent,willbeautomaticallycreated)

ClicktheplusbuttonnexttotheIntentslabel.

EnterHighScoresfortheIntentname.

EnterShowmethehighscoresforthepastweekforEnteranexampleofacommandthattriggersthisintent.(Thisisalsoknownasasampleutterance.)

ClickSave.

TheutterancewillnowdisplayintheNewutterancestab.

WewantthisutterancetotriggertheHighScoresIntent,soselectitfromthedropdown.

WealsowanttodetecttheassociatedEntity.

Clickonthewordweek,itwillthenbehighlighted,andapopupboxwillappear.

SelectPeriodOfTime.

Finally,clickSubmit.

Continuetoenterandlabeladditionalutterances.

Note:RemembertolabelanyEntitiesthatindicateanumberasDays.

Continuetotraintheservice.

YouwillnoticethateventuallyitwillstartdetectingtheEntitiesonitsown.

However,manytimesyouwillstillhavetocorrectit.

Enterandcorrectatleasttendifferentutterances.

ClicktheTrainbuttoninthebottomleft-handcorneroftheinterfacetotrainthemodel.

Next,clickthePublishbutton.

Finally,clickthePublishwebservicebutton.

Thepublishedend-pointwillbedisplayed.

MakenoteoftheAppIDandSubscriptionKey.YouwillneedtheselatertobeusedintheBotapplication.

Note:Starting12/31/2016,AppIDwillnolongerbeused.YouwillonlyuseaSubscriptionKeytoconnecttoyourLUISapplication.

Note:Foraproductionapplication,youwillobtainyoursubscriptionkeyfromAzure.

Now,weneedtoupdatetheBottocalltheLUISservice…

UpdateTheBotApplication

OpentheprojectfromthepreviouschapterinVisualStudio.

AddanewfilecalledLUISDialogClass.cs,usingthefollowingcode:

ThiscodewillpasstextenteredintotheBottotheLUISapplicationandtriggertheNoneorHighScoresmethodsbasedonwhattheLUISapplicationdeterminestheIntentis,whichtheenteredtextmatches.

WedecorateeachmethodwithaLuisIntentdecoration,settingthenameofanIntent(forexample,[LuisIntent(“HighScores”)])toindicatewhichmethodshouldbetriggered.

Note:Thecodeisnotcompleteatthispoint.Wewillcompletethecodeinlatersteps.

EnsurethatyouentertheAppIDandSubscriptionKeyfromyourLUISapplicationintheLuisModeldecorationatthetopoftheclass.

ThisishowthecodeknowswhatLUISapplicationtoconnectto.

WenowneedtocalltheLUISDialogClass,insteadofthepreviouslyconfiguredNumberGuesserDialogclass,whenausercommunicateswiththeBot.

ThenewLUIScode(LUISDialogClass)willcalltheNumberGuesserDialogclasswhenneeded,forexample,whentheuserhasnottriggeredtheHighScoresintent.

OpentheMessagesController.csfileintheControllersfolder.

Replacethefollowingcode:

With:

ThereareplaceswheretheNumberGuesserDialogwillneedtocallLUISDialogClass,forexample,whentheuserhasenteredaresponsethatisnotanumberbeingguessedaspartofthegame.

TheNumberGuesserDialogclasswillneedtoreturncontrolbacktotheLUISDialogClass.

ReplacethecodeintheNumberGuesserDialogclass(encapsulatedinthebrackets)thatbeginslikethetextbelow:

Withthefollowingcode:

TheNumberGuesserDialogclassisnolongertherootclass,sowewillneedtoalteritslightlyagain,soitstartsupthegameproperlywhenitistriggeredbytheLUISDialogClass.

LocatethefollowingcodeintheStartAsyncmethod:

Replaceitwith:

Thiscodeshowsthewelcomescreentostartthenumberguessinggame.

ImplementHighScores

Atthispoint,ifweruntheapplicationandconnecttoitintheMicrosoftBotFrameworkEmulator,wecanplaythegame.

However,ifwetypeanythingthattriggerstheHighScoresLUISIntent,wewillreceiveanerrorbecausethecodetohandlethishasnotbeenimplementedyet.

OpentheLUISDialogClass.csfileandlocatethefollowingcode:

Replaceitwith:

Thiscodewillsetthenumberofdaystheuserisaskingthehighscorestoinclude.Itfirsttriestodetectifaperiodoftimewaspassed(inthePeriodOfTimeentity).Ifithasbeen,thecodeconvertsaknownperiodoftimetoanumberofdays.

Ifanumberofdayswaspassed(intheDaysentity),thecodetriestoconvertthedaysintoanumber.Ifitcannot,itassumesthenumberofdayswaspassedasawordnotanumber.Ifthisisthecase,itpassesthevaluetotheParseEnglishmethodthatconvertsthewordtoanumber.

Note:YoucangettheParseEnglishmethodfromhttp://stackoverflow.com/questions/11278081/convert-words-string-to-int

Thenumberofdays(andthecurrentcontext)isthenpassedtotheShowHighScoresmethod.

Asthefinalstep,enterthefollowingcodetoimplementtheShowHighScoresmethodintotheLUISDialogClass:

Chapter8:CallingTheMicrosoftBotFrameworkUsingTheDirectLineAPI

Thesamplecodeforthischaptercanbeobtainedatthelink“CallingTheMicrosoftBotFrameworkUsingTheDirectLineAPI”athttp://AiHelpWebsite.com/Downloads

YoumayneedtocallyourMicrosoftBotFrameworkBotdirectlyfromacustomapplication,aservice,orawebsite.TheMicrosoftBotConnectorDirectLineRESTAPIallowsyoutodothis.Inaddition,itallowsyoutoauthenticateauserinyourapplicationandsecurelycommunicatewiththeBotasthatuser.

TheDirectLineAPIexposesaRESTAPIthatallowsyoutocommunicatewithasingleBotthathasbeenregisteredwiththeMicrosoftBotConnectorService.

ThisAPIisintendedfordeveloperswhowanttocommunicatewiththeirBotfromtheirownclientapplications,suchasmobileapps,aservice,orevenaHoloLens.

TheprocedureforworkingwiththeAPIis:

1. RegisteryourBotwiththeBotFrameworkDeveloperPortal2. ConfiguretheDirectLineConnector3. UsethecredentialsobtainedfromtheBotFrameworkDeveloperPortaltomake

RESTbasedcallstocommunicatewiththeBotInourexample,wewillusetheMicrosoft.Bot.Connector.DirectLineNugetpackagetohelpusmakethecalls.

Note:TherenderingoftheoutputwillbetheresponsibilityofthedeveloperofthecustomapplicationthatiscallingtheDirectLineAPI.

Mediasuchanimages,cards,andbuttonswillrequirecustomcodetorenderinamannerthatisappropriatefortheparticularapplication.

Theexampleapplicationwewillbuildwillcreateacustomclientthatwillallowausertocreateanaccount,sign-in,andsecurelycommunicatewiththeBotthatwascreatedinthepreviouschapter.

ConfiguringTheDirectLineConnector

WewanttoconfiguretheDirectLineconnectorforourBot.

Gotohttps://dev.botframework.com/,login,andselectMyBots.

OpenaBotthathasbeendeployedtotheMicrosoftBotFrameworkDeveloperPortal.

ThefirststepistomakeanoteoftheBothandleyougaveyourBot.YouwillneedthislaterwhenyoucreatetheWebApplication.

UnderAddanotherchannel,clicktheAddbuttonnexttoDirectLine.

WhentheConfigureDirectLinescreenappears,clicktheGenerateDirectLinesecretbutton.

CopytheSecretcode.YouwillneedthislaterwhenyoucreatetheWebApplication.

ClickI’mdoneconfiguringDirectLinebutton.

Thescreenwillclose.

CreateTheWebApplication

OpenVisualStudio.

FromthetoolbarinVisualStudio,selectFile,thenNew,andthenProject.

SelectWebandthenASP.NETWebApplication(.NetFramework).

EnterDirectLineBotfortheName.

SelecttheCreatedirectoryforsolutionbox.

PressOK.

Whentheapplicationconfigurationboxappears,selecttheMVCtemplate.

EnsurethatIndividualUserAccountsisselectedforAuthentication.Ifnot,clicktheChangeAuthenticationbuttonandchangeit.

PressOK.

Theapplicationwillbecreated.

WeneedtoaddtheMicrosoft.Bot.Connector.DirectLineNuGetPackagethatwillallowustoeasilycommunicatewiththeDirectLineAPI.

IntheSolutionExplorer,right-clickontheDirectLineBotprojectnode(nottheSolutionnode),andselectManageNuGetPackages.

WhentheNuGetPackageconfigurationwindowappears,clicktheBrowsebutton.

EnterMicrosoft.Bot.Connector.DirectLineinthesearchboxtoconductthesearch.

WhentheMicrosoft.Bot.Connector.DirectLinepackageshowsup,clickonit,soits

propertiesappearinthewindowontheright.

ClicktheInstallbuttontoinstallthepackage.

ClickOKwhenthePreviewwindowshows.

ClicktheIAcceptbuttonwhentheLicenseAcceptancewindowappears.

TheMicrosoft.Bot.Connector.DirectLineassemblywillbeinstalled.

HitF5todebugandruntheapplication.

Theapplicationwillopeninthewebbrowser.

YouwillseethedefaultwebapplicationcreatedbytheMVCtemplate.

WecanclicktheRegisterbuttontocreateanewaccount.

WecanalsoclicktheLoginbuttontologinusingaregisteredaccount.

CompleteTheWebApplication

WewillupdatethehomepagetoshowthechatboxandtheBotresponseonlyiftheuserhascreatedanaccountandloggedin.

StopdebuggingtheapplicationandopentheIndex.cshtmlfileintheViews/Homefolder.

Replaceallofthecodewiththefollowingcode:

OpentheHomeController.csfileintheControllersfolder,andreplaceallthecodewiththefollowingcode:

Atthispointthecodeisnotcomplete;however,itsetsupthebasicframework.

Replace**INSERTYOURSECRETCODEHERE**and**INSERTYOURBOTIDHERE**withthevaluesfromyouownpublishedBot.

WhenaloggedinuserloadsthepageorsubmitstexttotheBot,theTalkToTheBotmethodiscalled.

Toimplementit,addthefollowingmethodtotheHomeControllerclass:

TheTalkToTheBotmethodcallstheReadBotMessagesAsyncmethodtoreadtheresponsefromtheBot.

Toimplementit,addthefollowingmethodtotheHomeControllerclass:

WhenthereisanimagethatisreturnedbytheBot,theReadBotMessagesAsyncmethodcallstheRenderImageHTMLmethod.

Toimplementit,addthefollowingmethodtotheHomeControllerclass:

RunTheApplication

HitF5toruntheapplication.

Theapplicationwillopeninthewebbrowser.Initially,wearenotloggedin,sowewillbeunabletocommunicatewiththeBot.

ClicktheRegisterbuttontocreateanaccount.

FillintherequiredinformationandclicktheRegisterbutton.

Afteryouhavecreatedanaccount,youcanclicktheLoginbuttontologin(ifyouarenotalreadyloggedin).

YouwillknowyouareloggedinwhenyouseeyouremailaddressinthemenubarandontheHomepage.

YoucannowcommunicatewiththeBotandrunthesamecodethatwascreatedinthepreviouschapter.

WhenwelookatthedatainthedatabaseonAzure,weseetheUserIDandUserNameformessagespostedtotheBotarecompletelyunderthecontrolofthefollowingcustomcode:

Chapter9:UsingApplicationInsightsToMonitorYourBot

Thesamplecodeforthischaptercanbeobtainedatthelink“UsingApplicationInsightsWithMicrosoftBotFramework”athttp://AiHelpWebsite.com/Downloads

WithApplicationInsights,youcaninsertafewlinesofcodeinyourBottofindoutwhatyourusersaredoing.

WhenyouinstallApplicationInsights,youareinstallingasmallinstrumentationpackageinyourapplication.Next,yousetupanApplicationInsightsresourceintheMicrosoftAzureportal.

TheinstrumentationyouinstallmonitorsyourappandsendstelemetrydatatotheMicrosoftAzureportal.TheMicrosoftAzureportalshowsstatisticalchartsandhaspowerfulsearchtoolstohelpyoumonitoryourapplicationanddiagnoseanyproblems.

Todemonstratethis,wewillstartwiththeBotcreatedinChapterSix.

ThiswillrequireusingMicrosoftAzure.IfyoudonothaveaMicrosoftAzureaccount,gotohttps://azure.microsoft.comandcreateanaccountandasubscription.

EnableApplicationInsights

OpentheAiNumberGuesserBotprojectinVisualStudio.

IntheSolutionExplorer,right-clickontheProject(nottheSolution),andselectAddApplicationInsightsTelemetry.

First,youwillberequiredtologintoyourMicrosoftAzureAccount.

Afterdoingso,youwillbepresentedwithaformtocreateanApplicationInsightsresource(bychoosingtheNewresourceoptionintheSendtelemetrytodropdown)orconnecttoanexistingApplicationInsightsresource(byselectingitintheSendtelemetrytodropdown).

Afterselectingtheconfigurationoptions,clicktheAddbuttontoproceed.

ApplicationInsightsassemblieswillbeaddedtotheproject.

Ifyougetanerror,mostlikelyyouhavecomponentsthatneedtobeupdated.

IntheSolutionExplorerinVisualStudio,right-clickontheProject(nottheSolution),andselectManageNuGetPackages.

SelectUpdates,selectthecomponentsthattheerrormessageindicatesneedtobeupdated,andclicktheUpdatebutton.

WhentheReviewChangesboxshows,clicktheOKbutton.

Next,right-clickontheProjectandselectAddApplicationInsightsTelemetryagaintore-starttheprocess.

TheApplicationInsightscomponentsshouldnowinstallsuccessfully.

DebugTheApplication

Beforeyoutrytodebug,clearanyMicrosoftAppIdandMicrosoftAppPasswordsettingstheremaybeintheWeb.configfileandthensavethefile.

Thisisrequired,soyoucaneasilydebuglocally.

Remembertoreplaceanysettingsifyouneedtore-publishtheapplication.

HitF5toruntheproject.

Theapplicationwillopeninthewebbrowser.

Notethewebaddress,asyouwillneeditinthenextstep.

UsingTheBotEmulator

OpenandruntheMicrosoftBotFrameworkEmulator.

Whentheemulatorstarts,connecttotheBotbysettingtheaddresstotheoneindictedinthewebbrowser;however,add/api/messagestotheend.

IntheBotEmulator,enterHellointhetextboxandclickthesendkey(orpressenter).

YouwillseetheresponseintheChatwindowandtheJSONcontentsoftheresponseintheJSONwindow.

Youshouldseeawindowpopupthatprovideslinkstothetelemetrydata.

YoucanalsoaccessthedatabyclickingonthelinksintheApplicationInsight.configsectionintheSolutionExplorerofVisualStudiowhiletheapplicationisrunning.

Also,youcanright-clickontheProjectandselectApplicationInsightstoshowthemenuthatwillprovidealltheoptions.

SelectingSearchLiveTelemetryorSearchDebugSessionTelemetrywillopenawindowinVisualStudiothatwilldisplaytelemetrydata.

Note:SeeLearnmoreaboutApplicationInsightstoolsinVisualStudioathttps://azure.microsoft.com/en-us/documentation/articles/app-insights-visual-studio/formoreinformationonusingthesewindows.

ForfullTelemetryReadiness,ensureallthegreendotsarechecked.Ifanyaren’t,clickonthem.

Itwillstopdebuggingtoaddcomponents.

Youwillbeabletoclickabuttontoaddorconfigurethecomponents.

Thecomponentswillbeadded.

Theresultwillbedisplayed.

CustomTelemetry

OneofthemostpowerfulfeaturesofApplicationInsightsisbeingabletouseittotrackyourowncustomtelemetry.

Wewillnowdemonstrateusingittotrackwhenagameisstarted,completed,whatnumberauserneededtoguess,andhowmanyattemptstheyrequired.

IntheAiNumberGuesserBotproject,opentheNumberGuesserDialog.csfileandaddthefollowingusingstatements:

Next,addthefollowinglinetotheclass:

Finally,addthefollowinglinestotheStartAsyncmethod:

Thiswilltrackagamebeingstartedandthenumbertheuserneedstoguess.

Also,addthefollowingcodetotrackthegamecompleted:

ThereareanumberofAPIcallswecanusetotrackcustomeventsasthefollowingtableillustrates:

ApplicationInsightsAPIsummary

From:https://azure.microsoft.com/en-us/documentation/articles/app-insights-api-custom-events-metrics/

Method Usedfor

TrackPageView Pages,screens,blades,orforms

TrackEvent Useractionsandotherevents.Usedtotrackuserbehaviorortomonitorperformance.

TrackMetric Performancemeasurementssuchasqueuelengthsnotrelatedtospecificevents

TrackException Logexceptionsfordiagnosis.Tracewheretheyoccurinrelationtoothereventsandexaminestacktraces.

TrackRequest Logthefrequencyanddurationofserverrequestsforperformanceanalysis.

TrackTrace Diagnosticlogmessages.Youcanalsocapture3rd-partylogs.

TrackDependency Logthedurationandfrequencyofcallstoexternalcomponentsonwhichyourappdepends.

Youcanattachpropertiesandmetricstomostofthesetelemetrycalls.

Runtheapplicationandentersomesampledata.

WhenyouselecttheApplicationInsightsmenuinVisualStudioandselectExploreTelemetryTrends…

…youcanthenselectInspectyourcustomevents.

ClicktheAnalyzeTelemetrybuttontoprocessthelatestdata.YouwillseewherethePropertiesandMetricshavebeentracked.

Note:Itwilltakeafewminutesforyourcustomeventstoshow.

Youcandouble-clickonatrendtodrillintothedata.

Thiswilltakeyoutothesearchscreenwhereyoucanfilterfurtherandviewthedetailsofeachindividualevent.

ApplicationInsightsPortal

YoucanaccesstheApplicationInsightsPortalontheMicrosoftAzuresitebyselectingitfromthemenuinVisualStudio.

ItisthereyoucanseeandchangeyourPricingtier.

YoucanalsoobtainyourInstrumentationKey.

MonitoringAPublishedApplication

YoucanmonitoryourpublishedBot.

PublishyourBot.(SeeChapter2fordirectionsonthis.)AfteryourBotispublishedonthehttps://dev.botframework.com/site,selectMybots.

EdittheBotconfiguration.

EntertheInstrumentationKey(fromtheMicrosoftAzuresite)andclickSavechanges.

Thiswillenableadditionalpropertiesandmetricstotrack.

ReturntotheApplicationInsightsresourceontheMicrosoftAzuresite.

Youcannowmonitoryourpublishedapplicationandcreatecustomchartsusingdefaulttrackingdataandyourcustompropertiesandmetrics.

Chapter10:CreatingaSkypeBot

Thesamplecodeforthischaptercanbeobtainedatthelink“CreatingaSkypeBotUsingTheMicrosoftBotFramework”athttp://AiHelpWebsite.com/Downloads

YoucaneasilycreateaSkypeBotanddeployittoSkype.

Todemonstratethis,wewillstartwiththeBotcreatedinChapterSix.

Note:IfyouhavenotpreviouslydeployedyourBot,skipdowntothesectionlabeled

“RegisterSkype”.

PublishingTheBot

ThefirststepistoconnecttheAiNumberGuesserBottotheMicrosoftBotFrameworkDeveloperPortal.

Todothis,weneedtopublishitinapublicallyaccessiblelocation.Thiscanbeanyserver;however,publishingtoAzureisrecommendedbecausepublishingtoithasbuilt-insupportinVisualStudio.

First,gotohttps://azure.microsoft.comandcreateanaccountandasubscription(ifyoudon’talreadyhaveone).

Next,opentheAiNumberGuesserBotprojectinVisualStudioandright-clickontheProjectnode(nottheSolutionnode),andselectPublish.

SelectMicrosoftAzureAppService.

SignintoyourAzureaccountandthenclicktheNewbutton.

EnsurethetypeisWebApp.

EnterauniqueWebAppname,selectyoursubscription,selectorcreateaserviceplanandresourcegroupandclicktheCreatebutton.

Afterthewebapphasbeencreated,clickthePublishbutton.

Thewebappwillopeninthewebbrowser.

Notethewebaddressasyouwillneeditinalaterstep.

RegisteringTheBotWithTheBotConnector

GototheMicrosoftBotFrameworkportalathttp://dev.botframework.comandsigninwithyourMicrosoftAccount.

SelectRegisterabot.

Fillinallofthefields.

Note:Theendpointwebaddressiswhatyousawwhenthewebbrowseropenedinthepreviousstep.

However,youhavetoadd/api/messagestotheendoftheaddressandusehttps://ratherthanhttp://.

Atonepointintheform,youwillseealinkyouwillclicktogoto

https://apps.dev.microsoft.com

ItistherethatyouwillgetanApplicationIDandapassword.

Makeanoteofthembecauseyouwillneedtousethemtoupdatetheweb.configfileintheVisualStudioprojectlater.

ClicktheRegisterbutton.

TheBotregistrationwillbecreated.

Whenyoureturntothehttp://dev.botframework.compage,youwillseetheMicrosoftAppIDfromthehttps://apps.dev.microsoft.comsitehasbeenenteredintoyourBot’sconfiguration.

CopytheBotID(Bothandle)andMicrosoftAppIdandMicrosoftAppPasswordfromhttp://dev.botframework.comandhttps://apps.dev.microsoft.comtotheweb.configoftheBotinVisualStudio.

Note:IfyouforgottonotetheMicrosoftAppPasswordintheearlierstep,youcanclicktheGenerateNewPasswordbuttonathttps://apps.dev.microsoft.comtocreateanotherone.

InVisualStudio,PublishtheBotagain.

YouaredoingthisbecausetheBotConnectorwillpasstheBotIDandMicrosoftAppIdandMicrosoftAppPasswordwhenitcommunicateswithit.

ReturntotheBotconfigurationpageathttp://dev.botframework.com.

YoucannowclicktheTestbuttononthatpagetotesttheconnectiontoyourBot.

YoucannowconfigurechannelstoyourBot.

Whenyouhaveconfiguredchannels,ifyoudesire,youcanclickthePublishbuttontosubmityourbottotheBotDirectory.

EvenifyoudonotpublishittotheBotDirectory,youcanstillcallitfromyourown

applicationsandthroughanychannelsyouconfigure.

ConfigureSkype

ToaddtheBottoSkype,clicktheAddtoSkypebuttonontheBotconfigurationpageathttp://dev.botframework.com.

YouwillbedirectedtoaSkypeconfigurationpagefortheBot.

ClickthebuttontoAddtoContacts.

ClickAllowinthepopupbox.

Skypewillopen,andyoucanselecttheBotfromyourcontactsandconversewithit.

Chapter11:CreatingAFacebookMessengerBot

Thesamplecodeforthischaptercanbeobtainedatthelink“CreatingAFacebookBotUsingMicrosoftBotFramework”athttp://AiHelpWebsite.com/Downloads

YoucaneasilycreateaBotanddeployitonFacebook.

Todemonstratethis,wewillstartwiththeBotcreatedinChapterTwo.

Set-UpFacebook

ThefirststepistologintoyourFacebook.comaccount(orcreateone).

SelectCreatePage.

Selectatemplate,fillintherequiredinformation,andclickGetStarted.

TogettheFacebookPageID,whichyouwillneedlater,clickontheAbouttab.

LocatetheFacebookPageID.

CreateAFacebookDeveloperAccount

Gotohttps://developers.facebook.com/docs/apps/registerandclickthebuttontocreateaFacebookDeveloperAccount.

ClicktheslidertoYestoacceptthepoliciesandclickRegister.

CreateAFacebookApp

Next,gotohttps://developers.facebook.com/andloginagainifneeded.

SelectAddaNewApp.

Selectbasicsetup.

FillintheinformationandclickCreateAppID.

MakeanoteoftheAppIDasyouwillneeditinalaterstep.

ClicktheShowbuttontodisplaytheAppSecret.Makeanoteofitasyouwillneeditinalaterstep.

NowthattheAppiscreated,youneedtoconfigureittouseFacebookMessenger.

ClickAddProduct.

SelectMessenger.

SelectGetStarted.

FacebookMessengerhasbeenadded.

YounowneedtoconfigureittotalktotheMicrosoftBotConnector.

ConfigureTheCallbackURLandVerifyToken

Gotohttps://dev.botframework.com/andSignin.

SelectMybots.

Selectapublishedbot.(SeeChapterTwofordirectionsonhowtodothis.)

ClicktheAddbuttonnexttotheFacebookMessengerchannel.

ClicktheexpandernexttoSetwebhookcallbackurlandverifytoken.

UsetheSelectbuttonstoindividuallyselectandcopytheCallbackUrlandVerifyToken.

Returntohttps://developers.facebook.com,selectyourapplication,andinthesettingsforMessenger,clicktheSetupWebhooksbutton.

EntertheCallbackURLandVerifyTokenyoucopied,checktheSubscriptionFieldsindicatedintheimageabove,andclicktheVerifyandSavebutton.

AftertheWebhookshavebeenset,clickthedropdownnexttoSelectaPage.

SelecttheFacebookpageyoucreatedearlier.

Next,clicktheSubscribebutton.

GetPageToken

IntheTokenGenerationsection,selectthepagethatyoupreviouslycreated.

APageAccessTokenwillbecreated.

CopythePageAccessToken.

ConfigureTheMicrosoftBotConnector

Returntohttps://dev.botframework.com/andselectyourBotagain.ThenclicktheEditbuttonnexttotheFacebookMessengerchannel.

ClicktheexpandernexttoEnteryourcredentials.

EntertheinformationyougatheredintheearlierstepsandclicktheResubmitbutton.

ChecktheboxnexttoEnablethisbotonFacebookMessenger.

ClickI’mdoneconfiguringFacebookMessengerbutton.

TalkingToYourBot

YoucannowtalktoyourBotbynavigatingto

https://www.messenger.com/t/{YourPageID}/

ThiswilltakeyoutoFacebookMessenger,andafterlogginginwithyourFacebookID,itwillallowyoutoconversewithyourBot.

UntilyourAppisapprovedandmadepublic,onlyyoucanchatwithyourBot.

Tocreateaccountstotestit,gotohttps://developers.facebook.com/s

SelecttheAppandthenselectRolesandthenTestUsers.

Fillintheformthatdisplaystocreatetestusers.

ToallowrealFacebookuserstotestit,selectRolesandthenAddTesters.

Fillintheformthatdisplaystoallowaccessfortheusers.

TomaketheBotpublic,selectAppReview.ThenclicktheslidertochangeitfromNotoYes.

Torequesttheneededpermissions,selectSettingsunderMessengerthenclicktheRequestPermissionsbutton.

Selectpages_messagingandthenclicktheAdd1Itembutton.

SeethispageformoreinformationontheAppreviewprocess

https://developers.facebook.com/docs/messenger-platform/app-review

AboutTheAuthor

MichaelWashingtonisanASP.NET,C#,andVisualBasicprogrammer.Hehasextensiveknowledgeinprocessimprovement,billingsystems,andstudentinformationsystems.HeisaMicrosoftMVP.Hehasason,Zachary,andresidesinLosAngeleswithhiswife,Valerie.

Hehaswrittenseveraltutorialsthatarepostedathttp://AiHelpWebsite.com/Blog.

Heistheauthorofsixpreviousbooks:

CreatingHTML5WebsitesandCloudBusinessAppsUsingLightSwitchInVisualStudio2013-2015(LightSwitchHelpWebsite.com)CreatingWebPagesUsingtheLightSwitchHTMLClientInVisualStudio2012(LightSwitchHelpWebsite.com)ODataAndVisualStudioLightSwitch(LightSwitchHelpWebsite.com)CreatingVisualStudioLightSwitchCustomControls(BeginnertoIntermediate)(LightSwitchHelpWebsite.com)BuildingWebsiteswithVB.NETandDotNetNuke4(PacktPublishing)BuildingWebsiteswithDotNetNuke5(PacktPublishing)

Recommended