Xamarin Forms and AI Bot Framework with LUIS - Part 2

Posted by seven.srikanth@gmail.com at 28-05-2018 17:33:21 in Article


Hi Guys, We will continue by creating our own Bot Connector using Microsoft Bot Framework Connector. The idea was to integrate to a different communication channels like Skype, SMS, Email and others, In our case we gonna integrate it with Directline so that our app will be able to communicate with LUIS. If you missed the first topic you can browse it here. This is a three part series and if you already confident about the topic you can proceed to the next. Xamarin.Forms and AI Bot Framework with LUIS -  Part 3

Getting started with the Connector

This is a step-by-step guide to writing a Bot in C# using the Bot Framework Connector SDK .NET template.
  1. Install prerequisite software Visual Studio 2015 (latest update) - you can download the community version here for free: www.visualstudio.com
  2. Important: Please update all VS extensions to their latest versions Tools->Extensions and Updates->Updates
  3. Download and install the Bot Application template
  4. Open Visual Studio
  5. Create a new C# project using the new Bot Application template. 
  6. The template is a fully functional Echo Bot that takes the user's text utterance as input and returns it as output. In order to run however,
  • The bot has to be registered with Bot Connector
  • The AppId and AppPassword from the Bot Framework registration page have to be recorded in the project's web.config
  • The project needs to be published to the web

Building your Bot

The core functionality of the Bot Template is all in the Post function within Controllers\MessagesController.cs. In this case the code takes the message text for the user, then creates a reply message using the CreateReplyMessage function. The BotAuthentication decoration on the method is used to validate your Bot Connector credentials over HTTPS.
public class MessagesController : ApiController
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
if (activity.Type == ActivityTypes.Message)
// calculate something for us to return
int length = (activity.Text ?? string.Empty).Length;
// return our reply to the user
Activity reply = activity.CreateReply($"You sent {activity.Text} which was {length} characters");
await connector.Conversations.ReplyToActivityAsync(reply);
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;


Use the Bot Framework Emulator to test your Bot application The Bot Framework provides a a channel emulator that lets you test calls to your Bot as if it were being called by the Bot Framework cloud service. To install the Bot Framework Emulator, download it from here. Once installed, you're ready to test. First, start your Bot in Visual Studio using a browser as the application host.
Now open the Bot Framework Emulator. There are a few items that you will need to configure in the tool before you can interact with your Bot Application. When working with the emulator with a bot running locally, you need: The Url for your bot set the localhost:<port> pulled from the last step. > Note: will need to add the path "/api/messages" to your URL when using the Bot Application template. Empty out the MicrosoftAppId field Empty out the MicrosoftAppPassword field This will only work with the emulator running locally; in the cloud you would instead have to specify the appropriate URL and authentication values. For more about the emulator, read here.
Now that everything is configured you can interact with your service. The bottom of the Bot Framework Emulator application has a Text Box that you can use to enter a message, this message will be echoed back to you.

Adding LUIS

