Understanding Azure Chat bot

Posted: March 23, 2018 in Uncategorized

In the next blog posts I will go through the different components of the Azure Chat Bot and how can you benefit from it in your application.

First of all, you can consider the chatbot is like your application but with different interface. Its main target is to facilitate the workflow for your users in a conversational format. Most of the chat bot available online is to make it easier for your users to make it easy to submit a new order for your product. One of the great benefits of the chat bot is it will give your application the ability to reach your customers through different channels easily just by some configuration on your chat bot. Also the Bots are able to communicate with your users using different formats that you can define whether using text, UI, like the HeroCard, and even using speech.

In the following picture that I got from Microsoft Website to showcase the similarity between the traditional application and the bot application.

In this blog post, I will clarify the different components of the libraries that you can use to build the bot application and its workflow. So for the Microsoft Chat Bot, they have done some work decoupling the services that you will need to work with to build your bot. There are 2 main libraries that you will be using to develop the application using the .Net:

  • The Bot Connector (.Net Library)
    • This library is mainly used to connect your bot to your channels and vice versa using the REST API. The Connector then uses the Activity object to pass the information from one side to another. There are some predefined channels that you can use to develop your bot application like Skype, Twililio and others… If you don’t see the desired channel you can start by using the Direct Line API to communicate between the Bot connector and your channel.
  • The Bot Builder (.Net Library)
    • The bot builder library is mainly used to develop your bot application whether by a guided conversation (FormFlow) or by understanding your user intention for example. The Bot Builder library has different sub libraries that helps you create the convenient bot application for your users.
  • Now for the bot application state, the bot framework is providing some services for the working with your bot state In-Memory, however for production environment it is definitely recommended that you use some storage to store your chatbot state like the Azure Cosmos DB or the Azure table storage.

Talking about the storage that you can use for your bot, there are some predeveloped functions that you can use to store the details of the application. There are some Azure Extensions for the azure table storage and the azure Cosmos DB shared in the following GitHub for both .Net and Node.js

Just a quick walkthrough for the Azure Chatbot integration with the different type of storage even if it is InMemory, you can use the following code to define the what you want to implement:

//azure cosmos DB


var cosmosdb = new DocumentDbBotDataStore(uri, key, databasename, collectionname);


//azure table storage


var tablestorage = new TableBotDataStore(new CloudTable(tableuri));


//InMemory


var inmemory = new InMemoryDataStore();

 

then you can keep updating the status of the conversation with the following code, just change the cosmosdb with the desired attribute for the storage you are willing to work with:

Conversation.UpdateContainer(builder =>

{

builder.Register(c => cosmosdb)

.Keyed<IBotDataStore<BotData>>(AzureModule.Key_DataStore)

.AsSelf().SingleInstance();

});

 

Don’t forget to download the ChatBot emulator that you can use to test running your application locally.

In the following GitHub links, there are Microsoft Chatbots code that you can work with and understand how the chat bot really works with some real demos using .Net, and I am also sharing some of the work that I have done using .Net for the chatbot that I will keep updating from time to time.

Advertisements

During the last BUILD 2014, Microsoft has released few updates on Azure, one of them was the latest SDK (software development kit) for developing on it. The main new updates are mainly around the different capabilities you can do through your Visual Studio, like for example creating new Virtual Machines directly from the VS. To do so you have to open your visual Studio and open Server Explorer, you will find one the available drop downs, Windows Azure, connect to your azure account by right clicking on Windows Azure then click on “Connect to Windows Azure” and sign in easily.

If you go to Virtual Machine and you right click on it, choose “Create a Virtual Machine“, you will get a wizard, where the first step is where you can choose which Azure Subscription you will be choose. After that you will follow the normal steps like creating a Microsoft Azure Virtual Machine from the portal.

Choosing the Virtual Machine OS:

Select the Machine Settings:

Select the Cloud Service you want the VM to join:

At the end, customizing the VM Endpoints as you need:

TADA! Now you can create the Virtual Machine directly from your VS.

The second feature that was added to the SDK, is that you can directly connect to your Microsoft Azure Virtual Machines or websites to directly and easily publish the new content without the usual hassle of debugging and uploading the different content of application. You can find all the details and see the different ways to debug a VM or a Website, publish new application through this MSDN link.

