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, message with attachment like image, File(pdf,word,excel,ppt) , mp3, Video or more complex rich cards .



In this article, will help you to sending reply message with different type of media file attachment.

Prerequisite

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

Create New Bot Application

Let's create a new bot application using Visual Studio 2017. Open Visual Studio > Select File > Create New Project (Ctrl + Shift +N) > Select Bot application.



The Bot application template was created with all the components and all required NuGet references installed in the solutions.


Create New AttachmentDialog Class

Step 1

You can Create new AttachmentDialog class for show the attachment dialog. Right Click project > Select Add New Item > Create a class that is marked with the [Serializable] attribute (so the dialog can be serialized to state) and implement the IDialog interface.

using System;


using System.Threading.Tasks;


using Microsoft.Bot.Builder.Dialogs;


using Microsoft.Bot.Connector;


using System.IO;


using System.Web;


using System.Collections.Generic;





namespace BotAttachment.Dialogs


{


[Serializable]


public class AttachmentDialog : IDialog<object>


{



Step 2


IDialog interface has only StartAsync() method. StartAsync() is called when the dialog becomes active. The method is passed the IDialogContext object, used to manage the conversation.




public async Task StartAsync(IDialogContext context)


{


context.Wait(this.MessageReceivedAsync);


}






Step 3:


Create a MessageReceivedAsync method and write following code for welcome message and show the list of demo options dialog.
private readonly IDictionary<string, string> options = new Dictionary<string, string>


{


{ "1", "1. Attach Local-Image " },


{ "2", "2. Attach Internet Image" },


{"3" , "3. File Attachment" },


{"4" , "4. Get local PDF" },


{"5" , "5. Video Attachment" },


{"6" , "6. Youtupe video Attachment" },


{"7" , "7. MP3 Attachment" },





};


public async virtual Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)


{


var message = await result;


var welcomeMessage = context.MakeMessage();


welcomeMessage.Text = "Welcome to bot Attachment Demo";





await context.PostAsync(welcomeMessage);





await this.DisplayOptionsAsync(context);


}





public async Task DisplayOptionsAsync(IDialogContext context)


{


PromptDialog.Choice<string>(


context,


this. SelectedOptionAsync,


this.options.Keys,


"What Demo / Sample option would you like to see?",


"Please select Valid option 1 to 6",


6,


PromptStyle.PerLine,


this.options.Values);


}





public async Task SelectedOptionAsync(IDialogContext context, IAwaitable<string> argument)


{


var message = await argument;





var replyMessage = context.MakeMessage();





Attachment attachment = null;





switch (message)


{


case "1":


attachment = GetLocalAttachment();


replyMessage.Text = "Attach Image from Local Machine";


break;


case "2":


attachment = GetInternetAttachment();


replyMessage.Text = "Attach Image from Internet";


break;


case "3":


attachment = GetinternetFileAttachment();


replyMessage.Text = "Click Link for navigate PDF internet location";


break;


case "4":


attachment = GetLocalFileAttachment();


replyMessage.Text = "Click Link for navigate PDF local location";


break;


case "5":


attachment = GetinternetVideoAttachment();


replyMessage.Text = "Click on play button ";


break;


case "6":


attachment = GetinternetYoutupeAttachment();


replyMessage.Text = "Showing video from Youtupe ";


break;


case "7":


attachment = GetinternetMP3Attachment();


replyMessage.Text = "Showing MP3 from internet ";


break;





}


replyMessage.Attachments = new List<Attachment> { attachment };





await context.PostAsync(replyMessage);





await this.DisplayOptionsAsync(context);


}






After user enter the first message, bot will reply welcome message and list of demo option and waiting for user input like below





Step 4: Local Image Attachment:


The following code showing for reply message with image, to add image as an attachment to a message, create an Attachment object for the message activity and set following


ContentType


ContentUrl


Name




/// <summary>


/// dispaly local image


/// </summary>


/// <returns></returns>


private static Attachment GetLocalAttachment()


{


var imagePath = HttpContext.Current.Server.MapPath("~/images/demo.gif");





var imageData = Convert.ToBase64String(File.ReadAllBytes(imagePath));





return new Attachment


{


Name = "demo.gif",


ContentType = "image/gif",


ContentUrl = $"data:image/gif;base64,{imageData}"


};


}



After user provide inpute, Bot will reply message with local image like below





Internet Image Attachment:


The Internet image option is the simplest but requires the image to be already on the Internet and be publicly accessible. provide a content Url pointing to image url path.




/// <summary>


/// Dispaly image from internet


/// </summary>


/// <returns></returns>


private static Attachment GetInternetAttachment()


{


return new Attachment


{


Name = "architecture-resize.png",


ContentType = "image/png",


ContentUrl = "https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png"


};


}






The following output screen showing, after user provide the input, bot will fetch image from internet and display in emulator















Internet File Attachment:


You can refer following code for add hyperlink to fetch file from internet and attach to reply message, same code will be reuse for all the type of document but need to change content type and content url




/// <summary>


/// attach internet file


/// </summary>


/// <returns></returns>


public static Attachment GetinternetFileAttachment()


{


Attachment attachment = new Attachment();


attachment.ContentType = "application/pdf";


attachment.ContentUrl = "https://qconlondon.com/london-2017/system/files/presentation-slides/microsoft_bot_framework_best_practices.pdf";


attachment.Name = "Microsoft Bot Framework Best Practices";









The following output screen , after user provide input, bot will reply message with hyperlink for document, user need to click an hyperlink for open the document



Local File Attachment:


You can add pdf file into your project and add the following code for attach local pdf document in reply message




/// <summary>


/// Get local file


/// </summary>


/// <returns></returns>


public static Attachment GetLocalFileAttachment()


{


var pdfPath = HttpContext.Current.Server.MapPath("~/File/BotFramework.pdf");


Attachment attachment = new Attachment();


attachment.ContentType = "application/pdf";


attachment.ContentUrl = pdfPath;


attachment.Name = "Local Microsoft Bot Framework Best Practices";


return attachment;


}






The following output showing reply message with hyperlink for download attached pdf document





Video Attachment:


The following code showing reply message with attach video file




/// <summary>


/// Dispaly video from internet


/// </summary>


/// <returns></returns>


public static Attachment GetinternetVideoAttachment()


{





Attachment attachment = new Attachment();


attachment = new VideoCard("Build a great conversationalist", "Bot Demo Video", "Build a great conversationalist", media: new[] { new MediaUrl(@"https://bot-framework.azureedge.net/videos/skype-hero-050517-sm.mp4") }).ToAttachment();


return attachment;


}






The following output showing, after user provided input ,bot will reply message with video attachment











YouTube Video Attachment:


The following code showing replay message with attach YouTube video . you need to Provide contentype and content url in Attachment property




/// <summary>


/// Display Youtupe Video


/// </summary>


/// <returns></returns>


public static Attachment GetinternetYoutupeAttachment()


{


Attachment attachment = new Attachment();


attachment.ContentType = "video/mp4";


attachment.ContentUrl = "https://youtu.be/RaNDktMQVWI";


return attachment;


}






The following output showing, message with youtupe video attachment





MP3 File Attachment:


The following code showing, attached mp3 file in reply message, the attachment type is in the Content Type property, which should be a valid mime type is “image/mpeg3” or “audio/mp3”.







/// <summary>


/// attach internet file


/// </summary>


/// <returns></returns>


public static Attachment GetinternetMP3Attachment()


{


Attachment attachment = new Attachment();


attachment.ContentType = "audio/mpeg3";


attachment.ContentUrl = "http://video.ch9.ms/ch9/f979/40088849-aa88-45d4-93d5-6d1a6a17f979/TestingBotFramework.mp3";


attachment.Name = "Testing the Bot Framework Mp3";


return attachment;


}






The output showing reply message with attached mp3 file








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




Test Application on Bot Emulator


You can follow the below steps to test your bot application.


Open Bot Emulator.


Copy the above localhost url and paste it in emulator e.g. - http://localHost:3979


You can append the /api/messages in the above url; e.g. - http://localHost:3979/api/messages.


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 learned how to create a Bot application using Visual Studio 2017 and sending reply message with different type of media file attachment. If you have any questions/feedback/ issues, please write in the comment box.

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 a specified on a class. Bot Dialog also its more powerful but handling a conversation like a registration, ordering, its required more effort to complete process using bot dialog. 

In this article will help you to understand how to use Bot Form Flow and how you can use them to collect information from the users. We are creating sample Demo Bot for Bus booking bot.


Prerequisite:

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

Create New Bot Service:

Let’s create a new bot service application using Visual Studio 2017. Open Visual Studio > Select File on menu > Create New Project (Ctrl + Shift +N) > Select Bot application



The Bot application template was created with all the components and all required NuGet references installed in the solutions and add new class for BusFormFlow to the project.



In this Solution, we have two main class MessagesController.cs and BusFormFlow class. Let us start discussing here.

Create New FormFlow Class:

We can start create a class that represents our form and create properties for each field. Form fields can be one of the following types
  • Enum
  • List of Enum
  • Integral – sbyte, byte, short, ushort, int, uint, long, ulong
  • Floating point – float, double
  • String
  • DateTime
  • FormFlow will automatically validate type based on user input and reply the validation message.

Create a new enum field for Bus start from.

/// <summary>
/// From City Enum
/// </summary>

public enum FromCity
{
 Bangalore,Chennai,Madurai,Trichy,Coimbatore,Tanjore,pudukkottai
}

The bot output look like below



Create a new enum field for Bus end point.

/// <summary>
/// To City Enum
/// </summary>

public enum ToCity
{
Bangalore, Chennai, Madurai, Trichy, Coimbatore, Tanjore, Pudukkottai
}

The bot output look like below




Create a new enum for Bus type

/// <summary>
/// Bus Type Enum
/// </summary>

public enum BusType
{
 AC, NonAC,Slepper, Siting
}

The output look like below



Create a new enum for gender

/// <summary>
/// Gender
/// </summary>

public enum Gender
{
 Male,Female
}

The output look like below



create a class for FormFlow with the [Serializable] attribute and create build Form method for show form flow

using Microsoft.Bot.Builder.FormFlow;
using Microsoft.Bot.Builder.Dialogs;
using System;
namespace FormFlowBot.FormFlow
{
[Serializable]
public class BusFormFlow
{
/// <summary>
/// List of Form Flow
/// </summary>
public FromCity? FromAddress;
public ToCity? ToAddress;
public DateTime? StartDate;
public BusType? BusTypes;
public Gender? SelectGender;
public string Name;
public int Age;
/// <summary>
/// Build Form
/// </summary>
/// <returns></returns>
public static IForm<BusFormFlow> BuildForm()
{
return new FormBuilder<BusFormFlow>()
.Message("Welcome to the BotChat Bus Booking !")
.OnCompletion(async (context, profileForm) =>
{
string message = "Your Bus booking Successfully Completed .You will get confirmation email and SMS .Thanks for using Chat Bot Bus Booking , Welcome Again !!! :)";
await context.PostAsync(message);
})
.Build();
}
}
}

Calling Form Flow :

The Messagescontroller class added in the solution and add the following MakeRootDialog from a Messagescontroller class

internal static IDialog<BusFormFlow> MakeRootDialog()
{
return Chain.From(() => FormDialog.FromForm(BusFormFlow.BuildForm));
}
Call MakeRootDialog from post method in MessagesController calss
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
 if (activity.Type == ActivityTypes.Message)
{
 await Conversation.SendAsync(activity, MakeRootDialog);
}
else
{
HandleSystemMessage(activity);
}
 var response = Request.CreateResponse(HttpStatusCode.OK);
 return response;
}

Run Bot Application:

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