Now we are ready to add LUIS to our bot connector app all we need is to inherit LuisDialog<object> to handle query. below is the code which handles all the Intents coming from the json result of query. Note: please provide your own modelId and subscription key which can be obtain from https://www.luis.ai/ -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.FormFlow;
using Microsoft.Bot.Builder.Luis;
using Microsoft.Bot.Builder.Luis.Models;
using Microsoft.Bot.Builder.Resource;
using Microsoft.Bot.Connector;
namespace TravelAppBot.Dialogs
/// <summary>
/// you can get modelid and subscriptionkey from luis.ai
/// </summary>
[LuisModel("24474ca3-51d5-4338-ba05-f6aac8c1e7c4", "ed802dde7db34d20894d6a552cd1d028")]
public class RootLuisDialog : LuisDialog<object>
public async Task None(IDialogContext context, LuisResult result)
string message = $"Sorry, I did not understand '{result.Query}'. Type 'help' if you need assistance.";
await context.PostAsync(message);
public async Task Help(IDialogContext context, LuisResult result)
await context.PostAsync("Hi! Try asking me things like 'book me a flight from london to paris' or 'what is the weather like in new york'");
public async Task BookFlight(IDialogContext context, LuisResult result)
GetEntityRecommendation("Location::FromLocation", "FromLocation", result);
GetEntityRecommendation("Location::ToLocation", "ToLocation", result);
GetEntityRecommendation("builtin.datetime.date", "DepartureDate", result);
await context.PostAsync("booking you flight...");
var form = new BookFlightForm();
var hotelsFormDialog = new FormDialog<BookFlightForm>(form, this.BuildHotelsForm, FormOptions.PromptInStart, result.Entities);
context.Call(hotelsFormDialog, this.ResumeAfterFlightFormDialog);
private static void GetEntityRecommendation(string fromType, string toType, LuisResult result)
EntityRecommendation dateEntityRecommendation;
if (result.TryFindEntity(fromType, out dateEntityRecommendation))
dateEntityRecommendation.Type = toType;
private IForm<BookFlightForm> BuildHotelsForm()
OnCompletionAsyncDelegate<BookFlightForm> processBooking = async (context, state) =>
var message = "Thank you for completing the query, we are about to book you a flight...";
await context.PostAsync(message);
return new FormBuilder<BookFlightForm>()
.Field(nameof(BookFlightForm.FromLocation), (state) => string.IsNullOrEmpty(state.FromLocation))
.Field(nameof(BookFlightForm.ToLocation), (state) => string.IsNullOrEmpty(state.ToLocation))
.Field(nameof(BookFlightForm.DepartureDate), (state) => string.IsNullOrEmpty(state.DepartureDate))
private async Task ResumeAfterFlightFormDialog(IDialogContext context, IAwaitable<BookFlightForm> result)
var searchQuery = await result;
var fromLocation = searchQuery.FromLocation;
var toLocation = searchQuery.ToLocation;
var scheduledDate = searchQuery.DepartureDate;
var message = $"Your flight has been booked from {fromLocation} to {toLocation} scheduled {scheduledDate}";
await context.PostAsync(message);
catch (FormCanceledException ex)
string reply;
if (ex.InnerException == null)
reply = "You have canceled the operation.";
reply = $"Oops! Something went wrong :( Technical Details: {ex.InnerException.Message}";
await context.PostAsync(reply);
public class BookFlightForm
[Prompt("From which city do you want to leave from? {||}", AllowDefault = BoolDefault.True)]
[Describe("Location, example: Amsterdam")]
public string FromLocation { get; set; }
[Prompt("To which city you want to fly to? {||}", AllowDefault = BoolDefault.True)]
[Describe("Location, example: Las Vegas")]
public string ToLocation { get; set; }
[Prompt("When do you want to leave? {||}", AllowDefault = BoolDefault.True)]
[Describe("Departure date, example: tomorrow, next week or any date like 12-06-2016")]
public string DepartureDate { get; set; }
view raw RootLuisDialog.cs hosted with ❤ by GitHub
- For the complete source you can download it here.

Publishing your Bot Application to Microsoft Azure

In this tutorial, we use Microsoft Azure to host the Bot application. To publish your Bot Application you will need a Microsoft Azure subscription. You can get a free trial from here: azure.microsoft.com/en-us/ Make what changes you like to the project, and now you're ready to publish. Right click on the project and choose "Publish", and then your appropriate Azure subscription information. By default, the bot should be published as an Microsoft Azure App Service. When publishing, keep track of the URL you chose because we'll need it to update the Bot Framework registration endpoint. The first time you publish there are a few extra steps; but you only have to do them once. In Visual Studio, right clicking on the project in Solution Explorer and select "Publish" - or alternately selecting "Build | Publish" displays the following dialog:
The next step in the Azure App Service publishing process is to create your App Service. Click on "New…" on the right side of the dialog to create the App Service.
The Create App Service dialog will be displayed, fill in the details as appropriate.Make sure to choose "Web App" from the Change Type drop down in the top right instead of "API App"(which is the default).
One final complexity on this dialog is the App Service Plan. This just lets you give a name to a combination of location and system size so you can re - use it on future deployments. Just put in any name, then choose the datacenter and size of deployment you want. Once you hit okay on the App Service Plan, you'll have defined your App Service completely. Hit Create, and you'll be taken back to the Publish Web Wizard. Now that you've returned to the Publish Web wizard copy the destination URL to the clipboard, you'll need it in a few moments. Hit "Validate Connection" to ensure the configuration is good, and if all goes well, click "Next". By default your Bot will be published in a Release configuration. If you want to debug your Bot, change Configuration to Debug. Regardless, from here you'll hit "Publish" and your Bot will be published to Azure. You will see a number of messages displayed in the Visual Studio 2015 "Output" window. Once publishing is complete you will also see the web page for your Bot Application displayed in your browser (the browser will launch, and render your Bot Application HTML page), see below.

