Advertisements

C# Corner MVP 2018 !! 3 years of glory !! Hatrick 🏆


Hatrick !! Yes three in a row , It is a great privilege to my professional career as well a great motivation through out my upcoming years. I believe that one day each award I receive will mark my identity in the industry.I would like to extend my gratitude to my family and friends..Tadit , Sayed , Priyan , Ronen, C# Corner Team,etc are my greatest inspiration to write articles in technical community.

Thank you for all support 🙏

Three years of glory : 2015-16 , 2016-17 , 2017-18

Thank you Stratis for your awesome Tshirt & Power bank.

Fabulous Tshirts…!!

Advertisements

Cognitive Services : Analyze an Image Using Computer Vision API With ASP.Net Core & C#


Introduction

One of the important Cognitive Services API is Computer Vision API and it helps to access the advanced algorithms for processing images and returning valuable information. For example By uploading an image or specifying an image URL, Microsoft Computer Vision algorithms can analyze visual content in different ways based on inputs and user choices. So we will get various information about the given image. We need a valid subscription key for accessing this feature.

Prerequisites

  1. Subscription key ( Azure Portal ).
  2. Visual Studio 2015 or 2017

Subscription Key Free Trail

If you don’t have Microsoft Azure Subscription and want to test the Computer Vision API because it requires a valid Subscription key for processing the image information. Don’t worry !! Microsoft gives a 7 day’s trail Subscription Key ( Click here ) . We can use that Subscription key for testing purpose. If you sign up using the Computer Vision free trial, Then your subscription keys are valid for the westcentral region ( https://westcentralus.api.cognitive.microsoft.com )

Requirements

These are the major requirements mention in the Microsoft docs.

  1. Supported input methods: Raw image binary in the form of an application/octet stream or image URL.
  2. Supported image formats: JPEG, PNG, GIF, BMP.
  3. Image file size: Less than 4 MB.
  4. Image dimension: Greater than 50 x 50 pixels.

Computer Vision API

First, we need to log into the Azure Portal with our Azure credentials. Then we need to create an Azure Computer Vision Subscription Key in the Azure portal.

Click on “Create a resource” on the left side menu and it will open an “Azure Marketplace”. There, we can see the list of services. Click “AI + Machine Learning” then click on the “Computer Vision”.

Provision a Computer Vision Subscription Key

After clicking the “Computer Vision”, it will open another section. There, we need to provide the basic information about Computer Vision API.

Name : Name of the Computer Vision API.

Subscription : We can select our Azure subscription for Computer Vision API creation.

Location : We can select our location of resource group. The best thing is we can choose a location closest to our customer.

Pricing tier : Select an appropriate pricing tier for our requirement.

Resource group : We can create a new resource group or choose from an existing one.

Now click on the MenothVision in dashboard page and it will redirect to the details page of MenothVision ( “Overview” ). Here, we can see the Manage Key ( Subscription key details ) & Endpoint details. Click on the Show access keys links and it will redirect to another page.

We can use any of the Subscription key or Regenerate the given key for getting image information using Computer Vision API.

Endpoint

As we mentioned above the location is same for all the free trail Subscription Key. In Azure we can choose available locations while creating a Computer Vision API. The following Endpoint we have used in our code.

https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze

View Model

The following model will contain the API image response information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace VisionApiDemo.Models
{
public class Detail
{
public List<object> celebrities { get; set; }
}

public class Category
{
public string name { get; set; }
public double score { get; set; }
public Detail detail { get; set; }
}

public class Caption
{
public string text { get; set; }
public double confidence { get; set; }
}

public class Description
{
public List<string> tags { get; set; }
public List<Caption> captions { get; set; }
}

public class Color
{
public string dominantColorForeground { get; set; }
public string dominantColorBackground { get; set; }
public List<string> dominantColors { get; set; }
public string accentColor { get; set; }
public bool isBwImg { get; set; }
}

public class Metadata
{
public int height { get; set; }
public int width { get; set; }
public string format { get; set; }
}

public class ImageInfoViewModel
{
public List<Category> categories { get; set; }
public Description description { get; set; }
public Color color { get; set; }
public string requestId { get; set; }
public Metadata metadata { get; set; }
}
}

Request URL

We can add additional parameters or request parameters ( optional ) in our API “endPoint” and it will provide more information for the given image.

https://%5Blocation%5D.api.cognitive.microsoft.com/vision/v1.0/analyze%5B?visualFeatures%5D%5B&details%5D%5B&language%5D

Request parameters

Currently we can use 3 optional parameters.

  1. visualFeatures
  2. details
  3. language

visualFeatures

The name itself clearly mentions it returns Visual Features of the given image. If we add multiple values in a visualFeatures parameters then put a comma for each value. The following are the visualFeatures parameters in API.

  • Categories
  • Tags
  • Description
  • Faces
  • ImageType
  • Color
  • Adult

details

This parameter will return domain specific information whether it is Celebrities or Landmarks.

Celebrities : If the detected image is of a celebrity it identify the same.

Landmarks : If the detected image is of a landmark it identify the same.

language

The service will return recognition results in specified language. Default language is english.

Supported languages.

  • en – English, Default.
  • zh – Simplified Chinese

Vision API Service

The following code will process and generate image information using Computer Vision API and its response is mapped into the “ImageInfoViewModel”. We can add the valid Computer Vision API Subscription Key into the following code.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using VisionApiDemo.Models;

namespace VisionApiDemo.Business_Layer
{
public class VisionApiService
{
const string subscriptionKey = "<Enter your subscriptionKey>";
const string endPoint =
"https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze";

public async Task<ImageInfoViewModel> MakeAnalysisRequest()
{
string imageFilePath = @"C:\Users\Rajeesh.raveendran\Desktop\Rajeesh.jpg";
var errors = new List<string>();
ImageInfoViewModel responeData = new ImageInfoViewModel();
try
{
HttpClient client = new HttpClient();

// Request headers.
client.DefaultRequestHeaders.Add(
"Ocp-Apim-Subscription-Key", subscriptionKey);

// Request parameters. A third optional parameter is "details".
string requestParameters =
"visualFeatures=Categories,Description,Color";

// Assemble the URI for the REST API Call.
string uri = endPoint + "?" + requestParameters;

HttpResponseMessage response;

// Request body. Posts a locally stored JPEG image.
byte[] byteData = GetImageAsByteArray(imageFilePath);

using (ByteArrayContent content = new ByteArrayContent(byteData))
{
// This example uses content type "application/octet-stream".
// The other content types you can use are "application/json"
// and "multipart/form-data".
content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");

// Make the REST API call.
response = await client.PostAsync(uri, content);
}

// Get the JSON response.
var result = await response.Content.ReadAsStringAsync();

if (response.IsSuccessStatusCode)
{

responeData = JsonConvert.DeserializeObject<ImageInfoViewModel>(result,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Include,
Error = delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs earg)
{
errors.Add(earg.ErrorContext.Member.ToString());
earg.ErrorContext.Handled = true;
}
}
);
}

}
catch (Exception e)
{
Console.WriteLine("\n" + e.Message);
}

return responeData;
}

static byte[] GetImageAsByteArray(string imageFilePath)
{
using (FileStream fileStream =
new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
{
BinaryReader binaryReader = new BinaryReader(fileStream);
return binaryReader.ReadBytes((int)fileStream.Length);
}
}
}
}

