The Bing Web Search API provides an experience similar to Bing.com/Search by returning search results that Bing determines are relevant to the user's query. The API results include Web pages, images, videos, news, and entities, along with related search queries, spelling corrections, time zones, unit conversion, translations, and calculations. The web Search API uses JSON format for data exchange, and API Keys for authentication.



In this article, I will show how to generate Bing Search subscription key and integrate into the Xamarin application.

Register Bing Search in Azure Portal:

You need to create an Azure account and generate subscription key for implementation to the Xamarin Mobile application.

Step 1: 

 Sign in to Azure portal .

Step 2: 

Create On “+ Create a resource “> Under Azure Marketplace, select AI + Cognitive Services and discover the list of available APIs. > Select “ Bing Search v7 APIs”


Step 3: 

on the create page, Provide the name, pricing, resource group a click on Create


Step 4: 

 wait for few seconds, After the Cognitive Services account is successfully deployed, click the notification or tile in the dashboard to view the account information. You can copy the Endpoint URL in the Overview section and keys in the Keys section to start making API calls in our Xamarin applications.


Create Bing Web Search Xamarin Application:

Let's start with creating a new Xamarin Forms Project using Visual Studio. Open Run >> Type “Devenev.Exe” and enter >> New Project (Ctrl+Shift+N) >> select Blank Xaml App (Xamarin.Forms) template.


It will automatically create multiple projects, like .NET Standard, Android, iOS, and UWP.

Install Newtonsoft.Json :

Bing Web Search API will return Json object value so make sure you have added the Newtonsoft JSON NuGet Package to your all project. Right Click on Solution > Manage Nuget Package > Install Newtonsoft Json


Install Microsoft.Csharp :

This steps is optional, if you get Error "Microsoft.CSharp.RuntimeBinder.Binder.Convert" not found by the compiler for dynamic type so adding a reference as Microsoft.CSharp to the Dotnet Standard /PCL project , issue will get resolve .


Design View:

After successfully install above two nuget package. Let start design UI design from Dot Standard /PCL project. In PCL Project > Open MainPage.Xaml page and add design Entry and list view control with item template in Xaml

<?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:XamarinBingWebSearch"
:Class="XamarinBingWebSearch.MainPage">
<ContentPage.Content>
<StackLayout>
<Label Text="Search" ></Label>
<Entry x:Name="entrysearch" Placeholder="Type Your text" TextChanged="OnTextChangesEvent" />
<ListView x:Name="lstwebsearch" BackgroundColor="Azure">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Vertical">
<Label Text="{Binding Snippet}">
</Label>
<Label Text="{Binding DisplayUrl}">
</Label>
<Label Text="{Binding Name}" TextColor="Gray"></Label>
<Label Text="{Binding Url}" TextColor="Gray"></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>

Bing web search will return ID ,Name, URL ,Snippet and DispalyUrl so create model class for web search .

namespace XamarinBingWebSearch.Model
{
public class WebSearch
{
public string Id { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Snippet { get; set; }
public string DisplayUrl { get; set; }
}
}

Configure the project:

We need to get web search result so send a GET request to the following endpoint and replace subscription key from Mainpage.xaml.cs
private string WebSearchEndPoint = "https://api.cognitive.microsoft.com/bing/v7.0/search?";
public HttpClient WebSearchClient
{
get;
set;
}
public MainPage()
{
InitializeComponent();
WebSearchClient = new HttpClient();
WebSearchClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "YOUR API KEY");
}

Get and Parse Json Data:

HttpClient class provides a base class for get/Post the HTTP requests/responses from a URL. It is a supported async feature of .NET framework. HttpClient is able to process multiple concurrent requests. The following code showing get all Json data using Bing web Search API url and Parse the json and binding into the list view for display search result