Registering your Bot with the Microsoft Bot Framework

Registering your Bot tells the Connector how to call your Bot's web service. Note that the MicrosoftAppId and MicrosoftAppPassword** are generated when your Bot is registered with the Microsoft Bot Framework Connector, the MicrosoftAppId and MicrosoftAppPassword are used to authenticate the conversation, and allows the developer to configure their Bot with the Channels they'd like to be visible on. The BotId, which you specify, is used for the URL in the directory and developer portal.
  1. Go to the Microsoft Bot Framework portal at https://dev.botframework.com and sign in with your Microsoft Account.
  2. Click the "Register a Bot" button and fill out the form. Many of the fields on this form can be changed later. Use a the endpoint generated from your Azure deployment, and don't forget that when using the Bot Application tempalate you'll need to extend the URL you pasted in with the path to the endpoint at / API / Messages. You should also prefix your URL with HTTPS instead of HTTP; Azure will take care of providing HTTPS support on your bot. Save your changes by hitting "Create" at the bottom of the form.
Once your registration is created, Microsoft Bot Framework will take you through generating your MicrosoftAppId and MicrosoftAppPassword. These are used to authenticate your Bot with the Microsoft Bot Framework. NOTE: When you generate your MicrosoftAppPassword, be sure to record it somewhere as you won't be able to see it again. Now that the Bot is registered, you need to update the keys in the web.config file in your Visual Studio project. Change the following keys in the web.config file to match the ones generated when you saved your registration, and you're ready to build. Clicking the "show" link will show the value, along wtih exposing the regenerate link if you ever need to change your AppPassword. Update your web.config, and re-publish your bot to Azure. -
<? xml version = "1.0" encoding = "utf-8" ?>
< !--
For more information on how to configure your ASP.NET application, please visit
< configuration >
< appSettings >
< !--update these with your appid and one of your appsecret keys-->
< add key = "MicrosoftAppId" value = "[GUID]" />
< add key = "MicrosoftAppPassword" value = "[PASSWORD]" />
</ appSettings >
view raw appsettings.xml hosted with ❤ by GitHub

Testing the connection to your bot

Back in the developer dashboard for your Bot there's a test chat window that you can use to interact with your Bot without further configuration, and verify that the Bot Framework can communicate with your Bot's web service. Note that the first request after your Bot starts up can take 10 - 15 s as Azure starts up the web service for the first time. Subsequent requests will be quick. This simple viewer will let you see the JSON object returned by your Bot.

Configuring Channels

Now that you have a Bot up and running, you'll want to configure it for one or more channels your users are using. Configuring channels is a combination of Microsoft Bot Framework workflow and conversation service workflow, and is unique for each channel you wish to configure.
  1. To configure a channel, go back to the Bot Framework portal at https://www.botframework.com. Sign in, select your Bot, and go to the channels panel.
Pick the channel you wish to configure, and click add. You'll be taken to a page of instructions for registering a Bot. In the end in most cases you're configuring your credentials as a developer on the target service, registering your app, and getting a set of Oauth keys that Microsoft Bot Framework can use on your behalf. In our case we will use DirectLine in order for our apps to have easy communication with LUIS. We can use the secret keys for our Xamarin.Forms App and should be able to connect with directline channel. And for the Xamarin.Forms project we will have it on part 3 of this series. Xamarin.Forms and AI Bot Framework with LUIS -  Part 3
Original Author: 
Source: http://winstongubantes.blogspot.in/2017/02/xamarinforms-and-ai-bot-framework-with.html

Tags: Xamarin Forms and AI Bot Framework with LUIS

Login to comment.

Recent Comments

Be the first to Comment. You can ask a Query or Share your toughts or Just say thanks.