XamarinCentral

Xamarin help you to write mobile Apps for Android and IOS using C#. At XamarinCentral, we will help you to learn Xamarin and get your job done. You can read articles or ask questions.

Learn more »

Recent articles


Building cross-platform native mobile apps with Xamarin Forms

Posted by seven.srikanth@gmail.com at 29 May 2018 in Article


 Hi guys, This is the first time i cover Xamarin.Forms here in my blog and my first written topic since year 2014. Very timely since we will have our "Love2Code" event coming this February 14 2017 sponsored by Microsoft. This topic will cover the basic fundamentals of of Cross-Platform mobile development using Xamarin.Forms and why is it worth to learn. We will be using Visual Studio 2015 as of this time since VS 2017 are still on release candidate. Image result for xamarin 
 Oh right, 2016 was a great year for Xamarin and Xamarin.Forms devs emerging as the winner of the Microsoft's acquisition of the Xamarin and have included it on Visual Studio editions (e.g. Community Editions) and for some reasons they have "open sourced" the Xamarin.Forms source code (Yes you read it right its open sourced) on GitHub you can skim it here. Before diving into cross-platform development with Xamarin.Forms, This are the things we need to consider.
  1. Is it cost-saving?
  2. Faster time to market
  3. User experience
  4. Potential user reach
  5. Learning Curve
Cost Saving
There were lot of cheapest options you can choose from take for example the Cordova and ReactNative. Maybe the cheapest of them all, and which is also open sourced, You can utilized existing skills of the team. But as you tailor some functionality (e.g. Platform specific and complex UI transitions) it will become more expensive. With Xamarin.forms you can also utilize your existing .NET team and most of all you can always fall back to native if it needs to. You can share libraries across all platform through portable class library (PCL) project on up to 80 to 90 percent.
Faster Time to Market
Cordova the clear winner here (Only when the app doesn't have complex requirement) and and some Competitor maybe also good but you cannot easily fall back to native approach. But for an enterprise-level app which have a good cloud integrations and tools the Xamarin is a clear winner here.
User Experience
Nothing beats a Native approach  when it comes to a better user experience, competitively Xamarin come near as close to native performance (users cannot take notice of it) it feels like native because its native (sound confusing but it is). Cordova fall as the lowest of them all, you can feel the slowness and some gestures doesn't work properly. When developing a five star apps we can always set the bar high the factor in choosing our platform of development.
Potential User Reach
Native approach fall behind on this matter, Now you want to reach all platforms as much as possible you need Cross-Platform approach like Xamarin.Forms.
Learning Curve
This is equally important with User Experience in my opinion especially when your working with a team. This is where the .NET team is dominant especially for wpf/silverlight xaml developers you can always utilize them using the same tools, libraries and principle in mobile development. Long term is always a big factor and Xamarin roadmap is taken into a higher level, please take a glimpse here
Comparisons:
Cross Platform
Hybrid
Native
Dev Cost
Reasonable
Cheap
Expensive
Dev Tool Cost
Cheap
Cheap
Free
Dev Time
Short
Short
Long
Portability
High
High
None
Performance
Near Native
Slow / Sluggish
Very Fast
Learning Curve
Great
Great
Good
Getting Started with Xamarin.Forms Xamarin are now shipped with all Visual Studio Editions, Installation are very straightforward, However you may encounter a couple of issues during or after installation. Common problems like missing features and SDK problems. Latest Visual Studio updates are now capable of installing missing features.  Make sure to checked the following feature during installation. Image result for Visual Studio install missing feature 
  Frequently Encountered Issues and How to fix them 1.) Resource.Designer.cs issue, usually occur with merging issue or deleted resource assets, this can be fixed by deleting Resource.Designer.cs in project then  rebuild the Droid project then re-include Resource.Designer.cs file. DefaultNamespace2.png 
 2.) Could not find android.jar for API level XX, This happen when we upgrade our Xamarin.Forms nuget libraries on our Droid Project which has dependencies with higher version of SDK. Upgrading android SDK will resolve this issue under Tools> Android> Android SDK Manager. VcdXd.png 
 3.) m2Repository Error, This is caused by interrupted first time build of a Droid project in a newly installed VS/Xamarin (Usually it downloads Xamarin SDK), deleting all zip files under C:\Users\[UserName]\AppData\Local\Xamarin\zips will fix this problem. iN2os.png 
 4.) Application could not be started, Ensure that the application has been installed to the target device and has a launchable activity (MainLauncher = true). Solution: On your Android device delete the old version of the app on application manager
  201306211522.jpg 
  Creating our First Xamarin.Forms Project Create a Blank Xaml App (Xamarin.Forms  Portable) under Cross-Platform Category and name "MyApp" or name whatever you want.  
 The template will create atleast 5 or 6 Project, It will create 1 portable project referenced to all platform specific project. Select Droid project as startup when you want to run the project in android emulator or device. Visual Studio comes with Visual Studio Android emulator make sure you have enabled Hyper-V feature.  
 Right click on the Droid project and select "Set as startup project", Then select the emulator of choice to Run the Droid project. If you encounter an issue please refer to "Frequently Encountered Issue and How to fix it. Then you should see something like this after you run the project: Viola
   
  Spice up your Page Lets add some spin on the project by adding basic controls and layouts inside a ContentPage. The first thing we do is to add a Grid Layout without columns and rows. It should look something like this: -
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyApp"
x:Class="MyApp.MainPage">
<ContentPage.Content>
<Grid>
<Image Source="background.png" Aspect="AspectFill"></Image>
<StackLayout Margin="30,60, 30, 30" HorizontalOptions="FillAndExpand">
<Label Text="iApp" HorizontalTextAlignment="Center"
TextColor="White"
FontAttributes="Bold" FontSize="60"></Label>
</StackLayout>
<StackLayout VerticalOptions="End">
<Button Text="App Walkthrough"
TextColor="White"
Font="Bold"
BackgroundColor="Transparent"
BorderColor="White"
BorderRadius="25"
BorderWidth="1"></Button>
</StackLayout>
</Grid>
</ContentPage.Content>
</ContentPage>
view raw page.xaml hosted with ❤ by GitHub
-
Before executing your project download the background image from here and name it background.png. And save in each platforms assets. For Android:
 
 While for iOS project can be found on Resources folder, Windows Phone and UWP can be found on Assets. Now execute your project.
 

