264

An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

  • Upload
    ali-dz

  • View
    179

  • Download
    2

Embed Size (px)

Citation preview

Page 1: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 2: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 3: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

AnIntroductiontotheMicrosoftBotFramework

CreateFacebookandSkypeChatbotsusingMicrosoftVisualStudioandC#

(ThisbookcoverstheMicrosoftBotFrameworkPreviewEdition)

Copyright2016

PublishedBy

TheAiHelpWebsite

http://AiHelpWebsite.com

Page 4: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Copyright

Copyright©2016byMichaelWashington

Coverandinternaldesign©MichaelWashington

EditingbyAndreaDickinson(www.QualityBookServices.com)

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

Allbrandnamesandproductnamesusedinthisbookaretrademarks,registeredtrademarks,ortradenamesoftheirrespectiveholders.Wearenotassociatedwithanyproductorvendorinthisbook.

MicrosoftVisualStudioisaregisteredtrademarkofMicrosoftCorporation.

SkypeisaregisteredtrademarkofMicrosoftCorporation.

FacebookisaregisteredtrademarkofFacebookInc.

Page 5: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 6: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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

Page 7: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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

Page 8: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

MonitoringAPublishedApplication

Chapter10:CreatingaSkypeBot

PublishingTheBot

RegisteringTheBotWithTheBotConnector

ConfigureSkype

Chapter11:CreatingAFacebookMessengerBot

Set-UpFacebook

CreateAFacebookDeveloperAccount

CreateAFacebookApp

ConfigureTheCallbackURLandVerifyToken

GetPageToken

ConfigureTheMicrosoftBotConnector

TalkingToYourBot

AboutTheAuthor

Page 9: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Dedication

Page 10: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

MichaelWashington

Asalways,forValerieandZachary

Page 11: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 12: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ThankYouMicrosoft

DanDriscoll

JimLewallen

SimonMichael

AnnaRoth

RebeccaDuffy

DanielEgan

Page 13: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Community

EzequielJadib

JoeMayo

RobinOsborne

GaryPretty

MaheshChand

JohnathanLightfoot

Page 14: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Preface

Page 15: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Requirements

YoumusthaveacomputerrunningMicrosoftWindowswithMicrosoftVisualStudio2015(orhigher)withUpdate3(orhigher)tocreatetheapplicationsdescribedinthisbook.

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

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

Page 16: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 17: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 18: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Chapter1:UnderstandingtheMicrosoftBotFramework

ThisbookcoversusingVisualStudio2015tocreateChatbotsusingtheMicrosoftBotFramework.Thepurposeofthisbookistodemonstrate,provideexamplesof,andtoexplainimportantconceptsofthetechnology.

Page 19: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

WhatIstheMicrosoftBotFramework?

TheMicrosoftBotFrameworkallowsyoutoeasilycreateBots.

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

Page 20: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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.

Page 21: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 22: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 23: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Chapter2:CreateaHelloWorld!Bot

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

ThepurposeofthischapteristodemonstratehowtogetstartedusingtheMicrosoftBotFramework,howtocreateasimpleBot,andhowtopublishittotheMicrosoftBotFrameworkDeveloperPortal.

Page 24: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

CreatingAHelloWorld!Bot

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

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

ProjectTemplates\VisualC#

ThiscreatesatemplatethatyoucanuseinVisualStudiotocreateBotprojects.

OpenVisualStudio.

CreateanewProject.

Page 25: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

SelecttheBotApplicationtemplateandnametheprojectHelloWorldBot.

OpentheMessagesController.csfileintheControllersfolder.

ChangethePostmethodtothefollowing:

Page 26: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

HitF5toruntheproject.

Notethewebaddress.Youwillneeditinthenextstep.

Page 27: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

UsingTheBotEmulator

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

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

IntheBotEmulator,enterHellointhetextboxandclickthesendkey(orpressenter).

YouwillseetheresponseintheChatwindowandtheJSONcontentsoftheresponseintheJSONwindow.

Page 28: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

SavingUserData

Animportantpartofanyconversationisrememberingwhatauserhaspreviouslysaid.

WecandothisusingGetPrivateConversationDataandSetPrivateConversationData.

Todemonstratehowthisishandled,addthefollowingtothetopoftheMessagesController.csfileintheControllersfolder:

Page 29: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Next,changethePostmethodintheMessagesController.csfiletothefollowing:

Page 30: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Finally,alterthefollowingsectionintheHandleSystemMessagemethod(intheMessagesController.csfile)tothefollowing:

NowwhenwechatwiththeBot,itcanrememberourname.

Page 31: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

IfwetellittoDeleteUserData…

Itwillrespectourwishes.

Page 32: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

PublishingTheBot

ToconnectyourBotthroughchannelssuchasSkypeandFacebookMessenger,youneedtoconfigureitontheMicrosoftBotFrameworkDeveloperPortal.Todothat,youwillfirstneedtopublishitinapubliclyaccessiblelocation.

Thiscanbeanyserver;however,publishingtoAzureisrecommendedbecausepublishingtoithasbuilt-insupportinVisualStudio.

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

Next,Right-clickontheProjectnode(nottheSolutionnode)inVisualStudioandselectPublish.

Page 33: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

SelectMicrosoftAzureWebApps.

SignintoyourAzureaccount.

Selectasubscription.

ThenclicktheNewbutton.

Page 34: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

EnterauniqueWebAppname.

Selectyoursubscription.

Selectorcreateaserviceplan,resourcegroupandregion.

ThenclicktheCreatebutton.

Afterthewebapphasbeencreated,clickthePublishbutton.

Page 35: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Thewebappwillopeninthewebbrowser.

Notethewebaddress.Youwillneeditinalaterstep.

Page 36: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

RegisteringTheBotWithTheMicrosoftBotFrameworkDeveloperPortal

GototheMicrosoftBotFrameworkDeveloperPortalathttps://www.botframework.comandsigninwithyourMicrosoftAccount.

SelectRegisterabot.

Page 37: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Fillinallofthefields.

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

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

ItistherethatyouwillgetanApplicationIDandapassword.

MakeanoteofthembecauseyouwillneedtousethemtoupdatetheVisualStudioprojectinlaterstep.

ClicktheRegisterbutton.

Page 38: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

TheBotregistrationwillbecreated.

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

Note:IfyouforgottonotetheMicrosoftAppPasswordintheearlierstep,youcanclicktheGenerateNewPasswordbuttontocreateanotherone.

Page 39: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

PublishtheBotagain.

YouaredoingthisbecausetheBotFrameworkwillpasstheBotID,MicrosoftAppId,andMicrosoftAppPasswordwhenitcommunicateswithit.

YoucannowtestyourBotusingtheBotFrameworkDeveloperPortalwebpage.

Page 40: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Ifyoudesire,youcanclickthePublishbuttontosubmityourBottotheBotDirectory.

YoucanalsoconfigurechannelsforyourBot.

EvenifyoudonotpublishyourBottotheBotDirectory,youcanstillcallitfromyourownapplicationsandthroughanychannelsyouconfigure.

