BinariesLid Corporate Website - ASPNET BOT Article (2024)

Creating an ASP.NET C# Bot using the Microsoft Bot Framework

This article will help you create your own ASP.NET Bot usingthe Microsoft Bot Framework. The bot main logic will be written in C# and usingVisual Studio 2015 (community edition).

Building a bot using Microsoft Bot Framework requires three mainparts:

<![if !supportLists]>1.<![endif]>Your own ConversationalBot, which is an ASP.NET web API application. You can implement your ownconversation logic using the Microsoft “Bot builder SDK(Microsoft.Bot.Builder.dll) and you can handle the conversation messaging andsecurity using the “Bot Connector libraries”.

<![if !supportLists]>2.<![endif]>MicrosoftOperated Service, which is a Microsoft hosted azure service, also known asthe Microsoft Bot Connector. It acts as an interface between your bot and variouscommunication channels. This service will forward messages from the user toyour Bot and from your bot to the user.

<![if !supportLists]>3.<![endif]>Communicationchannels: the communication channels that your user will use to communicatewith your bot; such as the web using an embedded web chat controller, SMS,email, slack, skype, GroupMe, telegram, and other communication services. Youcan configure your bot communication channels in the Azure Bot Connectorservice.

BinariesLid Corporate Website - ASPNET BOT Article (1)

<![if !vml]>BinariesLid Corporate Website - ASPNET BOT Article (2)<![endif]>

<![if !supportLists]>1.<![endif]>Download and install the visual studio 2015 Botapplication template:

<![if !supportLists]>a.<![endif]>Download the template from: http://aka.ms/bf-bc-vstemplate

<![if !supportLists]>b.<![endif]>To install the template into Visual studio allyou need to do is save the downloaded zip file into your Visual Studio 2015project template directory. The directory is usually found underdocuments\visual studio 2015\templates\ProjectTemplates\Visual C#\

<![if !supportLists]>2.<![endif]>Create a new C# bot project:

<![if !supportLists]>a.<![endif]>Restart visual studio and create a new C#project of type “Bot Application Template”

<![if !vml]>BinariesLid Corporate Website - ASPNET BOT Article (3)<![endif]>

<![if !supportLists]>b.<![endif]>Keep the default name: “Bot Application1”

<![if !supportLists]>c.<![endif]>The created project is an ASP.NET web APIproject that references the Bot connector libraries (Microsoft.Bot.Connector).

<![if !supportLists]>3.<![endif]>Write your own bot logic:

<![if !supportLists]>a.<![endif]>The created project main functionality is in theControllers\MessageController.cs class and more specifically in the following Postfunction of an api/Messages call:

<![if !vml]>BinariesLid Corporate Website - ASPNET BOT Article (4)<![endif]>

<![if !supportLists]>b.<![endif]>The MessageController defines an asynchronousmethod that accepts a Microsoft.Bot.Connector.Message object from the requestbody and returns a Microsoft.Bot.Connector.Message object.

<![if !supportLists]>i.<![endif]>The Message object Type field having the value “Message”, which refers to a simplecommunication between a user and the bot. Check the following link for theavailable message types: http://docs.botframework.com/connector/message-types/

<![if !supportLists]>ii.<![endif]>This sample code calculate the length of theuser message and call message.CreateReplyMessage(Text,[language]) to send a replytext to the user. The createReplyMessage function takes a text string propertyin “MarkDown” syntax that will be returned to the user and an optional languageproperty that takes a language code. A Text property allows the returned textto be rendered according to a set of markdowns, for example if you set the textto “Helo **Tom**” the rendered message will make Tom bold. Check the followinglink for the available Markdown elements: http://docs.botframework.com/connector/message-content/#the-text-property-is-markdown

<![if !supportLists]>c.<![endif]>The default sample function will just return atext message to the user that includes the length of the user message string.

<![if !supportLists]>4.<![endif]>To test your application you can use the BotFramework Emulator. The emulator is a separate desktop application that has anembedded chat controller and that can connect directly to your bot web APIservice (without the need for the Bot Connector service). You can use it totest your created bot API interaction.

