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<object> result)
{
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");
}
text.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



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.

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.

Bot Builder SDK introduced Form Flow, it will automatically generate the dialogs conversation based on your property and type that a specified on a class. Bot Dialog also its more powerful but handling a conversation like a registration, ordering, its required more effort to complete process using bot dialog.

In this article will help you to understand how to use Bot Form Flow and how you can use them to collect information from the users. We are creating sample Demo Bot for Bus booking bot.


Prerequisite:

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

Create New Bot Service:

Let’s create a new bot service application using Visual Studio 2017. Open Visual Studio > Select File on menu > Create New Project (Ctrl + Shift +N) > Select Bot application



The Bot application template was created with all the components and all required NuGet references installed in the solutions and add new class for BusFormFlow to the project.



In this Solution, we have two main class MessagesController.cs and BusFormFlow class. Let us start discussing here.

Create New FormFlow Class:

We can start create a class that represents our form and create properties for each field. Form fields can be one of the following types

Enum
List of Enum
Integral – sbyte, byte, short, ushort, int, uint, long, ulong
Floating point – float, double
String
DateTime
FormFlow will automatically validate type based on user input and reply the validation message.
Create a new enum field for Bus start from.
///
/// From City Enum
///

public enum FromCity
{
Bangalore,Chennai,Madurai,Trichy,Coimbatore,Tanjore,pudukkottai
}

The bot output look like below



Create a new enum field for Bus end point.

///
/// To City Enum
///

public enum ToCity
{
Bangalore, Chennai, Madurai, Trichy, Coimbatore, Tanjore, Pudukkottai
}

The bot output look like below 


Create a new enum for Bus type

///
/// Bus Type Enum
///

public enum BusType
{
AC, NonAC,Slepper, Siting
}

The output look like below


Create a new enum for gender

///
/// Gender
///

public enum Gender
{
Male,Female
}

The output look like below 



create a class for FormFlow with the [Serializable] attribute and create build Form method for show form flow

using Microsoft.Bot.Builder.FormFlow;
using Microsoft.Bot.Builder.Dialogs;
using System;

namespace FormFlowBot.FormFlow
{
[Serializable]

public class BusFormFlow
{

///
/// List of Form Flow
///

public FromCity? FromAddress;
public ToCity? ToAddress;
public DateTime? StartDate;
public BusType? BusTypes;
public Gender? SelectGender;
public string Name;
public int Age;
///
/// Build Form
///
///

public static IForm<BusFormFlow> BuildForm()
{
return new FormBuilder<BusFormFlow>()
.Message("Welcome to the BotChat Bus Booking !")
.OnCompletion(async (context, profileForm) =>
{
string message = "Your Bus booking Successfully Completed .You will get confirmation email and SMS .Thanks for using Chat Bot Bus Booking , Welcome Again !!! :)";
await context.PostAsync(message);
})
.Build();
}
}
}

Calling Form Flow :

The Messagescontroller class added in the solution and add the following MakeRootDialog from a Messagescontroller class

internal static IDialog<BusFormFlow> MakeRootDialog()
{
return Chain.From(() => FormDialog.FromForm(BusFormFlow.BuildForm));
}
Call MakeRootDialog from post method in MessagesController calss
///
/// POST: api/Messages
/// Receive a message from a user and reply to it
///

public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.Type == ActivityTypes.Message)
{
await Conversation.SendAsync(activity, MakeRootDialog);
}
else
{
HandleSystemMessage(activity);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}

Run Bot Application:

The emulator is a desktop application that lets we test and debug our bot on localhost. Now, you can click on "Run the application" in Visual studio and execute in the browser.


  • Test Application on Bot Emulator
  • You can follow the below steps for test your bot application.
  • Open Bot Emulator.
  • Copy the above localhost url and paste it in emulator e.g. - http://localHost:3979
  • You can append the /api/messages in the above url; e.g. - http://localHost:3979/api/messages.
  • You won't need to specify Microsoft App ID and Microsoft App Password for localhost testing, so click on "Connect".

Summary:

In this article, how to use FormFlow and how you can use them to collect information from the users. If you have any questions/ feedback/ issues, please write in the comment box.
Azure Functions is a solution for easily running small pieces of code in the cloud. We can create, execute, and test our custom logic function without creating a VM or web applications and also without needing to install any software or infrastructure to run the function. In this article, How to implement azure functions and directly called through HTTP from Xamarin Forms Application 


Create Azure Functions :

I have explained about different ways to create basic Azure Functions in my previous article, you can refer any of the below one article for creating new Azure functions.

Create New Xamarin Forms Client Application :

We need to create a new blank Xamarin.Forms application and add a new XAML page .You can refer to my previous article for setting up and creating new Xamarin.Forms application.

If you have already installed VS on your machine, open Visual Studio >> Create New Project ( Ctrl +Shift +N) >> Select Cross Platform Template >> Select Blank Xamarin Forms Application >> Provide Project name and Press OK

The Solution will be created with all the platform and PCL projects.

.

Design portable UI :

The UI will have a few elements on the screen. Entry Control for providing user input value and label for print output text .

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="AzureFunctionsDemo.MainPage">
<StackLayout>
<!--Title text-->
<Label Text ="Building Serverless Mobile App with Azure Functions using Xamarin Forms" HorizontalOptions="Center" TextColor="Green" FontSize="30" />
<!--Provide Input Parameter to Azure Functions-->
<Entry TextColor="Green" x:Name="txtname" Placeholder =" Enter Your Name" />
<!--Click On Button For Communicate to Azure Functions-->
<Button Text="Connect to Azure Functions" Clicked="OnButtonClicked" />
<!--Activity Indicator will show progress of client and Azure connection and excution-->
<ActivityIndicator x:Name="waitindicator" IsVisible ="false"
Color="Black" />
<!--Output label-->
<Label x:Name="lblname" HorizontalOptions="Center" TextColor="Green" FontSize="30" />
</StackLayout>
</ContentPage>

Create Aure Functions Helper Class :

Its time to integrate Azure functions in to the Mobile Applciation ,now you can add Newtonsoft.JSON from portable project . Right Click on Portable Project > Manage Nuget Packages > Select Newtonsoft.Json from Browse tab > click on Install


Create Uri custom extension method for append the query string .

public static class Common
{
/// <summary>
/// BuildQueryString
/// </summary>
/// <param name="uri"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public static Uri BuildQueryString(this Uri uri, Dictionary<string, string> parameters)
{
var stringBuilder = new StringBuilder();
string str = "?";
foreach (KeyValuePair<string, string> item in parameters)
{
stringBuilder.Append(str + item.Key + "=" + item.Value);
str = "&";
}
return new Uri(uri + stringBuilder.ToString());
}
}

We already created Get Azure Functions, before writing c# code, copy functions url of Azure portal and write HTTP get client method as per below. The HTTP Client will automatically include in the latest Dot net framework.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace AzureFunctionsDemo
{
public class AzureFunctionHelper
{
// Remember to paste below your Azure Function url copied before in the Portal:
const string AZURE_FUNCTION_URL = "https://devenvexefunctiondemo.azurewebsites.net/api/HttpTriggerCSharp1";
// Remember to paste below your Azure Function Key copied before in the Portal:
const string AZURE_CODE = "fnNK7ncbR3QKAgMgXAaV1gnPMgaPaqUTH3mbv7gi9nM9zt7yJImeng==";

/// <summary>
///Get Azure Functions
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="name"></param>
/// <returns></returns>

public async Task<object> GetAsync<T>(string value)
{
var httpClient = new HttpClient();
Dictionary<string, string> query = new Dictionary<string, string>();
query["code"] = AZURE_CODE;
query["name"] = value;
Uri uri = new Uri(AZURE_FUNCTION_URL).BuildQueryString(query);
var content = await httpClient.GetStringAsync(uri);
return JsonConvert.DeserializeObject(content);
}
}

Now you can start calling GetAsync method from MainPage.xaml.cs file

using System;
using Xamarin.Forms;
namespace AzureFunctionsDemo
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
async void OnButtonClicked(object sender, EventArgs args)
{
//Show Wait indicator
waitindicator.IsVisible = true;
waitindicator.IsRunning = true;
//Calling Azure Function
AzureFunctionHelper oazurehelper = new AzureFunctionHelper();
var value = await oazurehelper.GetAsync<string>(txtname.Text);
//print azure fucntion return value
lblname.Text = value.ToString();
//Disable wait Indicator after loading output
waitindicator.IsVisible = false;
waitindicator.IsRunning = false;
}
}
}

We have completed all the code for consuming Azure Function from xamarin, we can select the platform and Press F5, the output look like below





Summary :

You have Learned from here ,how to create an Azure function without own server . Azure Functions were directly called through HTTP from Xamarin Forms Application .This article share for beginners , you should try different service in Azure Functions and implement in Xamarin Forms Application .

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

Introduction:

Azure Functions is a solution for easily running small pieces of code in the cloud. We can create, execute, and test our custom logic function without creating a VM or web applications and also without needing to install any software or infrastructure to run the function.

In this article, you will learn about create, test, debug and deploy azure functions using Visual Studio 2017. Azure Functions tools are available as part of the Azure development workload in Visual Studio 2017 version 15.3, or a later version.


Prerequisites:

Download and Install Visual 2017 version 15.3 .

If you already Installed Visual Studio 2017, Update Visual Studio from Extensions and updates

Open Visual Studio 2017 > Tools > Extensions and Updates > Select product Updates under the Products category and select Visual studio update 15.3 preview 7.0 version and click on update


Step 1: 

Create Azure Functions Project in Visual Studio 2017

Open Visual Studio 2017 Preview 15.3 > Select File >click on New Project (Ctrl +Shift +N) > Select on Visual C# >Click on Cloud > select Azure Functions, type a Name for your project, and click on OK


Step 2: 

Create New Function
Azure Functions Solution will generate like below with host.json and locl.settings.json file .



In Solution Explorer, right-click on your Azure function project and select Add > New Item. Select Azure Function and click Add.



Select HttpTrigger as Azure Function type, select Functions for Access Rights, and click Create. The function created is accessed by an HTTP request from any client.



After click on Ok, will generates a new class with a Static Run method, that is attributed with [FunctionName] attribute. The [FunctionName] attribute indicates that the method is the entry for an Azure Function

using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;

namespace DevEnv_AzureFunctionsDemo
{
public static class DemoFunctions
{
[FunctionName("DemoFunctions")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
// parse query parameter
string name = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
.Value;
// Get request body
dynamic data = await req.Content.ReadAsAsync<object>();
// Set name to query string or body data
name = name ?? data?.name;
return name == null
? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
: req.CreateResponse(HttpStatusCode.OK, "Hello " + name + "Welcome C# Corner ");
}
}
}

Step 3:

 Azure Functions Test:

You can Press F5 for run, test and debug your azure function, if prompted, accept the request from Visual Studio to download and install Azure Functions Core (CLI) tools. You may also need to enable a firewall exception so that the tools can handle HTTP requests.

Copy the Azure function local deploy url on runtime output window



Append the name parameter to the query string. Use an actual name for the <Enter a name here> placeholder.
https://<Local Host url> /api/<Your Function Name>? name=<Enter a name here>
Paste the URL into your browser, and you should get a response similar to the following.


If you are Function locally working as expected means, you can initiate to publish the project to Azure.

Step 4:

 Publish Project to Azure:

If you don't have an Azure subscription, create a free account before start deploy azure function.

In Solution Explorer, right-click the project and select Publish. Choose Create New and then click on Publish.



If you haven't already connected Visual Studio to your Azure account, click Add an Account and Provide the login details and connect

In the Create App Service dialog, provide Hosting settings as specified below



Click Create to create a function app in Azure with these settings. After the provisioning is complete, make a note of the Site URL value, which is the address of your function app in Azure.
Copy the base URL of the function app from the Publish profile page. Replace the localhost:port of the URL you used when testing the function locally with the new base URL. As before, make sure to append the query string with &name=<yourname> to this URL and execute the request.

Download Source Code :


Related Article:


Summary:

In this article, you learned about Azure Functions and how to create, test, publish Azure Functions using visual studio 2017.

If you have any questions/ feedback/ issues, please write in the comment box.
Azure Functions is a solution for easily running small pieces of code in the cloud. We can create, execute, and test our custom logic function without creating a VM or web applications and also without needing to install any software or infrastructure to run the function. In this article, you will learn about create and test azure functions using azure Portal

Steps to Create Azure Functions:

Step 1

Navigate to https://functions.azure.com and click on “Login in to your account".


Step 2:

We should be following two ways to create Azure Functions

Navigate to https://functions.azure.com and Provide Azure Functions details and create the Azure Functions.



Navigate to https://portal.azure.com , Click on New from Azure portal > Web + Mobile >Click on see All or Search > Function App



Step 3: Create Azure Functions App:

Provide the functions App Name and following details for create new functions
App Name – Provide your Unique functions name

Subscriptions – Select your subscription Free or any type

Resource Group -create or select existing resource group name.

Hosting Plan – You can Select default hosting plan as consumption plan, you have to pay only for the time functions code runs.

Location – Select Your nearest location (eg. South Central US).

Storage Account – You can Select or existing storage account.


Step 4:

Click on create and wait for a few minutes to deploy the new Azure Function app. Expand your new function app and click the + button next to Functions.


Step 5:

After clicking on + button, you will get the following screen, select WebHook + API, choose a language for your function, and click on Create this function.


Step 6: Azure Functions Editor

The .csx file format allows you to write a C# function. Include any assembly references and namespaces at the beginning of the file as usual in C# and write your logic in Run method, just like below.


Step 7:

Run and Test Azure Functions:

You can provide JSON string like the following in the request body and Click on the Run button for test the Azure Functions


Testing in Web Browser:

The web browser is a simple way to trigger functions via HTTP. You can use a browser for GET requests that do not require a body payload, and that use only query string parameters.

To test the function we defined earlier, copy the Function Url from the Azure function portal like below



Append the name parameter to the query string. Use an actual name for the <Enter a name here> placeholder.

https://<Your Function App>.azurewebsites.net/api/<Your Function Name>?code=<your access code>&name=<Enter a name here>, Paste the URL into your browser, and you should get a response similar to the following.


Related Article:

Getting Started with Azure Functions Using Azure Free Trial Account

Summary:

In this article, you learned about Azure Functions, how to create and test Azure Functions in Azure Portal.

If you have any questions/ feedback/ issues, please write in the comment box.
Azure Function is a solution for easily running small pieces of code in the cloud. Create, Execute and test your custom logic function without creating a VM, Web Applications, and no need install any software and infrastructure to run the function. You can use development language of as per your choice below
  • C#
  • F#
  • Node.js
  • Python
  • PHP
Pay only for the time your code runs and trust Azure to scale as needed. Azure Functions let you develop server less applications on Microsoft Azure. In this Article, you will learn how to create azure Functions without create Azure account.

How to create an Azure Functions:

Step 1: Navigate to https://functions.azure.com and click on try it For Free



Step 2: Create Azure Premade function.

Choose the functions scenario (WebAPI/timer/Processing),

Free trail will allow only two language (c# and JavaScript), Select your Language and click on Create the Function.


Step 3: Login with any of following provider without creating azure account.



Step 3: Azure Function Editor



Azure functions Edit was following feature

Microsoft Azure free trial Functions edit will give access only 60 Minutes .

You can edit c# azure function in Run.csx file as per your requirement

Save the changes

Run the Functions

Get Function URL button will provide the public functions url

View File button for list of file will display

Test button for Test the function

View File Window.

You can Add and upload file using File explore window and system will generate two files functions.json for configuration and run.csx file for create c# custom method .



Run.csx File

The .csx file format allows you to writing a C# function. Include any assembly references and namespaces at the beginning of the file as usual in c# and write your logic in Run method as like below


Function.Json File

The function.json file defines the function bindings and other configuration settings. how to pass data into and return data from function execution. The name that is used for the bound data in the function. For C#, this is an argument name; for JavaScript, it's the key in a key/value list.

You can refer the following is an example function.json file.



Test the Function

You can test Azure functions on multiple way, Here I will explain on two ways to Run /test from an Azure Function editor and test with the Browser

You can use to do testing with click on a test button and provide the request body a JSON string similar to the following in the request body field and click on the Run button



Test with a Browser

The web browser is a simple way to trigger functions via HTTP. You can use a browser for GET requests that do not require a body payload, and that use only query string parameters.

To test the function, we defined earlier, copy the Function Url from the Azure function portal like below



Append the name parameter to the query string. Use an actual name for the <Enter a name here> placeholder.

https://<Your Function App>.azurewebsites.net/api/<Your Function Name>?code=<your access code>&name=<Enter a name here>

Paste the URL into your browser, and you should get a response similar to the following.




The Chrome browser will have returned string in XML. Other browsers display just the string value.

Summary

In this article, you learned about Azure functions, how to create Azure functions with create Azure account and test Azure functions

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