Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Building a Bot using C# and Debugging using Bot Framework Emulator

7 Jul 2016 1  
This article demonstrates how to build a basic Bot using C# and debug the Bot using Bot Framework Emulator

Introduction

Microsoft Bot framework enables developers to build intelligent bots that can interact with end users through Skype, Facebook and other such services. This article demonstrates how to build a simple Insurance bot that will assist an insurance policy holder raise a claim for a loss. From a development perspective, developers should debug and test the bot before registering it. Microsoft Bot framework Emulator is an excellent tool that helps developers to debug the bot code base.

Background

Microsoft Bot framework consists of components like Bot Builder SDK, Bot Connector, Bot Directory. Bot Builder SDK helps in developing bots either using C# or Node.js. Bot connector helps in connecting the bot and the end user. Bot directory is the repository of all the bots. Bots developed using Microsoft Bot framework has to be registered in Bot directory and approved. Once approved, the bot will be available to the end users.

Using the Code

Prerequisites

Visual Studio template to develop bot framework can be downloaded from here. The downloaded zip file has to be copied to %USERPROFILE%\Documents\Visual Studio 2015\Templates\ProjectTemplates\Visual C#. Once this is copied, the Bot Application template will be available in Visual Studio 2015. Visual Studio solution has to be created using Bot Application template.

Microsoft.Bot.Builder and Microsoft.Bot.Connector packages has to be installed from NuGet package manager. Check for the packages.config in the attached solution for all packages that are needed for his Bot application.

Install Microsoft Bot Framework Emulator from here.

Building the Bot Class

InsuranceBot class defines the form that a policy holder needs to fill in while interacting with the Insurance Bot. This class has fields like PolicyNumber, LossType, LossDate, WhereDidThisHappen and LossDetail that represents the fields in a form flow that would be presented to the user while interacting with the Bot. Prompt attribute on each of the field specifies the text corresponding to the field that Bot will present to the user during interaction. {||} specified in the Prompt attribute displays all choices available.

FormBuilder in BuildForm method in the class builds the form flow for the bot. Field method adds the class field as a form field. Once the form is complete and all fields are presented to the user, OnCompletion method is called. All wrap up activities (for example displaying some confirmation message) can be done here.

public enum LossTypeOptions
{
    Stolen=1,
    Accident,
    NaturalCalamity
}
[Serializable]
public class InsuranceBOT
{
    [Prompt("Please give me your policy number")]
    public string PolicyNumber;

    [Prompt("What happened to your vehicle {||}")]
    public LossTypeOptions LossType;

    [Prompt("When did this happen")]
    public DateTime? LossDate;

    [Prompt("Where did this happen")]
    public string WhereDidThisHappen;

    [Prompt("How this happened in detail")]
    public string LossDetail;

    public static IForm<InsuranceBot> BuildForm()
    {
        OnCompletionAsyncDelegate<InsuranceBot> wrapUpRequest = async (context, state) =>
        {
            string wrapUpMessage= "Your loss
            ["+state.LossType+"] on "+state.LossDate.Value.ToShortDateString()
            +" against Policy number "+state.PolicyNumber+@"
            is being processed. You will also receive a mail in your
            registered mail ID once this is initiated.Thank you for using our Bot service.";
            await context.PostAsync(wrapUpMessage);

        };
        return new FormBuilder<InsuranceBot>().Message
        ("Welcome to XXX Insurance. Sorry to know about your loss.")
            .Field(nameof(PolicyNumber))
            .Field(nameof(LossType))
            .Field(nameof(LossDate))
            .Field(nameof(WhereDidThisHappen))
            .Field(nameof(LossDetail))
            .OnCompletion(wrapUpRequest)
            .Build();
    }
}

Build the Message Controller

The form has to be connected to the bot framework. Chain class provides methods that help in creating chainable interfaces for dialogs. Form dialog is created using FormDialog.FromForm. Modify the Post method to invoke Conversation.SendAsync to enable interaction between end user and the bot.

public class MessagesController : ApiController
{
    internal static IDialog<InsuranceBOT> BuildInsuranceDialog()
    {
        return Chain.From(() => FormDialog.FromForm(InsuranceBOT.BuildForm));
    }

    [ResponseType(typeof(void))]
    public virtual async Task<HttpResponseMessage> Post([FromBody] Activity activity)
    {
        await Conversation.SendAsync(activity, BuildInsuranceDialog);
        return new HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
    }
}

Configuration File Changes

Add the below settings in the configuration file.

<appSettings>
   <add key="BotId" value="123"></add>
</appSettings>

Debugging the Bot using Microsoft Bot Framework Emulator

Build and run the Bot solution.

Launch the Microsoft Bot Framework emulator. Provide the url of the bot as -

http://[localhost]:[portnumber]/api/messages in the emulator.

Breakpoint can be set in the Bot code base. For each of the conversion in the emulator, the breakpoint will hit.

User initiates the conversation by typing Hi in the user chat input area.

Bot responds with Welcome message and asks for policy number.

User responds with policy number and Bot asks for loss type.

User responds loss type as Stolen by clicking on the form field and Bot continues with next set of questions and user gives responses.

In the end, Bot wraps up the conversation by giving a summarized message.

Points of Interest

The attached zip file contains a solution for the Insurance bot demonstrated. The solution is created using Visual Studio 2015 Community Edition. Please connect to the internet while building the solution so that the NuGet packages are restored in the solution. You can download the zip file from here.

Next steps would be to register the bot here and use it with Skype or Facebook or any other such services.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here