API Response – Based on the given Image

The successful json response.

{
"categories": [
{
"name": "people_group",
"score": 0.6171875,
"detail": {
"celebrities": []
}
},
{
"name": "people_many",
"score": 0.359375,
"detail": {
"celebrities": []
}
}
],
"description": {
"tags": [
"person",
"sitting",
"indoor",
"posing",
"group",
"people",
"man",
"photo",
"woman",
"child",
"front",
"young",
"table",
"cake",
"large",
"holding",
"standing",
"bench",
"room",
"blue"
],
"captions": [
{
"text": "a group of people sitting posing for the camera",
"confidence": 0.9833507086594954
}
]
},
"color": {
"dominantColorForeground": "White",
"dominantColorBackground": "White",
"dominantColors": [
"White",
"Black",
"Red"
],
"accentColor": "AD1E3E",
"isBwImg": false
},
"requestId": "89f21ccf-cb65-4107-8620-b920a03e5f03",
"metadata": {
"height": 346,
"width": 530,
"format": "Jpeg"
}
}

Download

Output

Image information captured using Computer Vision API.For demo purpose, I have taken only a few data even though you can get more information about the image.

Reference

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Summary

From this article we have learned how to implement One of the important Cognitive Services API ( Computer Vision API ). I hope this article is useful for all Azure Cognitive Services API beginners.

