Basics of Conversational UI with Telerik UI for Xamarin-870x220

Telerik UI for Xamarin now includes Conversational UI – smart controls for hooking up Xamarin apps to chatbots. This article explores the basic structure of Conversational UI components out of the box.

Back in May, the R2 2018 release of Telerik DevCraft and Kendo UI went live. This was one of our biggest and most innovative releases in the recent past. After months of development, feedback and testing, the cat was finally out of the bag - Conversational UI, a set of framework-agnostic chatbot user interface controls.

With AI and Bot Frameworks ruling the developer world, it's time to equip developers with modern polished UI to enable chatbot scenarios - for web, mobile and desktop apps. Rarely do we get to announce software feature parity across all our product lines - Conversational UI was a monumental effort and enables seamless consistent human-bot conversations across platforms.

While there are different nuances on how to use Conversational UI between .NET and JavaScript clients, the core ideas are the same. This article starts to explore how to use Conversational UI - pure components that come in the box, without any service integrations. While we shall dive into Conversational UI from a Xamarin mobile developer's perspective, the core concepts remain the same across web and desktop. Let's jump in.

Let's Get Chatty

The foundational UI component for Conversational UI in Xamarin apps is the mighty RadChat. Drop this into your Xamarin apps to light up modern conversational chatbot UI across your mobile apps for various platforms. RadChat exposes some core objects as properties - enabling developers to configure the chat experience as desired:

Author

The Author property represents the current user and the Bot who are sending messages using the Chat UI. The given instance of the Author object determines the alignment of messages – incoming messages are placed on the left, outgoing messages on the right. There are two self-explanatory properties for each Author object:

  • Name
  • Avatar

Message

The Message property defines the current message typed into the input field. Each TextMessage object has two basic properties:

  • Author
  • Text

Items

The Items collection property contains all the chat items included in the current chat conversation - this is the placeholder that keeps the entire chat conversation together. The Items collection can include simple TextMessages, but also advanced components like Pickers and Hero Cards. The Items collection is essentially an extended .NET generic class - and developers get full programmatic access to the entire chat conversation at any given time. One important event raised by the Items collection is CollectionChanged - this is the indication that the collection is changing (items added/deleted/changed) and the developer may take appropriate actions to update the chat conversational UI.

Pickers

Simple text messages in a chatbot conversation are easy to handle - the real value in Conversational UI is in complex custom UI. This is achieved through what's called Pickers - presenting the user with a selection of choices as a part of the chat conversation. If you had to choose pizza toppings, would you type them down in text, or rather simply check off a list - you get the point. In a chat conversation, it is almost always quicker to elicit user responses when presented with a collection of items to choose from.

The Conversational UI component that allows such Pickers is - the RadChatPicker. Depending on the information that is to be presented to the user and the choice that should be made, the RadChatPicker allows developers to render one of the following types:

  • DatePicker: for displaying a Calendar to choose a date
  • TimePicker: for displaying a clock view to choose a time
  • ItemPicker: for presenting a list of suggestions the end user could choose from
  • CardPicker: for presenting a list of cards with structured layout

The RadChatPicker showcases the value we can offer developers with Conversational UI; the polished sophistication through custom complex chat UI. Telerik and Kendo UI already have native Date/Time/HeroCard controls for various platform. Now, they're included as a part of chatbot conversational pickers.

Conversational Chatbot UI in Action

Something as visual as Conversational UI for chatbot integration is best shown in action, rather than just words. Let's look into the basics of RadChat and what it offers out of the box. We'll look into the more complicated pickers another day.

First, to see a chat UI in action, we need a chatbot. To simplify getting started and keeping implementation locally, let us define a RepeatBotService - this will be a local echo bot, that simply relays back what it is told. We start a vanilla Xamarin.Forms project and add this class in our shared .NET Standard library:

public class RepeatBotService
{
  private Action<string> onReceiveMessage;

  internal void AttachOnReceiveMessage(Action<string> onMessageReceived)
  {
    this.onReceiveMessage = onMessageReceived;
  }

  internal void SendToBot(string text)
  {
    Task.Delay(500).ContinueWith(t => this.onReceiveMessage?.Invoke(text));
  }
}

The code in the RepeatBotService should be self-explanatory: the bot receives messages, waits a little and spits the same message back. Our .NET Standard library and platform-specific projects need to have two references: Xamarin.Forms and Telerik UI for Xamarin. The Telerik bits, as you know, can be brought in as downloaded DLLs or simply through a NuGet package.

projectbasics

With our references in place and an XML namespace declaration, we are now ready to initiate our chatbot UI in the MainPage.XAML file - here's some simple code:

<?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:local="clr-namespace:ConversationalUIPlayground" 
             xmlns:telerikConversationalUI="clr-namespace:Telerik.XamarinForms.ConversationalUI;assembly=Telerik.XamarinForms.ConversationalUI"
             x:Class="ConversationalUIPlayground.MainPage">

  <ContentPage.Content>
    <telerikConversationalUI:RadChat x:Name="chat" 
                                     BackgroundColor="#FFF6F8FB"
                                     ItemsSource="{Binding Items}"
                                     Margin="5,30,5,30" />
  </ContentPage.Content>
</ContentPage>