private async void OnTextChangesEvent(object sender, TextChangedEventArgs e)
{
try
{
if (entrysearch != null)
lstwebsearch.ItemsSource = await SearchBingWeb(entrysearch.Text);
}
catch (Exception)
{

}

}
async Task<IEnumerable<WebSearch>> SearchBingWeb(string searchText)
{
List<WebSearch> websearch = new List<WebSearch>();
string count = "10";
string offset = "0";
string mkt = "en-us";
var result = await RequestAndAutoRetryWhenThrottled(() => WebSearchClient.GetAsync(string.Format("{0}q={1}&count={2}&offset={3}&mkt={4}", WebSearchEndPoint, WebUtility.UrlEncode(searchText), count, offset, mkt)));
result.EnsureSuccessStatusCode();
var json = await result.Content.ReadAsStringAsync();
dynamic data = JObject.Parse(json);
for (int i = 0; i < 10; i++)
{
websearch.Add(new WebSearch
{
Id = data.webPages.value[i].id,
Name = data.webPages.value[i].name,
Url = data.webPages.value[i].url,
Snippet = data.webPages.value[i].snippet,
DisplayUrl = data.webPages.value[i].displayUrl
});
}
return websearch;
}
private async Task<HttpResponseMessage> RequestAndAutoRetryWhenThrottled(Func<Task<HttpResponseMessage>> action)
{
int retriesLeft = 6;
int delay = 500;
HttpResponseMessage response = null;
while (true)
{
response = await action();
if ((int)response.StatusCode == 429 && retriesLeft > 0)
{
await Task.Delay(delay);
retriesLeft--;
delay *= 2;
continue;
}
else
{
break;
}
}
return response;
}

Run the Application:

We have completed the coding now start run the application so you can select the platform iOS,Android , Windows and Click on Run (f5) the application .



You can find the source code at C# Corner attachment and Github XamarinBingWebSearch repository as Microsoft-Cognitive-Service.



Summary

In this article, you learned about how to generate Bing search subscription key and integrate into the Bing web search Xamarin application. If you have any questions/ feedback/ issues, please write in the comment box.


Introduction:

The Azure AD is the identity provider, responsible for verifying the identity of users and applications and providing security tokens upon successful authentication of those users and applications.in this article I have explained about create Azure AD authentication and integrate into bot application using AuthBot library.



The Bot show very simple dialog with openUrl button and this button launches the web browser for validate user credential and AD will response the message with authentication code, you can copy same code and reply back to the bot, bot will validation and response the welcome message.

You can follow below given steps one by one and you will get to see an interesting demo at end of article.

Azure AD App registration:

I will show the steps given below for the azure application creation, user creation and permission configuration. While implementing bot application, We need Client ID, tenant, return URL, so here I will show how to get all the configuration information from the steps given below.

Step 1:

 Login to Microsoft Azure portal and choose Azure Active Directory from the sidebar.

Step 2:

 If you have not created AZURE Active directory, try to create new AD creation for tenant url or Select or add tenant url from Domain names sections



Step 3: 

Select Application Registration and Provide the details given below, name for the application , application type must be Web app/API, enter your application redirect URL and click on Create.



Step 4: 

We need to give the permission to access the application from Bot, so grand the permission. Select newly created Application > select Required Permission > Click Grand permission.

Step 5:

 create new user from users and groups sections (optional)

Step 6: 

Create client secret key from Application. Select Application > Select keys > add new / copy client secret key .


Step 4:

 You can copy tenant, client ID and Client Secret and you can follow below steps for create and implement AD authentication in Bot

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 gets created with all the components and all required NuGet references installed in the solutions.


Install AuthBot Nuget Package:

The AuthBot provide Azure Active Directory authentication library for implement Azure AD login in Bot .
Right click on Solution, select Manage NuGet Package for Solution > Search “ AuthBot” > select Project and install the package.



You can follow given below steps for integrate AD authentication

Step 1: 

Select Web.config file and add Mode,resourceID,Endpointurl ,Tenant,clientID,clientSecret and redirect url appsettings property and replace Azure AD details as per below
<appSettings>
<add key="BotId" value="YourBotId" />
<add key="MicrosoftAppId" value="" />
<add key="MicrosoftAppPassword" value="" />
<add key="ActiveDirectory.Mode" value="v1" />
<add key="ActiveDirectory.ResourceId" value="https://graph.windows.net/" />
<add key="ActiveDirectory.EndpointUrl" value="https://login.microsoftonline.com" />
<add key="ActiveDirectory.Tenant" value="dxdemos.net" />
<add key="ActiveDirectory.ClientId" value="2d3b5788-05a5-486d-b2a4-2772a4511396" />
<add key="ActiveDirectory.ClientSecret" value="wU3oFBJ1gjWcB8Lo/fMaaCwg7ygg8Y9zBJlUq+0yBN0=" />
<add key="ActiveDirectory.RedirectUrl" value="http://localhost:3979/api/OAuthCallback" />
</appSettings>