  • Test Application on Bot Emulator
  • You can follow the below steps for test your bot application.
  • Open Bot Emulator.
  • Copy the above localhost url and paste it in emulator e.g. - http://localHost:3979
  • You can append the /api/messages in the above url; e.g. - http://localHost:3979/api/messages.
  • You won't need to specify Microsoft App ID and Microsoft App Password for localhost testing, so click on "Connect".



Summary:

In this article, how to use FormFlow and how you can use them to collect information from the users. If you have any questions/ feedback/ issues, please write in the comment box.

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 prompt Dialogs that allow user to model conversations and manage conversation flow. The prompt is used whenever a bot needs input from the user. You can use prompts to ask a user for a series of inputs by chaining the prompts.

In this article will help you to understand how to use prompts and how you can use them to collect information from the users. We are creating sample Demo Bot for our c# corner Annual Conference 2018 registration process automation.



Prerequisite:

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

Create New Bot Service:

Let’s create a new bot service application using Visual Studio 2017. Open Visual Studio > Select File > Create New Project (Ctrl + Shift +N) > Select Bot application



The Bot application template was created with all the components and all required NuGet references installed in the solutions and add new annualplanDialog class to the project.



In this Solution, we have three main class MessagesController.cs , RootDialog.cs and AnnualPlanDialog class . Let us start discussing here.

RootDialog Class:

Step 1:

You can create / Edit the RootDialog class, create a class that is marked with the [Serializable] attribute (so the dialog can be serialized to state) and implement the IDialog interface.

using System;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
[Serializable]

public class RootDialog : IDialog<object>
{

}

Step 2:

IDialog interface has only StartAsync() methond. StartAsync() is called when the dialog becomes active. The method is passed the IDialogContext object, used to manage the conversation.

public async Task StartAsync(IDialogContext context)
{

}

Step 3: Design Title and Image for Welcome:

Create a method with hero card and return the attachment. The Hero card is a multipurpose card, it is having single title, subtitle, large image, button and a "tap action “. The following code added for C# Corner annual conference 2018 registration welcome message using Bot Hero card.

/// <summary>
/// Design Title with Image and About US link
/// </summary>
/// <returns></returns>

private static Attachment GetHeroCard()
{
 var heroCard = new HeroCard
{

Title = "Annual Conference 2018 Registrtion ",
Subtitle = "DELHI, 13 - 15 APRIL 2018",
Text = "The C# Corner Annual Conference 2018 is a three-day annual event for software professionals and developers. First day is exclusive for C# Corner MVPs only. The second day is open to the public, and includes presentations from many top names in the industry. The third day events are, again, exclusively for C# Corner MVPs",
Images = new List<CardImage> { new CardImage("https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiE5XHanlTvde5T3qHspW4utJ4QoVrFopi21t6uTrhmGKRUfdiBGq_06WVp2YIxyvP2MA0v8_Up2J-3-7aLpF9cTZCHxyXqMDc5dQCpxslZNbOQkrIhZ2FEhuBWF3bfNmrhRtrs2eRrTvk/h120/annuvalevent.PNG") },
Buttons = new List<CardAction> { new CardAction(ActionTypes.OpenUrl, "About US", value: "http://conference.c-sharpcorner.com/") 
}
};
return heroCard.ToAttachment();
}

Welcome banner its look like below




Step 4: Custom Prompt Dialog:

The custom prompts a dialog for asking the user to select a registration plan, which he/she is interested. Like below Design .



Define the enum for different type pass. it’s a prompt list item 

public enum AnnuvalConferencePass
{
EarlyBird,
Regular,
DelegatePass,
CareerandJobAdvice,
}
Create a method ShowAnnuvalConferenceTicket with Prompt Dialog choice like below 

public virtual async Task ShowAnnuvalConferenceTicket(IDialogContext context, IAwaitable<IMessageActivity> activity)
{
var message = await activity;
PromptDialog.Choice(
context: context,
resume: ChoiceReceivedAsync,
options: (IEnumerable<AnnuvalConferencePass>)Enum.GetValues(typeof(AnnuvalConferencePass)),
prompt: "Hi. Please Select Annuval Conference 2018 Pass :",
retry: "Selected plan not avilabel . Please try again.",
promptStyle: PromptStyle.Auto
);
}

The PropmptDialog. choice method has different parameter, you can refer below for parameter and uses
  • Context - user context message
  • Resume - its Resume handler, what next process
  • Options - list of prompt item
  • Retry - What to show on retry.
  • Attempts -The number of times to retry.
  • PromptStyle - Style of the prompt Prompt Style
  • Descriptions - Descriptions to display for choices.
  • When the user selects an option, the ChoiceReceivedAsync method will be called.
public virtual async Task ChoiceReceivedAsync(IDialogContext context, IAwaitable<AnnuvalConferencePass> activity)
{
 AnnuvalConferencePass response = await activity;
 context.Call<object>(new AnnualPlanDialog(response.ToString()), ChildDialogComplete);
}

if its bot conversation is completed, the ChildDialogComplete method will execute for show thanks message

public virtual async Task ChildDialogComplete(IDialogContext context, IAwaitable<object> response)
{
 await context.PostAsync("Thanks for select C# Corner bot for Annual Conference 2018 Registrion .");
context.Done(this);
}

Step 3:

You can wait for a message from the conversation, call context.Wait(<method name>) and pass it the method you called when the message is received. When ShowAnnuvalConferenceTicket () is called, it's passed the dialog context and an IAwaitable of type IMessageActivity. To get the message, await the result.

public async Task StartAsync(IDialogContext context)
{
//Show the title with background image and Details
 var message = context.MakeMessage();
 var attachment = GetHeroCard();
 message.Attachments.Add(attachment);
 await context.PostAsync(message);
// Show the list of plan
context.Wait(this.ShowAnnuvalConferenceTicket);
}

AnnualPlanDialog :

Create a new class file for registration prompt dialog and implement IDialog interface. In resume parameter, we can specify which dialog method to be called next after the user has responded. The response from the user is passed to the subsequent dialog methods and called to the following class.

In this class , Bot will collect all the user information one by one using prompt dialog like below

namespace BotPromptDialog.Dialogs
{
[Serializable]
public class AnnualPlanDialog : IDialog<object>
{
 string name;
 string email;
 string phone;
 string plandetails;

