Friday, May 19, 2017

Xamarin.Forms Hybrid Apps

Why Hybrid Apps?



This has always been a common approach if you do Cordova or PhoneGap and it should do a great job for simple apps that doesn't rely too much platform specific feature, The question is why should we do it in Xamarin? Or what scenario would persuade us to use hybrid approach?


My early days with Xamarin development, That time where there were no reliable Charting library available yet, My team were force to use other alternative and so we decided to use webview with the help of Xlab's HybridWebview library and highcharts javascript library we were able to satisfy our customers need.


Be aware that Xlabs project is no longer maintained. It may NOT work with newer versions of Xamarin.Forms. Though it has done a great job i am not recommending it for use because its somewhat bloated, things that we are not gonna need. Fortunately for us i have found this lightweight HybridWebview library thanks to Ryan Dixon. Now we should be able to do Hybrid apps, Later we will discuss how to setup our web files per each platform, I will provide two examples, First is we will gonna use Highcharts and second we will gonna use Pignoise calendar.


This libraries along with hybridwebview is a better alternative if you cannot afford a pricey libraries from known component vendors (you know them), Though they have done a great job in bringing this native component it is of course your choice.









Creating Your Xamarin.Forms project



Very straightforward just a create a xamarin project and you should be able to create three platforms project atleast and one PCL project. Then you must install Webview nuget package by Ryan Dixon this is a very lightweight library, Make sure to install it on all platforms. In our case we used TabbedPage to showcase each javascript library.











Setup Your Highcharts and Calendar page



Now to setup your highcharts library, keep in mind that the file structures differs per each platform, For Android project, all your html, styles and javascript file must be placed under Assets folder while in iOS project it should be placed under Resources folder and For UWP or WindowsPhone project must be under its root. You can take a look how it should be structured per platform.


Android





iOS





UWP









Communicate Your Web Page to Backend



If you want to know the details how the communication between your page and your Backend explains so much in this documentation. First thing you should do is to register a callback using RegisterLocalCallBack method (the complete documentation and source code can be found here).
In our case we use the calendar selectdate method(to call backend method).

Register a callback something like this in You Xamarin Code:




Now in your html page you can call a method like this to invoke the callback from Xamarin Code








Additional Note



Here is the minimal reason in my case that if we do hybrid we should do it in Xamarin.Forms rather than Cordova.
  • It’s performant; it compiles down to native.
  • Implements most logic in C# with minimal amounts of native code specific to Android or iOS.
  • You can use most javascript libraries like Jquery, Ember and AngularJs




Wrapping Up


Doing native is not always the silver bullet, there were times we need to do simple stuff to accomplish the needed business needs. But Xamarin.Forms can always do both if it needs to. I hope this article have helped you. If you want the full sample source you can check it right here LINK.













Friday, February 10, 2017

Xamarin.Forms Creating Your Own Custom Dialog

Overview


Sometimes the existing dialogs from Xamarin.forms does not conforms to what we need like custom dialog which contains some entry and ok cancel button or perhaps a listview inside a dialog that may contain complex UI, existing libraries like in this link and acr dialog doesnt give us what exactly we want in a dialog. And worst we will resort with custom renderers to achieve this.

So i made a custom dialog made purely in xaml without custom renderer. Yes you read it right its pure xaml, you can check the full source code here.





How to use


Just copy the source implementation of PopUpDialogView just like you see in the screen below, you can customize it to conform with your design Or may add another animation transition during show and hide.






Adding PopUpDialogView in your page is simple, you will  need to add a Grid Layout without rows and columns, please take a look at the code below.


- -


Wrapping Up


You can check the full source here, For more about Xamarin.Forms you can always check their site and if you want something fresh you can check their blog. If you have questions please feel free to comment just below this article.










Thursday, February 9, 2017

Xamarin.Forms and Azure Easy Tables (as easy as 1 2 3)

Overview


Hi Guys, we are about to discuss Xamarin.Forms with Azure Appservices Easy Tables, great front-end apps need great back-end and there is tons of solution or options of doing it, But today we will see how Azure has done a great job making it relatively easy for developers to connect on back-end service without coding it.



Getting Started


Now lets create a Mobile App Service in Azure Portal, Go ahead by clicking "Mobile App" as shown in a screenshot below.