Wrap Up

Our first Xamarin.Forms app works well, Next topic we will discuss more about Controls and Layouts as we progress we will move to more advance topic.
Original Author: 
Source: http://winstongubantes.blogspot.in/2017/01/building-cross-platform-native-mobile.html

Tags: Building cross-platform native mobile apps with Xamarin Forms



Xamarin Forms and AI Bot Framework with LUIS - Part 3

Posted by seven.srikanth@gmail.com at 28 May 2018 in Article


 Overview

Hi guys, for the final part of the series we will create a Xamarin.Forms projects for our Bot client. This will only need a little setup to connect with our Bot using DirectLine channel discuss on the part 2 of this article. If you missed the first topic you can browse it here. This is a three part series and if you already confident about the topic you just have to skip it. Xamarin.Forms and AI Bot Framework with LUIS -  Part 1 Xamarin.Forms and AI Bot Framework with LUIS -  Part 2

Creating our Xamarin.Forms Project

Create a Blank Xaml App (Xamarin.Forms Portable) under Cross-Platform Category and name it "TravelAgent" or name whatever you want. Now we have to create Models and ViewModels for our Travel Agent Page. First we need to create a ChatBot Model which is the standard schema for Chat Bot Messaging. -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace TravelAppMobile.Models
{
public class MessageSet
{
[JsonProperty(PropertyName = "messages")]
public BotMessage[] Messages { get; set; }
[JsonProperty(PropertyName = "watermark")]
public string WaterMark { get; set; }
[JsonProperty(PropertyName = "eTag")]
public string ETag { get; set; }
}
public class BotMessage
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "conversationId")]
public string ConversationId { get; set; }
[JsonProperty(PropertyName = "created")]
public DateTime Created { get; set; }
[JsonProperty(PropertyName = "from")]
public string From { get; set; }
[JsonProperty(PropertyName = "text")]
public string Text { get; set; }
[JsonProperty(PropertyName = "channelData")]
public string ChannelData { get; set; }
[JsonProperty(PropertyName = "images")]
public string[] Images { get; set; }
[JsonProperty(PropertyName = "attachments")]
public Attachment[] Attachments { get; set; }
[JsonProperty(PropertyName = "eTag")]
public string ETag { get; set; }
}
public class Attachment
{
[JsonProperty(PropertyName = "url")]
public string Url { get; set; }
[JsonProperty(PropertyName = "contentType")]
public string ContentType { get; set; }
}
public class Conversation
{
[JsonProperty(PropertyName = "conversationId")]
public string ConversationId { get; set; }
[JsonProperty(PropertyName = "token")]
public string Token { get; set; }
[JsonProperty(PropertyName = "eTag")]
public string ETag { get; set; }
}
}
view raw ChatBotModels.cs hosted with ❤ by GitHub
- Then we need to create ConversationMessage model for our Xaml Page Message UI. -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace TravelAppMobile.Models
{
public class ConversationMessage
{
public string Id { get; set; }
public string Message { get; set; }
public string FromUser { get; set; }
public ImageSource UserImageUrl { get; set; }
}
}
- Next is we create our ChatBotService  we will use to converse with our chatbot connector. Make sure you obtain a Directline key for us to connect with BotConnector. -
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using TravelAppMobile.Models;
namespace TravelAppMobile.Services
{
public class ChatBotService
{
private readonly string _baseBotEndPointAddress = "https://directline.botframework.com";
private HttpClient _client;
private string _directLineKey = "Q9IBXWIBSUg.cwA.1pw.aVXMkIWleOmQgRWWRKzYJwMoj63fP57FCeATbE7qW40"; //USE YOUR OWN DIRECTLINE KEY
private Conversation _lastConversation = null;
public ChatBotService()
{
_client = new HttpClient();
_client.BaseAddress = new Uri(_baseBotEndPointAddress);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BotConnector", _directLineKey);
InitializeConversation();
}
private async void InitializeConversation()
{
var response = await _client.GetAsync("/api/tokens/");
if (response.IsSuccessStatusCode)
{
var conversation = new Conversation();
HttpContent contentPost = new StringContent(JsonConvert.SerializeObject(conversation), Encoding.UTF8,
"application/json");
response = await _client.PostAsync("/api/conversations/", contentPost);
if (response.IsSuccessStatusCode)
{
var conversationInfo = await response.Content.ReadAsStringAsync();
_lastConversation = JsonConvert.DeserializeObject<Conversation>(conversationInfo);
}
}
}
public async Task<MessageSet> SendMessage(string message)
{
try
{
var messageToSend = new BotMessage() { Text = message, ConversationId = _lastConversation.ConversationId };
var contentPost = new StringContent(JsonConvert.SerializeObject(messageToSend), Encoding.UTF8, "application/json");
var conversationUrl = $"{_baseBotEndPointAddress}/api/conversations/{_lastConversation.ConversationId}/messages/";
var response = await _client.PostAsync(conversationUrl, contentPost);
var messageInfo = await response.Content.ReadAsStringAsync();
var messagesReceived = await _client.GetAsync(conversationUrl);
var messagesReceivedData = await messagesReceived.Content.ReadAsStringAsync();
var messages = JsonConvert.DeserializeObject<MessageSet>(messagesReceivedData);
return messages;
}
catch (Exception ex)
{
return SetExceptionMessage(ex);
}
}
private static MessageSet SetExceptionMessage(Exception ex)
{
Debug.WriteLine(ex.Message);
return new MessageSet()
{
Messages = (new List<BotMessage>
{
new BotMessage
{
Text = "Something went wrong!",
From = "Bot"
}
}).ToArray()
};
}
}
}
view raw ChatBotService.cs hosted with ❤ by GitHub
- We will have to create a TravelAgent Xaml page to display our conversation with the bot. -
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:TravelAppMobile.ViewModels;assembly=TravelAppMobile"
x:Class="TravelAppMobile.Pages.TravelAgentPage"
Title="Travel Agent">
<ContentPage.BindingContext>
<viewModels:TravelAgentPageViewModel></viewModels:TravelAgentPageViewModel>
</ContentPage.BindingContext>
<ContentPage.Content>
<StackLayout Orientation="Vertical"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
<ListView ItemsSource="{Binding Messages}"
Margin="10"
HasUnevenRows="True"
IsPullToRefreshEnabled="True"
IsRefreshing="{Binding IsRefreshing }">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
Orientation="Horizontal">
<Image Source="{Binding UserImageUrl}"></Image>
<Label Text="{Binding Message}"></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackLayout VerticalOptions="End" HorizontalOptions="FillAndExpand">
<Entry Placeholder="Please enter message.." Text="{Binding TextMessage}"></Entry>
<Button Text="Send" Command="{Binding SendMessageCommand}"></Button>
</StackLayout>
</StackLayout>
</ContentPage.Content>
</ContentPage>
view raw TravelAgentPage.xaml hosted with ❤ by GitHub
- Oh right, This how it should look like. We can now start to converse with our LUIS AI.