<![if !supportLists]>a.<![endif]>Build and run your created Bot service in visualstudio, that will start IIS express and the load browser with the default url(http://localhost:3978/api/messages).

<![if !supportLists]>b.<![endif]>Download the Bot Framework Emulator applicationfrom the following link: https://aka.ms/bf-bc-emulator

<![if !supportLists]>c.<![endif]>Install the emulator application, and run it(keep the default setting for now):

<![if !vml]>BinariesLid Corporate Website - ASPNET BOT Article (5)<![endif]>

<![if !supportLists]>d.<![endif]>Write your own message in the emulator (Text boxin the bottom of the application)

<![if !supportLists]>e.<![endif]>The emulator will send a JSON API request toyour Bot API, return the Bot reply and display it in the Chat Window.

<![if !supportLists]>f.<![endif]>The emulator will display the received JSONreply in the left window

<![if !supportLists]>g.<![endif]>The emulator needs the Bot URL, the Bot app id,and the Bot Secret to communicate with your Bot API. The default bot API URL isset in the emulator as http://localhost:3978/api/messages(make sure the application port match the emulator set port), the default appid as “YourAppId”, and the default App Secret as “YourAppSecret”. Your Bot app id and app secret are stored inyour project web.config file and they are used to secure the communication withbetween the bot and the user.

<![if !vml]>BinariesLid Corporate Website - ASPNET BOT Article (6)<![endif]>

<![if !supportLists]>1.<![endif]>Install the Bot Builder SDK: To use Bot dialogswe need to install the Bot Builder SDK:

<![if !supportLists]>a.<![endif]>Right click on your newly created project andselect “Manage Nuget Packages”.

<![if !supportLists]>b.<![endif]>In the “browse” tab write“Microsoft.Bot.Builder”, click install and accept changes.

<![if !vml]>BinariesLid Corporate Website - ASPNET BOT Article (7)<![endif]>

<![if !supportLists]>2.<![endif]>Write conversational logic using Bot Builder SDKDialog Object: The dialog model is a conversational process that encapsulatesits own state in a C# class. We can use the Dialog object to writesophisticated bot logic:

<![if !supportLists]>a.<![endif]>First, add the following namespace to theControllers\MessageController.cs file:

Using Microsoft.Bot.Builder.Dialogs;

<![if !supportLists]>b.<![endif]>Next, change the MessageController Post methodto call a class that implements IDialog. We will call that class HelpDialog:

public async Task<Message> Post([FromBody]Message message)

{

if(message.Type == “Message”)

{

return await Conversation.SendAsync(message, () => new HelpDialog());

}

<![if !supportLists]>c.<![endif]>Now let us add the C# class HelpDialog in thefile Controllers\MessageController.cs:


namespace
Bot_Application1

{

[Serializable]

public class HelpDialog : Idialog<object>

{

public async Task StartAsync(IdialogContext context)

{

}


<![if !supportLineBreakNewLine]>
<![endif]>

<![if !supportLists]>i.<![endif]>HelpDialogis marked with the attribute Serializableso that the object instance of this class can participate in the runtimeserialization, which allows for all state of the dialog to be serialized peruser and per conversation and stored in IbotDataBag.

<![if !supportLists]>ii.<![endif]>HelpDialogimplements an Idialog that can call child dialogs or send messages to a user.Dialogs are suspended while waiting for message from the user and they areresumed when they receive a message from a user.

<![if !supportLists]>iii.<![endif]>StartAsync is a member function of the Idialoginterface, which takes the dialog context as parameter and return aSystem.Threading.tasks.Task that represents an asynchronous operation.StartAsync is the first function called when a dialog is started.

<![if !supportLists]>iv.<![endif]>IdialogContext is an interface that provides the services needed to save stateand communicate. It includes the following functions:

<![if !supportLists]>1. <![endif]>Call: call a child dialog and add it to the top of the stack.

<![if !supportLists]>2. <![endif]>Done: complete the current dialog and return a result to theparent dialog.

<![if !supportLists]>3. <![endif]>MakeMessage: Make a message.

<![if !supportLists]>4. <![endif]>PostAsync: Post a message to be sent to the user,

<![if !supportLists]>5. <![endif]>Wait: suspend current dialog until the user has sent a messageto the bot.

<![if !supportLists]>d. <![endif]>Next,we will add an implementation for the context.Wait function in the HelpDialog StartAsyncmethod, which will suspend the dialog until the user has sent a message to thebot and then call a method to resume the dialog when the message has beenreceived:


public async Task StartAsync(IdialogContext context)

{

context.Wait(YourFunctionForMessageReceived);

}
<![if !supportLineBreakNewLine]>
<![endif]>

<![if !supportLists]>e.<![endif]>Next we need to add some code to YourFunctionForMessageReceived:

public async TaskYourFunctionForMessageReceived(IdialogContext context, Iawaitable<Message> argument)

{

varmessage = await argument;

if(message.Text == “help”)

{

PromptDialog.Confirm(

context,

YourFunctionForHelpCommand,

“Are you sure you want todisplay help?”,

“Didn’t get that!”);

}

else

{

int length = (message.Text ?? string.Empty).Length;

await context.PostAsync($”You sent {length} characters”);

context.Wait(YourFunctionForMessageReceived);

}

}

<![if !supportLists]>i.<![endif]>This function takes the context as argument andthe user message.

<![if !supportLists]>ii.<![endif]>We check the user received message if it is equalto “help” then we will display a yes/no prompt dialog to confirm his request.

<![if !supportLists]>iii.<![endif]>Microsoft.Bot.Builder.Dialogs.PromptDialog classcontains severalclasses to prompt the user for confirmation. In this implementation we usedthe PromptDialog.Confirm class that takes as input the context, a function tobe called when the user respond to the confirmation dialog, a prompt to showthe user, and another to show the user when asking for a retry.

<![if !supportLists]>iv.<![endif]>If the user typed anything other than “help”,the bot will just display the length of the message (This is the same code that used to be in the MessageController Postfunction)

<![if !supportLists]>f.<![endif]>Lastly, we add some code toYourFunctionForHelpCommand:

public async Task YourFunctionForHelpCommand(IdialogContext context, Iawaitable<bool> argument)

{

varconfirm = await argument;

if(confirm)

{

await context.PostAsync(“I am a simple bot that will display the length of your messages! Youcan display this message by typing \”help\”!”);

}

context.Wait(YourFunctionForMessageReceived);

}
<![if !supportLineBreakNewLine]>
<![endif]>

<![if !supportLists]>i.<![endif]>This function is called when the user isprompted to confirm his help command. The function takes as argument thecontext and a Boolean argument.

<![if !supportLists]>ii.<![endif]>If the user confirmed his request, a messagewill be returned to the user using the context.PostAsync function to displaysome information.

<![if !supportLists]>iii.<![endif]>Context.Wait is called to suspend the dialoguntil the user sends a message to the bot. The resume function is specified asthe first function (YourFunctionForMessageReceived) to be called when a message isreceived from the user.

<![if !supportLists]>3.<![endif]>A sample conversational run for this code usingthe Bot Framework Emulator:

<![if !vml]>BinariesLid Corporate Website - ASPNET BOT Article (8)<![endif]>

This sample code can be found on github at: https://github.com/Binarieslid/Bot-Application1/


Do you want to have your bot on the hololens? check this link:HoloLens Development

BinariesLid Corporate Website - ASPNET BOT Article (2024)
Top Articles
Starting from One Piece: Multiverse Simulation Chapter 11 - Chapter 11: The Boy Favored by the Navy Admiral
BMF Release Date, Cast And Plot - What We Know So Far
Funny Roblox Id Codes 2023
Golden Abyss - Chapter 5 - Lunar_Angel
Www.paystubportal.com/7-11 Login
Joi Databas
DPhil Research - List of thesis titles
Shs Games 1V1 Lol
Evil Dead Rise Showtimes Near Massena Movieplex
Steamy Afternoon With Handsome Fernando
fltimes.com | Finger Lakes Times
Detroit Lions 50 50
18443168434
Newgate Honda
Zürich Stadion Letzigrund detailed interactive seating plan with seat & row numbers | Sitzplan Saalplan with Sitzplatz & Reihen Nummerierung
Grace Caroline Deepfake
978-0137606801
Nwi Arrests Lake County
Justified Official Series Trailer
London Ups Store
Committees Of Correspondence | Encyclopedia.com
Pizza Hut In Dinuba
Jinx Chapter 24: Release Date, Spoilers & Where To Read - OtakuKart
How Much You Should Be Tipping For Beauty Services - American Beauty Institute
Free Online Games on CrazyGames | Play Now!
Sizewise Stat Login
VERHUURD: Barentszstraat 12 in 'S-Gravenhage 2518 XG: Woonhuis.
Jet Ski Rental Conneaut Lake Pa
Unforeseen Drama: The Tower of Terror’s Mysterious Closure at Walt Disney World
Ups Print Store Near Me
C&T Wok Menu - Morrisville, NC Restaurant
How Taraswrld Leaks Exposed the Dark Side of TikTok Fame
University Of Michigan Paging System
Dashboard Unt
Access a Shared Resource | Computing for Arts + Sciences
Speechwire Login
Healthy Kaiserpermanente Org Sign On
Restored Republic
3473372961
Craigslist Gigs Norfolk
Moxfield Deck Builder
Senior Houses For Sale Near Me
Whitehall Preparatory And Fitness Academy Calendar
Jail View Sumter
Birmingham City Schools Clever Login
Thotsbook Com
Funkin' on the Heights
Caesars Rewards Loyalty Program Review [Previously Total Rewards]
Vci Classified Paducah
Www Pig11 Net
Ty Glass Sentenced
Latest Posts
Article information

Author: Twana Towne Ret

Last Updated:

Views: 6430

Rating: 4.3 / 5 (64 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Twana Towne Ret

Birthday: 1994-03-19

Address: Apt. 990 97439 Corwin Motorway, Port Eliseoburgh, NM 99144-2618

Phone: +5958753152963

Job: National Specialist

Hobby: Kayaking, Photography, Skydiving, Embroidery, Leather crafting, Orienteering, Cooking

Introduction: My name is Twana Towne Ret, I am a famous, talented, joyous, perfect, powerful, inquisitive, lovely person who loves writing and wants to share my knowledge and understanding with you.