Step 2:

 Select Global.asax.cs file and call all the bot app setting property and assign to AuthBot model class, like below
using System.Configuration;
using System.Web.Http;
namespace DevAuthBot
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
AuthBot.Models.AuthSettings.Mode = ConfigurationManager.AppSettings["ActiveDirectory.Mode"];
AuthBot.Models.AuthSettings.EndpointUrl = ConfigurationManager.AppSettings["ActiveDirectory.EndpointUrl"];
AuthBot.Models.AuthSettings.Tenant = ConfigurationManager.AppSettings["ActiveDirectory.Tenant"];
AuthBot.Models.AuthSettings.RedirectUrl = ConfigurationManager.AppSettings["ActiveDirectory.RedirectUrl"];
AuthBot.Models.AuthSettings.ClientId = ConfigurationManager.AppSettings["ActiveDirectory.ClientId"];
AuthBot.Models.AuthSettings.ClientSecret = ConfigurationManager.AppSettings["ActiveDirectory.ClientSecret"];
}
}
}

Step 3: 

You can create a new AzureADDialog class to show the default login and logout UI Design dialog. Rightclick on 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 AuthBot;
using AuthBot.Dialogs;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using System;
using System.Configuration;
using System.Threading;
using System.Threading.Tasks;
namespace DevAuthBot.Dialogs
{
[Serializable]
public class AzureADDialog : IDialog<string>
{

Step 4 :

IDialog interface has only StartAsync() method. StartAsync() is called when the dialog becomes active. The method passes the IDialogContext object, used to manage the conversation.
public async Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
}

Step 5:

 Create a MessageReceivedAsync method and write the following code for the login and logout default dialog and create a ResumeAfterAuth for after the user login, bot will reply the user name and email id details.
///
/// Login and Logout
///
/// context">
/// item">
///
public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> item)
{
var message = await item;
//endpoint v1
if (string.IsNullOrEmpty(await context.GetAccessToken(ConfigurationManager.AppSettings["ActiveDirectory.ResourceId"])))
{
//Navigate to website for Login
await context.Forward(new AzureAuthDialog(ConfigurationManager.AppSettings["ActiveDirectory.ResourceId"]), this.ResumeAfterAuth, message, CancellationToken.None);
}
else
{
//Logout
await context.Logout();
context.Wait(MessageReceivedAsync);
}
}
///
/// ResumeAfterAuth
///
/// context">
/// result">
///
private async Task ResumeAfterAuth(IDialogContext context, IAwaitable<string> result)
{
//AD resposnse message
var message = await result;
await context.PostAsync(message);
context.Wait(MessageReceivedAsync);
}
After the user enters the first message, our bot will reply and ask to login to the AD. Then, it waits for Authentication code and bot will reply the user details as a response like below.


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".


Related Article:

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

Summary

In this article, you learned how to create a Bot Azure AD login authentication and Logout using AuthBot. If you have any questions/feedback/ issues, please write in the comment box.




The Bot Framework has supports different type of rich cards and provides a richer interaction experience to the user. In this article, I will show how to integrate Receipt card UI design in a Bot Application. If you are developing as shopping card Bot chat application; receipt card is very important one. Receipt card class having property as list of items, total, tax, vat, title and image. We can re-use all receipt card property and add tab action event for navigating to original invoice website.


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 gets created with all the components and all required NuGet references installed in the solutions.


Create New ReceiptCardCardDialog Class:

Step 1:

You can Create new ReceiptCardDialog class for a show the receiptCard dialog. Right Click on 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 Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace BotReceiptCard.Dialogs
{
[Serializable]
public class ReceiptCardDialog : IDialog<object>
{

Step 2

IDialog interface has only StartAsync() method. StartAsync() is called when the dialog becomes active. The method is passes 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 the welcome message and show the list of demo options dialog.

///
/// MessageReceivedAsync
///

/// context">
/// result">
///

public async virtual Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
var message = await result;
var welcomeMessage = context.MakeMessage();
welcomeMessage.Text = "Your Invoice Details below , if you requred detail click on 'Request Email' Options ";

await context.PostAsync(welcomeMessage);
await this.DisplayThumbnailCard(context);
}

///
/// DisplayReceiptCard
///
/// context">
///
public async Task DisplayReceiptCard(IDialogContext context)
{
var replyMessage = context.MakeMessage();
Attachment attachment = getBotReceiptCard(); ;
replyMessage.Attachments = new List<Attachment> { attachment };
await context.PostAsync(replyMessage);
}

After user enter the first message, bot will reply welcome message like below


Step 4: Design Receipt Card:

The Receipt card enables a bot to provide a receipt to the user. It typically contains the list of items to include on the receipt, tax and total ,vat and title text.
Title - Title text of the card
Facts – Fact is set of key-value pairs and rendered with default style so developer no need to specify style
ReceiptItems –Receipt Items has list of item title, image, prize, Quantity, subtitle, text and tab navigation for every single item.
Tab – tab provide navigate to different screen or actions
Tax – assign tax amount into tax property.
Vat – assign vat amount into vat property.
Total – calculate and assign total amount into total property
Card Actions – add list of actions in the receipt card and also action card has image, title, type and value property.
The following code showing design the online shopping receipt card design with image, text, Facts, tab,vat,total and action button. .
///
/// getBotReceiptCard
///
/// 

private static Attachment getBotReceiptCard()
{
var receiptCard = new ReceiptCard
{
Title = "Online Shopping",
Facts = new List<Fact> { new Fact("Name:","Nikhil"),
new Fact("Address:","Bangalore"),
new Fact("------------------------",""),
new Fact("Phone :97420XXXX2",""),
new Fact("Email:jssXXXXX@gmail.com",""),
new Fact("Order Number:97421",""),
new Fact("Payment Method : Master 5555-****", ""),
new Fact("------------------------","")
},
Items = new List<ReceiptItem>
{

new ReceiptItem("Hit Refresh",subtitle:"by Satya Nadella (Author)",text:"Kindle Edition", price: "278.31", quantity: "1", image: new CardImage(url: "https://images-eu.ssl-images-amazon.com/images/I/41eAfVuUzeL.jpg"),tap: new CardAction("Read More")),

new ReceiptItem("XamarinQA",subtitle:"by Suthahar J (Author)",text:"Kindle Edition", price: "116.82", quantity: "1", image: new CardImage(url: "https://images-eu.ssl-images-amazon.com/images/I/51z6GXy3FSL.jpg"),tap: new CardAction("Read More")),

new ReceiptItem("Surface Pro 4",subtitle:"Core i5 - 6th Gen/4GB/128GB/Windows 10 Pro/Integrated Graphics/31.242 Centimeter Full HD Display", price: "66,500", quantity: "1", image: new CardImage(url: "https://images-na.ssl-images-amazon.com/images/I/41egJVu%2Bc0L.jpg"),tap: new CardAction("Read More")),

new ReceiptItem("Windows 10 pro",subtitle:"by Microsoft", price: "13,846", quantity: "1", image: new CardImage(url: "https://images-na.ssl-images-amazon.com/images/I/7176wliQYsL._SL1500_.jpg"),tap: new CardAction("Read More"))
},

Tax = "2000",
Total = "82,741.13",
Tap =new CardAction(ActionTypes.OpenUrl,value: "https://www.microsoft.com/en-in/store/b/home?SilentAuth=1&wa=wsignin1.0"),
Buttons = new List<CardAction>
{
new CardAction(
ActionTypes.OpenUrl,
"Request Email",
"https://assets.onestore.ms/cdnfiles/external/uhf/long/9a49a7e9d8e881327e81b9eb43dabc01de70a9bb/images/microsoft-gray.png",
"mailto:jssuthahar@gmail.com?subject=Order%20Number:97421&body=Hi%team,%20I%need%20Invoice")
}
};
return receiptCard.ToAttachment();
}

The above code will generate receipt card and reply to the user like below


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 create receipt card design using bot framework. If you have any questions/feedback/ issues, please write in the comment box.

Introduction:

The Bot Framework has supported the different type of rich cards and provides a richer interaction experience to the user. In this article, I will share about how to integrate Thumbnail card UI design in Bot Application. The Thumbnail card is a multipurpose card, its contains small an image, title text, sub text, multiple buttons, and a card tap action.

A Hero Card and a Thumbnail Card have different in the size of image and text alignment of card.


Prerequisite:

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

Download Source:


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 ThumbnailCardDialog Class:

Step 1:

You can Create new ThumbnailCardDialog class for a show the ThumbnailCard dialog. Right Click on 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 Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace BotThumbnailCard.Dialogs
{
[Serializable]


public class ThumbnailCardDialog : 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 the welcome message and show the list of demo options dialog.

///
/// MessageReceivedAsync
///
/// context">
/// result">
///
public async virtual Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
var message = await result;
var welcomeMessage = context.MakeMessage();
welcomeMessage.Text = "Welcome to bot Thumbnail Card Demo";
await context.PostAsync(welcomeMessage);
await this.DisplayThumbnailCard(context);
}
///
/// DisplayThumbnailCard
///
/// context">
///

public async Task DisplayThumbnailCard(IDialogContext context)
{
var replyMessage = context.MakeMessage();
Attachment attachment = GetProfileThumbnailCard(); ;
replyMessage.Attachments = new List<Attachment> { attachment };
await context.PostAsync(replyMessage);
}

After user enter the first message, bot will reply welcome message like below


Step 4: Design Thumbnail Card:

The Thumbnail card typically contains a small image with left alignment, one or more buttons, and text. Thumbnail Card class has the following property

Title - Title text of the card

Subtitle -sub title text for the title

Text – Summary text to display on the card

Images – Display small image with left alignment

Buttons - One or more buttons. The Skype allow only 5 buttons will display on a card. If you have more buttons, you can create two cards.

Tap - An action that is triggered when a user taps on the card.

The following code showing design the user profile message with image, text, subtext and action button. .

///
/// GetProfileThumbnailCard
///
///
private static Attachment GetProfileThumbnailCard()
{
var thumbnailCard = new ThumbnailCard
{
// title of the card
Title = "Suthahar Jegatheesan",
//subtitle of the card
Subtitle = "Microsoft certified solution developer",
// navigate to page , while tab on card

Tap = new CardAction(ActionTypes.OpenUrl, "Learn More", value: "http://www.devenvexe.com"),
//Detail Text

Text = "Suthahar J is a Technical Lead and C# Corner MVP. He has extensive 10+ years of experience working on different technologies, mostly in Microsoft space. His focus areas are Xamarin Cross Mobile Development ,UWP, SharePoint, Azure,Windows Mobile , Web , AI and Architecture. He writes about technology at his popular blog http://devenvexe.com",

// smallThumbnailCard Image

Images = new List<CardImage> { new CardImage("http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/AuthorImage/jssuthahar20170821011237.jpg") },

// list of buttons

Buttons = new List<CardAction> { new CardAction(ActionTypes.OpenUrl, "Learn More", value: "http://www.devenvexe.com"), new CardAction(ActionTypes.OpenUrl, "C# Corner", value: "http://www.c-sharpcorner.com/members/suthahar-j"), new CardAction(ActionTypes.OpenUrl, "MSDN", value: "https://social.msdn.microsoft.com/profile/j%20suthahar/") }
};

return thumbnailCard.ToAttachment();
}

The above code will generate thumbnail card and reply to the user


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 create Thumbnail card design using bot framework. If you have any questions/feedback/ issues, please write in the comment box.
The Bot Framework has supported the different type of rich cards and provides a richer interaction experience to the user. In this article, I will share about how to integrate Hero card UI design in Bot Application. The Hero card is a multipurpose card, its contains large a image, title text, sub text, multiple buttons, and a card tap action.

Prerequisite:

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

Download Demo Code :


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 HeroCardDialog Class:

Step 1:

You can Create new HeroCardDialog class for a show the HeroCard dialog. Right Click on 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 Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace BotHeroCard.Dialogs
{
[Serializable]
public class HeroCardDialog : 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 the welcome message and show the list of demo options dialog.

///
/// MessageReceivedAsync
///
/// context">
/// result">
///

public async virtual Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
var message = await result;
var welcomeMessage = context.MakeMessage();
welcomeMessage.Text = "Welcome to bot Hero Card Demo";
await context.PostAsync(welcomeMessage);
await this.DisplayHeroCard(context);
}
///
///
///
/// context">
///

public async Task DisplayHeroCard(IDialogContext context)
{
var replyMessage = context.MakeMessage();
Attachment attachment = GetProfileHeroCard(); ;
replyMessage.Attachments = new List<Attachment> { attachment };
await context.PostAsync(replyMessage);
}

After user enter the first message, bot will reply welcome message like below


Step 4: Design Hero Card:

The Hero card typically contains a large image, one or more buttons, and text. Hero Card class has the following property

Title - Title text of the card

Subtitle -sub title text for the title

Text – Summary text to display on the card

Images – Display large image

Buttons - One or more buttons. The Skype allow only 5 buttons will display on a card. If you have more buttons, you can create two cards.

Tap - An action that is triggered when a user taps on the card.

The following code showing design the user profile message with image, text, subtext and action button. .

private static Attachment GetProfileHeroCard()
{
var heroCard = new HeroCard
{
// title of the card
Title = "Suthahar Jegatheesan",
//subtitle of the card
Subtitle = "Microsoft certified solution developer",
// navigate to page , while tab on card
Tap = new CardAction(ActionTypes.OpenUrl, "Learn More", value: "http://www.devenvexe.com"),
//Detail Text

Text = "Suthahar J is a Technical Lead and C# Corner MVP. He has extensive 10+ years of experience working on different technologies, mostly in Microsoft space. His focus areas are Xamarin Cross Mobile Development ,UWP, SharePoint, Azure,Windows Mobile , Web , AI and Architecture. He writes about technology at his popular blog http://devenvexe.com",

// list of Large Image

Images = new List<CardImage> { new CardImage("http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/AuthorImage/jssuthahar20170821011237.jpg") },

// list of buttons

Buttons = new List<CardAction> { new CardAction(ActionTypes.OpenUrl, "Learn More", value: "http://www.devenvexe.com") , new CardAction(ActionTypes.OpenUrl, "C# Corner", value: "http://www.c-sharpcorner.com/members/suthahar-j"), new CardAction(ActionTypes.OpenUrl, "MSDN", value: "https://social.msdn.microsoft.com/profile/j%20suthahar/") }
};

return heroCard.ToAttachment();
}

The above code will generate hero card and reply to the user


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 create hero card design using bot framework. 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, the message with an attachment like the image, File (pdf, word, excel, ppt), mp3, Video or more complex rich cards.



In this article, will help you to send a reply message with the 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 the 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. Youtube 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 = GetinternetYoutubeAttachment();
replyMessage.Text = "Showing video from Youtube ";
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 wait 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
///
/// dispaly local image
///
///
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 provides 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. provides a content Url pointing to image url path.

///
/// Dispaly image from internet
///
///

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 provides 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

///
/// attach internet file
///
///
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 provides input, bot will reply message with hyperlink for document, user need to click a 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

///
/// Get local file
///
/// 

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

///
/// Dispaly video from internet
///
///
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 provides input ,bot will reply message with video attachment


YouTube Video Attachment:

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

///
/// Display Youtube Video
///
///

public static Attachment GetinternetYoutubeAttachment()
{
Attachment attachment = new Attachment();
attachment.ContentType = "video/mp4";
attachment.ContentUrl = "https://youtu.be/RaNDktMQVWI";
return attachment;
}

The following output showing, message with youtube video attachment


MP3 File Attachment:

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

///
/// attach internet file
///
///

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 a reply message with the different type of media file attachment. 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