I also liked a new way of sending the notification to your device applications, which you can also find in the server explorer node, under the Windows Azure, the “Notification Hub“. You can also find the link here, on how to do that.

Like the same introduction for the Microsoft Azure
CDN, maybe it will be nearly the same for the Microsoft Azure Cache. The network regulation for an IT infrastructure, a better way for sending the content for the end users. If you are dealing with basic websites or HTTP protocols, the Microsoft Azure Cache Service will be the perfect match for you.

Well yes the Microsoft Cache is still in preview, however I will go to some features that might be helpful. The Microsoft Azure Cache Service is a very useful solution for building an accelerated high scalable application, there are several ways to so, based on the MSDN page there are around 3 ways to do so, one is through the Microsoft Azure Portal, you will find the Cache Service in one of the services at the left most of the page, you just need to scroll down. Or you can do the caching service through the In-Role Caching, through your Cloud Service, whether through the WebRole or even the WorkerRole and the third way is through the Sharing Cache Service, I won’t be covering this one as it will retire soon.

So to do the Microsoft Azure Caching service through the portal you will have to go to the Portal and scroll down until you find the cache Service.

Or you can go directly to the Data Services, you will find the “Cache -> Quick Create -> Continue the configuration”

cache configuration

So as normal for the region you will have to choose the nearest place to your target customers, after that we will have few Cache offerings:

  • Basic 128MB to 1GB
  • Standard 1GB to 10GB
  • Premium 5GB to 150GB

After that you can find the cache memory and you will choose what best suits you based on the cache offering chosen.

The other way the In-Role Cache, is a way to cache your data in a previously created, running role whether it was a WebRole or a WorkerRole, you can do so simply by modifying the Role Configuration file (which is ServiceConfigurationSetting) and the Client Configuration file (which is the web.config). You can do so following the instructions from the following link. In this case you don’t need anything from the caching service on the portal just you need to know and understand the capacity planning.

A new feature of Microsoft Azure has been released on the last April 2nd, not quite a very new one, but an updated one. If you are familiar with the CDN or the content Delivery network from previous engagement with Microsoft Azure than you will be certainly aware what it is about.

The CDN stands for content Delivery network, it is like a dummy datacenter that acts only for delivering the content to the customers. With the growth of the internet usage and the also the increasing number of the Cloud Consumers, the datacenter no matter how strong was its network infrastructure cannot process all the incoming requests so what really happens is, that the Microsoft CDN is mainly used for caching the Microsoft Unstructured storage (BLOB) and the static content used by the Cloud Service
(like mentioned in the MSDN page). Their main target is to deliver the content to the target customers in an easy and more effective way. You can check the locations of the latest Microsoft Azure CDNs locations, so for example if you do have an application hosted on Microsoft Azure, you can put your data (BLOB storage) or your web role (Cloud Service) in the nearest place for your customers to better serve them.

So how to work with Microsoft Azure CDN?

First thing go to your portal and go down until you find the CDN tab

Or you can directly create it by pressing “New -> app Services -> CDN -> Quick Create”, now you create CDN based on your previously created Azure Storage account or based on a Cloud Service previously created.

PS: if you choose to create a new CDN based on your storage account, you will find the origin domain will be “accountstoragedomain.blob.core.windows.net“. If you created based on your Cloud Service, the origin domain will be “CloudService.cloudapp.net“.

After you click the create button, you will be able to see the CDN that has been created for you in few seconds. Once you open the CDN you have created you can see all the configuration that are working on your CDN, so let me get to the CDN tabs at the bottom of the page.

What I really want go through is the manage domains, you can get you own customized domains and subdomains to map the exiting CDN domains.

 

To work more on Microsoft Azure CDN and to learn more about hosting Websites on Azure CDN, kindly follow this link.

During the development of Windows Azure Mobile services I have faced some errors that I would love to share. It might help you with your development especially you might have nothing wrong in your code but with the logic.

Normally I have created the Windows Azure Mobile Services on Windows Azure with a data table let us call it mytable in this blog. I have created a class for the table in my visual studio project, I add into it the different type of properties I want to insert into the table. Like the following code:

public
class
mytable

{


public
string name { set; get; }


public
string desc { set; get; }

}