 public AnnualPlanDialog(string plan)
 {
 plandetails = plan;
 }

 public async Task StartAsync(IDialogContext context)
{
 await context.PostAsync("Thanks for Select "+ plandetails + " Plan , Can I Help for Registrtion ? ");
 context.Wait(MessageReceivedAsync);
}

 public virtual async Task MessageReceivedAsync(IDialogContext context,   IAwaitable<IMessageActivity> activity)
{
 var response = await activity;
 if (response.Text.ToLower().Contains("yes"))
{
 PromptDialog.Text(
 context: context,
 resume: ResumeGetName,
 prompt: "Please share your good name",
 retry: "Sorry, I didn't understand that. Please try again."
);
}
else
{
context.Done(this);
}
}

public virtual async Task ResumeGetName(IDialogContext context, IAwaitable<string> Username)
{
string response = await Username;
name = response; ;
PromptDialog.Text(
context: context,
resume: ResumeGetEmail,
prompt: "Please share your Email ID",
retry: "Sorry, I didn't understand that. Please try again."
);
}

public virtual async Task ResumeGetEmail(IDialogContext context, IAwaitable<string> UserEmail)
{
string response = await UserEmail;
email = response; ;
PromptDialog.Text(
context: context,
resume: ResumeGetPhone,
prompt: "Please share your Mobile Number",
retry: "Sorry, I didn't understand that. Please try again."
);
}

public virtual async Task ResumeGetPhone(IDialogContext context, IAwaitable<string> mobile)
{
string response = await mobile;
phone = response;
await context.PostAsync(String.Format("Hello {0} ,Congratulation :) Your C# Corner Annual Conference 2018 Registrion Successfullly completed with Name = {0} Email = {1} Mobile Number {2} . You will get Confirmation email and SMS", name, email, phone));
context.Done(this);
}
}
}

After execute above code, the output look like below



MessagesController Class :

The RootDialog class is added to the conversation in the MessageController class via the Post() method. In the Post() method, the call to Conversation.SendAsync() creates an instance of the RootDialog, adds it to the dialog stack to make it the active dialog, calling the RootDialog.StartAsync() from Post method

[BotAuthentication]
public class MessagesController : ApiController
{
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>

public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.Type == ActivityTypes.Message)
{
await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
}
else
{
HandleSystemMessage(activity);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}

private Activity HandleSystemMessage(Activity message)
{
if (message.Type == ActivityTypes.DeleteUserData)
{
// Implement user deletion here
// If we handle user deletion, return a real message
}
else if (message.Type == ActivityTypes.ConversationUpdate)
{
// Handle conversation state changes, like members being added and removed
// Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
// Not available in all channels
}
else if (message.Type == ActivityTypes.ContactRelationUpdate)
{
// Handle add/remove from contact lists
// Activity.From + Activity.Action represent what happened
}
else if (message.Type == ActivityTypes.Typing)
{
// Handle knowing tha the user is typing
}
else if (message.Type == ActivityTypes.Ping)
{

}
return null;
}
}

