Introduction:

Microsoft offer a different service in the Cloud, Mail, Calendar, Contact, Chat and files from common Microsoft portal and also if you want to integrate to your application, you can access unified API wrapper in the Microsoft graph SDK. In this article you will get understand, how to implement login authentication and Send mail using Microsoft graph API in the Xamarin Forms application


Prerequisites:

Download and install Visual 2017 Community Edition or higher.

Create Microsoft Account (If you already register Microsoft account, it’s not required)

Getting Start Create Application:

Step 1:

 You can navigate following URL https://developer.microsoft.com/en-us/graph/quick-start for register app and create sample app.

Step 2: 

Select the platform and Microsoft will create simple app that connects to Office 365 and calls the Microsoft Graph API.

Step 3: 

Register APP ID: You can register the application using click on “Get an app ID” and it will navigate to Microsoft application registration portal where you will be able to get an App ID and redirect URL. You will need either a School / Work /corporate / Azure AD or Microsoft account.


Step 4: 

Registration Success: after login with your Microsoft account and wait for few second appid and redirect url will generate automatically. if you want to modify or manage your app, you can click on application registration portal .

Step 5:

 Manage App in Registration Portal: You can manage or edit application from portal in the following App Name, redirect URL, generate new password, application logo, update the permission and click on Save button.


Step 6: 

Download Sample Code: you can download and unzip the source code > open the source code using Visual Studio. in the Sample application have multiple platform support as iOS, Android, UWP. The code sample will introduce you to authentication and send an email from your account.


Step 7: 

Microsoft Graph Client Library:

Microsoft Graph Client Library allows you to call Office 365, Azure AD and other Microsoft services through a single unified developer experience so right click on your solution and verify below NuGet package installed in the solution.


Step 8: 

Configure the project: Open the App.cs file from XamarinConnect PCL project > replace your client ID and add the user permission scope.
public static string ClientID = "< Update your Client ID > ";

public static PublicClientApplication IdentityClientApp = new PublicClientApplication(ClientID);

public static string[] Scopes = { "User.Read", "Mail.Send", "Files.ReadWrite" };

Step 9: 

Configure Send mail: Open the MainHelper.cs from XamarinConnect PCL project > update ComposeAndSendMailAsync method as per your requirement

public async Task ComposeAndSendMailAsync(string subject,string bodyContent,string recipients)
{

// Get current user photo
Stream photoStream = await GetCurrentUserPhotoStreamAsync();
// If the user doesn't have a photo, or if the user account is MSA, we use a default photo
if (photoStream == null)
{
var assembly = typeof(MailHelper).GetTypeInfo().Assembly;
photoStream = assembly.GetManifestResourceStream("XamarinConnect.test.jpg");
}
MemoryStream photoStreamMS = new MemoryStream();
// Copy stream to MemoryStream object so that it can be converted to byte array.
photoStream.CopyTo(photoStreamMS);
DriveItem photoFile = await UploadFileToOneDriveAsync(photoStreamMS.ToArray());
MessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage();
attachments.Add(new FileAttachment
{
ODataType = "#microsoft.graph.fileAttachment",
ContentBytes = photoStreamMS.ToArray(),
ContentType = "image/png",
Name = "me.png"
});
// Get the sharing link and insert it into the message body.
Permission sharingLink = await GetSharingLinkAsync(photoFile.Id);
string bodyContentWithSharingLink = String.Format(bodyContent, sharingLink.Link.WebUrl);
// Prepare the recipient list
string[] splitter = { ";" };
var splitRecipientsString = recipients.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
List<Recipient> recipientList = new List<Recipient>();
foreach (string recipient in splitRecipientsString)
{
recipientList.Add(new Recipient { EmailAddress = new EmailAddress { Address = recipient.Trim() } });
}
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
var email = new Message
{
Body = new ItemBody
{
Content = bodyContentWithSharingLink,
ContentType = BodyType.Html,
},
Subject = subject,
ToRecipients = recipientList,
Attachments = attachments
};
try
{
await graphClient.Me.SendMail(email, true).Request().PostAsync();
}
catch (ServiceException exception)
{
throw new Exception("We could not send the message: " + exception.Error == null ? "No error message returned." : exception.Error.Message);
}
}
catch (Exception e)
{
throw new Exception("We could not send the message: " + e.Message);
}
}

Step 9: Run the Application:

Select iOS,android and Windows project and run the application .

Click on Connect Button from iOS/Android /Windows


Sign in with your personal or work or school account and grant the requested permissions.



4. Click on Send mail button. When the mail is sent, a Success message is displayed.

This mail message includes the photo as an attachment and also provides a sharing link to the uploaded file in OneDrive. Check your mail from Inbox or Spam.


Download Source Code:

You can download the complete source code from MSDN sample. 


Summary:

In this article, you learned about how to implement login authentication and Send mail using Microsoft graph API in the Xamarin Forms application.

If you have any questions/ feedback/ issues, please write in the comment box.

Introduction:

The Bots Framework that run inside 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 our bot API.

In this article, how you can integrate a bot right into your Xamarin.Forms application via the Microsoft Bot Framework Web bots.


Create new bot Application:

You can read my previous article for Getting Started with Bots Using Visual Studio 2017 from following URL http://www.c-sharpcorner.com/article/getting-started-with-bots-using-visual-studio-2017/


Publish Bot Application to Azure:

You can read my previous articles for publish bot application to azure from following URL http://www.c-sharpcorner.com/article/getting-started-deploy-a-bot-to-azure-using-visual-studio-2017/

Generate Web Chat Code:

After publish you bots into azure, you can generate web Chat html code from bots portal as per below

Step 1

Sign in to the Bot framework Portal - https://dev.botframework.com/

Step 2

Click My Bots

Step 3

Select your bot that you want to generate code

Step 4:

Click on Get bot embed Codes > Click on Web Chat icon > Click on (Click here to open Web Chat configuration page)


Step 5:

It will navigate to new web page for configuration and click on + Add New Site > Provide site or application name > Click on Done


Step 6:

You can copy your secret keys and embed code for integrate to xamarin forms application


Create new Xamarin .Forms Application :

Go to Run (Windows key +R) > type Devenv.exe or select from Windows Application list and select New project from File menu > New Project (ctrl +Shift+N) or click More project template from VS Start screen.



New Project >select Cross -Platform from Template > Cross platform App(Xamarin.Forms or native). It will show the screen, as shown below.



You can find above screen only on VS 2017. Select Blank apps > select Xamarin.Forms > Select PCL and click on Ok .it will generate all the mobile platform project with PC



Open your MainPage.xaml file add webview control with following code for web chat enable
<StackLayout WidthRequest="300" HeightRequest="500" >
<Image Source="profile.png" WidthRequest="200" HeightRequest="200"></Image>
<Label Text="Live Chat with Suthahar via C Sharp corner" FontSize="20" ></Label>
<WebView x:Name="webview" Source="https://webchat.botframework.com/embed/DevEnvExeBot?s=8XGcUROXkAA.cwA.pZo.8pJ-6oQ3sJRpxq0tqIo9uLPji4oxBQuz2pW5qWobw2c"
WidthRequest="300" HeightRequest=" 300"></WebView>
</StackLayout>

Now you can run the application in windows ,Android and iOS


Download

You can download the complete source code from MSDN sample.


Summary

In this article, your learned how to create a Bot application, publish Bot to Azure and bot implementation to Xamarin Forms using Visual Studio 2017. If you have any questions/ feedback/ issues, please write in the comment box.












Introduction:

The Azure Bot Service is powered by the Microsoft Bot Framework and bot service allows developers to build conversational applications that plug into many popular chat applications including Facebook Messenger, Skype and Office 365, etc. In this article, we can be creating and testing a bot by using the Azure Bot Service.



Create new Bot Service:

Logon to the Azure portal with your registered Azure Microsoft account. If you don’t have azure subscription, you can Create a free trial Azure subscription from Azure portal.
In Azure Portal > click on + Add > Select on Data Analytics


Step 1:

 Select on new Bot service from data analytics menu


Step 2: 

You can provide following information for create new bot service unique App name to your bot’s name. The name is used as the subdomain in azure website (eg DevEnvExeBot.azurewebsites.net).
Select the Azure subscription.
Select the resource group or create new user group.

Select the location. And click on Create button


Step 3:

 After clicking on Create button, wait a few minutes for the Bot Service to be deployed successfully before proceeding. You will get confirmation notification for after success.


Register Bot Application:

You can click on confirmation notification. then, you will get the following screen where you need to create App ID. This is a prerequisite to authenticating your bot with the bot framework.

Step 1: 

Click on Create Microsoft App ID and Password


Step 2: 

App ID and password will generate following screen and click on button for go back to Bot framework


Step 3: 

Select the Programming language and template for developing bot application

Step 4: 

Now bot application successfully created and running in the cloud, you can edit code from Azure Develop code editor and also you can manage channels, analytics and setting.


Test Bot Application:

You can click on Test button and provide sample input text.


Summary

In this article, your learned about create and test a bot by using the Azure Bot Service. 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 or more complex rich cards that contain text, images, and action buttons. And you can add natural language interactions, which let your users interact with your bots in a natural and expressive way.

In this article, we can deploy a bot to azure using visual studio 2017, register app with bot portal and testing it with the Bot Framework Emulator.

Setup and Create New Bot Application.

You can read my previous article for Getting Started with Bots Using Visual Studio 2017 from following URL http://www.c-sharpcorner.com/article/getting-started-with-bots-using-visual-studio-2017/

You need azure account for deploy bot application to azure so If you do not have an Azure account, you can click following url for a free trial azure subscription. https://azure.microsoft.com/en-us/free/

Register Bot Application:

Step 1: Navigate to Bot Framework Portal from https://dev.botframework.com/
Step 2: Click on Sign in button and login with credential
Step 3: Click on Create a Bot or Skill
Step 4: Click on Create a Bot and click on Register
Step 5: Upload relevant app png icon and max size should be 30k
Step 6: Provide your bot's Display Name.
Step 6: Provide a Description of your bot.
Step 7: Provide your bots Https endpoint in configuration section.

We are not yet deployed our bot to the cloud so leave the endpoint blank for now. we will return to the Bot Framework Portal later and specify the endpoint after we have deployed our bot.

Step 8: On the next page, click Generate an app password to continue.
Step 9: Copy and securely store the password that is shown, and then click Ok.
Step 10: Click Finish and go back to Bot Framework.
Step 11: Back in the Bot Framework Portal, the App ID field is now populated.
Click 12: Click on Register to complete the registration process.

Update Web Configuration file:

Open your project in Visual Studio and update the Microsoft App Id and Microsoft App Password values in your web configuration settings to specify the app ID and password values that were generated for your bot during the above registration process.



<appSettings>
<!-- update these with your BotId, Microsoft App Id and your Microsoft App Password-->
<add key="BotId" value="DevEnvExeBot" />
<add key="MicrosoftAppId" value="2f3edda3-d36d-4d88-8acf-e448d870348e" />
<add key="MicrosoftAppPassword" value="L6KOPcc3jqZB6hKPe06yxsH" />
</appSettings>

Azure publishing wizard:

Step 1: Right click on Project > Select on Publish and start publish bot application into azure



Step 2: Select on Microsoft Azure App Service > select on Create New and click on Publish button


Step 3: Login with Microsoft azure account and click on create app service


Step 4: Copy the Destination URL value to the clipboard (you'll need this value later to test the connection to the bot)


Update Site Url from Bot Portal:

Step 1: Sign in to the Bot framework Portal - https://dev.botframework.com/
Step 2: Click My Bots.
Step 3: Select the bot that you want to configure and click Settings.
Step 4: Provide your bot's HTTPS endpoint. This is the endpoint where your bot will receive HTTP POST messages from Bot Connector. If you built your bot by using the Bot Builder SDK, the endpoint should end with /api/messages.
Step 5: Click on Save Changes.

Test Bot Application on Portal:

After publish Bot application into azure, you can test bot application from portal and emulator .

Step 1: Sign in to the Bot framework Portal - https://dev.botframework.com/
Step 2: Click on Test and provide input text


Test Bot Application on Emulator:

Open Bot Emulator and Provide your bot's HTTPS endpoint with api/messages .
Provide Microsoft App ID and Password and click on Connect



If you are getting following error, Click on Edit Tunneling (ngrok) setting.



download Tunneling (ngrok.exe) from https://ngrok.com/download and click on browse and associate ngrok.exe path



Click on refresh from Bot emulator and provide your input for test application


Download

You can download the complete source code from MSDN sample.


Summary

In this article, your learned how to Deploy a bot to Azure using Visual studio 2017. 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 or more complex rich cards that contain text, images, and action buttons. And you can add natural language interactions, which let your users interact with your bots in a natural and expressive way.

In this article, we can create a bot by using the Visual studio 2017 with Bot template and testing it with the Bot Emulator.

Install Visual Studio 2017:

Download Visual Studio 2017 from the following URL given below.

Download Visual Studio 2017 from https://www.visualstudio.com/downloads/.
Refer Visual Studio 2017 system requirement from https://www.visualstudio.com/en-us/productinfo/vs2017-system-requirements-vs.


Note:

You can build bots for free with Visual Studio 2017 Community.

The Bot Builder SDK for .NET currently supports Only on Windows. Visual Studio for Mac is not supported.

Bot Application template:

Download the Bot Application template from the following url http://aka.ms/bf-bc-vstemplate and install the template by saving the .zip file to your Visual Studio 2017 project templates directory.
The Visual Studio 2017 project templates directory is typically located following url

%USERPROFILE%\Documents\Visual Studio 2017\Templates\ProjectTemplates\Visual C#\


Create New Project:

Let's start with creating a new Bot application in Visual Studio 2017.
Click on Windows Key > Select Visual Studio 2017.

Now, open VS and create new project with c# project, select the Bot applications template as per below



The Bot application was created with all of the components and installed all required Nuget reference


Update Bot Builder Nuget Package:

Verify your application Microsoft.Bot.Builder nuget package was installed under reference .if not , refer follow below steps
Right-click on the Bot project(DevEnvExeBot) and select Manage NuGet Packages.In the Browse tab, type "Microsoft.Bot.Builder" and click on Search
Locate the Microsoft.Bot.Builder package in the list of search results, and click the Update button for that package or Uninstall and Install the package .


Update Code:

The Default application added simple conde snipper, no need to change anything. if you want to test your custom message, you can change like below.

You can find messagereceiveAsync method from Dialogs / RootDialog.cs file.

In this method activity.Text will return user text input so you can reply message based input text .

private async Task MessageReceivedAsync(IDialogContext context, IAwaitable
{
var activity = await result as Activity;
// calculate something for us to return
int length = (activity.Text ?? string.Empty).Length;
// return our reply to the user
//test
if (activity.Text.Contains("technology"))
{
await context.PostAsync("Refer C# corner website for tecnology http://www.c-sharpcorner.com/");
}
else if (activity.Text.Contains("morning"))
{
await context.PostAsync("Hello !! Good Morning , Have a nice Day");
}
//test
else if (activity.Text.Contains("night"))
{
await context.PostAsync(" Good night and Sweetest Dreams with Bot Application ");
}
else if (activity.Text.Contains("date"))
{
await context.PostAsync(DateTime.Now.ToString());
}
else
{
await context.PostAsync($"You sent {activity.Text} which was {length} characters");
}
context.Wait(MessageReceivedAsync);
}

Install bot Emulator:

You will need to download and install the emulator for testing bot application .You can download bot emulator from https://docs.microsoft.com/en-us/bot-framework/debug-bots-emulator .


Run Bot Application:

The emulator is a desktop application that lets you test and debug your bot on localhost or remotely. Now, you can click on run the application in any browser


Test Application on Bot Emulator:

  • You can follow below steps for test bot application
  • Open Bot Emulator
  • Copy above localhost url and past it from emulator eg: http://localHost:3979
  • You can append the /api/message from above localhost url eg: 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



Download

You can download the complete source code from MSDN sample. 


Summary:

This article your learned about how to create Bot application using visual studio 2017.If you have any questions/ feedback/ issues, please write in the comment box.

Featured Post

How to Get an Free Azure Subscription for Learning

This guide will help you get started with Microsoft Azure for free. It explains three easy ways: using a Free Azure Account Signing up for A...

MSDEVBUILD - English Channel

MSDEVBUILD - Tamil Channel

Popular Posts