Create and Connect Azure SQL database in the Azure portal


Introduction

This article explains how to create and connect Azure SQL database in the Azure portal.

SQL database

First, we need to log into the Azure Portal with our Azure credentials. Then we need to create an Azure SQL database in the Azure portal.

Click on “Create a resource” on the left side menu and it will open an “Azure Marketplace”. There, we can see the list of services. Click “Databases” then click on the “SQL Database”.

SQL database

SQL database

Create a SQL database

After clicking the “SQL Database”, it will open another section. There, we need to provide the basic information about our database like Database name, Storage Space, Server name, etc.

Database Creation

Database Creation

Database name : The valid name of our SQL Database ( We have given the Database name as “AzureSQLDB” ).

Subscription : We can select our Azure subscription for SQL Database creation.

Resource group : We can create a new resource group or choose from an existing one ( We have selected our existing resource group as “WebAppAzureSql” ).

Select source : We select Blank database ( This will create a blank database ). The following Select source categories are available in the SQL Database.

  1. Blank database – This will create a blank database.
  2. AdventureWorksLT This will generate an AdventureWorksLT sample schema.
  3. Backup : Create a new database from an existing backup.

Server

Under the server, we need to configure required settings.

  1. Server name : Any globally unique name we can give which will store our database information.
  2. Server admin login : Create our server admin name for future access.
  3. Password & Confirm Password : Create our server admin password for future access.
  4. Location : Choose an available location that will be more suitable for our requirement.

Once we enter all the “Server” details then Click on “Select”.

Pricing tier : Select an appropriate pricing tier for our requirement.

Collation : Create a name for the Collation (Collation defines the rules that sort and compare the data and cannot be changed after the database creation ).

Click on “Create” to provision the database.

Database provisioned successfully!! Go to the Dashboard and Click on the Sql Database ( “AzureSqlDB” ).

DashBoard

DashBoard

Now open the details page of SQL database ( “Overview” ). Here, we can see the Server name and other created details. We can access the SQL Database through this Server name in Azure Portal & Local MSSQL.

Create a server-level firewall rule

We need to setup a firewall rule for accessing our Azure Sql database in Azure Portal. So the SQL Database service creates a firewall at the server-level that prevents external applications and tools from connecting to the server. If we not set up any firewall rule in Azure SQL database portal, then we will get the following error.

Setup Firewall Rule

Click on the “Set server Firewall” in the Overview Section.

The “Client IP address” automatically fetched into the Firewall Setting. We just copy the IP Address and Add the START IP & END IP Section (This will add based on more than one IP address ). Set a “RULE NAME” of our Firewall. Once it’s all done then the information saves automatically into the firewall rule section.

SQL Database Login in Azure Portal

Click on the “Query editor ( preview)” and Click on the “Login” and it will display a Login portal for accessing our Azure SQL Database in Azure. So give or appropriate database credential into it. Once it’s done Click on “OK” button.

Output 1

It will open our Azure Sql Database Query Editor window with Database details.

Output 2

Accessing through our Local “Microsoft SQL Server Management Studio”.

Reference

See Also

You can download other ASP.NET Core & Azure source codes from MSDN Code, using the link, mentioned below.

Summary

In this article, we are going to create and connect Azure SQL database to the Azure portal. I hope this article is useful for all Azure beginners & experts.

Code First Migration – ASP.NET MVC 5 With EntityFrameWork & MySql


Introduction

We know how to use Code First Migration in SQL Server. But in most cases, a customer will think we can use it for the open source database. So that’s the reason we pick the “MySQL” database, and we can follow the same steps we follow in the “SQL” database. In this article, we are going to explain Code First Migration in ASP.NET MVC 5 with Entity FrameWork & MySQL.