Now click create.






Name your app accordingly, in our case we named it "conversationapp". If you have no existing resource you can create new one or you can use your existing one. Now click create.





Now click "Easy Tables" in order for us to create table.






You will notice that, you will need to configure your easy tables as it has detected that no database has been created for use in your easy tables.







Now click the highlighted link below to create a new database.







Click add to create database.










Now name your database, in our example we name it "conversationdb".







You can select pricing accordingly, in our case we use free since this is for testing purpose. But in production we should use a more appropriate capacity according to our app's scaling need.







We also gonna need to create a server for our db, in our case we use the location "East Asia".






When you are done with creating a database, you are now ready to initialize App Service to use easy tables. Now click Initialize App.






Now go and create a table named "Message", we make it more simple as possible. You can create as many tables depending on your app. We can also set table relationship when it needs to, be aware to editing deleting columns created by Azure tables that might cause an issue with syncing.





And that's it for the App Service.




Creating our app to Connect With Easy Tables


Now that our app service is ready to rock in roll, we can now create our app to connect with easy tables. First create a new Xamarin.Forms project and name it "ConversationApp".






Create model for Message


- -


Creata ViewModel for ConversationPage and name it "ConversationPageViewModel"


- -


Create a new Page and name it ConversationPage.xaml






- -


Now create our AzureService client class to make a sync calls to our easy tables, but before that, we will need to install nuget packages for MobileServiceClient in our PCL and Platform projects as shown below.






Initialize the Azure Mobile Client



Add the Azure Mobile Client SDK initialization code in the platform projects. For iOS, the following code must be added to the FinishedLaunching method of the AppDelegate class:

Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
SQLitePCL.CurrentPlatform.Init();



For Android, add the following to the OnCreate method of your MainActivity:

Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();


We will now create AzureDataService , the following are the code



- -



We will now be able to run our Xamarin project, please make sure to make platform project as a startup. It should look like this.






You should be able to see the data you sync in Azure Easy Tables, without a sweat :D


Please check the full source code here.


Wrapping Up

Azure App Services provides more flexibility for mobile development integrating Authentication, Notification and that what makes it a developer centric tool. To learn more of this please check our Xamarin Blog  https://blog.xamarin.com . Please dont hesitate to leave a message if you have clarification or question. Thats all.











Xamarin.Forms and AI Bot Framework with LUIS - Part 3

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.

- -


Then we need to create ConversationMessage model for our Xaml Page Message UI.

- -

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.

- -


We will have to create a TravelAgent Xaml page to display our conversation with the bot.

- -


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.










Xamarin.Forms and AI Bot Framework with LUIS - Part 2

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.

- -

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/



- -

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.


- -


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


























Xamarin.Forms and AI Bot Framework with LUIS - Part 1

Overview


Hi Guys, We are about to discuss another Xamarin.Forms article which introduce the idea of conversational computing in an organic way (AI), where hoomans can use their natural language in making a command to apps which can have an IoT integration or can be simple conversational bot with a human understanding.

First, we gonna discuss about Language Understanding Intelligent Services (LUIS) and how to utilize its capability. 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 2

Xamarin.Forms and AI Bot Framework with LUIS -  Part 3

Benefits to using LUIS


One of the key problems in human-computer interactions is the ability of the computer to understand what a person wants, and to find the pieces of information that are relevant to their intent. For example, in a travel agent app, you might say "Book me a ticket to Paris" in which case there is the intention to "BookTicket" while "Paris" is the location entity. Intention can be defined as the desired action and usually contains a verb, in this case "book", and the entity is the topic/subject, in this case "Paris", of the action.



Using LUIS for the first time


Language Understanding Intelligent Services (LUIS) brings the power of machine learning to your apps, you can custom design a set of intentions and entities that are relevant to your application, then let LUIS guide you through the process of building a language understanding system.

To use LUIS, first make sure that you have an up-to-date version of Microsoft Edge, Internet Explorer or Google Chrome. Go to the home page www.luis.ai and log in. You will see a screen like the one below.



Creating your first LUIS application


