Xamarin Forms and AI Bot Framework with LUIS - Part 3

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



 Overview

Hi guys, for the final part of the series we will create a Xamarin.Forms projects for our Bot client. This will only need a little setup to connect with our Bot using DirectLine channel discuss on the part 2 of this article. 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 just have to skip it. Xamarin.Forms and AI Bot Framework with LUIS -  Part 1 Xamarin.Forms and AI Bot Framework with LUIS -  Part 2

Creating our Xamarin.Forms Project

Create a Blank Xaml App (Xamarin.Forms Portable) under Cross-Platform Category and name it "TravelAgent" or name whatever you want. Now we have to create Models and ViewModels for our Travel Agent Page. First we need to create a ChatBot Model which is the standard schema for Chat Bot Messaging. -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace TravelAppMobile.Models
{
public class MessageSet
{
[JsonProperty(PropertyName = "messages")]
public BotMessage[] Messages { get; set; }
[JsonProperty(PropertyName = "watermark")]
public string WaterMark { get; set; }
[JsonProperty(PropertyName = "eTag")]
public string ETag { get; set; }
}
public class BotMessage
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "conversationId")]
public string ConversationId { get; set; }
[JsonProperty(PropertyName = "created")]
public DateTime Created { get; set; }
[JsonProperty(PropertyName = "from")]
public string From { get; set; }
[JsonProperty(PropertyName = "text")]
public string Text { get; set; }
[JsonProperty(PropertyName = "channelData")]
public string ChannelData { get; set; }
[JsonProperty(PropertyName = "images")]
public string[] Images { get; set; }
[JsonProperty(PropertyName = "attachments")]
public Attachment[] Attachments { get; set; }
[JsonProperty(PropertyName = "eTag")]
public string ETag { get; set; }
}
public class Attachment
{
[JsonProperty(PropertyName = "url")]
public string Url { get; set; }
[JsonProperty(PropertyName = "contentType")]
public string ContentType { get; set; }
}
public class Conversation
{
[JsonProperty(PropertyName = "conversationId")]
public string ConversationId { get; set; }
[JsonProperty(PropertyName = "token")]
public string Token { get; set; }
[JsonProperty(PropertyName = "eTag")]
public string ETag { get; set; }
}
}
view raw ChatBotModels.cs hosted with ❤ by GitHub
- Then we need to create ConversationMessage model for our Xaml Page Message UI. -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace TravelAppMobile.Models
{
public class ConversationMessage
{
public string Id { get; set; }
public string Message { get; set; }
public string FromUser { get; set; }
public ImageSource UserImageUrl { get; set; }
}
}
- Next is we create our ChatBotService  we will use to converse with our chatbot connector. Make sure you obtain a Directline key for us to connect with BotConnector. -
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using TravelAppMobile.Models;
namespace TravelAppMobile.Services
{
public class ChatBotService
{
private readonly string _baseBotEndPointAddress = "https://directline.botframework.com";
private HttpClient _client;
private string _directLineKey = "Q9IBXWIBSUg.cwA.1pw.aVXMkIWleOmQgRWWRKzYJwMoj63fP57FCeATbE7qW40"; //USE YOUR OWN DIRECTLINE KEY
private Conversation _lastConversation = null;
public ChatBotService()
{
_client = new HttpClient();
_client.BaseAddress = new Uri(_baseBotEndPointAddress);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BotConnector", _directLineKey);
InitializeConversation();
}
private async void InitializeConversation()
{
var response = await _client.GetAsync("/api/tokens/");
if (response.IsSuccessStatusCode)
{
var conversation = new Conversation();
HttpContent contentPost = new StringContent(JsonConvert.SerializeObject(conversation), Encoding.UTF8,
"application/json");
response = await _client.PostAsync("/api/conversations/", contentPost);
if (response.IsSuccessStatusCode)
{
var conversationInfo = await response.Content.ReadAsStringAsync();
_lastConversation = JsonConvert.DeserializeObject<Conversation>(conversationInfo);
}
}
}
public async Task<MessageSet> SendMessage(string message)
{
try
{
var messageToSend = new BotMessage() { Text = message, ConversationId = _lastConversation.ConversationId };
var contentPost = new StringContent(JsonConvert.SerializeObject(messageToSend), Encoding.UTF8, "application/json");
var conversationUrl = $"{_baseBotEndPointAddress}/api/conversations/{_lastConversation.ConversationId}/messages/";
var response = await _client.PostAsync(conversationUrl, contentPost);
var messageInfo = await response.Content.ReadAsStringAsync();
var messagesReceived = await _client.GetAsync(conversationUrl);
var messagesReceivedData = await messagesReceived.Content.ReadAsStringAsync();
var messages = JsonConvert.DeserializeObject<MessageSet>(messagesReceivedData);
return messages;
}
catch (Exception ex)
{
return SetExceptionMessage(ex);
}
}
private static MessageSet SetExceptionMessage(Exception ex)
{
Debug.WriteLine(ex.Message);
return new MessageSet()
{
Messages = (new List<BotMessage>
{
new BotMessage
{
Text = "Something went wrong!",
From = "Bot"
}
}).ToArray()
};
}
}
}
view raw ChatBotService.cs hosted with ❤ by GitHub
- We will have to create a TravelAgent Xaml page to display our conversation with the bot. -
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:TravelAppMobile.ViewModels;assembly=TravelAppMobile"
x:Class="TravelAppMobile.Pages.TravelAgentPage"
Title="Travel Agent">
<ContentPage.BindingContext>
<viewModels:TravelAgentPageViewModel></viewModels:TravelAgentPageViewModel>
</ContentPage.BindingContext>
<ContentPage.Content>
<StackLayout Orientation="Vertical"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
<ListView ItemsSource="{Binding Messages}"
Margin="10"
HasUnevenRows="True"
IsPullToRefreshEnabled="True"
IsRefreshing="{Binding IsRefreshing }">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
Orientation="Horizontal">
<Image Source="{Binding UserImageUrl}"></Image>
<Label Text="{Binding Message}"></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackLayout VerticalOptions="End" HorizontalOptions="FillAndExpand">
<Entry Placeholder="Please enter message.." Text="{Binding TextMessage}"></Entry>
<Button Text="Send" Command="{Binding SendMessageCommand}"></Button>
</StackLayout>
</StackLayout>
</ContentPage.Content>
</ContentPage>
view raw TravelAgentPage.xaml hosted with ❤ by GitHub
- Oh right, This how it should look like. We can now start to converse with our LUIS AI.

Wrapping Up

With Cognitive Services offering from Microsoft the possibilities are endless, with a little effort you can leverage a more natural human interaction elements to your apps. For more of this please browse here. The complete source code for this series can be found here. And we also gonna thank all who attended  "Love2Code" Session, And hoping to have more of this. If you have question or clarification just leave a comment below or you can go and shoot a message on our Xamarin Group. Original Author: 

Tags: Xamarin Forms and AI Bot Framework with LUIS



0 Comments
Login to comment.

Recent Comments

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