Prerequisites

  1. MySQL Installer
  2. Download MySQL Workbench
  3. Visual Studio ( We are using Visual Studio 2017 Community Edition ).

Create a Web Application using MVC 5

Click on File -> New -> Project -> Visual C# -> Web -> ASP.Net Web Application ( .Net Framework ).

Click on “OK” then click on “MVC”.

Install EntityFramework & MySql Entity

Go to Visual Studio “Tools -> Nuget Package Manager -> Manage Nuget Packages for Solution” or Right click on your Web Application then click on “Manage Nuget Packages”.

EntityFramework

Search EntityFramework in the “Browse” Section.

MySql.Data.Entity

Search MySql.Data.Entity in the “Browse” Section.

Once we installed EntityFramework & MySql Entity in our application then it will generate a SQL and MySQL Provider inside the EntityFramework Section in Web.Config.

<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.8.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider></providers>
</entityFramework>

Model Class

We just created a sample model class for demo purpose.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebAppWithMySql.Models
{
public class Student
{
public int Id { get; set; }

public string Name { get; set; }

public string Password { get; set; }
}
}

Creation of DBContext

Create a db context class in our application. The following dbcontext will point out our connection string in WebConfig.

using MySql.Data.Entity;
using System.Data.Entity;
using WebAppWithMySql.Models;

namespace WebAppWithMySql
{
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class WebAppContext : DbContext
{
public DbSet<Student> Products
{
get;
set;
}
public WebAppContext()
//Reference the name of your connection string ( WebAppCon )
: base("WebAppCon") { }
}
}

Connection String

We added the same connection string name that we added in the dbcontext class. The following connection string represents “MySql” Db.

<connectionStrings>
<add name="WebAppCon" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;userid=root;password=rajeesh123;database=WebAppMySql;persistsecurityinfo=True" />
</connectionStrings>

Migration Steps

  1. Enable-Migrations – ( We need to enable the migration, only then can we do the EF Code First Migration ).
  2. Add-Migration IntialDb (migration name) – ( Add a migration name and run the command ).
  3. Update-Database -Verbose — if it is successful then we can see this message (Running Seed method).

Once Migration is done; then, we can see that the respective files are auto-generated under the “Migrations” folder.

OutPut

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Summary

In this article, we are going to explain Code First Migration in ASP.NET MVC 5 with EntityFrameWork & MySql. I hope this article is useful for all Azure beginners.

Channel Configuration : Azure Bot Service to Slack Application


Introduction

This article explains how to configure Azure Bot Service to Slack Applications. So, before reading this article, please read our previous article related to Create and Connect a chat bot with Azure Bot Service. Then, we will get a clear idea of how to create a Bot service in Azure.

Create a Web App Bot in Azure

Click on “New” on the left side menu and it will open an Azure Marketplace. There, we can see the list of services. Click “AI + Cognitive Services” then click on the “Web App Bot” for your bot service app.

Bot Service

Fill the following details and add the location based on your client location or your Geolocation.

Once the build is successful, click on the “Dashboard” and we can see that the “menothbotdemo” bot is created in the All resources list. Bot is ready for use!

Create a Slack Application for our bot

First, we need to create a workspace in Slack Account. Check the following link to create a Slack Account: New slack account

Create an app and assign a Development Slack team or Slack Workspace

  1. Click on the url https://api.slack.com/apps. Then, click on the “Create New App” !!.

Once the Slack workspace is created, then only we can create a slack application under the Workspace. Now, we are going to create and assign our slack app name into the Workspace. We have given our App a name as “menothbotdemo”.

Click on the “Create App” button. Then, Slack will create our app and generate a Client ID and Client Secret. We can use these IDs for channel configuration in Azure Web App bot.

Add a new Redirect URL

Click on the “OAuth & Permission” tab in the left panel. Then, add the redirect URLs as “https://slack.botframework.com&#8221; and save it properly.

Create Bot Users

Click on the “Bot Users” tab in the left panel. Then, click on “Add a Bot User”. In this section, we can give our bot “Display name”. For example, we created our bot user’s name as “menothbotdemo”. If we want our bot to always show as Online, then click on the “On” button. After that, click “Add Bot User” button.