LUIS applications are centered around a domain-specific topic, for example booking of tickets, flights, hotels, rental cars etc. or content related to exercising, tracking fitness efforts and setting goals. You need to decide on a domain-specific topic before you can create your LUIS application. In this case, let's take the example of a virtual travel booking agency application. In the application, you will bundle together the intents and entities that are important to your task. Two intents relevant to the domain of travel booking are "BookFlight" and "GetWeather". Two entities that are important are "Location" and "DateTime". Once you have identified the intents and entities, it is possible for LUIS to take appropriate action, when a user interacts with your application.


Step 1: Creating an application






Step 2: Adding intents, entities and labels


Next, we will add two intents to the application. At the top left of the menu panel, you will see an area for intents. All applications come with one pre-defined intent, None. This will recognize user statements that have nothing to do with the application, for example if someone says "Get me a great cookie recipe".

Go ahead and click + next to Intents on the horizontal bar. You'll see a dialog box appear to add a new intent. Enter the intent name of "BookFlight", and the example command that triggers the intent as "Book flight to Paris". This will look like the screenshot below.



Click Save, and the utterance will be presented for labeling. The intent "BookFlight" (just click on it) will be highlighted, and you will see a drop-down with the entities you've defined. Click Submit to submit the utterance to your LUIS app.




Defining entities


  1. In the Application Editor workspace, find Entities in the left-hand menu panel, then click the + sign.
  2. In the Add a new Entity dialog box, type "Location" as the entity name.
  3. Click the plus sign next to the Entity Children.
  4. In the text box that appears, type the name of the first child, "ToLocation".
  5. Click the plus sign again to add the second child, “FromLocation”, and so on.
  6. To delete a child, if you made a mistake, click the trash can sign next to the entity child.
  7. When finished, click "Save".





Step 3: Seeding the system by labeling utterances


With a set of intents and entities defined, the next step is to provide more examples of utterances that illustrate these concepts. Click on the New Utterances tab at the top of the screen. Type "Book a flight to London" into the entry box and hit Enter. You will see a drop-down box showing the possible intents. Select "BookFlight" by highlighting it. Click on "london" and select "Location" from the drop-down box and you'll see the word "london" highlighted in yellow, indicating that you've labeled the word "london" as a "Location". Choose whether it is a "ToLocation" or "FromLocation", then click Submit to submit this label.






The system needs to be seeded with several examples of each intent, and several examples of each entity. Don't forget to add an example or two of a None intent, for example, enter "I like ice cream". Note, that LUIS converts all utterances to lower case.

The system has now been seeded with enough data to deploy an initial application. That is done by training and publishing a model.

Step 4: Training


When you "train" a model, LUIS generalizes from the examples you have labeled, and develops code to recognize the relevant intents and entities in the future. Internally, LUIS uses logistic regression classifiers to determine intents, and conditional random fields (CRFs) to determine the entities. The training process results in optimized classifiers and CRFs, referred to as models, that LUIS can use in the future. To do training, just click the Train button at the left bottom corner of the page. Training also occurs automatically with regular intervals.

Step 5: Publishing a model


The next step is to deploy the model to an HTTP endpoint that will interpret the sentences we send it. Click the Publish button in the upper left-hand corner, and then Publish web service in the resulting window. After a couple of moments, you will see a url that makes your model available as a web service. LUIS will look like the below screenshot. To acquire a subscription key, see Creating Subscription Keys Via Azure Ibiza.


Understanding the JSON response


  1. Set the URL parameter to be your query/utterance, for example, "Book me a flight to Boston on May 4", then click Update published application..
  2. Hit the Enter key or click on the generated URL in the dialog box.





FieldJson typeDescription of content in example
QuerystringQuery/utterance: "Book me a flight to Boston on May 4"
IntentsobjectAll intents listed (each with their highest score): "BookFlight", "None", "GetWeather"
ScorenumberConfidence score, between 0 and 1. Only the highest score is listed for each intent.
Entitiesobject"boston", Type: Location::ToLocation (parent::child). "may 4", Type: builtin.datetime.date
ScorenumberConfidence score, between 0 and 1. Only the highest score is listed for each entity.
"date"string"XXXX-05-04"

Oh right, we are good but we are not done yet

On our part 2 we gonna continue by creating our Bot Connector using Microsoft Bot Framework,


Summary

You have now built a basic LUIS application. This application can be enhanced by adding more advanced features.