Run Bot Application:

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



  • Test Application on Bot Emulator
  • You can follow the below steps for test your bot application.
  • Open Bot Emulator.
  • Copy the above localhost url and paste it in emulator e.g. - http://localHost:3979
  • You can append the /api/messages in the above url; e.g. - http://localHost:3979/api/messages.
  • You won't need to specify Microsoft App ID and Microsoft App Password for localhost testing, so click on "Connect".



Summary:

In this article, how to use prompts and how you can use them to collect information from the users. If you have any questions/ feedback/ issues, please write in the comment box.

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 Dialogs, Users allow to model conversations and manage conversation flow. Dialogs can contain waterfall steps and prompts(Options). As the user interacts with the bot, the bot will start, stop, and switch between various dialogs in response based on user messages.



In this article, we will learn about the condition inside waterfall Bot Framework.

Prerequisite:

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

Create New Bot Service:

Let start create new bot service application using Visual Studio 2017. Open Visual Studio > Select File > Create New Project (Ctrl + Shift +N) > Select Bot application



The Bot application template was created with all the components and all required NuGet references installed in the solutions .



In this Solution, we have two main class MessagesController.cs and RootDialog.cs , Let we start discuss about here .

RootDialog Class:

Step 1:

You can create / Edit the RootDialog class, create a class that is marked with the [Serializable] attribute (so the dialog can be serialized to state) and implement the IDialog interface.