Event Subscriptions

  1. Select “Event Subscriptions” tab in the left panel.
  2. Click Enable Events to On.
  3. In the “Request URL” we need to add the following URL to our “Bot Handle Name”.

https://slack.botframework.com/api/Events/{bot handle name}

The “Bot Handle” name we will get inside the “Web App Bot ( we created our web app as “menothbotdemo”)” Settings.

Finally, we can add the Request URL inside the Event Subscriptions.

4.  In Subscribe to Bot Events, click “Add Bot User Event”.

5. In the list of events, click “Add Bot User Event” and select the following event name.

Subscribe to Bot Events

6. Click “Save Changes”.

Configure Interactive Messages ( Optional )

  1. Select the “Interactive Components” tab and click “Enable Interactive Components”.
  2. Enter https://slack.botframework.com/api/Actions as the request URL.
  3. Click the “Enable Interactive Messages” button, and then click the “Save Changes” button.

App Credentials

Select the “Basic Information” tab and then we will get the ClientID & Client Secret & Verification Token for our channel configuration in Azure Bot Service.

Channel Configuration

There is a very simple way to connect our bot service app to Slack in Azure. Just follow the following steps.

Click on the “Channels” menu on the left side option. Then, it will open a window with channel details where you can see “More channels” options. Then, select “Slack” in the channels list.

Add the following Slack App ( Already Created Slack App ) credentials into the Azure Slack configuration section.

  • ClientID
  • Client Seceret
  • Verification Token

Once the configuration is done, we can see our Slack configured into the channel.

C# Code

We have done some changes in the default code in bot service.

using System;
using System.Threading.Tasks;

using Microsoft.Bot.Connector;
using Microsoft.Bot.Builder.Dialogs;
using System.Net.Http;

namespace Microsoft.Bot.Sample.SimpleEchoBot
{
[Serializable]
public class EchoDialog : IDialog<object>
{
protected int count = 1;

public async Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
}

public async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
var message = await argument;

if (message.Text == "reset")
{
PromptDialog.Confirm(
context,
AfterResetAsync,
"Are you sure you want to reset the count?",
"Didn't get that!",
promptStyle: PromptStyle.Auto);
}
else if (message.Text == "Hi")
{
await context.PostAsync($"{this.count++}: Slack Configured in Bot App !!");
context.Wait(MessageReceivedAsync);
}
else
{
await context.PostAsync($"{this.count++}: You said {message.Text}");
context.Wait(MessageReceivedAsync);
}
}

public async Task AfterResetAsync(IDialogContext context, IAwaitable<bool> argument)
{
var confirm = await argument;
if (confirm)
{
this.count = 1;
await context.PostAsync("Reset count.");
}
else
{
await context.PostAsync("Did not reset count.");
}
context.Wait(MessageReceivedAsync);
}

}
}

Output

Reference

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Summary

We learned how to configure Azure Bot Service to Slack application. I hope this article is useful for all Azure beginners.

Create An Intelligent Bot Application Using Microsoft Bot Framework


Introduction

In our previous article, we learned how to Create and Connect a chat bot with Azure Bot Service . In this article, we are going to create an intelligent bot application using Microsoft Bot Framework.

ngrok Software

So first we need to download ngrok software. What is ngrok ?

“ngrok” is a network tunneling software. The Bot Framework Emulator works with ngrok to communicate with bots hosted remotely. Click this link https://ngrok.com/download to download ngrok network tunneling software.

Bot Framework Emulator

The Bot Framework Emulator is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel. So we need to download Bot Framework Emulator for both local and server testing. So please go through this link to download Bot Framework Emulator click here.

After successful download please run the exe file for Bot Framework Emulator. Then first time it will open a “App Settings Window” there we need to provide the exact path of ngrok in our system ( Provide “ngrok” saved folder path in our system ).

The following screenshot “ngrok” saved into C drive Downloads folder ( C:\Users\RajeeshMenoth\Downloads\ngrok ).

Web.config

