Getting Started With Customizing A FormFlow Using Microsoft Bot Framework

Introduction

The Bot Framework enables you to build bots that support different types of interactions with users. You can design conversations in your bot to be freeform. Your bot can also have more guided interactions where it provides the user choices or actions. The conversation can use simple text strings or more complex rich cards that contain text, images, and action buttons. And you can add natural language interactions, which let your users interact with your bots in a natural and expressive way.

Bot Builder SDK introduced Form Flow, it will automatically generate the dialogs conversation based on your property and type that is specified on a class. Before reading this article, you can refer to my previous article for basic understanding about Form Flow

In this article, will help you to customize the forming process, change prompt text, field order and how to add condition field. We are going to edit bus booking bot and add validation and form flow attribute.

Prerequisite

 I have explained about Bot framework Installation, deployment, and implementation in the below article.

  1. Getting Started with Chatbot Using Azure Bot Service
  2. Getting Started with Bots Using Visual Studio 2017
  3. Deploying A Bot to Azure Using Visual Studio 2017
  4. How to Create ChatBot In Xamarin
  5. Getting Started with Dialog Using Microsoft Bot Framework
  6. Getting Started with Prompt Dialog Using Microsoft Bot Framework
  7. Getting Started With Conversational Forms And FormFlow Using Microsoft Bot Framework

Customize Form Flow Property Text

Prompt Text

The Form Flow provides default prompt text-based o the property name; for example, Email Property default prompt text is “Please enter email “ but Bot Framework provides feature for customizing text using prompt attribute like below.

  1. [Prompt("When you are satrting from")]  
  2. public DateTime? StartDate  

The output looks like below,

output
Enum List Item with Prompt text

The following code shows the prompt text with the list of data .You can add custom prompt text and add pattern language({&},{||} ) to dynamically populate list of data at runtime.

  • {&} will replace the replace with description of the field.
  • {||} is replaced with the list of choice in the enumeration
  1. [Prompt("You can Select {&}  {||}")]  
  2.       public FromCity? FromAddress;  
  3.       [Prompt("You can Select {&}  {||}")]  
  4.       public ToCity? ToAddress;  

The output looks like below.

output

Form Flow User Input Validation

Numeric field

The Numeric attribute is used to specify and restrict the range of allowed values for a numeric field. The following code allows a number between 1 and 5.

  1. [Numeric(1,5)]  
  2.     public int? NumberofSeat;  

If user provides the value above 5 or below 1, bot will show the validation message like below.

output

Optional Field

In the Form Flow attribute, by default, every field is required and must be filled in the form. If you specify the Optional attribute, it will select as “No preference “.

  1. [Optional]  
  2.         public string Address;  

The Optional Field type output look like below

output

Pattern field

A regular expression is an object that describes a pattern of characters. Regular expressions are used to perform pattern-matching and "search-and-replace" functions on text. You can add regular expressions into pattern attribute and validate the user input. The following code will validate user email id .

  1. [Pattern(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")]  
  2.         public string Email;  

The below output shows a user trying provide invalid email id, immediately bot will reply and ask for valid email

output

Terms

You can add the Terms attribute to match the user input. When we ask the user for gender they are presented with buttons for them to choose between Male or Female. However, they don’t have to use the buttons and can instead type their answer if they wish.  By default, if the user types their answer they must enter the choice exactly, e.g. “Male” or “Female”, but in the context of a natural conversation the user might say something like “M” or “girl”. 

  1. /// <summary>  
  2.         /// Gender  
  3.         /// </summary>  
  4. public enum Gender  
  5.         {  
  6.             [Terms("M","boy")]  
  7.              Male,  
  8.             [Terms("F","girl")]  
  9.              Female  
  10.   
  11.         }  

The Form Flow is like below and the user can select or provide terms

output

Custom message for Enum

The following code shows how to show custom item list for enum . We have attribute for describing customized enum item using Describe

  1. public enum Food  
  2.      {  
  3.          [Describe("Yes, I want South indian meal")]  
  4.          SMeal = 1,  
  5.   
  6.          [Describe("Yes, I want South North Indain meal")]  
  7.          NMeal = 2,  
  8.   
  9.          [Describe("Yes , I want Fruits")]  
  10.          Fruts = 3 ,  
  11.          [Describe("Thanks , I dont want any Food")]  
  12.          No =4  
  13.      }  

The output looks like below

output

Template Attribute

The Template attribute enables you to replace the default templates that FormFlow uses to automatically generate prompts. The following code example uses the Template attribute to redefine how the form handles enumeration fields. The attribute indicates that the user may select only one item, sets the prompt text by using pattern language, and specifies that the form should display only one item per line.

  1. [Template(TemplateUsage.NotUnderstood, "Sorry , \"{0}\" Not avilable .""Try again, I don't get \"{0}\".")]  
  2. public Food LunchFood;  

Pattern language uses curly braces ({}) to identify elements that will be replaced at runtime with actual values.  The output looks like below

output

Custom Template Error

The following code redefines the TemplateUsage.NotUnderstood template to specify two different variations of message. When the bot needs to communicate that it does not understand a user's input, it will determine message contents by randomly selecting one of the two text strings.

  1. [Template(TemplateUsage.NotUnderstood, "Sorry , \"{0}\" Not avilable .""Try again, I don't get \"{0}\".")]  
  2. public Food LunchFood;  

The output looks like below

output

Welcome, Confirmation and Form Builder

The following code example uses FormBuilder to define the steps of the form, validation, welcome message and dynamically define a field value and confirmation. By default, steps in the form will be executed in the sequence in which they are listed

  1. public static IForm<BusFormFlow> BuildForm()  
  2.         {  
  3.             return new FormBuilder<BusFormFlow>()  
  4.                     .Message("Welcome to the BotChat Bus Booking !")  
  5.                     .Field(nameof(ToAddress))  
  6.                     .Field(nameof(StartDate))  
  7.                     .Field(nameof(BusTypes))  
  8.                     .Field(nameof(NumberofSeat))  
  9.                     .Field(nameof(LunchFood))  
  10.                     .Message("Passenger Details")  
  11.                     .AddRemainingFields()  
  12.                     .Message("You will get confirmation email and SMS .Thanks for using Chat Bot Bus Booking")  
  13.                     .OnCompletion(async (context, profileForm) =>  
  14.                     {  
  15.                         string message = "Your Bus booking Successfully Completed  , Welcome Again !!! :)";  
  16.                         await context.PostAsync(message);  
  17.                     })  
  18.                     .Build();  
  19.         }  

Run Bot Application

The emulator is a desktop application that lets us test and debug our bot on localhost. Now, you can click on "Run the application" in Visual studio and execute in the browser.

output

Test Application on Bot Emulator

You can follow the below steps for testing your bot application.

  1. Open Bot Emulator.
  2. Copy the above localhost url and paste it in emulator e.g. - http://localHost:3979
  3. You can append the /api/messages in the above url; e.g. - http://localHost:3979/api/messages.
  4. You won't need to specify Microsoft App ID and Microsoft App Password for localhost testing, so click on "Connect".



Summary

In this article, you have learned about customizing the form process, changing prompt text, field order, and how to add condition field.  If you have any questions/ feedback/ issues, please write in the comment box.

Up Next
    Ebook Download
    View all
    Learn
    View all