Introduction

Azure AD is cloud-based identity and access management service, which helps employees to sign in and access company resources such as Microsoft 365, the Azure portal, and thousands of other SaaS applications. AZURE AD will provide different below feature
  1. Employee admin can enable Azure AD to require multi-factor authentication when accessing important organizational resources. you can use Azure AD to automate user provisioning between your existing Windows Server AD and your cloud apps, including Microsoft 365.
  2. Company has any enterprise application which provide related company information, timesheet app, employee inventory management app like that company can develop any application which allow only company users to access using Azure AD as a standards-based approach for adding single sign-on (SSO) and allowing it to work with a user's pre-existing credentials and no need add any other registration or login screen for your application.

Azure Active Directory(AD) with Custom domain

Create new tenant

  1. Login to personal / organization Azure portal https://portal.azure.com
  2. Create new Resource menu having “Azure Active Directory” as like below and click on Azure Active Directory





On Create a tenant page, click on “create active directory



On the create a tenant confirmation as information below
  1. Organization name - you can provide here as your organization name
  2. Initial domain name – provide here as your initial domain name
  3. Country/ Region – provide your county name.

Azure Active Directory(AD) with Custom domain

You will get new screen for review and confirmation tenant creation, after validation you will get initial domain as like this <your domain name>.onmicrosoft.com, example MSDEVJS.onmicrosoft.com


Azure Active Directory(AD) with Custom domain

Tenant creation is in progress and it will take a few minutes for get confirmation

Azure Active Directory(AD) with Custom domain

Your new tenant is created with the domain MSDEVJS.onmicrosoft.com.

Setup Custom Domain Name

You have successfully created new Azure AD tenant with default Microsoft sub domain, you can’t change Microsoft default sub domain, but you add you company custom domain, it will help you to create email and access Microsoft app with your domain name.

Step 1: Select option as a Custom Domain

Step 2: Click on Add custom domain in menu options


Azure Active Directory(AD) with Custom domain

In Custom domain name, enter your organization's new name, in this example, devenvexe.com. Select Add domain

Azure Active Directory(AD) with Custom domain

You must add universal domain extension like .in, .com, etc . devenvexe.com page appears showing your DNS information. Save this information. You need provide a TXT or MX record to configure DNS.

Azure Active Directory(AD) with Custom domain

After you add your custom domain name to Azure AD, you must return to your domain registrar provider and add the Azure AD DNS information from your copied TXT file. Creating this TXT record for your domain verifies ownership of your domain name.

Go back to your domain registrar and we have register domain in big rock and create a new TXT record for your domain based on your copied DNS information. Set the time to live (TTL) to 3600 seconds (60 minutes), and then add the record.

Azure Active Directory(AD) with Custom domain

After you add your custom domain name, make sure it is valid in Azure AD. The domain registrar to Azure AD can be taking a few days, depending on your domain registrar.

Summary


In this article, you learned about, Create a new tenant with Custom domain in Azure Active Directory. If you have any questions/ feedback/ issues, please write in the comment box.
Introduction
Microsoft Azure services are available in 53 regions around the world, with plans announced for 7 additional regions and 140+ available country. Select Azure region is more important to setup the cloud environment, this gives you the flexibility to bring applications closer to your users no matter where they are. It also provides better scalability, redundancy, and preserves data residency for your services.
Understanding about Azure Region, Geographies, Availability Zones and Region Pairs
Azure region
A region is a geographical area on the planet containing at least one, but potentially multiple datacenters that are nearby and networked together with a low-latency network. Azure intelligently assigns and controls the resources within each region to ensure workloads are appropriately balanced.

When you deploy a resource in Azure, you will often need to choose the region where you want your resource deployed. Region A set of datacenters deployed within a latency-defined perimeter and connected through a dedicated regional low-latency network.

Geographies in Azure
Azure divides the world into geographies that are defined by geopolitical boundaries or country borders. An Azure geography is a discrete market typically containing two or more regions that preserve data residency and compliance boundaries. 

This division has several benefits.
  • Geographies allow customers with specific data residency and compliance needs to keep their data and applications close.
  • Geographies ensure that data residency, sovereignty, compliance, and resiliency requirements are honored within geographical boundaries.
  • Geographies are fault-tolerant to withstand complete region failure through their connection to dedicated high-capacity networking infrastructure.
Availability Zones
Availability Zones are physically separate datacenters within an Azure region.Each Availability Zone is made up of one or more datacenters equipped with independent power, cooling, and networking. It is set up to be an isolation boundary. If one zone goes down, the other continues working. Availability Zones are connected through high-speed, private fiber-optic networks.


Azure Availability Zones

Region Pairs
Each Azure region is always paired with another region within the same geography (such as US, Europe, or Asia) at least 300 miles away. This approach allows for the replication of resources (such as virtual machine storage) across a geography that helps reduce the likelihood of interruptions due to events such as natural disasters, civil unrest, power outages, or physical network outages affecting both regions at once. If a region in a pair was affected by a natural disaster, for instance, services would automatically fail over to the other region in its region pair.Examples of region pairs in Azure are West US paired with East US, and SouthEast Asia paired with East Asia.