When you are connecting to remote server or anything other than local host then we need to provide the following credentials “BotId” & “MicrosoftAppId” & “MicrosoftAppPassword” in Web.Config and Bot Framework Emulator. This we will get it from azure “AppSettings” in our created Web App Bot.

<configuration>
<appSettings>
<!-- update these with your BotId, Microsoft App Id and your Microsoft App Password-->
<add key="BotId" value="YourBotId" />
<add key="MicrosoftAppId" value="" />
<add key="MicrosoftAppPassword" value="" />
</appSettings>
</configuration>

Microsoft Bot Framework In Visual Studio

Click on “File -> New -> Project -> Visual C# -> Bot Application”

Note : If the Bot Application Template is not present in the Visual Studio 2015 then please go to “Tools -> Extensions and Updates”. Then search and Install the “Bot Application” in our Visual Studio.

Code

I just changed the default code for Web App Bot. Then we added our own logic into this C# Code in Bot Application.

using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Bot.Connector;

namespace Bot_App
{
[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)
{
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
// calculate something for us to return
int length = (activity.Text ?? string.Empty).Length;
Activity reply = activity.CreateReply("");

// return our reply to the user
switch (activity.Text)
{
case "hi":
case "hello":
reply = activity.CreateReply($"{activity.Text} buddy, How may I assist you ?");
break;
case "how are you":
reply = activity.CreateReply($"Fine , What about you ?");
break;
case "Where are you ?":
reply = activity.CreateReply($"Bangalore , What about you ?");
break;
case "bye":
reply = activity.CreateReply($"Bye , Thank you !!");
break;
default:
reply = activity.CreateReply($"This is chat bot using Bot Framework !!");
break;
}

await connector.Conversations.ReplyToActivityAsync(reply);
}
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
IConversationUpdateActivity update = message;
var client = new ConnectorClient(new Uri(message.ServiceUrl), new MicrosoftAppCredentials());
if (update.MembersAdded != null && update.MembersAdded.Any())
{
foreach (var newMember in update.MembersAdded)
{
if (newMember.Id != message.Recipient.Id)
{
var reply = message.CreateReply();
reply.Text = $"Welcome {newMember.Name}!";
client.Conversations.ReplyToActivityAsync(reply);
}
}
}
}
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;
}
}

}

Localhost

Run our Bot Application in local then it will open our application with a localhost port number. So we can use this in our “Bot Framework Emulator”.

The bot endpoint like this : http://your_bots_hostname/api/messages&#8221;

Bot Endpoint

In the Bot Framework Emulator we can add our localhost or remote server “bot end point”. We can directly connect localhost port number in Bot Framework Emulator. But note that in the actual server endpoint we need to given “Microsoft App ID” and “Microsoft App Password”.

Actual endpoint of our chat bot is getting from Apps Setting ( for this we need to create a Web Chat Bot in Azure Using Bot Service ).

Application Settings

We will get all the credentials of our Web Chat Bot App ( Azure ) in Apps Setting ( for this we need to create a Web Chat Bot in Azure Using Bot Service ).

Output

Click on the “Connect” then it will trigger our Bot Application.

Summary

We learned how to Create An Intelligent Bot Application Using Microsoft Bot Framework. I hope this article is useful for all Azure chat bot beginners.

Reference

Download

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Create and Connect a chat bot with Azure Bot Service


Introduction

This article explains how to Create and Connect a chat bot with Azure Bot Service.

Azure Account

First, we need to create an account on the Azure portal. Only then can we host the application in the cloud environment. So, please check the following steps to create an Azure account.

Azure Account Registration

Create an account through this link to  click here.

Web App Bot

  1. Click on “New” on the left side menu and it will open an Azure Marketplace , there we can see list of services so click on “AI + Cognitive Services” then click on the “Web App Bot” for our bot service app.