Notice that we're dropping the RadChat UI component in our XAML markup with just one line of code - that's all it takes to light up a chatbot conversation UI. It is bound by the ItemSource property to the Items collection - this will hold all of the chat conversations back and forth. And yes, RadChat has full support for MVVM pattern through Commanding.

In our code-behind, let's new up a reference to our RepeatBotService and create a dummy bot Author - here's some code:

using Telerik.XamarinForms.ConversationalUI;
using Xamarin.Forms;

public partial class MainPage : ContentPage
{
  private RepeatBotService botService;
  private Author botAuthor;

  public MainPage()
  {
    InitializeComponent();

    this.botService = new RepeatBotService();
    this.botService.AttachOnReceiveMessage(this.OnBotMessageReceived);

    this.botAuthor = new Author ();
    this.botAuthor.Name = "MyBot";
    this.botAuthor.Avatar = "BotFace.jpeg";
  }
}

We're simply new'ing up our Bot as a chat Author with Name and Avatar properties defined. To be noted, for Avatar images to be picked up by the chat UI, the corresponding resources need to present in each platform-specific project, like the Resources directory for iOS apps.

botface

Also, see the OnBotMessageReceived event handler in the code above? This is raised every time our RepeatBotService receives a message from the user. When that happens, the service will relay back what the user said - we need to stick this into the ongoing chat's Item collection. The Item collection is an ObservableCollection of ChatItems - it is initialized by default with the RadChat, but you may also bind the UI to your own collection. Here's our OnBotMessageReceived event handler:

private void OnBotMessageReceived(string message)
{
  Device.BeginInvokeOnMainThread(() =>
  {
    TextMessage textMessage = new TextMessage();
    textMessage.Data = message;
    textMessage.Author = this.botAuthor;
    textMessage.Text = message;
    chat.Items.Add(textMessage);
  });
}

Next up, we need to let our chat aware anytime the Item collection changes - for obvious reasons of updating UI. Let's add the all-important CollectionChanged event, like so:

public MainPage()
{
  InitializeComponent();

  this.botService = new RepeatBotService();
  this.botService.AttachOnReceiveMessage(this.OnBotMessageReceived);

  this.botAuthor = new Author ();
  this.botAuthor.Name = "MyBot";
  this.botAuthor.Avatar = "BotFace.jpeg";

  ((INotifyCollectionChanged)this.chat.Items).CollectionChanged += ChatItems_CollectionChanged; ;
}

The Item collection raises the CollectionChanged event every time the user types something in - that's when the user's message is added to the collection. Now, in the CollectionChanged event handler, we simply send off the user's message to our RepeatBotService. Once the bot relays back our message, the OnBotMessageReceived event handler will stick the bot's message into the Item collection.

private void ChatItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
  if (e.Action == NotifyCollectionChangedAction.Add)
  {
    TextMessage chatMessage = (TextMessage)e.NewItems[0];
    if (chatMessage.Author == chat.Author)
    {
      this.botService.SendToBot(chatMessage.Text);
    }
  }
}

That's it - we have now hooked up all the pieces to have a simple conversational chatbot and its corresponding UI. Let's fire up our app, and you should see a simple clean chat interface. The user can type any message and our RepeatBotService relays the message back faithfully. And our bot's avatar shows up to add some legitimacy to our human-bot chat conversation - how cute.

repeatbot

Before the user begins typing, you may want to initiate the chat with a friendly message from the bot, like so:

chat.Items.Add(new TextMessage { Author = this.botAuthor, Text = "Welcome to our chat!" });

The point is the Item collection is the all important placeholder to hold the chat conversation. User interactions are automatically hooked up - you would have to add the bot messages. And developers have full programmatic access to the Item collection - go have fun.

programmaticmessage

Summing Up

Chatbots are all the rage these days - with major tech companies offering cloud services to empower bots across various platforms. The major draw for chatbots would be how intelligent they can get - applying Machine Learning towards better contextual awareness and to have more and more genuine conversations with humans. The cost savings of bot automations can be substantial.

As we push the envelope with chatbot technologies, however, the big stumbling block for developers is often the UI. How does one render polished UI to capture all the complexities of modern chatbot conversations? And furthermore, do it consistently for web/desktop/mobile? This is where Conversational UI components for Telerik and Kendo UI come in - polished customizable chat UI for all chatbot integration needs across platforms.

As I mentioned above, Conversational UI is built into our UI for Xamarin, as well as all our other products - feel free to try it out with a free trial of Telerik UI for Xamarin or anything else in our DevCraft bundle.

Try Telerik UI for Xamarin

Try Telerik DevCraft

We really just looked at the tip of the iceberg - the basic anatomy of Conversational UI. Lots more is possible. The real power is with smart Pickers, customizable Hero cards and service integrations. All of that follows in upcoming articles. Until then, stay chatty!


Sam Basu
About the Author

Sam Basu

Sam Basu is a technologist, author, speaker, Microsoft MVP, gadget-lover and Progress Developer Advocate for Telerik products. With a long developer background, he now spends much of his time advocating modern web/mobile/cloud development platforms on Microsoft/Telerik technology stacks. His spare times call for travel, fast cars, cricket and culinary adventures with the family. You can find him on the internet.

Related Posts

Comments

Comments are disabled in preview mode.