using System;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
[Serializable]

public class RootDialog : IDialog<object>
{

}

Step 2:

IDialog interface have only StartAsync() methond. StartAsync() is called when the dialog becomes active. The method is passed the IDialogContext object, used to manage the conversation.

public async Task StartAsync(IDialogContext context)
{

}

Step 3:

You can wait for a message from the conversation, call context.Wait(<method name>) and pass it the method you called when the message is received. When MessageReceivedAsync() is called, it's passed the dialog context and an IAwaitable of type IMessageActivity. To get the message, await the result.

[Serializable]

public class RootDialog : IDialog<object>
{
public Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
return Task.CompletedTask;
}

private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{

}
}

Step 4:

Let start edit MessageReceivedAsync method as per your requirement or create new async method. The following code is welcome message conversation dialog.

[Serializable]
public class RootDialog : IDialog<object>
{
static string username;
int count = 0;
public async Task StartAsync(IDialogContext context)
{
await context.PostAsync("Hello, I am Microsoft Bot");
context.Wait(MessageReceivedAsync);
}

private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var message = await result as Activity;
if(count >0)
username = message.Text;
if (string.IsNullOrEmpty(username))
{
await context.PostAsync("what is your good name");
count++;
}
else
{
await context.PostAsync($"Hello {username} , How may help You");
}
context.Wait(MessageReceivedAsync);
}
}