BOT Service Registration

  1. Bot name  : The display name of our bot service and that appears in channels and directories. We can change this name at any time.
  2. Subscription : We can select our Azure subscription for chat bot service.
  3. Resource group : We can create a new resource group or choose from an existing one ( We selected our existing resource group as “AzureDemo” ).
  4. Location : We can select our location of resource group. The best thing is we can choose a location closest to our customer. The location cannot be changed once the bot is created.
  5. Pricing tier : Select a pricing tier of bot service.
  6. App name : The unique URL name of our bot service , We given “menothbot” as our App name and the URL is look like this : http://menothbot.azurewebsites.net/
  7. Bot template : There are two templates available in bot C# and Node.js. We can choose any of the template and that will create a echo bot.
  8. App service plan/Location : We can choose a best service plan that closest to our customer.
  9. Azure Storage : We can create a new data storage account or use an existing one. By default, the bot will use Table Storage.
  10. Application Insights : This will provide service-level and instrumentation data like traffic, latency, and integrations. We can switch on or off this option.

11.Click on the “Create” button and wait for the build success.

12. Once the build is succeeded, then click on the “Dashboard” and we can see “menothbot” bot is created in the All resources list . Bot is ready for use !!.

Online Code Editor

  1. Click on the “menothbot” bot in dashboard window , Then After we can see a list option available for our bot service. So click on the “Build” option in left side menu and it will open multiple option in right side. Just click on “Open online code editor” link.

2. Online code editor will open a source code window of our bot service app. So we can edit and add code in this section and currently it will display the default “echo bot” code of our bot service. Click on “WWWROOT -> Dialogs -> EchoDialog.cs”.

3. If you made any changes in the online code editor then click on the “build console” option on the left side menu and run it “build.cmd” command for the execution and deployment of the code.

Test in Web Chat

We can quickly test our bot through “Test in Web Chat” option. , So just click on the “Test in Web Chat” in the left side menu and it will open a chat bot on right side window. Here it will display few messages that we already added in the “EchoDialog.cs” in online code editor.

Code :

using System;
using System.Threading.Tasks;
using Microsoft.Bot.Connector;
using Microsoft.Bot.Builder.Dialogs;
using System.Net.Http;

namespace Microsoft.Bot.Sample.SimpleEchoBot
{
[Serializable]
public class EchoDialog : IDialog<object>
{
protected int count = 1;

public async Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
}

public async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
var message = await argument;

if (message.Text == "reset")
{
PromptDialog.Confirm(
context,
AfterResetAsync,
"Are you sure you want to reset the count?",
"Didn't get that!",
promptStyle: PromptStyle.Auto);
}
else if (message.Text == "hi")
{
await context.PostAsync($"{this.count++}: Hi , How may I assist you ?");
context.Wait(MessageReceivedAsync);
}
else if (message.Text == "how are you ?")
{
await context.PostAsync($"{this.count++}: fine , What about u ?");
context.Wait(MessageReceivedAsync);
}
else if (message.Text == "hello")
{
await context.PostAsync($"{this.count++}: Hello , Tell Me !!");
context.Wait(MessageReceivedAsync);
}
else
{
await context.PostAsync($"{this.count++}: You said {message.Text} , This is Azure Bot Service !! Thank You All !!
by
RajeeshMenoth !! ");
context.Wait(MessageReceivedAsync);
}
}

public async Task AfterResetAsync(IDialogContext context, IAwaitable<bool> argument)
{
var confirm = await argument;
if (confirm)
{
this.count = 1;
await context.PostAsync("Reset count.");
}
else
{
await context.PostAsync("Did not reset count.");
}
context.Wait(MessageReceivedAsync);
}

}
}

 Connect a bot to Web Chat

This is very simple way to connect our bot service app to Web Chat in Azure. Please check the following steps !!.

  1. Click on the “Channels” menu in the left side option. Then it will open a window with channels details there you can see edit option in “Web Chat” channel.

2. Click on the edit option in “Web Chat” channel and It will display two “Secret Keys” with Iframe code. So choose the first “Secret Key” and add it on iframe code.

iframe code

Copy paste your iframe code in your html code and add the secret key available in the web chat edit option . Then it will display the Web chat bot in your app.

<iframe src='https://webchat.botframework.com/embed/menothbot?s=YOUR_SECRET_HERE'></iframe>

Output

Reference

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Summary

We learned how to Create and Connect a chat bot with Azure Bot Service. I hope this article is useful for all Azure chat bot beginners.

 

%d bloggers like this: