Creating an ASP.NET C# Bot using the Microsoft Bot Framework
This article will help you create your own ASP.NET Bot usingthe Microsoft Bot Framework. The bot main logic will be written in C# and usingVisual Studio 2015 (community edition).
Building a bot using Microsoft Bot Framework requires three mainparts:
<![if !supportLists]>1.<![endif]>Your own ConversationalBot, which is an ASP.NET web API application. You can implement your ownconversation logic using the Microsoft “Bot builder SDK(Microsoft.Bot.Builder.dll) and you can handle the conversation messaging andsecurity using the “Bot Connector libraries”.
<![if !supportLists]>2.<![endif]>MicrosoftOperated Service, which is a Microsoft hosted azure service, also known asthe Microsoft Bot Connector. It acts as an interface between your bot and variouscommunication channels. This service will forward messages from the user toyour Bot and from your bot to the user.
<![if !supportLists]>3.<![endif]>Communicationchannels: the communication channels that your user will use to communicatewith your bot; such as the web using an embedded web chat controller, SMS,email, slack, skype, GroupMe, telegram, and other communication services. Youcan configure your bot communication channels in the Azure Bot Connectorservice.
<![if !vml]><![endif]>
<![if !supportLists]>1.<![endif]>Download and install the visual studio 2015 Botapplication template:
<![if !supportLists]>a.<![endif]>Download the template from: http://aka.ms/bf-bc-vstemplate
<![if !supportLists]>b.<![endif]>To install the template into Visual studio allyou need to do is save the downloaded zip file into your Visual Studio 2015project template directory. The directory is usually found underdocuments\visual studio 2015\templates\ProjectTemplates\Visual C#\
<![if !supportLists]>2.<![endif]>Create a new C# bot project:
<![if !supportLists]>a.<![endif]>Restart visual studio and create a new C#project of type “Bot Application Template”
<![if !vml]><![endif]>
<![if !supportLists]>b.<![endif]>Keep the default name: “Bot Application1”
<![if !supportLists]>c.<![endif]>The created project is an ASP.NET web APIproject that references the Bot connector libraries (Microsoft.Bot.Connector).
<![if !supportLists]>3.<![endif]>Write your own bot logic:
<![if !supportLists]>a.<![endif]>The created project main functionality is in theControllers\MessageController.cs class and more specifically in the following Postfunction of an api/Messages call:
<![if !vml]><![endif]>
<![if !supportLists]>b.<![endif]>The MessageController defines an asynchronousmethod that accepts a Microsoft.Bot.Connector.Message object from the requestbody and returns a Microsoft.Bot.Connector.Message object.
<![if !supportLists]>i.<![endif]>The Message object Type field having the value “Message”, which refers to a simplecommunication between a user and the bot. Check the following link for theavailable message types: http://docs.botframework.com/connector/message-types/
<![if !supportLists]>ii.<![endif]>This sample code calculate the length of theuser message and call message.CreateReplyMessage(Text,[language]) to send a replytext to the user. The createReplyMessage function takes a text string propertyin “MarkDown” syntax that will be returned to the user and an optional languageproperty that takes a language code. A Text property allows the returned textto be rendered according to a set of markdowns, for example if you set the textto “Helo **Tom**” the rendered message will make Tom bold. Check the followinglink for the available Markdown elements: http://docs.botframework.com/connector/message-content/#the-text-property-is-markdown
<![if !supportLists]>c.<![endif]>The default sample function will just return atext message to the user that includes the length of the user message string.
<![if !supportLists]>4.<![endif]>To test your application you can use the BotFramework Emulator. The emulator is a separate desktop application that has anembedded chat controller and that can connect directly to your bot web APIservice (without the need for the Bot Connector service). You can use it totest your created bot API interaction.
<![if !supportLists]>a.<![endif]>Build and run your created Bot service in visualstudio, that will start IIS express and the load browser with the default url(http://localhost:3978/api/messages).
<![if !supportLists]>b.<![endif]>Download the Bot Framework Emulator applicationfrom the following link: https://aka.ms/bf-bc-emulator
<![if !supportLists]>c.<![endif]>Install the emulator application, and run it(keep the default setting for now):
<![if !vml]><![endif]>
<![if !supportLists]>d.<![endif]>Write your own message in the emulator (Text boxin the bottom of the application)
<![if !supportLists]>e.<![endif]>The emulator will send a JSON API request toyour Bot API, return the Bot reply and display it in the Chat Window.
<![if !supportLists]>f.<![endif]>The emulator will display the received JSONreply in the left window
<![if !supportLists]>g.<![endif]>The emulator needs the Bot URL, the Bot app id,and the Bot Secret to communicate with your Bot API. The default bot API URL isset in the emulator as http://localhost:3978/api/messages(make sure the application port match the emulator set port), the default appid as “YourAppId”, and the default App Secret as “YourAppSecret”. Your Bot app id and app secret are stored inyour project web.config file and they are used to secure the communication withbetween the bot and the user.
<![if !vml]><![endif]>
<![if !supportLists]>1.<![endif]>Install the Bot Builder SDK: To use Bot dialogswe need to install the Bot Builder SDK:
<![if !supportLists]>a.<![endif]>Right click on your newly created project andselect “Manage Nuget Packages”.
<![if !supportLists]>b.<![endif]>In the “browse” tab write“Microsoft.Bot.Builder”, click install and accept changes.
<![if !vml]><![endif]>
<![if !supportLists]>2.<![endif]>Write conversational logic using Bot Builder SDKDialog Object: The dialog model is a conversational process that encapsulatesits own state in a C# class. We can use the Dialog object to writesophisticated bot logic:
<![if !supportLists]>a.<![endif]>First, add the following namespace to theControllers\MessageController.cs file:
Using Microsoft.Bot.Builder.Dialogs;
<![if !supportLists]>b.<![endif]>Next, change the MessageController Post methodto call a class that implements IDialog. We will call that class HelpDialog:
public async Task<Message> Post([FromBody]Message message)
{
if(message.Type == “Message”)
{
return await Conversation.SendAsync(message, () => new HelpDialog());
}
<![if !supportLists]>c.<![endif]>Now let us add the C# class HelpDialog in thefile Controllers\MessageController.cs:
namespace Bot_Application1
{
[Serializable]
public class HelpDialog : Idialog<object>
{
public async Task StartAsync(IdialogContext context)
{
}
…
<![if !supportLineBreakNewLine]>
<![endif]>
<![if !supportLists]>i.<![endif]>HelpDialogis marked with the attribute Serializableso that the object instance of this class can participate in the runtimeserialization, which allows for all state of the dialog to be serialized peruser and per conversation and stored in IbotDataBag.
<![if !supportLists]>ii.<![endif]>HelpDialogimplements an Idialog that can call child dialogs or send messages to a user.Dialogs are suspended while waiting for message from the user and they areresumed when they receive a message from a user.
<![if !supportLists]>iii.<![endif]>StartAsync is a member function of the Idialoginterface, which takes the dialog context as parameter and return aSystem.Threading.tasks.Task that represents an asynchronous operation.StartAsync is the first function called when a dialog is started.
<![if !supportLists]>iv.<![endif]>IdialogContext is an interface that provides the services needed to save stateand communicate. It includes the following functions:
<![if !supportLists]>1. <![endif]>Call: call a child dialog and add it to the top of the stack.
<![if !supportLists]>2. <![endif]>Done: complete the current dialog and return a result to theparent dialog.
<![if !supportLists]>3. <![endif]>MakeMessage: Make a message.
<![if !supportLists]>4. <![endif]>PostAsync: Post a message to be sent to the user,
<![if !supportLists]>5. <![endif]>Wait: suspend current dialog until the user has sent a messageto the bot.
<![if !supportLists]>d. <![endif]>Next,we will add an implementation for the context.Wait function in the HelpDialog StartAsyncmethod, which will suspend the dialog until the user has sent a message to thebot and then call a method to resume the dialog when the message has beenreceived:
public async Task StartAsync(IdialogContext context)
{
context.Wait(YourFunctionForMessageReceived);
}
<![if !supportLineBreakNewLine]>
<![endif]>
<![if !supportLists]>e.<![endif]>Next we need to add some code to YourFunctionForMessageReceived:
public async TaskYourFunctionForMessageReceived(IdialogContext context, Iawaitable<Message> argument)
{
varmessage = await argument;
if(message.Text == “help”)
{
PromptDialog.Confirm(
context,
YourFunctionForHelpCommand,
“Are you sure you want todisplay help?”,
“Didn’t get that!”);
}
else
{
int length = (message.Text ?? string.Empty).Length;
await context.PostAsync($”You sent {length} characters”);
context.Wait(YourFunctionForMessageReceived);
}
}
<![if !supportLists]>i.<![endif]>This function takes the context as argument andthe user message.
<![if !supportLists]>ii.<![endif]>We check the user received message if it is equalto “help” then we will display a yes/no prompt dialog to confirm his request.
<![if !supportLists]>iii.<![endif]>Microsoft.Bot.Builder.Dialogs.PromptDialog classcontains severalclasses to prompt the user for confirmation. In this implementation we usedthe PromptDialog.Confirm class that takes as input the context, a function tobe called when the user respond to the confirmation dialog, a prompt to showthe user, and another to show the user when asking for a retry.
<![if !supportLists]>iv.<![endif]>If the user typed anything other than “help”,the bot will just display the length of the message (This is the same code that used to be in the MessageController Postfunction)
<![if !supportLists]>f.<![endif]>Lastly, we add some code toYourFunctionForHelpCommand:
public async Task YourFunctionForHelpCommand(IdialogContext context, Iawaitable<bool> argument)
{
varconfirm = await argument;
if(confirm)
{
await context.PostAsync(“I am a simple bot that will display the length of your messages! Youcan display this message by typing \”help\”!”);
}
context.Wait(YourFunctionForMessageReceived);
}
<![if !supportLineBreakNewLine]>
<![endif]>
<![if !supportLists]>i.<![endif]>This function is called when the user isprompted to confirm his help command. The function takes as argument thecontext and a Boolean argument.
<![if !supportLists]>ii.<![endif]>If the user confirmed his request, a messagewill be returned to the user using the context.PostAsync function to displaysome information.
<![if !supportLists]>iii.<![endif]>Context.Wait is called to suspend the dialoguntil the user sends a message to the bot. The resume function is specified asthe first function (YourFunctionForMessageReceived) to be called when a message isreceived from the user.
<![if !supportLists]>3.<![endif]>A sample conversational run for this code usingthe Bot Framework Emulator:
<![if !vml]><![endif]>
This sample code can be found on github at: https://github.com/Binarieslid/Bot-Application1/
Do you want to have your bot on the hololens? check this link:HoloLens Development