Note:Chapters10and11coverhowtousetheBotFrameworkDeveloperPortaltoconfiguretheSkypeandFacebookMessengerchannelstodeployyourBotonthosenetworks.

Page 41: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 42: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 43: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Chapter3:UsingFormFlow

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

UsingFormFlowwiththeMicrosoftBotFrameworkallowsyoutoquicklycreateaguidedconversationtogatherinformationfromauserwiththeleastamountofcode.WhileitislessflexiblethanusingDialogs(Dialogsarecoveredinthenextchapter),itcanbecombinedwithDialogstoincreaseitsfunctionality.

Page 44: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

AWalkThrough

WhenauserbeginsaconversationwiththeBot,itintroducesitselfandaskstheuser’sname.

TheBotproceedstoaskquestionsandgathertheresponses.

Page 45: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

AfeatureofFormFlowisthattheusercantypehelpatanytimetoobtainassistancewithanyquestionortheFormFlowitself.

Asadeveloper,yougetthisfunctionalitywithouttheneedtowriteanyadditionalcode.

TheFormFlowcontinuesuntiltheformiscomplete.

Page 46: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

CreatingTheProject

OpenVisualStudio.

CreateanewProject.

SelecttheBotApplicationtemplateandnametheprojectHelloFormFlowBot.

Theprojectwillbecreated.

Page 47: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Right-clickontheproject.SelectAddandthenNewItem.

WewillnowcreatetheclassthatwillcontainthelogicforourFormFlow.

AddanewC#classcalledProfileForm.cs.

Page 48: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Replaceallthecodewiththefollowingcode:

ThiscodeindicatesthefieldswewillgatherwithourFormFlow.

Noticethattheclass,aswellastheGenderenumthatitconsumes,ismarked[Serializable].

TheMicrosoftBotFrameworkrequiresthattheclassesmustbeserializable,sotheBotcanbestateless.

Savethefile.

Page 49: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

OpentheMessagesController.csfile.

Addthefollowingusingstatementsatthetopofthefile(tosupporttheFormFlowcode):

Page 50: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

AddthefollowingMakeRootDialogmethodtotheMessagesControllerclasstocalltheBuildFormmethodintheProfileFormclasswecreatedearlier:

Finally,alterthePostmethodintheMessagesControllerclasstothefollowing:

Savethefile.

Page 51: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

TestTheApplication

HitF5toruntheapplication.

Thewebbrowserwillopen.

Notetheportnumberandthewebaddress.

OpenandruntheMicrosoftBotFrameworkEmulator.

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

Page 52: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

EnsurethattheBotURLisconnectingtothecorrectaddress.

Typeamessageandclickthesendkey(orpressEnter).

YoucannowconversewiththeBotandfillouttheFormFlow.

Page 53: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

SavingTheData

Currentlytheapplicationdoesnotsavetheresponsesfromtheuser.Infact,afteryoufilltheFormFlowout,itwillsimplyaskyoutofillitoutagain.

WecanusetheBotStateServicetosaveandretrievethevalues.

Page 54: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

AltertheBuildFormmethodintheProfileForm.csfiletothefollowingtosavethevaluesenteredintotheform:

Wearenotonlystoringthevaluesprovidedbytheuser,butwearealsosettingaflag(ProfileComplete),sowedon’tasktheusertofillouttheformagain.

Page 55: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Finally,alterthePostmethodintheMessagesControllerclasstothefollowing:

Page 56: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

NowtheapplicationwillonlyasktheusertofillintheformonetimeanddisplaythevaluesreceivedusingtheBotStateService.

ThevalueswillbepersistedbytheMicrosoftBotFrameworkkeyedtothatuserinthatconversation.

Page 57: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Inourexample,weusedPrivateConversationData,buttheBotStateServiceexposesthefollowingmethods,eachwithadifferentscope:

Method Scoped Description

SetUserData() User Rememberingcontextobjectwithauser

SetConversationData() Conversation Rememberingcontextobjectwithaconversation

SetPrivateConversationData() User&Conversation

Rememberingcontextobjectwithapersoninaconversation

Page 58: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 59: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 60: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Chapter4:UsingDialogs

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

UsingDialogswiththeMicrosoftBotFrameworkallowsyoutomodelaconversationwithauser.WhiletheyaremoreflexiblethanusingaFormFlow(coveredintheprecedingchapter),Dialogsrequiremorecode.

ADialogisaclassthatimplementstheIDialoginterface.Dialogscanbecomposedwithotherdialogstomaximizereuse.

ADialoghasacontextthatcontainsastackofdialogsactiveinaconversationandwillmaintainthestateoftheconversation.ADialogsendsmessagestoauserandissuspendedwhenitiswaitingforaresponsefromauser.

ADialogusesastatestoredinitscontexttoresumeaconversation.ThisstateisstoredinthestateserviceprovidedbytheMicrosoftBotFrameworkservice.

Page 61: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

WalkThrough

TheconversationstartswhentheUsertypesinamessage.

TheBotrespondswithagreetingandthedirectionsofthegame,whichistoguessanumberfrom1to10(chosenatrandom).

TheUserguessesanumber,andtheBotinformstheUseriftheyarecorrectornot.

Page 62: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

WhentheUserguessesthenumbercorrectly,theyareofferedachancetoplaythegameagain.

IftheUserchoosesnottoplaythegameagain,theBottellsthemgoodbye.

Page 63: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

CreatingTheApplication

OpenVisualStudio.

CreateanewProject.

SelecttheBotApplicationtemplateandnametheprojectAiNumberGuesserBot.

Page 64: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Theprojectwillbecreated.

Right-clickontheproject.SelectAddandthenNewItem.

WewillnowcreatetheclassthatwillcontainthelogicfortheDialog.

Page 65: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

AddanewC#classcalledNumberGuesserDialog.cs.

Page 66: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Replaceallthecodewiththefollowingcode:

ADialogisaclassthatinheritsfromIDialog.

Notethatwemustdecoratethisclassas[Serializable].

ThisrequiresyoutoimplementaStartAsyncmethod.

Toimplementthis,hoverthemouseoverIDialog<object>,waitafewseconds,andtheinterfaceoptionwindowwillappear.

Page 67: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ClicktheblackarrownexttothelightbulbandselectImplementinterface.

TheStartAsyncmethodwillbecreated.

ThiswillbecalledwhentheDialogisfirstinstantiated.

Wewantthecodetorunasynchronously,soaddasynctothemethodsignature.

Page 68: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Now,changethecodeinsidethemethod,sothecompletemethodiscodedasfollows:

Thelastlineinthemethodiscontext.Wait.ThissuspendsthecurrentDialoguntiltheuserhassentamessagetotheBot.

TheWaitmethodtakesamethodasaparameter(inthiscaseMessageReceivedAsync)tobecalledtoresumetheconversationwhentheresponsehasbeenreceived.

Toimplementit,hoverthemouseoverMessageReceivedAsync,waitafewseconds,andtheinterfaceoptionwindowwillappear.

ClicktheblackarrownexttothelightbulbandselectGeneratemethod‘NumberGuesserDialog.MessageReceivedAsync.