Wrapping Up

With Cognitive Services offering from Microsoft the possibilities are endless, with a little effort you can leverage a more natural human interaction elements to your apps. For more of this please browse here. The complete source code for this series can be found here. And we also gonna thank all who attended  "Love2Code" Session, And hoping to have more of this. If you have question or clarification just leave a comment below or you can go and shoot a message on our Xamarin Group. Original Author: 

Tags: Xamarin Forms and AI Bot Framework with LUIS



Xamarin Forms and AI Bot Framework with LUIS - Part 2

Posted by seven.srikanth@gmail.com at 28 May 2018 in Article


 Overview

Hi Guys, We will continue by creating our own Bot Connector using Microsoft Bot Framework Connector. The idea was to integrate to a different communication channels like Skype, SMS, Email and others, In our case we gonna integrate it with Directline so that our app will be able to communicate with LUIS. If you missed the first topic you can browse it here. This is a three part series and if you already confident about the topic you can proceed to the next. Xamarin.Forms and AI Bot Framework with LUIS -  Part 3

Getting started with the Connector

This is a step-by-step guide to writing a Bot in C# using the Bot Framework Connector SDK .NET template.
  1. Install prerequisite software Visual Studio 2015 (latest update) - you can download the community version here for free: www.visualstudio.com
  2. Important: Please update all VS extensions to their latest versions Tools->Extensions and Updates->Updates
  3. Download and install the Bot Application template
  4. Open Visual Studio
  5. Create a new C# project using the new Bot Application template. 
  6. The template is a fully functional Echo Bot that takes the user's text utterance as input and returns it as output. In order to run however,
  • The bot has to be registered with Bot Connector
  • The AppId and AppPassword from the Bot Framework registration page have to be recorded in the project's web.config
  • The project needs to be published to the web