Azure Region Pairs
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

Building Bot Application with Azure AD Login Authentication using AuthBot

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.

Building Bot Application with Azure AD Login Authentication using AuthBot

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 .

Building Bot Application with Azure AD Login Authentication using AuthBot

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.

Building Bot Application with Azure AD Login Authentication using AuthBot


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

Building Bot Application with Azure AD Login Authentication using AuthBot

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.

Building Bot Application with Azure AD Login Authentication using AuthBot

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.

Building Bot Application with Azure AD Login Authentication using AuthBot

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


Building Bot Application with Azure AD Login Authentication using AuthBot
  • 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".
Building Bot Application with Azure AD Login Authentication using AuthBot

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.



Microsoft Cognitive services is set of cloud based intelligence APIs for building richer and smarter application development. Cognitive API will use for Search meta data from Photos and video and emotions, sentiment analysis and authenticating speakers via voice verification.

Cognitive Computer Vision API: Intelligent Image Object Detection Bot

The Computer Vision API will help developers to identify the objects with access to advanced algorithms for processing images and returning image meta data information. In this article, you will learn about Computer Vision API and how to implement Compute Vision API into Bot application.


You can follow below steps for implement object detection in Bot Application 
 

Computer Vision API Key Creation

Computer Vision ApI returns information about visual content found in an image. You can follow below steps for create Vision API key.

Navigate to https://azure.microsoft.com/en-us/try/cognitive-services/

Cognitive Computer Vision API: Intelligent Image Object Detection Bot

Click on “Get API Key “or Login with Azure login.

Login with Microsoft Account and Get API key

Cognitive Computer Vision API: Intelligent Image Object Detection Bot

Copy API key and store securely, we will use this API key into our application

Step 2: 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.

Cognitive Computer Vision API: Intelligent Image Object Detection Bot

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

Cognitive Computer Vision API: Intelligent Image Object Detection Bot

In this solution, we are going edit Messagecontroller and add Service class.

Install Microsoft.ProjectOxford.Vision Nuget Package

The Microsoft project oxford vision nuget package will help for access cognitive service so Install “Microsoft.ProjectOxford.Vision” Library from the solution

Cognitive Computer Vision API: Intelligent Image Object Detection Bot

Create Vision Service: Create new helper class to the project called VisionService that wraps around the functionality from the VisionServiceClient from Cognitive Services and only returns what we currently need.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.ProjectOxford.Vision;
using Microsoft.ProjectOxford.Vision.Contract;
namespace BotObjectDetection.Service
{
public class VisionService : ICaptionService
{
/// <summary>
/// Microsoft Computer Vision API key.
/// </summary>
private static readonly string ApiKey = "<API Key>";
/// <summary>
/// The set of visual features we want from the Vision API.
/// </summary>

private static readonly VisualFeature[] VisualFeatures = { VisualFeature.Description };

public async Task<string> GetCaptionAsync(string url)
{
var client = new VisionServiceClient(ApiKey);
var result = await client.AnalyzeImageAsync(url, VisualFeatures);
return ProcessAnalysisResult(result);
}
public async Task<string> GetCaptionAsync(Stream stream)
{
var client = new VisionServiceClient(ApiKey);
var result = await client.AnalyzeImageAsync(stream, VisualFeatures);
return ProcessAnalysisResult(result);
}
/// <summary>
/// Processes the analysis result.
/// </summary>
/// <param name="result">The result.</param>
/// <returns>The caption if found, error message otherwise.</returns>

private static string ProcessAnalysisResult(AnalysisResult result)
{
string message = result?.Description?.Captions.FirstOrDefault()?.Text;
return string.IsNullOrEmpty(message) ?
"Couldn't find a caption for this one" :
"I think it's " + message;
}
}
}


In the above helper class, replace vision API key and call the Analyze image client method for identify image meta data

Messages Controller

MessagesController is created by default and it is the main entry point of the application. it will call our helper service class which will handle the interaction with the Microsoft APIs. You can update “Post” method like below

using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Http;
using BotObjectDetection.Service;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;

namespace BotObjectDetection
{
[BotAuthentication]
public class MessagesController : ApiController
{
private readonly ICaptionService captionService = new VisionService();
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>

public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.Type == ActivityTypes.Message)
{
//await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
string message;
try
{
message = await this.GetCaptionAsync(activity, connector);
}
catch (Exception)
{
message = "I am object Detection Bot , You can Upload or share Image Url ";
}
Activity reply = activity.CreateReply(message);
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
}
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;
}
private async Task<string> GetCaptionAsync(Activity activity, ConnectorClient connector)
{
var imageAttachment = activity.Attachments?.FirstOrDefault(a => a.ContentType.Contains("image"));
if (imageAttachment != null)
{
using (var stream = await GetImageStream(connector, imageAttachment))
{
return await this.captionService.GetCaptionAsync(stream);
}
}
string url;
if (TryParseAnchorTag(activity.Text, out url))
{
return await this.captionService.GetCaptionAsync(url);
}
if (Uri.IsWellFormedUriString(activity.Text, UriKind.Absolute))
{
return await this.captionService.GetCaptionAsync(activity.Text);
}
// If we reach here then the activity is neither an image attachment nor an image URL.
throw new ArgumentException("The activity doesn't contain a valid image attachment or an image URL.");
}