TheMessageReceivedAsyncmethodwillbecreated.

NoticeittakesthecontextoftheDialogandanargument(result).

Page 69: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ChangethetypeoftheargumentfromobjecttoIMessageActivityandchangethenameofthevariablefromresulttoargument.

Again,wewantthecodetorunasynchronously,soaddasynctothemethodsignatureandmarkitasvirtual.

Alterthecodeinthemethod,sothecompletemethodiscodedasfollows:

Noticethelastline(context.Wait(MessageReceivedAsync))simplycallsthemethodthecodeiscontainedinagainandagain.

Weareonlydoingthistomakethisexampleassimpleaspossible.WewillexploreamorerealisticexampleinthenextsectionwhenweaddaPromptDialog.

Page 70: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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

MessagesController.cs

Replacethedefaultcodeinthecodeblockthatbegins:

Withthecode:

ThistellstheBottodirectanymessagestotheNumberGuesserDialogclass.

Page 71: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Finally,addthefollowingusingstatementtothetopofthecodefile:

Page 72: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

TestTheApplication

HitF5toruntheapplication.

Thewebbrowserwillopen.Notetheportnumberandthewebaddress.

OpenandruntheMicrosoftBotFrameworkEmulator.

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

EnsurethattheBotURLisconnectingtothecorrectaddress.

Page 73: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Typeamessageandclickthesendkey(orpressEnter).

TheBotwillrespond.

ThisisalltheBotwilldoatthispoint;however,thisexampleshowstheminimalcodetocreateandconsumeaDialogclass.

Page 74: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

DialogPrompts

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

ThisistheprimarymeansofcontrollingprogramflowwithinaDialogclass.

APromptDialogcanbeoneofthefollowingtypes:

PromptforanattachmentPromptforoneofasetofchoicesAskayes/noquestionPromptforalongPromptforadoublePromptforastring

WewillenhanceourapplicationtoimplementaPromptDialogthatasksayes/noquestion.

Page 75: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

First,addthefollowingcodetotheMessageReceivedAsyncmethod:

Thiscodewillsimplykeeploopingandcountingtheguessingattemptsiftheuserdoesnotguesstherandomnumber.

Iftheuserdoesguessthenumber,thecodeintheelseblockwillbecalled.

Rightnow,thecodeisnotcomplete.WeneedtoaddaPromptDialogundertheline//PutPromptDialoghere.

Page 76: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

TypePromptDialogandpresstheperiod(.)key.TheautocompleteoptionswillshowandwewillseetheoptiontoimplementthevarioustypesofPromptDialogs.

ChoosetheConfirmoption.

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

Thefollowingshowsthecompletecodeforourimplementation:

Page 77: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Wenowneedtoimplementtheresumehandlermethodtohandletheresponse(PlayAgainAsync).

Toimplementit,hoverthemouseoverPlayAgainAsync,waitafewseconds,andtheinterfaceoptionwindowwillappear.

ClicktheblackarrownexttothelightbulbandselectGeneratemethod‘NumberGuesserDialog.PlayAgainAsync’.

Themethodwillbecreated.

Addasynctothemethodsignature.

Alterthemethod,sothecompletecodeisasfollows:

Page 78: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

HitF5toruntheprogramandconnecttoit,usingtheBotFrameworkEmulator…

Whenweguessthecorrectnumber,thePromptDialogwillappear.Whenweprovideananswer,thePlayAgainAsyncmethodwillimmediatelyruntoprocessouranswer.

WecanspawnanotherPromptDialoginsidethePlayAgainAsyncmethodifwechoose,effectivelycreatinganendlesschainofPromptDialogstocreatebranchesofcodeforaconversation.

Page 79: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 80: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 81: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 82: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Chapter5:UsingImages,Cards,Carousels,andButtons

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

Note:TheimageaboveshowstheBotinSkype.DeployingaBottoSkypeiscoveredinChapterTen.

ImplementingimagesinyourMicrosoftBotFrameworkapplicationaddsavisualelementtotheinteractionwithyourusers.

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

Page 83: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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

Page 84: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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

Page 85: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

TodemonstrateimplementingaHeroCard,wewillstartwiththecodefromthepreviouschapter.

Note:First,youwillhavetouseManageNuGetPackagesinVisualStudiotoupdateMicrosoft.Bot.Buildertothelateststableversionbeforeyoucontinue.

Also,wewillmakesomesmallchanges,suchasmakingthenumbertoguessfrom1to5ratherthan1to10,soitshowsupwellinSkypebecauseSkypewillonlydisplay5buttonsonasinglecard.

OpentheprojectinVisualStudio.

AddanewfolderandcallitImages.

Page 86: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

AddtheNumberGuesserOpeningCard.pngfile(youcangetthecodeontheDownloadspageoftheAiHelpWebsite.com)totheImagesfolder.

OpentheMessagesController.csfile(intheControllersdirectory),andaddthefollowingusingstatementtothetopofthefile:

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

ThismethodfireswhentheBotisaddedtotheContactlistofauser.

Replaceallthecodeinthesectionwiththefollowingcode:

Page 87: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

SavethefileandhitF5toruntheapplication.

Page 88: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

OpenandruntheBotusingtheMicrosoftBotFrameworkEmulator.

IntheEmulator,invoketheContactRelationUpdate-addevent.

TheHeroCardwilldisplay.

ClickingonthecardwilltakeyoutotheAiHelpWebsite.comwebsite.

Page 89: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Carousel

Acarouseldisplaysmultiplecards(eitherHeroCardsorThumbnailCards)horizontally.

AList(thedefaultlayoutformultiplecards)displaysthecardsvertically.

TheimageaboveshowswhatacarouseloftwoHeroCardslookslikeintheSkypeclient.

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

Page 90: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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

Savethefile,runtheapplication,andconnecttoitintheEmulator.

IntheEmulator,invoketheContactRelationUpdate-addevent.

Page 91: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Thefirstcardwillshow,butyouwillnowseeaslider.

Slideittotheright.

YouwillthenseethesecondHeroCard.

InSkype,theSubtitlepropertywilldisplayasahyperlinkandbeclickable.

Page 92: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

RichCardAttachmentsInDialogs

ThereareadditionalchallengeswhenimplementingrichcardattachmentsinDialogs.

Primarily,thebiggestchallengeisthat,insidetheDialogclass,youdonothaveaccesstothebaseURLoftheapplicationtodeterminewhereyourimagesare.

WecanaddressthisbyusingtheBotStateService.

OpentheMessagesController.csfile:

AddthefollowingcodetothetopofthePostmethod:

ThiswillstoretheCurrentBaseURLandtheRecipientusingtheBotStateService,sothevaluescanlaterberetrievedintheDialogclass.

Page 93: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

OpentheNumberGuesserDialog.csfile.

Addthefollowingcodeabovethenamespace:

Addthistothetopoftheclass:

ThiswillprovideaglobalvariablethatwillbeautomaticallyserializedandpersistedbetweencallstostoretheBaseURL.

AddthefollowingcodetothetopoftheMessageReceivedAsyncmethod:

ThiswillretrievethevalueofCurrentBaseURLthatwasstoredinBotStateServiceintheMessagesControllerclassandstoreitinthestrBaseURLglobalvariable.

AddthefollowingUtilitymethodtotheclass.Thismethodwillcreate5CardActionbuttonsthatwillbeattachedtotheHeroCard(thatwewillcreateinalaterstep):

Page 94: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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

Page 95: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

CreateTheHeroCardInTheDialogClass

WewillnowdisplayaHeroCardwith5buttonsintheDialogclass.

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

Page 96: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Next,findthefollowingcodeintheMessageReceivedAsyncmethod:

Page 97: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Replaceitwiththefollowingcode:

Savethefile,hitF5toruntheproject,andconnecttoitintheEmulator.

Page 98: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

TheBotwillnowdisplayanimageandbuttons.

Wecaneitherclickoneofthebuttonsorenteranumbertoplaythegame.

Page 99: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ThefollowingimageshowswhatitlookslikeinSkype:

Page 100: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

CreatingARe-UsableHeroCard

IfthereareafewmoreplacesweneedtodisplaytheHeroCardwiththebuttons,

wewillwanttocreateare-usableHeroCard.

ThisHeroCardwillnothaveanimage,onlybuttons.

Page 101: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

First,addthefollowingutilitymethodtotheDialogclass:

NotethatitcallstheCreateButtonsutilitymethodthatwecreatedearlier.

Page 102: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Now,locatethefollowingcode:

Replaceitwith:

ThecodewillnowcalltheShowButtonsmethodthatwillreturntheHeroCard.

Finally,findthefollowingcode:

Replaceitwith:

Page 103: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

TheBotwillnowdisplaytheHeroCard,withonlythebuttons,ineachsituationwherewecalledtheutilitymethod.

Page 104: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 105: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 106: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Chapter6:ImplementingASQLServerDatabaseWithYourBot

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

MicrosoftBotFrameworkChatbotapplicationsthatrequireinformationtobestored,queried,andsharedwithmultipleuserswillrequireacentralstoragerepository.

UsingMicrosoftSQLServerandMicrosoftAzurewillallowyoutoeasilyimplementthisfeature.

Page 107: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

TodemonstrateimplementingadatabasewithaMicrosoftBotFrameworkapplication,wewillstartwiththecodefromthepreviouschapter.

Page 108: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

CreateTheSQLServerDatabase

WewillstartbycreatingadatabaseandloggingthemessagessenttoandfromtheBot.

OpentheprojectinVisualStudio.

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

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

Page 109: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Right-clickontheApp_Datafolder.SelectAddandthenNewItem.

Page 110: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

AddaSQLServerDatabase.

NameitBotData.mdf.

Wewillnowcreateatableinthedatabasetoholdourdata.

Right-clickonthedatabaseandselectOpen.

Page 111: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Expandthedatabaseelementsinthetree.

Right-clickonTablesandselectAddNewTable.

PastethefollowingscriptinandclicktheUpdatebutton:

Page 112: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ClickUpdateDatabase.

Thetablewillbecreated.

Page 113: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Right-clickontheTablesnodeandselectRefresh.

Thetablewillshow.

Page 114: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

CreateAnADO.NETEntityDataModel

WewillnowcreateanEntityDataModeltoallowprogrammaticaccesstothedatabase.

SwitchtoSolutionExplorerview.

Page 115: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

CreateafoldercalledModels.

Right-clickontheModelsfolder.SelectAddandthenNewItem.

AddanADO.NETEntityDataModelandcallitBotData.

WhentheEntityDataModelWizardopens,selectEFDesignerfromdatabase.

ClickNext.

Page 116: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

SelectBotData.mdfinthedatabasedropdown(ifitisnotalreadyselected).

ChecktheboxnexttoSaveconnectionsettingsinWeb.Config.

ClickNext.

Page 117: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

SelectEntityFramework6.x.

ClickNext.

Page 118: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ExpandthetreetorevealtheUserLogtableandclickthecheckboxnexttoit.

Accepttheotherdefaultvalues.

ClickFinish.

TheBotData.edmxanEntityDataModelwillbecreated.

YoucanclosetheBotData.edmxfornow.

Page 119: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

LogToTheDatabase

Wewillnowcreatecodethatwilllog(mostof)themessagestoandfromtheBottothedatabase.

Page 120: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

First,createafilecalledUtility.csandusethefollowingcode:

Thiscreatesautilitymethodtoallowustotrimanytextwestoreinthedatabase.Thisensuresthatnomessageistoolongtobestoredinthedatabase.Thiswouldcauseanerror.

Page 121: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Next,findthefollowingcodeinMessagesController.cs:

Replaceitwith:

ThiscodelogsthemessagesbeingsentfromtheusertotheBot.

Page 122: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

LogMessagesInTheDialogClass

TheDialogclasscreatesaresponsetotheuser.

FindallcodeintheNumberGuessserDialog.csfile(therewillbemultipleplaces)thatsendatextresponsetotheuser,whichcontaintheselines:

Page 123: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Addthefollowingcodeabovetheexistinglinesofcode(again,therewillbemultipleplacesyouwilldothis):

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

FindthefollowingcodeintheDialogclass:

Page 124: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Addthefollowingcodeabovetheexistinglinesofcode:

Note:TheCongratulationsStringPromptissetbytheexistingcodetoindicatethattheuserhaswonthegame.

Page 125: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

TestTheDatabaseLoggingCode

HitF5toruntheapplication.

Thewebbrowserwillopen.

Notetheportnumberandthewebaddress.

OpenandruntheMicrosoftBotFrameworkEmulator.

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

Page 126: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

EnsurethattheBotURLisconnectingtothecorrectaddress.

EnterHelloandclickthesendbuttontostartaconversationwiththeBot.

PlaythegamewiththeBot.

ClosethewebbrowsertostoptheapplicationandreturntoVisualStudio.

Page 127: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ViewTheData

Wewillnowviewthedatathatwasloggedtothedatabase.

IntheSolutionExplorerinVisualStudio,right-clickonBotData.mdfandselectOpen.

ThiswillopentheServerExplorer.

Right-clickontheUserLogtableandselectShowTableData.

Page 128: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Theloggeddatawillbedisplayed.

Page 129: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

LoggingHighScores

WewillnowaddcodetologanddisplayHighScores.

Wehavetoalterthedatabasefirsttostorethenumberofturnsrequiredtowinandthenameofthewinner.

IntheServerExplorer,right-clickontheUserLogtableandselectOpenTableDefinition.

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

Page 130: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Addthefollowingfields:

CountOfTurnsToWin[int]WinnerUserName[nvarchar(150)]

ClicktheUpdatebutton.

WhenthePreviewDatabaseUpdatesboxshows,clickUpdateDatabase.

Page 131: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

TheDataToolsOperationswindowwillindicatewhentheupdateiscomplete.

Page 132: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

UpdateADO.NETEntityDataModel

WehavetoupdatetheADO.NETEntityDataModeltohaveprogrammaticaccesstothenewlyaddedfields.