IDialogContext have following Public Member Functions
Context.Call< R > (IDialog< R > child, ResumeAfter< R > resume)
Call a child dialog and add it to the top of the stack.
Context.Done< R > (R value)
Complete the current dialog and return a result to the parent dialog.
Context .Fail (Exception error)
Fail the current dialog and return an exception to the parent dialog.
Context .Forward< R, T > (IDialog< R > child, ResumeAfter< R > resume, T item, CancellationToken token)
Call a child dialog, add it to the top of the stack and post the item to the child dialog.
Context .Post< E > (E @event, ResumeAfter< E > resume)
Post an internal event to the queue.
Context .Reset ()
Resets the stack
Context .Wait< R > (ResumeAfter< R > resume)
Suspend the current dialog until an external event has been sent to the bot.

MessagesController Class :

The RootDialog class is added to the conversation in the MessageController class via the Post() method. In the Post() method, the call to Conversation.SendAsync() creates an instance of the RootDialog, adds it to the dialog stack to make it the active dialog, calling the RootDialog.StartAsync() from Post method

[BotAuthentication]
public class MessagesController : ApiController
{
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>

public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.Type == ActivityTypes.Message)
{
await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
}
else
{
HandleSystemMessage(activity);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}

Run Bot Application:

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



  • Test Application on Bot Emulator
  • You can follow the below steps to test your bot application.
  • Open Bot Emulator.
  • Copy the above localhost url and paste it in emulator e.g. - http://localHost:3979
  • You can append the /api/messages in the above url; e.g. - http://localHost:3979/api/messages.
  • You won't need to specify Microsoft App ID and Microsoft App Password for localhost testing, so click on "Connect".