private static async Task<Stream> GetImageStream(ConnectorClient connector, Attachment imageAttachment)
{
using (var httpClient = new HttpClient())
{
var uri = new Uri(imageAttachment.ContentUrl);
return await httpClient.GetStreamAsync(uri);
}
}

private static bool TryParseAnchorTag(string text, out string url)
{
var regex = new Regex("^<a href=\"(?<href>[^\"]*)\">[^<]*</a>$", RegexOptions.IgnoreCase);
url = regex.Matches(text).OfType<Match>().Select(m => m.Groups["href"].Value).FirstOrDefault();
return url != null;
}
}
}


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

Cognitive Computer Vision API: Intelligent Image Object Detection Bot

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

Cognitive Computer Vision API: Intelligent Image Object Detection Bot

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 an Intelligent Image Object Detection Bot using Microsoft Cognitive Computer Vision API. If you have any questions/feedback/ issues, please write in the comment box.
The Bot Application runs in  an application, like Skype, web chat, Facebook, Message, etc. Users can interact with bots by sending them messages, commands, and inline requests. You control your bots using HTTPS requests to the bot API.

The better visibility, the higher will be the chance of customers making a purchase. Unlike other bots which are available on business web pages which provide visibility only to the customers visiting their site, a Facebook bot is very easy to find. It is visible to around 1.3 billion users of Facebook. A Facebook bot interacts very well with customers. It can receive and send messages, images and provide clickable buttons like Buy Now. In this article, I am going to show how we can connect Facebook Messenger's channel and integrate Bot Application to the Messenger app.

In this Article, I am going to show how we can connect Facebook messengers’ channel and integrate Bot Application to the messengers App.


Create FAQ Bot Application

You can refer my previews article to create and build a Xamarin FAQ Bot using the Azure Bot Service and deploy it into Azure. I am not using any coding for developing the Bot Application, you can follow the steps provided in the article to create and deploy FAQ Bot.


Setup Facebook Page

We can implement Bot Application to the Facebook page. You can create Facebook page or select existing page and navigate to “About page” for fining and copy the Page ID.


Login to Facebook APP

Create a new Facebook App (https://bit.ly/1D0BHpg) on the Page and generate an App ID , App Secret and Page Access Token for integrating Bot to the page messenger. You can click on “Skip and Create APP Id” from following screen.




Create New App ID



Provide display Name and Contact Email for integrating Bot application and Click on Create.


After Create button, it will navigate to the App dashboard screen. The side navigation menu having Settings > Basic and copy the APPID and APP Secret. Provide the Privacy URL, Terms of Service URL, App icon and Select Category.




I have shown the following screen to Select Setting > Advanced and Set the "Allow API Access to App Settings slider to "Yes" and click on Save Changes.

Setup Message

Select Dashboard and Click on Setup button from messenger group


Create Page Access Token

Select Setting from the messenger side navigation menu to generate token, you can select the Page and generate access token and copy the page access token.

Setup Webhooks

Click Set up Webhooks to forward messaging events from Facebook Messenger to the bot.



Provide following callback URL and Verify token to the webhooks setup page and select the message, message_postbacks, messaging_optins and message_deliveries subscription fields. The following Steps 2, will show how to generate Callback URL and verify token from Azure portal.


You can click on “Verify and Save “and select the Facebook page to Subscribe the webhook to the Facebook page.

Connect Facebook Channel

Step 1: Login to Azure portal > Select the “All Resources” > Select Channels > Select Facebook Messengers, let we start configure “Facebook Messengers “Channel and follow below steps, the end of this article you can able to deploy Bot into the Facebook messenger



Step 2:The Azure Facebook configuration channel will generate following Callback URL and verify token, You can copy those information and Past to the Facebook webhook setup screen. (Return to the Facebook messenger setup screen).






Step 3: You can paste the Facebook App ID, Facebook App Secret, Page ID,and Page Access Token values copied from Facebook Messenger previously. You can use the same bot on multiple facebook pages by adding additional page ids and access tokens.


Submit to Facebook Review

Select App preview and Click and Submit for review after submit will take some time for the facebook team testing to the messenger bot and you can mark your app live available to the public , then you can test messenger from the Facebook page .


Facebook Team reviews and Testing

You can verify Facebook team testing progress, navigate to your Facebook page and Click on Inbox and verify, if anything problem to the messenger bot, the Team will update the bug list from App review screen.

Xamarin FAQ Messengers testing

You can select your Facebook page and test your bot application. I have trained 7000+ more questions to the Facebook messenger bot from Xamarin Q & A Page, If you want to look the xamarin FAQ demo. Navigate to Xamarin Q & A Facebook page and ask your xamairn related question.





Summary

In this article, you have learned how to integrate bot application right into your Facebook Page via Azure Microsoft AI. 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