IntheSolutionExplorer,clickonBotData.edmxtoopenitinthedesigner.

Inthedesigner,right-clickontheUserLogtableandselectUpdateModelfromDatabase.

Page 133: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

WhentheUpdateWizardshows,selecttheRefreshtabandthenselecttheUserLogtable.ClickFinish.

Page 134: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

AlterCodeToLogHighScores

WewillnowalterthecodeintheDialogclasstologthewinninguserandthenumberofturnstheyrequiredtowin.

IntheNumberGuesserDialog.csfile,locatethefollowingcode:

Addthefollowinglinesofcodebelowthecodeabove:

Page 135: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 136: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

DisplayTheHighScores

WewillnowaddcodetodisplaytheHighScoreswhenevertheusertypesHighScores.

Page 137: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

OpentheMessagesController.csfileandaddthefollowingmethodtotheclass:

WewillnowaddthecodethatwillcalltheShowHighScoresmethodwejustadded.

IntheMessagesController.csfile,locatethefollowingcode:

Replaceitwiththefollowingcode:

Page 138: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Finally,tolettheuserknowtheycantypeHighScorestoseethehighscores,findthefollowingcodeintheDialogclass:

Changeitto:

Page 139: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

TestTheCode

NowwhenwetypeHighScores,wecanseethehighscoresforthepastday.

TheimageaboveshowswhatthehighscoreslooklikewhentheBotispublishedandviewedthroughtheSkypeclient.

Page 140: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

PublishingAMicrosoftBotFrameworkApplicationThatUsesaDatabase

TopublishtheBot,wecanfollowthedirectionsinChapter2:CreateaHelloWorld!Bot.

However,unlikethischapter,thatchapterdoesnotcoverpublishingaBotthatusesadatabase.

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

Page 141: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

LogintotheAzurewebportalandselectSQLdatabases.

Addanewdatabase.

Page 142: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Fillintheformtocreateanewdatabase.

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

Afteryoucreatethedatabase,youcanviewtheADO.NET(SQLauthentication)connectionstringforthedatabaseintheOverviewsection.

Page 143: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Note:Theconnectionstringwillnothavetheusernameandpassword.YouwillusetheusernameandpasswordoftheAzureserverthatcontainsthedatabase.

Page 144: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

IntheSolutionExplorerinVisualStudio,right-clickontheprojectnodeandselectPublish.

InthePublishwizard,filloutthefieldstopublishyourBottoAzure.

Page 145: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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

Page 146: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ThiswillopentheSQLServerObjectExplorer.

Right-clickontheTablesnodeunderthedatabaseandselectAddNewTable.

UsethefollowingscripttocreatetherequiredtableandclicktheUpdatebutton:

Page 147: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

WhenthePreviewDatabaseUpdatesboxshows,clickUpdateDatabase.

Note:YoucanalsousetheCloudExplorerforVisualStudio2015extensiontomanageyourAzuredatabasesinsideVisualStudio.

Page 148: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 149: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 150: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Chapter7:ImplementingLanguageUnderstandingIntelligentService(LUIS)

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

UsingLanguageUnderstandingIntelligentService(LUIS)inyourMicrosoftBotFrameworkapplicationallowsyoutocreatechatbotsthatareeasierforyourend-userstointeractwith.

Forthisexample,wewillstartwiththecodecreatedinthepreviouschapter.

Page 151: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Thischaptercovershowtocreateanumberguessinggameandstoringanddisplayingthehighscores.Inthepreviouschapter,theuserisrequiredtotypeintheexactwordsHighScores,andtheycouldonlyseethehighscoresforthepastday.

Inthischapter,wewillalterthecodetoallowtheusertoseethehighscoresforthepastweek,thepastmonth,orthepastdaystheyspecify(upto30days).

Mostimportantly,wewillallowtheusertotypetheirrequestusingnormallanguageandthendetecttheintentoftheuserandtheimportantrelatedentities(suchasthenumberofdays).

WewilldothisbycreatinganapplicationusingtheLanguageUnderstandingIntelligentService(LUIS)andtheninterfacingthatapplicationwithourexistingBot.

Page 152: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

CreateTheLUISApplication

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

CreateaNewApplication.

Page 153: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

WewillcallitHighScores,andafterfillingouttheotherfields,weclickAddApp.

NowweneedtocreateEntities.Theseareelementswewillneedtoidentifyandgather,soourBotcanperformoperationsbasedontheirvalue.Inourexample,wewanttocreatetwoEntities:

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

ClicktheplusbuttonnexttotheEntitieslabel(ontheleft-handsideoftheeditor)toopenaboxthatwillallowyoutoaddeachEntity(oneatatime).

Whenyou’redone,theEntitieswillbedisplayed.

Next,wewilladdanIntent.

Page 154: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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

ClicktheplusbuttonnexttotheIntentslabel.

EnterHighScoresfortheIntentname.

EnterShowmethehighscoresforthepastweekforEnteranexampleofacommandthattriggersthisintent.(Thisisalsoknownasasampleutterance.)

ClickSave.

TheutterancewillnowdisplayintheNewutterancestab.

WewantthisutterancetotriggertheHighScoresIntent,soselectitfromthedropdown.

Page 155: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

WealsowanttodetecttheassociatedEntity.

Clickonthewordweek,itwillthenbehighlighted,andapopupboxwillappear.

SelectPeriodOfTime.

Finally,clickSubmit.

Continuetoenterandlabeladditionalutterances.

Note:RemembertolabelanyEntitiesthatindicateanumberasDays.

Page 156: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Continuetotraintheservice.

YouwillnoticethateventuallyitwillstartdetectingtheEntitiesonitsown.

However,manytimesyouwillstillhavetocorrectit.

Enterandcorrectatleasttendifferentutterances.

ClicktheTrainbuttoninthebottomleft-handcorneroftheinterfacetotrainthemodel.

Page 157: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Next,clickthePublishbutton.

Finally,clickthePublishwebservicebutton.

Thepublishedend-pointwillbedisplayed.

MakenoteoftheAppIDandSubscriptionKey.YouwillneedtheselatertobeusedintheBotapplication.

Page 158: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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

Note:Foraproductionapplication,youwillobtainyoursubscriptionkeyfromAzure.

Now,weneedtoupdatetheBottocalltheLUISservice…

Page 159: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

UpdateTheBotApplication

OpentheprojectfromthepreviouschapterinVisualStudio.

Page 160: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

AddanewfilecalledLUISDialogClass.cs,usingthefollowingcode:

ThiscodewillpasstextenteredintotheBottotheLUISapplicationandtriggertheNoneorHighScoresmethodsbasedonwhattheLUISapplicationdeterminestheIntentis,whichtheenteredtextmatches.

Page 161: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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

Note:Thecodeisnotcompleteatthispoint.Wewillcompletethecodeinlatersteps.

EnsurethatyouentertheAppIDandSubscriptionKeyfromyourLUISapplicationintheLuisModeldecorationatthetopoftheclass.

ThisishowthecodeknowswhatLUISapplicationtoconnectto.