Summary:

In this article, your learned how to create a Bot application using Visual Studio 2017 with Bot dialog API. If you have any questions/ feedback/ issues, please write in the comment box.

Introduction:

Microsoft Cognitive Services awesome APIs and services for developers to create more intelligent applications. You can add more interesting feature like people emotion and video detection, facial, speech and vision recognition and speech and language understanding into our all the application. The following sample image showing for emotion and face detection using cognitive service.



In this article, you will get understand how to Create a Cognitive Services APIs account in the Azure Portal.

Prerequisites:

Create a free trial Azure subscription from Azure portal.
If you are looking paid version, Click here for detail



Create a Cognitive Services Account in Azure:
You can follow below steps for Create a Cognitive Services APIs account in the Azure Portal.

Step 1: 

Sign in to the Azure portal.

Step 2: 

Click + NEW and Select AI + Cognitive Services


Step 3:

You can see the entire list of Cognitive Services APIs. Click on the API of your choice to proceed.


Step 4: 

Select on required API and read about the API and Click on Create


Step 5: 

after click on create button, provide the following information for create cognitive service and click on create.



Name: Name of the account, Microsoft recommend a descriptive name. for example, <common name><APIName>Account.

Subscription: Select the available Azure subscriptions.

Location: Select the service locations.

Pricing tier: you can choose your pricing tier. F0 is free service and S0 paid service. based on your usage you can choose the pricing tier



Select the Resource group > confirm the Microsoft notice and Click on create for create the account

Step 6: 

wait for few second and you will get notification after complete. If Cognitive Services account is successfully deployed, click the notification to view the account information.

You can see and copy the Endpoint URL in the Overview section.



You can also copy keys in the Keys section to start making API calls in our Xamarin or other applications.


Summary:

In this article, you learned about how to Create a Cognitive Services APIs account in the Azure Portal.

We can use these keys and end point URL to the next article with app to communicate intelligent feature in Xamarin application.

If you have any questions/ feedback/ issues, please write in the comment box.

Featured Post

Improving C# Performance by Using AsSpan and Avoiding Substring

During development and everyday use, Substring is often the go-to choice for string manipulation. However, there are cases where Substring c...

MSDEVBUILD - English Channel

MSDEVBUILD - Tamil Channel

Popular Posts