In my application code, which in my case was a Windows Phone application, I wrote the following code to insert the data into my table in the event handler of the button:

private
async
void tofa7a_Click(object sender, RoutedEventArgs e)

{


mytable at =
new
mytable();

at.name =
“abeer”;

at.desc =
“2ashta3’al l2anfokhak”;

 

 


await
App.MobileService.GetTable<mytable>().InsertAsync(at);

}

Certainly i have inserted the mobile service definition into my app.xaml.cs, to be able to consume it later on in my application. If you run the application you will get the following error:

The main reason I got this is because I didn’t define the ID property into the class that I created into my project. Let me clarify something more that you cannot change the value of the ID into your project because simply the Windows Azure mobile services increment automatically the value of the ID into your tables, so you only define the ID into your class to be able to read it, but not to insert an ID or you might face some errors.

So here is the solution of the code:

public
class
mytable

{


public
int id { set; get; }


public
string name { set; get; }


public
string desc { set; get; }

}

 

private
async
void tofa7a_Click(object sender, RoutedEventArgs e)

{


mytable at =
new
mytable();

at.name =
“abeer”;

at.desc =
“2ashta3’al l2anfokhak”;

 

 


await
App.MobileService.GetTable<mytable>().InsertAsync(at);

}

I have blogged previously on the Brokered Messaging API but in this blog I will get more deeper, with some technical examples that maybe it will help clarify how to best use the services bus brokered Messaging classes. You can also find the best practices for using the Windows Azure Service Bus Brokered Messaging in a previous blog post.

The Windows Azure Service Bus
Brokered Messaging has several main classes that are mainly used to deliver basic development for your application. You will have to use these classes:

  • BrokeredMessage: is the type of the message that will be send from an application through the service bus
  • QueueClient: is the client that you have to create to handle all the instructions when using the Windows Azure Brokered Messaging Queue
  • QueueDescription: handle all the metadata of the queue.
  • TopicClient: is the client that you have to create to handle all the instructions when using the Windows Azure Brokered Messaging Topic/Subscription.
  • TopicDescription: handle all the metadata of the topic created.
  • SubscriptionClient: is the client that you have to create to handle all the instructions for the subscriptions when working with the Windows Azure Messaging Topic/Subscription
  • SubscriptionDescription: handle all the metadata for the subscription you create.
  • NamespaceManager: is responsible for runtime of the operations of the service bus messaging entities from inserting, creating, deleting and so on.
  • MessagingFactory: is responsible for tracking, monitoring and handling the lifecycle of the message
  • MessageReciver: this is the class responsible for receiving the Brokered Message from the sender application
  • MessageSender: this is the class responsible for sending the Brokered Message from an application to another
  • MessageSession:
  • Filter: helps you filter the messages according to topics so you can easily send the brokered message to its exact target application.
  • TokenProvider: is the security token that you will need to use for initiating a new instance of messaging factory and namespace manager.

You can have a look on the Service Bus namespaces from the following 2 documents, the first one is an overview on the Microsoft.ServiceBus Namespace and the second one is the Microsoft.ServiceBus.Messaging Namespace.

Here is a simple example for starting developidng Windows Azure Service Bus Brokered Messaging, the queue using the .NET.

The following code example is for those who are interested to start developing Windows Azure Service Bus using the Node JS for both the Windows Azure Service Bus Brokered Messaging whether using queue:

//creating Windows Azure Service bus Brokered Message using queue

 

//here is a brief explanation

//the initialization is very sample

// the main three functions are, creating the queue, sending the message and receiving the message

 

var azure = require(‘azure’);

var queuename = ‘queuename’;

var queuemsg = ‘the msg you want to send through the queue’;

 

var sbclient = azure.createServiceBusService();

 

//function to create the Windows Azure Service bus Queue

function createSBQueue(){

    sbclient.createQueue(queuename, function(error){

    if(!error){

        console.log(“Queue Created”);

    }});

}

 

//function to send through the Windows Azure Service Bus Queue created

function sendQueueMsg(){

    sbclient.sendQueueMessage(queuename, queuemsg, function(error){

    if(!error){

        console.log(“Queue Message delivered”);

    }});

}

 