WenowneedtocalltheLUISDialogClass,insteadofthepreviouslyconfiguredNumberGuesserDialogclass,whenausercommunicateswiththeBot.

ThenewLUIScode(LUISDialogClass)willcalltheNumberGuesserDialogclasswhenneeded,forexample,whentheuserhasnottriggeredtheHighScoresintent.

OpentheMessagesController.csfileintheControllersfolder.

Replacethefollowingcode:

Page 162: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

With:

Page 163: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ThereareplaceswheretheNumberGuesserDialogwillneedtocallLUISDialogClass,forexample,whentheuserhasenteredaresponsethatisnotanumberbeingguessedaspartofthegame.

TheNumberGuesserDialogclasswillneedtoreturncontrolbacktotheLUISDialogClass.

ReplacethecodeintheNumberGuesserDialogclass(encapsulatedinthebrackets)thatbeginslikethetextbelow:

Page 164: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Withthefollowingcode:

TheNumberGuesserDialogclassisnolongertherootclass,sowewillneedtoalteritslightlyagain,soitstartsupthegameproperlywhenitistriggeredbytheLUISDialogClass.

LocatethefollowingcodeintheStartAsyncmethod:

Page 165: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 166: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Replaceitwith:

Thiscodeshowsthewelcomescreentostartthenumberguessinggame.

Page 167: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ImplementHighScores

Atthispoint,ifweruntheapplicationandconnecttoitintheMicrosoftBotFrameworkEmulator,wecanplaythegame.

However,ifwetypeanythingthattriggerstheHighScoresLUISIntent,wewillreceiveanerrorbecausethecodetohandlethishasnotbeenimplementedyet.

OpentheLUISDialogClass.csfileandlocatethefollowingcode:

Page 168: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 169: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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.

Page 170: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Asthefinalstep,enterthefollowingcodetoimplementtheShowHighScoresmethodintotheLUISDialogClass:

Page 171: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 172: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 173: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Chapter8:CallingTheMicrosoftBotFrameworkUsingTheDirectLineAPI

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

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

TheDirectLineAPIexposesaRESTAPIthatallowsyoutocommunicatewithasingleBotthathasbeenregisteredwiththeMicrosoftBotConnectorService.

ThisAPIisintendedfordeveloperswhowanttocommunicatewiththeirBotfromtheirownclientapplications,suchasmobileapps,aservice,orevenaHoloLens.

Page 174: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

TheprocedureforworkingwiththeAPIis:

1. RegisteryourBotwiththeBotFrameworkDeveloperPortal2. ConfiguretheDirectLineConnector3. UsethecredentialsobtainedfromtheBotFrameworkDeveloperPortaltomake

RESTbasedcallstocommunicatewiththeBotInourexample,wewillusetheMicrosoft.Bot.Connector.DirectLineNugetpackagetohelpusmakethecalls.

Note:TherenderingoftheoutputwillbetheresponsibilityofthedeveloperofthecustomapplicationthatiscallingtheDirectLineAPI.

Page 175: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Mediasuchanimages,cards,andbuttonswillrequirecustomcodetorenderinamannerthatisappropriatefortheparticularapplication.

Theexampleapplicationwewillbuildwillcreateacustomclientthatwillallowausertocreateanaccount,sign-in,andsecurelycommunicatewiththeBotthatwascreatedinthepreviouschapter.

Page 176: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ConfiguringTheDirectLineConnector

WewanttoconfiguretheDirectLineconnectorforourBot.

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

OpenaBotthathasbeendeployedtotheMicrosoftBotFrameworkDeveloperPortal.

ThefirststepistomakeanoteoftheBothandleyougaveyourBot.YouwillneedthislaterwhenyoucreatetheWebApplication.

Page 177: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

UnderAddanotherchannel,clicktheAddbuttonnexttoDirectLine.

WhentheConfigureDirectLinescreenappears,clicktheGenerateDirectLinesecretbutton.

Page 178: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

CopytheSecretcode.YouwillneedthislaterwhenyoucreatetheWebApplication.

ClickI’mdoneconfiguringDirectLinebutton.

Thescreenwillclose.

Page 179: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

CreateTheWebApplication

OpenVisualStudio.

FromthetoolbarinVisualStudio,selectFile,thenNew,andthenProject.

SelectWebandthenASP.NETWebApplication(.NetFramework).

EnterDirectLineBotfortheName.

SelecttheCreatedirectoryforsolutionbox.

PressOK.

Page 180: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Whentheapplicationconfigurationboxappears,selecttheMVCtemplate.

EnsurethatIndividualUserAccountsisselectedforAuthentication.Ifnot,clicktheChangeAuthenticationbuttonandchangeit.

PressOK.

Theapplicationwillbecreated.

WeneedtoaddtheMicrosoft.Bot.Connector.DirectLineNuGetPackagethatwillallowustoeasilycommunicatewiththeDirectLineAPI.

Page 181: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

IntheSolutionExplorer,right-clickontheDirectLineBotprojectnode(nottheSolutionnode),andselectManageNuGetPackages.

WhentheNuGetPackageconfigurationwindowappears,clicktheBrowsebutton.

EnterMicrosoft.Bot.Connector.DirectLineinthesearchboxtoconductthesearch.

WhentheMicrosoft.Bot.Connector.DirectLinepackageshowsup,clickonit,soits

Page 182: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

propertiesappearinthewindowontheright.

ClicktheInstallbuttontoinstallthepackage.

ClickOKwhenthePreviewwindowshows.

ClicktheIAcceptbuttonwhentheLicenseAcceptancewindowappears.

Page 183: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

TheMicrosoft.Bot.Connector.DirectLineassemblywillbeinstalled.

HitF5todebugandruntheapplication.

Theapplicationwillopeninthewebbrowser.

YouwillseethedefaultwebapplicationcreatedbytheMVCtemplate.

Page 184: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

WecanclicktheRegisterbuttontocreateanewaccount.

WecanalsoclicktheLoginbuttontologinusingaregisteredaccount.

Page 185: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

CompleteTheWebApplication

WewillupdatethehomepagetoshowthechatboxandtheBotresponseonlyiftheuserhascreatedanaccountandloggedin.

StopdebuggingtheapplicationandopentheIndex.cshtmlfileintheViews/Homefolder.

Replaceallofthecodewiththefollowingcode:

Page 186: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 187: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

OpentheHomeController.csfileintheControllersfolder,andreplaceallthecodewiththefollowingcode:

Atthispointthecodeisnotcomplete;however,itsetsupthebasicframework.

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

WhenaloggedinuserloadsthepageorsubmitstexttotheBot,theTalkToTheBotmethodiscalled.

Toimplementit,addthefollowingmethodtotheHomeControllerclass:

Page 188: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

TheTalkToTheBotmethodcallstheReadBotMessagesAsyncmethodtoreadtheresponsefromtheBot.

Toimplementit,addthefollowingmethodtotheHomeControllerclass:

Page 189: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

WhenthereisanimagethatisreturnedbytheBot,theReadBotMessagesAsyncmethodcallstheRenderImageHTMLmethod.

Toimplementit,addthefollowingmethodtotheHomeControllerclass:

Page 190: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 191: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

RunTheApplication

HitF5toruntheapplication.

Theapplicationwillopeninthewebbrowser.Initially,wearenotloggedin,sowewillbeunabletocommunicatewiththeBot.

ClicktheRegisterbuttontocreateanaccount.

Page 192: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

FillintherequiredinformationandclicktheRegisterbutton.

Afteryouhavecreatedanaccount,youcanclicktheLoginbuttontologin(ifyouarenotalreadyloggedin).

YouwillknowyouareloggedinwhenyouseeyouremailaddressinthemenubarandontheHomepage.

Page 193: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

YoucannowcommunicatewiththeBotandrunthesamecodethatwascreatedinthepreviouschapter.

Page 194: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

WhenwelookatthedatainthedatabaseonAzure,weseetheUserIDandUserNameformessagespostedtotheBotarecompletelyunderthecontrolofthefollowingcustomcode:

Page 195: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 196: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 197: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Chapter9:UsingApplicationInsightsToMonitorYourBot

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

WithApplicationInsights,youcaninsertafewlinesofcodeinyourBottofindoutwhatyourusersaredoing.

WhenyouinstallApplicationInsights,youareinstallingasmallinstrumentationpackageinyourapplication.Next,yousetupanApplicationInsightsresourceintheMicrosoftAzureportal.

TheinstrumentationyouinstallmonitorsyourappandsendstelemetrydatatotheMicrosoftAzureportal.TheMicrosoftAzureportalshowsstatisticalchartsandhaspowerfulsearchtoolstohelpyoumonitoryourapplicationanddiagnoseanyproblems.

Page 198: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Todemonstratethis,wewillstartwiththeBotcreatedinChapterSix.

Page 199: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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

Page 200: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

EnableApplicationInsights

OpentheAiNumberGuesserBotprojectinVisualStudio.

IntheSolutionExplorer,right-clickontheProject(nottheSolution),andselectAddApplicationInsightsTelemetry.

First,youwillberequiredtologintoyourMicrosoftAzureAccount.

Page 201: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Afterdoingso,youwillbepresentedwithaformtocreateanApplicationInsightsresource(bychoosingtheNewresourceoptionintheSendtelemetrytodropdown)orconnecttoanexistingApplicationInsightsresource(byselectingitintheSendtelemetrytodropdown).

Afterselectingtheconfigurationoptions,clicktheAddbuttontoproceed.

Page 202: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ApplicationInsightsassemblieswillbeaddedtotheproject.

Ifyougetanerror,mostlikelyyouhavecomponentsthatneedtobeupdated.

Page 203: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

IntheSolutionExplorerinVisualStudio,right-clickontheProject(nottheSolution),andselectManageNuGetPackages.

SelectUpdates,selectthecomponentsthattheerrormessageindicatesneedtobeupdated,andclicktheUpdatebutton.

Page 204: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

WhentheReviewChangesboxshows,clicktheOKbutton.

Next,right-clickontheProjectandselectAddApplicationInsightsTelemetryagaintore-starttheprocess.

TheApplicationInsightscomponentsshouldnowinstallsuccessfully.

Page 205: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

DebugTheApplication

Beforeyoutrytodebug,clearanyMicrosoftAppIdandMicrosoftAppPasswordsettingstheremaybeintheWeb.configfileandthensavethefile.

Thisisrequired,soyoucaneasilydebuglocally.

Remembertoreplaceanysettingsifyouneedtore-publishtheapplication.

HitF5toruntheproject.

Page 206: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Theapplicationwillopeninthewebbrowser.

Notethewebaddress,asyouwillneeditinthenextstep.

Page 207: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

UsingTheBotEmulator

OpenandruntheMicrosoftBotFrameworkEmulator.

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

IntheBotEmulator,enterHellointhetextboxandclickthesendkey(orpressenter).

YouwillseetheresponseintheChatwindowandtheJSONcontentsoftheresponseintheJSONwindow.

Page 208: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Youshouldseeawindowpopupthatprovideslinkstothetelemetrydata.

YoucanalsoaccessthedatabyclickingonthelinksintheApplicationInsight.configsectionintheSolutionExplorerofVisualStudiowhiletheapplicationisrunning.

Page 209: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Also,youcanright-clickontheProjectandselectApplicationInsightstoshowthemenuthatwillprovidealltheoptions.

SelectingSearchLiveTelemetryorSearchDebugSessionTelemetrywillopenawindowinVisualStudiothatwilldisplaytelemetrydata.

Page 210: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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

Page 211: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ForfullTelemetryReadiness,ensureallthegreendotsarechecked.Ifanyaren’t,clickonthem.

Itwillstopdebuggingtoaddcomponents.

Youwillbeabletoclickabuttontoaddorconfigurethecomponents.

Page 212: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Thecomponentswillbeadded.

Theresultwillbedisplayed.

Page 213: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

CustomTelemetry

OneofthemostpowerfulfeaturesofApplicationInsightsisbeingabletouseittotrackyourowncustomtelemetry.

Wewillnowdemonstrateusingittotrackwhenagameisstarted,completed,whatnumberauserneededtoguess,andhowmanyattemptstheyrequired.

Page 214: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

IntheAiNumberGuesserBotproject,opentheNumberGuesserDialog.csfileandaddthefollowingusingstatements:

Next,addthefollowinglinetotheclass:

Finally,addthefollowinglinestotheStartAsyncmethod:

Thiswilltrackagamebeingstartedandthenumbertheuserneedstoguess.

Page 215: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Also,addthefollowingcodetotrackthegamecompleted:

ThereareanumberofAPIcallswecanusetotrackcustomeventsasthefollowingtableillustrates:

Page 216: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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.

Page 217: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

WhenyouselecttheApplicationInsightsmenuinVisualStudioandselectExploreTelemetryTrends…

…youcanthenselectInspectyourcustomevents.

Page 218: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ClicktheAnalyzeTelemetrybuttontoprocessthelatestdata.YouwillseewherethePropertiesandMetricshavebeentracked.

Note:Itwilltakeafewminutesforyourcustomeventstoshow.

Youcandouble-clickonatrendtodrillintothedata.

Thiswilltakeyoutothesearchscreenwhereyoucanfilterfurtherandviewthedetailsofeachindividualevent.

Page 219: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ApplicationInsightsPortal

YoucanaccesstheApplicationInsightsPortalontheMicrosoftAzuresitebyselectingitfromthemenuinVisualStudio.

ItisthereyoucanseeandchangeyourPricingtier.

YoucanalsoobtainyourInstrumentationKey.

Page 220: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 221: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

MonitoringAPublishedApplication

YoucanmonitoryourpublishedBot.

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

EdittheBotconfiguration.

Page 222: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

EntertheInstrumentationKey(fromtheMicrosoftAzuresite)andclickSavechanges.

Thiswillenableadditionalpropertiesandmetricstotrack.

ReturntotheApplicationInsightsresourceontheMicrosoftAzuresite.

Youcannowmonitoryourpublishedapplicationandcreatecustomchartsusingdefaulttrackingdataandyourcustompropertiesandmetrics.