Building your Bot

The core functionality of the Bot Template is all in the Post function within Controllers\MessagesController.cs. In this case the code takes the message text for the user, then creates a reply message using the CreateReplyMessage function. The BotAuthentication decoration on the method is used to validate your Bot Connector credentials over HTTPS.
-
[BotAuthentication]
public class MessagesController : ApiController
{
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
if (activity.Type == ActivityTypes.Message)
{
// calculate something for us to return
int length = (activity.Text ?? string.Empty).Length;
// return our reply to the user
Activity reply = activity.CreateReply($"You sent {activity.Text} which was {length} characters");
await connector.Conversations.ReplyToActivityAsync(reply);
}
else
{
HandleSystemMessage(activity);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
}
-

Emulator

Use the Bot Framework Emulator to test your Bot application The Bot Framework provides a a channel emulator that lets you test calls to your Bot as if it were being called by the Bot Framework cloud service. To install the Bot Framework Emulator, download it from here. Once installed, you're ready to test. First, start your Bot in Visual Studio using a browser as the application host.
Now open the Bot Framework Emulator. There are a few items that you will need to configure in the tool before you can interact with your Bot Application. When working with the emulator with a bot running locally, you need: The Url for your bot set the localhost:<port> pulled from the last step. > Note: will need to add the path "/api/messages" to your URL when using the Bot Application template. Empty out the MicrosoftAppId field Empty out the MicrosoftAppPassword field This will only work with the emulator running locally; in the cloud you would instead have to specify the appropriate URL and authentication values. For more about the emulator, read here.
Now that everything is configured you can interact with your service. The bottom of the Bot Framework Emulator application has a Text Box that you can use to enter a message, this message will be echoed back to you.

Adding LUIS

Now we are ready to add LUIS to our bot connector app all we need is to inherit LuisDialog<object> to handle query. below is the code which handles all the Intents coming from the json result of query. Note: please provide your own modelId and subscription key which can be obtain from https://www.luis.ai/ -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.FormFlow;
using Microsoft.Bot.Builder.Luis;
using Microsoft.Bot.Builder.Luis.Models;
using Microsoft.Bot.Builder.Resource;
using Microsoft.Bot.Connector;
namespace TravelAppBot.Dialogs
{
/// <summary>
/// you can get modelid and subscriptionkey from luis.ai
///
/// </summary>
[Serializable]
[LuisModel("24474ca3-51d5-4338-ba05-f6aac8c1e7c4", "ed802dde7db34d20894d6a552cd1d028")]
public class RootLuisDialog : LuisDialog<object>
{
[LuisIntent("")]
[LuisIntent("None")]
public async Task None(IDialogContext context, LuisResult result)
{
string message = $"Sorry, I did not understand '{result.Query}'. Type 'help' if you need assistance.";
await context.PostAsync(message);
context.Wait(this.MessageReceived);
}
[LuisIntent("Help")]
public async Task Help(IDialogContext context, LuisResult result)
{
await context.PostAsync("Hi! Try asking me things like 'book me a flight from london to paris' or 'what is the weather like in new york'");
context.Wait(this.MessageReceived);
}
[LuisIntent("BookFlight")]
public async Task BookFlight(IDialogContext context, LuisResult result)
{
GetEntityRecommendation("Location::FromLocation", "FromLocation", result);
GetEntityRecommendation("Location::ToLocation", "ToLocation", result);
GetEntityRecommendation("builtin.datetime.date", "DepartureDate", result);
await context.PostAsync("booking you flight...");
var form = new BookFlightForm();
var hotelsFormDialog = new FormDialog<BookFlightForm>(form, this.BuildHotelsForm, FormOptions.PromptInStart, result.Entities);
context.Call(hotelsFormDialog, this.ResumeAfterFlightFormDialog);
}
private static void GetEntityRecommendation(string fromType, string toType, LuisResult result)
{
EntityRecommendation dateEntityRecommendation;
if (result.TryFindEntity(fromType, out dateEntityRecommendation))
{
dateEntityRecommendation.Type = toType;
}
}
private IForm<BookFlightForm> BuildHotelsForm()
{
OnCompletionAsyncDelegate<BookFlightForm> processBooking = async (context, state) =>
{
var message = "Thank you for completing the query, we are about to book you a flight...";
await context.PostAsync(message);
};
return new FormBuilder<BookFlightForm>()
.Field(nameof(BookFlightForm.FromLocation), (state) => string.IsNullOrEmpty(state.FromLocation))
.Field(nameof(BookFlightForm.ToLocation), (state) => string.IsNullOrEmpty(state.ToLocation))
.Field(nameof(BookFlightForm.DepartureDate), (state) => string.IsNullOrEmpty(state.DepartureDate))
.OnCompletion(processBooking)
.Build();
}
private async Task ResumeAfterFlightFormDialog(IDialogContext context, IAwaitable<BookFlightForm> result)
{
try
{
var searchQuery = await result;
var fromLocation = searchQuery.FromLocation;
var toLocation = searchQuery.ToLocation;
var scheduledDate = searchQuery.DepartureDate;
////EXECUTE BOOKFLIGHT
var message = $"Your flight has been booked from {fromLocation} to {toLocation} scheduled {scheduledDate}";
await context.PostAsync(message);
}
catch (FormCanceledException ex)
{
string reply;
if (ex.InnerException == null)
{
reply = "You have canceled the operation.";
}
else
{
reply = $"Oops! Something went wrong :( Technical Details: {ex.InnerException.Message}";
}
await context.PostAsync(reply);
}
finally
{
context.Done<object>(null);
}
}
[Serializable]
public class BookFlightForm
{
[Prompt("From which city do you want to leave from? {||}", AllowDefault = BoolDefault.True)]
[Describe("Location, example: Amsterdam")]
public string FromLocation { get; set; }
[Prompt("To which city you want to fly to? {||}", AllowDefault = BoolDefault.True)]
[Describe("Location, example: Las Vegas")]
public string ToLocation { get; set; }
[Prompt("When do you want to leave? {||}", AllowDefault = BoolDefault.True)]
[Describe("Departure date, example: tomorrow, next week or any date like 12-06-2016")]
public string DepartureDate { get; set; }
}
}
}
view raw RootLuisDialog.cs hosted with ❤ by GitHub
- For the complete source you can download it here.

Publishing your Bot Application to Microsoft Azure

In this tutorial, we use Microsoft Azure to host the Bot application. To publish your Bot Application you will need a Microsoft Azure subscription. You can get a free trial from here: azure.microsoft.com/en-us/ Make what changes you like to the project, and now you're ready to publish. Right click on the project and choose "Publish", and then your appropriate Azure subscription information. By default, the bot should be published as an Microsoft Azure App Service. When publishing, keep track of the URL you chose because we'll need it to update the Bot Framework registration endpoint. The first time you publish there are a few extra steps; but you only have to do them once. In Visual Studio, right clicking on the project in Solution Explorer and select "Publish" - or alternately selecting "Build | Publish" displays the following dialog:
The next step in the Azure App Service publishing process is to create your App Service. Click on "New…" on the right side of the dialog to create the App Service.
The Create App Service dialog will be displayed, fill in the details as appropriate.Make sure to choose "Web App" from the Change Type drop down in the top right instead of "API App"(which is the default).
One final complexity on this dialog is the App Service Plan. This just lets you give a name to a combination of location and system size so you can re - use it on future deployments. Just put in any name, then choose the datacenter and size of deployment you want. Once you hit okay on the App Service Plan, you'll have defined your App Service completely. Hit Create, and you'll be taken back to the Publish Web Wizard. Now that you've returned to the Publish Web wizard copy the destination URL to the clipboard, you'll need it in a few moments. Hit "Validate Connection" to ensure the configuration is good, and if all goes well, click "Next". By default your Bot will be published in a Release configuration. If you want to debug your Bot, change Configuration to Debug. Regardless, from here you'll hit "Publish" and your Bot will be published to Azure. You will see a number of messages displayed in the Visual Studio 2015 "Output" window. Once publishing is complete you will also see the web page for your Bot Application displayed in your browser (the browser will launch, and render your Bot Application HTML page), see below.

Registering your Bot with the Microsoft Bot Framework

Registering your Bot tells the Connector how to call your Bot's web service. Note that the MicrosoftAppId and MicrosoftAppPassword** are generated when your Bot is registered with the Microsoft Bot Framework Connector, the MicrosoftAppId and MicrosoftAppPassword are used to authenticate the conversation, and allows the developer to configure their Bot with the Channels they'd like to be visible on. The BotId, which you specify, is used for the URL in the directory and developer portal.
  1. Go to the Microsoft Bot Framework portal at https://dev.botframework.com and sign in with your Microsoft Account.
  2. Click the "Register a Bot" button and fill out the form. Many of the fields on this form can be changed later. Use a the endpoint generated from your Azure deployment, and don't forget that when using the Bot Application tempalate you'll need to extend the URL you pasted in with the path to the endpoint at / API / Messages. You should also prefix your URL with HTTPS instead of HTTP; Azure will take care of providing HTTPS support on your bot. Save your changes by hitting "Create" at the bottom of the form.
Once your registration is created, Microsoft Bot Framework will take you through generating your MicrosoftAppId and MicrosoftAppPassword. These are used to authenticate your Bot with the Microsoft Bot Framework. NOTE: When you generate your MicrosoftAppPassword, be sure to record it somewhere as you won't be able to see it again. Now that the Bot is registered, you need to update the keys in the web.config file in your Visual Studio project. Change the following keys in the web.config file to match the ones generated when you saved your registration, and you're ready to build. Clicking the "show" link will show the value, along wtih exposing the regenerate link if you ever need to change your AppPassword. Update your web.config, and re-publish your bot to Azure. -
<? xml version = "1.0" encoding = "utf-8" ?>
< !--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301879
-->
< configuration >
< appSettings >
< !--update these with your appid and one of your appsecret keys-->
< add key = "MicrosoftAppId" value = "[GUID]" />
< add key = "MicrosoftAppPassword" value = "[PASSWORD]" />
</ appSettings >
view raw appsettings.xml hosted with ❤ by GitHub
-

Testing the connection to your bot

Back in the developer dashboard for your Bot there's a test chat window that you can use to interact with your Bot without further configuration, and verify that the Bot Framework can communicate with your Bot's web service. Note that the first request after your Bot starts up can take 10 - 15 s as Azure starts up the web service for the first time. Subsequent requests will be quick. This simple viewer will let you see the JSON object returned by your Bot.

Configuring Channels

Now that you have a Bot up and running, you'll want to configure it for one or more channels your users are using. Configuring channels is a combination of Microsoft Bot Framework workflow and conversation service workflow, and is unique for each channel you wish to configure.
  1. To configure a channel, go back to the Bot Framework portal at https://www.botframework.com. Sign in, select your Bot, and go to the channels panel.
Pick the channel you wish to configure, and click add. You'll be taken to a page of instructions for registering a Bot. In the end in most cases you're configuring your credentials as a developer on the target service, registering your app, and getting a set of Oauth keys that Microsoft Bot Framework can use on your behalf. In our case we will use DirectLine in order for our apps to have easy communication with LUIS. We can use the secret keys for our Xamarin.Forms App and should be able to connect with directline channel. And for the Xamarin.Forms project we will have it on part 3 of this series. Xamarin.Forms and AI Bot Framework with LUIS -  Part 3
Original Author: 
Source: http://winstongubantes.blogspot.in/2017/02/xamarinforms-and-ai-bot-framework-with.html

Tags: Xamarin Forms and AI Bot Framework with LUIS