//function to receive from the clients through the Windows Azure Service Bus Queue Created

function receiveQueueMsg(){

    sbclient.receiveQueueMessage(queuename, function(error, message){

    if(!error){

        console.log(message.body);

    }});

}

or Topic/Subscription:

//creating Windows Azure Service bus Brokered Message using queue

 

//here is a brief explanation

//the initialization is very sample

//four functions are needed, one to create the topic, the second to create the subscription

//the third for sending the message to a subscription and the fourth to receive the message

 

var azure = require(‘azure’);

 

var topic = ‘topicname’;

var subsc = ‘subscriptionname’;

 

var msg = ‘my msg’;

 

var sbclient = azure.createServiceBusClient();

 

//function to create the topic

function createTopic(){

    sbclient.createTopic(topic, function(error){

        if(!error){

            console.log(‘Topic Created’);

        }});

}

 

//function to create the subscription

function createSub(){

    sbclient.createSubscription(subsc, function(error){

        if(!error){

            console.log(‘Subscription Created’);

        }});

}

 

//function to send a message

function sendMsg(){

    sbclient.sendTopicMessage(topic, msg, function(error){

        if(!error){

            console.log(‘Message sent’);

        }});

}

 

//function to receive a message

function receiveMsg(){

    sbclient.receiveSubscriptionMessage(topic, subsc, function(error, message){

        if(!error){

            console.log(message.body);

        }});

}

Previously I have blogged about Windows Azure Blob Storage, getting here in more details about it. The Windows Azure Blob Storage is the unstructured data, where a lot of solutions and services is based on. The Windows Azure PageBlob is another type of the Blob Storage after introducing the Windows Azure BlockBlob.

The Windows Azure PageBlob is mainly used for the pages that requires a lot input and output. For example a static page that waits a lot of incoming users to complete the form. The PageBlob is mainly designed to meet all these requirements. The Maximum size of a PageBlob is 1 TB where each page blob is up to 4MB after the user finish the writing request in the page.

You can also find the following code example for building an application using .Net and C# to start working with the Windows Azure PageBlob.

static void WriteToPageBlob(Uri blobEndpoint, string accountName, string accountKey)

{

//Create service client for credentialed access to the Blob service.

CloudBlobClient blobClient =

new CloudBlobClient(blobEndpoint, new StorageCredentialsAccountAndKey(accountName, accountKey));

// create container if it does not exist

CloudBlobContainer cloudContainer = blobClient.GetContainerReference(“mypageblobs”);

cloudContainer.CreateIfNotExist();

//Get a reference to the page blob that will be created.

CloudPageBlob pageBlob = cloudContainer.GetPageBlobReference(“apageblob”);

//Generate some data to write.

byte[] data = new byte[1024];

Random rnd = new Random();

rnd.NextBytes(data);

//Create a 100 MB page blob.

pageBlob.Create(100 * 1024 * 1024);

//Write two sets of pages. Note that you can write 4 MB per call to WritePages().

pageBlob.WritePages(new MemoryStream(data), 0);

pageBlob.WritePages(new MemoryStream(data), 4096);

//Populate the page blob’s attributes.

pageBlob.FetchAttributes();

Console.WriteLine(“Blob length = {0}”, pageBlob.Properties.Length);

//Print out the current range of pages.

PrintPageRanges(“Before write to 10240:”, pageBlob);

//Write another page.

pageBlob.WritePages(new MemoryStream(data), 10240);

//Print out the new range of pages.

PrintPageRanges(“After write to 10240:”, pageBlob);

//Clear a page.

pageBlob.ClearPages(4096, 1024);

//Print out the new range of pages.

PrintPageRanges(“After clearing page at 4096:”, pageBlob);

//Delete the page blob.

pageBlob.Delete();

}

static void PrintPageRanges(string msg, CloudPageBlob cloudBlob)

{

//Write out the page ranges for the page blob.

IEnumerable<PageRange> ranges = cloudBlob.GetPageRanges();

Console.Write(“{0}:<“, msg);

foreach (PageRange range in ranges)

{

Console.Write(” [{0}-{1}] “, range.StartOffset, range.EndOffset);

}

Console.WriteLine(“>”);

}

You can find another details about the other type of Windows Azure BlockBlob in this post.