Page 223: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 224: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 225: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Chapter10:CreatingaSkypeBot

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

YoucaneasilycreateaSkypeBotanddeployittoSkype.

Todemonstratethis,wewillstartwiththeBotcreatedinChapterSix.

Note:IfyouhavenotpreviouslydeployedyourBot,skipdowntothesectionlabeled

Page 226: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

“RegisterSkype”.

Page 227: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

PublishingTheBot

ThefirststepistoconnecttheAiNumberGuesserBottotheMicrosoftBotFrameworkDeveloperPortal.

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

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

Page 228: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Next,opentheAiNumberGuesserBotprojectinVisualStudioandright-clickontheProjectnode(nottheSolutionnode),andselectPublish.

SelectMicrosoftAzureAppService.

Page 229: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

SignintoyourAzureaccountandthenclicktheNewbutton.

EnsurethetypeisWebApp.

EnterauniqueWebAppname,selectyoursubscription,selectorcreateaserviceplanandresourcegroupandclicktheCreatebutton.

Page 230: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Afterthewebapphasbeencreated,clickthePublishbutton.

Thewebappwillopeninthewebbrowser.

Notethewebaddressasyouwillneeditinalaterstep.

Page 231: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

RegisteringTheBotWithTheBotConnector

GototheMicrosoftBotFrameworkportalathttp://dev.botframework.comandsigninwithyourMicrosoftAccount.

SelectRegisterabot.

Page 232: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Fillinallofthefields.

Page 233: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Note:Theendpointwebaddressiswhatyousawwhenthewebbrowseropenedinthepreviousstep.

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

Atonepointintheform,youwillseealinkyouwillclicktogoto

https://apps.dev.microsoft.com

ItistherethatyouwillgetanApplicationIDandapassword.

Page 234: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Makeanoteofthembecauseyouwillneedtousethemtoupdatetheweb.configfileintheVisualStudioprojectlater.

ClicktheRegisterbutton.

TheBotregistrationwillbecreated.

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

Page 235: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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

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

InVisualStudio,PublishtheBotagain.

YouaredoingthisbecausetheBotConnectorwillpasstheBotIDandMicrosoftAppIdandMicrosoftAppPasswordwhenitcommunicateswithit.

Page 236: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ReturntotheBotconfigurationpageathttp://dev.botframework.com.

YoucannowclicktheTestbuttononthatpagetotesttheconnectiontoyourBot.

YoucannowconfigurechannelstoyourBot.

Whenyouhaveconfiguredchannels,ifyoudesire,youcanclickthePublishbuttontosubmityourbottotheBotDirectory.

EvenifyoudonotpublishittotheBotDirectory,youcanstillcallitfromyourown

Page 237: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

applicationsandthroughanychannelsyouconfigure.

Page 238: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ConfigureSkype

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

YouwillbedirectedtoaSkypeconfigurationpagefortheBot.

ClickthebuttontoAddtoContacts.

Page 239: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ClickAllowinthepopupbox.

Skypewillopen,andyoucanselecttheBotfromyourcontactsandconversewithit.

Page 240: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 241: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 242: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Chapter11:CreatingAFacebookMessengerBot

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

YoucaneasilycreateaBotanddeployitonFacebook.

Page 243: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Todemonstratethis,wewillstartwiththeBotcreatedinChapterTwo.

Page 244: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Set-UpFacebook

ThefirststepistologintoyourFacebook.comaccount(orcreateone).

SelectCreatePage.

Selectatemplate,fillintherequiredinformation,andclickGetStarted.

Page 245: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

TogettheFacebookPageID,whichyouwillneedlater,clickontheAbouttab.

Page 246: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

LocatetheFacebookPageID.

Page 247: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 248: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

CreateAFacebookDeveloperAccount

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

ClicktheslidertoYestoacceptthepoliciesandclickRegister.

Page 249: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace
Page 250: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

CreateAFacebookApp

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

SelectAddaNewApp.

Selectbasicsetup.

Page 251: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

FillintheinformationandclickCreateAppID.

MakeanoteoftheAppIDasyouwillneeditinalaterstep.

ClicktheShowbuttontodisplaytheAppSecret.Makeanoteofitasyouwillneeditinalaterstep.

Page 252: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

NowthattheAppiscreated,youneedtoconfigureittouseFacebookMessenger.

ClickAddProduct.

SelectMessenger.

SelectGetStarted.

Page 253: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

FacebookMessengerhasbeenadded.

YounowneedtoconfigureittotalktotheMicrosoftBotConnector.

Page 254: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ConfigureTheCallbackURLandVerifyToken

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

SelectMybots.

Selectapublishedbot.(SeeChapterTwofordirectionsonhowtodothis.)

Page 255: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ClicktheAddbuttonnexttotheFacebookMessengerchannel.

ClicktheexpandernexttoSetwebhookcallbackurlandverifytoken.

Page 256: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

UsetheSelectbuttonstoindividuallyselectandcopytheCallbackUrlandVerifyToken.

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

EntertheCallbackURLandVerifyTokenyoucopied,checktheSubscriptionFieldsindicatedintheimageabove,andclicktheVerifyandSavebutton.

AftertheWebhookshavebeenset,clickthedropdownnexttoSelectaPage.

Page 257: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

SelecttheFacebookpageyoucreatedearlier.

Next,clicktheSubscribebutton.

Page 258: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

GetPageToken

IntheTokenGenerationsection,selectthepagethatyoupreviouslycreated.

APageAccessTokenwillbecreated.

CopythePageAccessToken.

Page 259: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

ConfigureTheMicrosoftBotConnector

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

ClicktheexpandernexttoEnteryourcredentials.

EntertheinformationyougatheredintheearlierstepsandclicktheResubmitbutton.

ChecktheboxnexttoEnablethisbotonFacebookMessenger.

ClickI’mdoneconfiguringFacebookMessengerbutton.

Page 260: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

TalkingToYourBot

YoucannowtalktoyourBotbynavigatingto

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

ThiswilltakeyoutoFacebookMessenger,andafterlogginginwithyourFacebookID,itwillallowyoutoconversewithyourBot.

UntilyourAppisapprovedandmadepublic,onlyyoucanchatwithyourBot.

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

Page 261: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

SelecttheAppandthenselectRolesandthenTestUsers.

Fillintheformthatdisplaystocreatetestusers.

ToallowrealFacebookuserstotestit,selectRolesandthenAddTesters.

Fillintheformthatdisplaystoallowaccessfortheusers.

TomaketheBotpublic,selectAppReview.ThenclicktheslidertochangeitfromNotoYes.

Page 262: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Torequesttheneededpermissions,selectSettingsunderMessengerthenclicktheRequestPermissionsbutton.

Page 263: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

Selectpages_messagingandthenclicktheAdd1Itembutton.

SeethispageformoreinformationontheAppreviewprocess

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

Page 264: An Introduction to the Microsoft Bot Framework: Create Facebook and Skype Chatbots using Microsoft Visual Studio and C# - By Michael Washington - Year 2016 - Publisher CreateSpace

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)