Mobile Archives | CodeGuru https://www.codeguru.com/mobile/ Mon, 09 Aug 2021 21:41:48 +0000 en-US hourly 1 https://wordpress.org/?v=6.3.2 Common Libraries Used in Xamarin Forms App Development https://www.codeguru.com/mobile/common-libraries-used-in-xamarin-forms-app-development/ Mon, 16 Oct 2017 07:15:00 +0000 https://www.codeguru.com/uncategorized/common-libraries-used-in-xamarin-forms-app-development/ Introduction In this article, we will discuss the libraries that are commonly used in mobile app development. The libraries discussed herein are from the perspective of developing an overall solution. They also suggest the common practices followed in app development. Description The following are the commonly used libraries: FreshMVVM The apps developed these days use […]

The post Common Libraries Used in Xamarin Forms App Development appeared first on CodeGuru.

]]>
Introduction

In this article, we will discuss the libraries that are commonly used in mobile app development. The libraries discussed herein are from the perspective of developing an overall solution. They also suggest the common practices followed in app development.

Description

The following are the commonly used libraries:

FreshMVVM

The apps developed these days use the MVVM pattern. This pattern helps in segregating the logic from the user interface which, in turn, results in clean and maintainable code. There are different MVVM toolkits available—MVVM Light and FreshMVVM. FreshMVVM is one of the popular and simpler toolkits used to implement the MVVM pattern in Xamarin forms.

FreshIOC

In addition, the FreshMVVM package also includes an IOC (Inversion of Control) container. This helps in registering and resolving the different services used in the app.

For example, there is a requirement to share text messages. Because sharing is a platform-level feature, this needs to be implemented in Android and iOS projects. To communicate from Xamarin forms to the platform level projects, we will use dependency service and dependency injection.

We first define an interface, ‘IShareInfo.cs,’ in the Xamarin Forms project. This interface has a method named ‘ShareText’. The interface then is registered with the IOC container in App.Xaml.cs:

FreshIOC.Container.Register(DependencyService
   .Get<IShareInfo>());
var shareService = FreshIOC.Container.Resolve<IShareInfo>();
MainPage = new ShareMessageAppPage(shareService);

This service then is passed as a parameter to the page model’s constructor or to the code behind. In this example, the constructor of the code behind is as shown next:

IShareInfo _shareInfo;
public ShareMessageAppPage(IShareInfo shareInfo)
{
   InitializeComponent();
   _shareInfo = shareInfo;
}

FFImageLoading

The FFImageLoading library provides a quick way to load and cache images. It supports images as a URL, from resource files, and also from stream content. It also supports SVG image formats. In addition, it also provides image transformations, such as round images. It has the provision to display a placeholder image while the image is being loaded and also to display an error image when the image is not found.

To use FFImageLoading, add the NuGet package to the Xamarin Forms project and, in the XAML, file add the references for the FFImageLoading as shown in the next code snippet:

xmlns:ffimg="clr-namespace:FFImageLoading.Forms;
   assembly=FFImageLoading.Forms"
xmlns_ffimgsvg="clr-namespace:FFImageLoading.Svg.Forms;
   assembly=FFImageLoading.Svg.Forms"
xmlns_ffimgtransform="clr-namespace:FFImageLoading
   .Transformations;assembly=FFImageLoading.Transformations"

Here’s how you can display a normal image as a circular image:

<ffimg:CachedImage WidthRequest="120"
HeightRequest="120"
Aspect="AspectFill"
LoadingPlaceholder="placeholder.gif"
Source="{Binding ImageUrl}">
<ffimg:CachedImage.Transformations>
<ffimgtransform:CircleTransformation />
</ffimg:CachedImage.Transformations>
</ffimg:CachedImage>

To display an image in SVG format, use the following code:

<ffimgsvg:SvgCachedImage WidthRequest="20"
HeightRequest="20"
Source="image.svg" />

ModernHTTPClient

HTTP calls are networking calls and are platform specific. iOS uses NSURLSession to do HTTP calls and Android uses OkHttp. ModernHTTPClient hides the platform-level complexities and makes it simple to call from the Xamarin Forms project. We still use the HttpClient of the System.Net.Http, and pass an object of NativeMessageHandler, a class in ModernHttpClient. Here’s an example:

var httpClient = new HttpClient(new NativeMessageHandler());

NativeMessageHandler also can be used with OAuth authentication by using ThinkTecture. Add the package ‘Thinktecture.IdentityModel.Client’ to the Xamarin Forms project. When creating the OAuth2Client object. pass the message handler as an object. Here’s a way to do that:

var handler = new NativeMessageHandler()
{
   AutomaticDecompression = DecompressionMethods.GZip
};

return new OAuth2Client(<Uri address>, clientId,
   clientSecret, handler,
OAuth2Client.ClientAuthenticationStyle.BasicAuthentication);

Where Uri address is the endpoint URL for authentication, clientId is the string that uniquely identifies the app, clientSecret is also a string. The handler is an instance of NativeMessageHandler (ModernHttpClient). And, the last parameter is the authentication style, which is set to Basic.

FlowListView

Flowlistview is another helpful library that helps in displaying the multiple records in a row (in multiple columns). The default list allows only one record per row.

Telerik Suite

Telerik provides a list of controls for Xamarin Forms and also for platform-level projects. The sideDrawer, chart, and list view are a few of the controls that can serve many requirements. Side drawer can be used to display different sets of options or action items. It also can be used for context menus. There are a variety of chart options provided by Telerik. However, it’s a paid set of controls.

GCM Client Component

Push notifications is one of the most common features of a mobile app. To enable push notifications on Android, we need a GCM Client component added to the Android project. We define a class that inherits from the GCMServiceBase and is decorated with a Service tag.

[Service]   // You must use the Service tag
public class DemoGcmService : GcmServiceBase
GcmClient.Register(Context, SENDER_IDS);

GcmClient.Register uses the project ID registered in the firebase console site. This then can be integrated with the Azure notification hub to send notifications.

Summary

In this article, we reviewed the common NuGet packages and components that can be used in app development. The FreshMVVM package helps you to follow the recommended pattern when developing apps. OAuth authentication is also a common scenario when accessing APIs from the app.

References

The post Common Libraries Used in Xamarin Forms App Development appeared first on CodeGuru.

]]>
Displaying Push Messages in a Custom UI (Xamarin-Android) https://www.codeguru.com/mobile/displaying-push-messages-in-a-custom-ui-xamarin-android/ Mon, 10 Jul 2017 07:15:00 +0000 https://www.codeguru.com/uncategorized/displaying-push-messages-in-a-custom-ui-xamarin-android/ Introduction Push notifications normally are displayed as a toast messages. There can be a scenario where a toast message is to be displayed in a custom UI as a popup or an alert message. In this article, we will display a popup dialog when a notification is received and the app is open. If the […]

The post Displaying Push Messages in a Custom UI (Xamarin-Android) appeared first on CodeGuru.

]]>
Introduction

Push notifications normally are displayed as a toast messages. There can be a scenario where a toast message is to be displayed in a custom UI as a popup or an alert message. In this article, we will display a popup dialog when a notification is received and the app is open. If the app is not active, we display the regular toast message. We will use BroadcastReceiver to broadcast the message internally in the app to display the message in a custom format.

Description

As a prerequisite, the GCM and Azure Notification bug are configured. We start with creating a Xamarin mobile application that will display the notification message in a custom UI.

GCMService Implementation

In Xamarin Studio, create a new multi-platform Xamarin Forms project. Add a “Google Cloud Messaging Client” component under the components folder:

Creating a new Xamarin Forms project
Figure 1: Creating a new Xamarin Forms project

Add a class file named “DemoBroadcastReceiver.cs” and place the following code in it:

[BroadcastReceiver(Permission = Constants.PERMISSION_GCM_INTENTS)]
// Allow GCM on boot and when app is closed
[IntentFilter(new[] { Intent.ActionBootCompleted })]
[IntentFilter(new string[] { Constants.INTENT_FROM_GCM_MESSAGE },
Categories = new string[] { "<Package name>" })]
[IntentFilter(new string[]
   { Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK },
Categories = new string[] { "<Package name>" })]
[IntentFilter(new string[]
   { Constants.INTENT_FROM_GCM_LIBRARY_RETRY },
Categories = new string[] { "<Package name>" })]
public class DemoGcmBroadcastReceiver :
   GcmBroadcastReceiverBase<DemoGcmService>
{
   // The SENDER_ID is the project number/sender Id from the
   // Google console/firebase
   public static string[] SENDER_IDS = { "Sender Id" };
}

Set the value of the sender ID with the saved project number/sender ID in the ‘Configure GCM’ section. Replace ‘<Package name>’ with the app’s package name.

Add another class file, named ‘DemoGcmService.cs’. This file has a prefix [Service] and is inherited from ‘GcmService.’ Add the following code to the class:

1. [Service]
   public class DemoGcmService : GcmServiceBase
   {
      static NotificationHub hub;
2.    public DemoGcmService() :
         base(DemoGcmBroadcastReceiver.SENDER_IDS)
      {
      }
3.    public static void Initialize(Context context)
       {
          var cs = "<Azure Listner End Point>";
          var hubName = "<Notification hub name>";
          // Azure notification
          hub = new NotificationHub(hubName, cs, context);
      }
4.    public static void Register(Context Context)
      {
         GcmClient.Register(Context,
            DemoGcmBroadcastReceiver.SENDER_IDS);
      }
5.    protected override void OnRegistered(Context context,
         string registrationId)
      {
         // Receive registration ID and register it on Azure
         if (hub != null)
            hub.Register(registrationId, "TEST");
      }
6.    protected override void OnUnRegistered(Context context,
         string registrationId)
      {
         if (hub != null)
            hub.Unregister();
      }
7.    protected override void
         OnMessage(Context context, Intent intent)
      {
         var notificationManager =
            GetSystemService(Context.NotificationService) as
            NotificationManager;
         var title = "Alert";
         var desc = intent.Extras.GetString("message");

         var uiIntent = new Intent(this, typeof(MainActivity));
         PendingIntent intent1 = PendingIntent.GetActivity(this,
            0, uiIntent, PendingIntentFlags.CancelCurrent);
         Android.App.Notification.Builder builder = new
            Android.App.Notification.Builder(this)
               .SetContentTitle(title)
               .SetContentText(desc)
               .SetFullScreenIntent(intent1, true)
               .SetAutoCancel(true)
               .SetSmallIcon(Android.Resource.Drawable
                  .SymActionEmail);

         // Build the notification:
         Android.App.Notification notification = builder.Build();

         notification.Defaults = NotificationDefaults.All;

         // Publish the notification:
         const int notificationId = 0;
         notificationManager.Notify(notificationId, notification);

      }
8.    protected override bool OnRecoverableError(Context context,
         string errorId)
      {
         // On Recoverable Error
         return true;
      }
9.    protected override void OnError(Context context,
         string errorId)
      {
         // On Error
      }
   }   // End of class

Let’s walk through the code. Line 1 prefixes the class as a [service] and is a required step. Stub 2 defines a constructor where we pass the sender’s ID—the project number created in Google Console. In Stub 3, we create an instance of the Azure notification hub.

To get the connection string for the Notification hub, navigate to Azure Portal → ‘All Resources’ →. Click the notification hub that was created earlier. On the Notification hub, click ‘Access Policies.’

Clicking 'Access Policies'
Figure 2: Clicking ‘Access Policies’

Copy the connection string with ‘Listen’ permissions to replace the connection string placeholder in Stub 3. Replace the ‘Notification hub name’ with the name of the Notification hub created in Azure. Step 4 registers the current context with the GCM component. Once Step 4 is completed successfully, it executes Step 5 to register the device with Azure. Step 6 is called when the user doesn’t want to receive the notifications.

Step 7, the ‘OnMessage’ method, is called when a message is received. It creates an instance of the notification manager, which displays the message on the UI. In this example, the format of the message received is:

{"data":{"message":"Notification Hub test notification"}}

So, the line

var desc = intent.Extras.GetString("message");

gets the message body. Next, we create an Intent and pass the intent to the notification builder with the message. Then, create a notification object using the notification builder and pass the notification object to the notification manager to display the message. The message finally displayed to the user is shown in Figure 3:

The displayed message
Figure 3: The displayed message

This displays the normal toast notification message.

Application State

To display a custom UI, we first create a class named “ApplicationStateVerification” inherited from ‘Application.’ A bool property named ‘applicationOnPause‘ is created; it saves the current state of the application. This property is private and is made available by using public methods.

1. public class ApplicationStateVerification : Application
2. {
3.    {
4.       static bool applicationOnPause = false;
5.       public override void OnCreate()
         {
            base.OnCreate();
         }
6.       public static bool IsActivityVisible()
         {
            return !applicationOnPause;
         }
7.       public static void ActivityResumed()
         {
            applicationOnPause = false;
         }
8.       public static void ActivityPaused()
         {
            applicationOnPause = true;
         }
9.    }

Broadcast Receiver

To display the custom UI, create a class named ‘NotificationBroadcastReceiver,’ inherited from ‘BroadcastReceiver,’ and implement the ‘OnReceive‘ method. This method will display the message as an alert.

class NotificationBroadcastReceiver : BroadcastReceiver
{
   public override void OnReceive(Context context, Intent intent)
   {
      var desc = intent.Extras.GetString("message");
      AlertDialog.Builder alert = new AlertDialog.Builder(context);
      alert.SetTitle ("Notification Received");
      alert.SetMessage (desc);

      alert.SetPositiveButton ("Close", (senderAlert, args) => {});

      Dialog dialog = alert.Create();
      dialog.Show();
   }
}

MainActivity Changes

On the ‘MainActivity.cs’, we register the ‘NotificationBroadcastReceiver.’ The necessary code follows:

1. const string NOTIFICATION_ACTION = "ReceiverValue";
2. private BroadcastReceiver notificationBroadcastReceiver =
      new NotificationBroadcastReceiver();

3. protected override void OnCreate(Bundle bundle)
   {
      // Initialization code
      ...

      // Initialize the GcmService
      DemoGcmService.Initialize (this);

      // Register device with GCM
      DemoGcmService.Register (this);
   }
4. protected override void OnStart()
   {
      base.OnStart();

      // Register the receiver
      IntentFilter intentFilter = new
         IntentFilter(NOTIFICATION_ACTION);
      RegisterReceiver(notificationBroadcastReceiver,
         intentFilter);

      // Set the application state
      ApplicationStateVerification.ActivityResumed();
   }
5. protected override void OnStop()
   {
      base.OnStop();

      // When the app is closed, un-register the receiver
      UnregisterReceiver(notificationBroadcastReceiver);

      // Set the application state
      ApplicationStateVerification.ActivityPaused();
   }
6. protected override void OnResume()
   {
      base.OnResume();
      // Set the application state
      ApplicationStateVerification.ActivityResumed();
   }

Line 1 defines the name of the intent and Line 2 creates an object of the ‘NotificationBroadcastReceiver,’ which is then registered in the ‘OnStart’ method, as in Stub 4. In Stub 5, the ‘OnStop’ method, the broadcast receiver is un-registered. The application state is set respectively in OnStart, OnStop, and the OnResume methods. ‘OnCreate‘ initializes and registers the device with the GCM Service.

Until now, the device is registered for notification, and the broadcast receiver is defined and registered. Now, when a notification message is received, it needs to be broadcast to display the message in a custom format. Add the next code to the ‘OnMessage’ method defined in the ‘GCM Service Implementation’ section:

1. bool isActivityVisible =
      ApplicationStateVerification.IsActivityVisible();
2. const string NOTIFICATION_ACTION = "ReceiverValue";
3. var desc = intent.Extras.GetString("message");
4. if (isActivityVisible)
   {
      Intent alerIntent = new Intent(NOTIFICATION_ACTION);
      alerIntent.PutExtra("message", desc);
      context.SendBroadcast(alerIntent);
   }
5. else
   {
      // Code to display the toast message
      ...
   }

Line 1 gets the current state of the application. Line 2 is the same constant value that was defined in ‘MainActivity.cs.’ Line 3 gets the message content received in the OnMessage method. If the app state is open, create a new intent, add the message to the intent, and then broadcast the message. This message is received by the ‘OnReceive‘ method of the broadcast receiver and the output is as shown in Figure 4:

The notification was received
Figure 4: The notification was received

To test this, navigate to notification hub created in Azure and click ‘Test Send.’

Ready to click 'Test Send'
Figure 5: Ready to click ‘Test Send’

Select the platform as ‘Android’ and click Send.

Summary

In this article, we went through the steps to configure the GCM with Azure and the App level changes to enable push notification. A broadcast receiver was implemented to display the custom UI message.

Reference

Sending Push Notifications from Azure Mobile Apps

The post Displaying Push Messages in a Custom UI (Xamarin-Android) appeared first on CodeGuru.

]]>
Using Microsoft Cognitive Services to Add Facial Recognition to Your Apps https://www.codeguru.com/mobile/using-microsoft-cognitive-services-to-add-facial-recognition-to-your-apps/ Mon, 19 Jun 2017 07:15:00 +0000 https://www.codeguru.com/uncategorized/using-microsoft-cognitive-services-to-add-facial-recognition-to-your-apps/ Introduction In my first article of the Cognitive Face API series, “Adding Facial Recognition to Your Apps,” I explained the process of face detection, features, subscription steps, and API service calls. In this tutorial on the Face API, I will create a Universal Windows Platform (UWP) app consuming the Microsoft Azure Cognitive Services API to […]

The post Using Microsoft Cognitive Services to Add Facial Recognition to Your Apps appeared first on CodeGuru.

]]>
Introduction

In my first article of the Cognitive Face API series, “Adding Facial Recognition to Your Apps,” I explained the process of face detection, features, subscription steps, and API service calls. In this tutorial on the Face API, I will create a Universal Windows Platform (UWP) app consuming the Microsoft Azure Cognitive Services API to demonstrate some of the characteristics of face recognition.

Prerequisites

1) You need to subscribe to Microsoft Azure Cognitive Services and get the subscription keys of the Face APIs. In my previous article, I explained the subscription steps.

2) Be sure you’re running the Microsoft Windows 10 OS. Universal Windows Platform (UWP) requires the Windows 10 operating system.

3) You’ll need Visual Studio 2015 Community Edition or the Preview Version of Visual Studio 2017 (free downloadable software is available from the Microsoft Webs ite).

4) You’ll need to reference the following NuGet packages. These packages can be downloaded and installed from the Visual Studio Solution Explorer window.

  • Microsoft.ProjectOxford.Face
  • Newtonsoft.Json
  • Win2D.uwp

Implementing the Face API

The face API can be accessed via C# code by using the Microsoft.ProjectOxford.Face NuGet package. By reading this article, you can learn how to use the Cognitive Service Face API in Universal Windows Apps development with Azure, XAML, and C#. The application development steps are simple and it cover the features mentioned below.

  1. Implement the Image upload functionality in UWP.
  2. Detect faces in the uploaded image.
  3. Show the detected faces highlighted in the XAML UI.

Setting Up the Project

Following are the steps to follow for app development.

Step 1

Open Visual Studio 2015. Go to Start -> New Project-> Select Universal (under Visual C# -> Windows ) -> Blank App -> Give a name for your app (MyNewFaceAPIApp) -> and click OK.

New project window
Figure 1: New project window

Entering MyNewFaceAPIApp as a new project name
Figure 2: Entering MyNewFaceAPIApp as a new project name

Select the target and minimum platform version that your UWP application will support.

UWP app target and minimum version
Figure 3: UWP app target and minimum version

Step 2

By default, developer mode is not enabled in Windows 10. Go to Start -> Windows Settings-> For Developers. Install the required packages to enable developer mode.

Windows settings developer mode
Figure 4: Windows settings developer mode

During developer mode enablement, I had to troubleshoot the following errors. I have mentioned a fix of each of the errors. These errors are due to failures during a Windows upgrade.

Error: DEP0100: Deployment failed due to a Developer Licensing issue. Could not obtain a developer license due to error 800704C7.

Fix: https://stackoverflow.com/questions/36324300/ensure-that-target-device-has-developer-mode-enabled-could-not-obtain-a-develop

Error: Developer mode package failed to install. Error code 0x8004005

Fix: http://windows10trickss.blogspot.in/2016/10/How-to-fix-Developer-Mode-package-failed-to-install-Error-code-0x80004005.html and https://social.msdn.microsoft.com/Forums/en-US/a7e94e5b-db19-492f-a1c1-d5fa3aa87d0d/enabling-developer-mode-fails-with-error-code-0x80004005?forum=Win10SDKToolsIssues

Step 3

Add the following references in the project by using the NuGet package manager.

  • Microsoft.ProjectOxford.Face
  • Newtonsoft.Json
  • Win2D.uwp

To add the Microsoft.ProjectOxford.Face reference, right-click your project (MyNewFaceAPIApp) and select “Manage NuGet Packages”.

NuGet package manager
Figure 5: NuGet package manager

Choose “Browse” and search “Microsoft.ProjectOxford.Face”. Select the package and install it.

Microsoft.ProjectOxford.Face installation
Figure 6: Microsoft.ProjectOxford.Face installation

Package manager will ask for confirmation before installation.

Confirmation before Installation
Figure 7: Confirmation before Installation

Accept the license agreement.

Accepting the license
Figure 8: Accepting the license

After successful installation, a Microsoft.ProjectOxford.Face reference will be added to the project.

Successfully installed Microsoft.ProjectOxford.Face package and added reference
Figure 9: Successfully installed Microsoft.ProjectOxford.Face package and added reference

Next, using the NuGet package manager, install a Newtonsoft.Json reference.

Newtonsoft.Json installation
Figure 10: Newtonsoft.Json installation

Choose “Browse” and search for “Newtonsoft.Json”. Select the package and install it. After successful installation, a Newtonsoft.Json reference will be added to the project.

Successfully installed Newtonsoft.Json package and added reference
Figure 11: Successfully installed Newtonsoft.Json package and added reference

Now, add a Win2D.uwp reference, used for drawing a rectangle in the face. From the NuGet package manager, choose “Browse” and search “Win2D.uwp”. Select the package and install it.

Win2D.uwp Installation
Figure 12: Win2D.uwp Installation

Package Manager will ask for confirmation before installation.

Confirm before installation
Figure 13: Confirm before installation

Accept the license agreement.

Accepting the license
Figure 14: Accepting the license

After successful installation, a Win2D.uwp reference will be added to the project.

Successfully installed Win2D.uwp package and added reference
Figure 15: Successfully installed Win2D.uwp package and added reference

The following NuGet packages will be added as a project reference.

All NuGet package references
Figure 16: All NuGet package references

Step 3

Add a facial image to the “Assets” folder for detecting. I have added my photo.

Added image in asset folder
Figure 17: Added image in asset folder

Step 4

Add the following XAML code in MainPage.xaml. I have used the Win2d library to draw a rectangle on the canvas.

<Page
   x_Class="MyNewFaceAPIApp.MainPage"
   
   xmlns_x="http://schemas.microsoft.com/winfx/2006/
      xaml"
   xmlns_local="using:MyNewFaceAPIApp"
   xmlns_d="http://schemas.microsoft.com/expression/
      blend/2008"
   xmlns_mc="http://schemas.openxmlformats.org/
      markup-compatibility/2006"
   xmlns_customCanvas="using:Microsoft.Graphics.Canvas
      .UI.Xaml"
   >
   <Grid Background="{ThemeResource
      ApplicationPageBackgroundThemeBrush}">
   <Image Source="Assets/tapas.jpg"
      Stretch="None"/>
   <customCanvas:CanvasControl Draw="MyCanvas_Draw"
      x_Name="MyCanvas"/>
   </Grid></Page>

Step 5

Add the following namespaces in Mainpage.xaml.cs for face detection and drawing the rectangle.

using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Pickers;
using Microsoft.ProjectOxford.Face;
using Microsoft.ProjectOxford.Face.Contract;
using Microsoft.Graphics.Canvas.UI.Xaml;

Step 6

Add the following code in MainPage.xaml.cs. The MyfaceAPIClient object will enable connections with the API. The DetectMyFaces function will upload my image, calling the API for facial recognition. Once the face is recognized, MyCanvas_Draw will draw a rectangle in the picture.

private readonly IFaceServiceClient MyfaceAPIClient =
      new FaceServiceClient("36ea74183e9a4213975ae3da1059b854");
   FaceRectangle[] MyfaceRectangles;
   public MainPage()
   {
      this.InitializeComponent();
      DetectMyFaces("ms-appx:///Assets/tapas.png");
   }

   async void DetectMyFaces(string imageFilePath)
   {
      try
      {
         StorageFolder MyappFolder = Windows.ApplicationModel
            .Package.Current.InstalledLocation;
         StorageFolder assets = await MyappFolder
            .GetFolderAsync("Assets");
         var MyFile = await assets.GetFileAsync("tapas.png");
         var MyAccessStream = await MyFile.OpenReadAsync();

         using (Stream stream =
            MyAccessStream.AsStreamForRead())
         {
            var myfaces = await
               MyfaceAPIClient.DetectAsync(stream);
            var myfaceRects =
               myfaces.Select(face => face.FaceRectangle);
            MyfaceRectangles = myfaceRects.ToArray();
            MyCanvas.Invalidate();
         }
      }
      catch (Exception ex)
      {
         System.Diagnostics.Debug.WriteLine(ex.Message);
      }
   }

   void MyCanvas_Draw(CanvasControl sender,
      CanvasDrawEventArgs args)
   {
      if (MyfaceRectangles != null)
         if (MyfaceRectangles.Length > 0)
         {
            foreach (var faceRect in MyfaceRectangles)
            {
               args.DrawingSession.DrawRectangle(faceRect.Left,
                  faceRect.Top, faceRect.Width, faceRect.Height,
                  Colors.Red);
            }
         }
      }

Run the application. If a face is present in the image, a rectangle will be drawn in the picture.

Application execution output
Figure 18: Application execution output

Summary

In this article, I tried to show how to use the Microsoft Cognitive Services Face API with the Universal Windows 10 App. There are more Cognitive APIs to use, such as Computer Vision API, Emotion API, Speaker Recognition API, and Text Analytics API. You can subscribe for these API’s from Azure portal and build intelligent applications. That’s all for today. Stay tuned for more.

The post Using Microsoft Cognitive Services to Add Facial Recognition to Your Apps appeared first on CodeGuru.

]]>
Adding Facial Recognition to Your Apps https://www.codeguru.com/mobile/adding-facial-recognition-to-your-apps/ Fri, 09 Jun 2017 07:15:00 +0000 https://www.codeguru.com/uncategorized/adding-facial-recognition-to-your-apps/ Introduction The Microsoft Cognitive Services Face API is a Cloud-based service with the most advanced machine learning algorithms. It offers detection of faces in images with attributes, extract features such as gender and age, organize images into groups, and identify individuals. The Ace API can detect up to 64 faces with high precision face location […]

The post Adding Facial Recognition to Your Apps appeared first on CodeGuru.

]]>
Introduction

The Microsoft Cognitive Services Face API is a Cloud-based service with the most advanced machine learning algorithms. It offers detection of faces in images with attributes, extract features such as gender and age, organize images into groups, and identify individuals. The Ace API can detect up to 64 faces with high precision face location in an image. You have to specify image by bytes or a valid image URL. Cognitive Services even has an API for detecting individuals’ emotions based on their facial expressions. Microsoft is currently offering a free plan with limited calls of 30,000 transactions per month. To calculate pricing above the mentioned number of free transaction, please visit URL given.

The Face API uses the JSON format for data exchange. By using Cognitive Services APIs, you can add face detection authentication to your mobile app. To consume the Face API, you need to register in Microsoft Azure Cognitive Services portal and get the subscription keys. I will mention subscription steps later in this article.

The following features are supported in the Cognitive Face API.

Face Detection

A developer can detect one or more human faces in an image and get face attributes that contain machine learning-based predictions of facial features. Detection of one or more human faces in an image is marked as rectangles. The face attribute features are age, emotion, gender, pose, smile, and facial hair, along with 27 landmarks for each face in the image. After detecting faces, we can take the face rectangle and pass it to the Emotion API to speed up the processing.

Recognizing a face
Figure 1: Recognizing a face

Face Verification

Face verification is based on a deep machine learning algorithm. It quickly and precisely detects facial features, recognizing faces with an impressively high rate of accuracy. The Face API checks the possibility of two faces belonging to the same or different person. it returns a confidence score.

Verifying a face
Figure 2: Verifying a face

Face Identification

A developer can search and identify faces, tag people and groups with user-provided data, and then search those for a match with previously unseen faces.

Similar Face Search

Finding similar-looking faces to a new face, from a given collection of faces, this API will return a collection of similar faces.

Face Grouping

Face grouping is organizing many unidentified faces together into groups, based on their visual similarity. A group contains a collection of similar faces, identified by their Face ID. In Face API terms, the PersonGroup is the image classifier unit, and is trained from the faces of the Person objects contained therein. Groups is derived from face grouping, which is a collection of faces according to facial similarity. Faces that are not similar to others are placed in a group called a messy group.

Creating a New Face API Key in Azure Portal

To use Face API, you first need to create an account or use an existing account to log in to the Azure portal.

Logging in to the Azure portal
Figure 3: Logging in to the Azure portal

From the Azure dashboard, click ‘+ NEW.’ Again, select ‘AI + Cognitive Services;’ you will get a list of available Cognitive APIs.

A list of available APIs
Figure 4: A list of available APIs

If you have not subscribed to Azure Service, it will ask your account name, subscription type (select free), and other details. After subscription, select API type as Face API from the list of available APIs.

For existing subscription holders, select Face API, and continue.

Selecting the Face API
Figure 5: Selecting the Face API

Next, you need to choose the location, pricing tier, resource group, and “Accept” the license term. To pin the account to the Azure portal dashboard, check the ‘Pin to Dashboard’ option and click Create.

Accepting the licensing terms
Figure 6: Accepting the licensing terms

A few minutes later, your Cognitive Services account will be successfully deployed and the Face API dashboard will appear. Click the tile in the dashboard to view the account information.

Viewing the account information
Figure 7: Viewing the account information

Use the API endpoint URL, and start making Face API calls from your applications.

Starting to make Face API calls
Figure 8: Starting to make Face API calls

Face API Service Call

Unlike other Cognitive APIs, the Face recognition API is currently available in the following five Azure zones:

  • West US: westus.api.cognitive.microsoft.com
  • East US 2: eastus2.api.cognitive.microsoft.com
  • West Central US: westcentralus.api.cognitive.microsoft.com
  • West Europe: westeurope.api.cognitive.microsoft.com
  • Southeast Asia: southeastasia.api.cognitive.microsoft.com

Four versions of Face APIs are available. The Post request formats of these versions are as follows:

  • Detect: https://[location].api.cognitive.microsoft.com/face/v1.0/detect[?returnFaceId][&returnFaceLandmarks][&returnFaceAttributes]
  • Find Similar Faces: https://[location].api.cognitive.microsoft.com/face/v1.0/findsimilars
  • Group: https://[location].api.cognitive.microsoft.com/face/v1.0/group
  • Identify: https://[location].api.cognitive.microsoft.com/face/v1.0/identify
  • Verify: https://[location].api.cognitive.microsoft.com/face/v1.0/verify

The following JSON code is a sample successful response of the API call with HTTP success code 200.

Detection result:
JSON:
   [
      {
         "7f64b5b0-0d78-47d6-ae44-ab1f951f8b3c",
         "FaceRectangle": {
            "Top": 277,
            "Left": 295,
         "Width": 215,
         "Height": 215
      },
      "FaceAttributes": {
         "Hair": {
         "Bald": 0.02,
         "Invisible": false,
         "HairColor": [
               {
                  "Color": "black",
                  "Confidence": 1.0
               },
               {
                  "Color": "gray",
                  "Confidence": 0.75
               },
               {
                  "Color": "other",
                  "Confidence": 0.52
               },
               {
                  "Color": "red",
                  "Confidence": 0.17
               },
               {
                  "Color": "brown",
                  "Confidence": 0.11
               },
               {
                  "Color": "blond",
                  "Confidence": 0.04
               }
            ]
         },
         "Smile": 0.008,
         "HeadPose": {
            "Pitch": 0.0,
            "Roll": -5.6,
            "Yaw": -2.7
         },
         "Gender": "male",
         "Age": 34.1,
         "FacialHair": {
            "Moustache": 0.4,
            "Beard": 0.3,
            "Sideburns": 0.3
         },
         "Glasses": "NoGlasses",
         "Makeup": {
            "EyeMakeup": false,
            "LipMakeup": false
         },
         "Emotion": {
            "Anger": 0.0,
            "Contempt": 0.002,
            "Disgust": 0.0,
            "Fear": 0.0,
            "Happiness": 0.008,
            "Neutral": 0.989,
            "Sadness": 0.0,
            "Surprise": 0.0
         },
         "Occlusion": {
            "ForeheadOccluded": false,
            "EyeOccluded": false,
            "MouthOccluded": false
         },
         "Accessories": [],
         "Blur": {
            "BlurLevel": "medium",
            "Value": 0.61
         },
         "Exposure": {
            "ExposureLevel": "goodExposure",
            "Value": 0.71
         },
         "Noise": {
            "NoiseLevel": "medium",
            "Value": 0.69
         }
      },
      "FaceLandmarks": {
         "PupilLeft": {
            "X": 353.1,
            "Y": 338.6
         },
         "PupilRight": {
            "X": 441.8,
            "Y": 329.4
         },
         "NoseTip": {
            "X": 405.2,
            "Y": 396.2
         },
         "MouthLeft": {
            "X": 360.1,
            "Y": 440.1
         },
         "MouthRight": {
            "X": 451.9,
            "Y": 426.9
         },
         "EyebrowLeftOuter": {
            "X": 318.8,
            "Y": 331.7
         },
         "EyebrowLeftInner": {
            "X": 375.0,
            "Y": 323.6
         },
         "EyeLeftOuter": {
            "X": 339.2,
            "Y": 342.5
         },
         "EyeLeftTop": {
            "X": 351.5,
            "Y": 334.4
         },
         "EyeLeftBottom": {
            "X": 354.0,
            "Y": 346.5
         },
         "EyeLeftInner": {
            "X": 368.0,
            "Y": 340.0
         },
         "EyebrowRightInner": {
            "X": 418.6,
            "Y": 317.0
         },
         "EyebrowRightOuter": {
            "X": 473.3,
            "Y": 310.9
         },
         "EyeRightInner": {
            "X": 429.1,
            "Y": 334.8
         },
         "EyeRightTop": {
            "X": 440.9,
            "Y": 325.3
         },
         "EyeRightBottom": {
            "X": 444.0,
            "Y": 338.1
         },
         "EyeRightOuter": {
            "X": 456.4,
            "Y": 328.7
         },
         "NoseRootLeft": {
            "X": 385.8,
            "Y": 340.9
         },
         "NoseRootRight": {
            "X": 414.1,
            "Y": 339.3
         },
         "NoseLeftAlarTop": {
            "X": 380.6,
            "Y": 380.0
         },
         "NoseRightAlarTop": {
            "X": 427.1,
            "Y": 375.4
         },
         "NoseLeftAlarOutTip": {
            "X": 372.0,
            "Y": 399.6
         },
         "NoseRightAlarOutTip": {
            "X": 436.8,
            "Y": 391.6
         },
         "UpperLipTop": {
            "X": 405.8,
            "Y": 428.7
         },
         "UpperLipBottom": {
            "X": 406.4,
            "Y": 437.6
         },
         "UnderLipTop": {
            "X": 405.8,
            "Y": 440.6
         },
         "UnderLipBottom": {
            "X": 406.9,
            "Y": 453.8
         }
      }
   }
]

Summary

I hope this article gave you insights on how to get started with the Face API, how the works, how to call the API functions, and how to create an Azure account for API subscription. In my next article, I will create an application using the Universal Windows Platform (UWP) to demonstrate Face API functionalities.

The post Adding Facial Recognition to Your Apps appeared first on CodeGuru.

]]>
Building a Dynamic Navigation Bar for iOS Apps Using Xamarin https://www.codeguru.com/mobile/building-a-dynamic-navigation-bar-for-ios-apps-using-xamarin/ Fri, 05 May 2017 07:15:00 +0000 https://www.codeguru.com/uncategorized/building-a-dynamic-navigation-bar-for-ios-apps-using-xamarin/ Introduction When developing applications, we come across requirements, such as displaying the count of new notifications, or the number of items in the cart on the toolbar. In this article, we will solve this problem in Xamarin forms with some elements at the platform level. This article is focused on iOS implementation. Description To begin […]

The post Building a Dynamic Navigation Bar for iOS Apps Using Xamarin appeared first on CodeGuru.

]]>
Introduction

When developing applications, we come across requirements, such as displaying the count of new notifications, or the number of items in the cart on the toolbar. In this article, we will solve this problem in Xamarin forms with some elements at the platform level. This article is focused on iOS implementation.

Description

To begin with, let’s start with creating a “Multiplatform” Xamarin forms application named “CustomNotificationIndicator.” It creates two projects, as shown in Figure 1:

Creating a "Multiplatform" Xamarin forms application
Figure 1: Creating a “Multiplatform” Xamarin forms application

Xamarin Form Level Changes

In the “CustomNotificationIndicator” project, add a ‘Forms Content Page Xaml’ file with code behind named ‘CustomNotificationIndicatorPage.xaml,’ as shown in Figure 2:

Adding a 'Forms Content Page Xaml' file
Figure 2: Adding a ‘Forms Content Page Xaml’ file

In the CustomNotificationIndicatorPage.Xaml file, add a button to increase the count of the number of notifications displayed on the toolbar.

<Button Command="{Binding AddNotificationCommand}" Text="Click Me" />

In the code behind file, declare an event that will be defined in the page renderer at the platform level.

1. public event EventHandler<string> ToolbarNotificationChangedEvent;

In the App.Xaml.cs resolve the page model, as demonstrated below:

2. var landingPage = new FreshNavigationContainer(
   FreshPageModelResolver.ResolvePageModel
      <CustomNotificationIndicatorPageModel>());

There are few more changes required in the code behind; however, let’s first look at the page model implementation. For this example, we are using FreshMVVM. Now, add a new class file named “CustomNotificationIndicatorPageModel.cs;” this will be view model file for the Xaml file created above. In the page model, we define a Command to handle the click event.

3. public ICommand AddNotificationCommand {get; set;}

In the constructor, we define the Command implementation, as follows:

4. public CustomNotificationIndicatorPageModel()
   {
      AddNotificationCommand = new Command(async () =>
         await AddNotificationValue());
   }

Define a static variable for type int that stores the count of the number of times the button was tapped. Also, declare an event object that is triggered whenever the count is changed.

5. static int NotifyCount;
6. public event EventHandler<string>
      NotificationValueChangedEvent;

The definition of “AddNotificationValue” is as below:

7. private async Task AddNotificationValue()
   {
      NotifyCount++;

      if (NotificationValueChangedEvent != null)
         NotificationValueChangedEvent.Invoke(this,
            NotifyCount.ToString());
   }

In this method, the static variable defined in Step 5 is incremented by 1 every time user taps the button. In addition, it also invokes the ‘NotificationValueChangedEvent’ defined in the Xaml code behind. The code in the CustomNotificationIndicatorPage.xaml.cs is as follows:

8. protected override async void OnBindingContextChanged()
   {
      base.OnBindingContextChanged();

      var pm = (CustomNotificationIndicatorPageModel)
         this.BindingContext;

      if (pm != null)
      {
         pm.NotificationValueChangedEvent +=
            Pm_NotificationValueChangedEvent;

      if (this.ToolbarItems.Count == 0)
      {
         this.ToolbarItems.Clear();

         this.ToolbarItems.Add(new ToolbarItem()
         {
            Order = ToolbarItemOrder.Default,
            Command = pm.NotificationClickCommand
         });

      }
   }

}

In this method, we first retrieve the binding context—the page model. Define an implementation for the “NotificationValueChangedEvent” and add a toolbaritem with a command associated with it. The implementation method for the NotificationValueChangedEvent is:

9. void Pm_NotificationValueChangedEvent(object sender, string e)
   {
      if (ToolbarNotificationChangedEvent != null)
         ToolbarNotificationChangedEvent.Invoke(this, e);
   }

This method, in turn, invokes the ToolbarNotificationChangedEvent event defined in the platform-specific page renderer.

Let’s summarize all the actions done so far. We have a page model named ‘CustomNotificationIndicatorPageModel.cs‘ that has an event named ‘NotificationValueChangedEvent,’ which is implemented in code behind file ‘CustomNotificationIndicatorPage.xaml.cs.’ The “AddNotificationValue” method is defined in the view model; this method increments the count and notifies the code behind page about the change. The changed value is passed as an event argument. The code behind page declares an event named ‘ToolbarNotificationChangedEvent;’ the implementation for this event resides in the PageRenderer—at the platform specific level.

Platform Level Changes

In the CustomNotificationIndicator.iOS project, add a class file named ‘NotificationPageRenderer.’ The code is as below:

 1. [assembly: ExportRenderer(typeof(CustomNotificationIndicatorPage),
       typeof(NavPageNavigator))
 2. namespace CustomNotificationIndicator.iOS
 3. {
 4.    public class NavPageNavigator : PageRenderer
 5.    {
 6.       protected override void OnElementChanged
             (VisualElementChangedEventArgs e)
          {
 7.          base.OnElementChanged(e);
 8.          var customPage =
                (CustomNotificationIndicatorPage)Element;
 9.          customPage.ToolbarNotificationChangedEvent +=
             customPage_ToolbarNotificationChangedEvent;
          }

10.       void customPage_ToolbarNotificationChangedEvent
             (object sender, string e)
         {
            var uiBarBtn =
               NavigationController.TopViewController.
               NavigationItem.RightBarButtonItem;
            var uiButton = (UIButton) uiBarBtn.CustomView;
            if (uiButton != null)
            {
               uiButton.SetTitle(e, UIControlState.Normal);
               uiButton.SetTitleColor(UIColor.Black,
                  UIControlState.Normal);
               uiBarBtn.CustomView = uiButton;

11.            NavigationController.TopViewController.
                  NavigationItem.RightBarButtonItem =
                     uiBarBtn;
            }

         }
      }
   }

Line 1 indicates this is a page renderer defined for the page of type ‘CustomNotificationIndicatorPage.” In Lines 6-9, the page Element is retrieved and assigns the implementation method for the “ToolbarNotificationChangedEvent” event. Line 10 defines the implementation of the event. It gets the CustomView of the RightBarButtonItem button and sets it title to the updated count value and assigns the button to the RightBarButtonItem. This reflects the updated count value on the toolbar.

To display an image and a text on the toolbar, we need to add another class file that inherits from the NavigationRenderer. Add a new class file and name it “NavRenderer.cs.” The code in the Navigation renderer is as follows:

 1. [assembly: ExportRenderer(typeof(NavigationPage),
       typeof(NavRenderer))]
 2. namespace CustomNotificationIndicator.iOS
 3. {
 4.    public class NavRenderer: NavigationRenderer
       {
 5.       public override void PushViewController
             (UIViewController viewController, bool animated)
          {
             base.PushViewController(viewController, animated);
 6.          if (TopViewController.NavigationItem.
                RightBarButtonItem != null)
             {
 7.             var uibutton = new UIButton();
                var rghtBarBtn = TopViewController.NavigationItem.
                   RightBarButtonItem;
                var image = UIImage.FromFile("icon-email.png");
                uibutton = UIButton.FromType(UIButtonType.Custom);
                uibutton.Font = UIFont.SystemFontOfSize(12);
 8.             uibutton.SetBackgroundImage(image, UIControlState.Normal);
 9.             uibutton.TitleEdgeInsets = new UIEdgeInsets(5, 5, 20, 2);
10.             uibutton.SetTitle(rghtBarBtn.Title, UIControlState.Normal);
11.             uibutton.Frame = new RectangleF(0, 0, 28, 20);
12.             uibutton.AddTarget(rghtBarBtn.Target, rghtBarBtn.Action,
                   UIControlEvent.TouchUpInside);
13.             var uiBarButton = new UIBarButtonItem(uibutton);

14.             TopViewController.NavigationItem.RightBarButtonItem =
                   uiBarButton;

             }
          }
       }
    }

Line 1 declares this page as a renderer of type Navigation Page. In Line 4, the page is inherited from NavigationRenderer. In Line 5, PushViewController method is overridden. In Line 6, we retrieve the RightBarButtonItem. Line 8 sets the background image of the button created in Line 7. Line 9 positions the title to be displayed. Line 10 sets the title of the button. Line 11 sets the height and width of the button. Line 12 assigns the events to the button. Line 13 creates the button of type UIBarButtonItem and, then, in Line 13 it assigns the button to the toolbar.

This finally displays a button with text on the top.

Summary

In this article, we saw how to add text over the button, a common scenario to display number of unread notifications/email or number of items in the cart. It also talks about how to communicate between a page model, code behind, and the renderers.

The post Building a Dynamic Navigation Bar for iOS Apps Using Xamarin appeared first on CodeGuru.

]]>
Are Hybrid Mobile Apps Right for You? https://www.codeguru.com/mobile/are-hybrid-mobile-apps-right-for-you/ Mon, 31 Oct 2016 07:15:00 +0000 https://www.codeguru.com/uncategorized/are-hybrid-mobile-apps-right-for-you/ By John Bristowe, Principal Developer Advocate, Progress. Hybrid mobile apps are like any other apps on your phone; you can find them in app stores, and you can use them to play games, engage your friends through social media, take photos, track your health, and much more. Although many similarities can be drawn, it can […]

The post Are Hybrid Mobile Apps Right for You? appeared first on CodeGuru.

]]>
By John Bristowe, Principal Developer Advocate, Progress.

Hybrid mobile apps are like any other apps on your phone; you can find them in app stores, and you can use them to play games, engage your friends through social media, take photos, track your health, and much more.

Although many similarities can be drawn, it can be very difficult to tell how a mobile application is built; trying to determine whether a mobile application is hybrid or native is like trying to differentiate rare grape varieties of wine. However, what matters is that the wine tastes good. A well-written hybrid app shouldn’t look or behave any differently than its native equivalent, and users don’t care which way the app is built, as long as it works just as well.

With all that said, many developers are left wondering about the benefits of going hybrid in today’s app-crazed world.

How Hybrid Mobile Apps Are Built

Hybrid mobile applications are built similarly to Web sites. Both use a combination of technologies such as HTML, CSS, and JavaScript. However, instead of targeting a mobile browser, hybrid applications target a WebView hosted inside a native container. This enables them to access device capabilities such as the accelerometer, camera, contacts, and more.

Today, most hybrid mobile applications leverage Apache Cordova, a platform that provides a consistent set of JavaScript APIs to access device capabilities through plug-ins that are built with native code. These plug-ins include APIs for accessing the device’s accelerometer, contacts, camera, and more. There are also a number of plug-ins that are built and maintained by the developer community at-large. These can be found in the Apache Cordova Plugins Registry.

Application assets like HTML, CSS, and JavaScript are packaged through the tooling made available through Apache Cordova to target platform SDKs. Once built, you have an application that can run like any other kind of application on the device.

Motivations to Go Hybrid

Hybrid mobile applications provide a way for developers to re-use their existing Web development skills. Generally, developers don’t like the prospect of getting locked into proprietary platforms. This includes the programming languages and SDKs provided by platform vendors.

Hybrid mobile application development tends to look appealing to an organization’s bottom line: Why hire a developer for each platform when you can hire one developer and target all of them through HTML, CSS, and JavaScript? Well, the reality is a bit more complicated.

Although it’s true that hybrid mobile application development enables developers to target more than one platform, each platform comes with a set of caveats when it comes to its Web runtime or WebView. This is especially true with Android, which is inconsistent between OS versions.

Moreover, there might be unique capabilities of certain platforms that a developer wants to target. In those instances, a combination of plug-ins and platform-specific code must be utilized to take advantage of those capabilities. Alternatively, developers can take advantage of third-party Web runtimes such as Crosswalk that can be embedded in your hybrid app.

Before committing to a platform strategy, it’s important to evaluate the technical and non-technical merits of hybrid versus alternatives like Web and native, especially as it relates to your mobile application’s requirements. To elaborate on this, let’s examine some questions worth asking yourself before embarking upon development of a mobile application:

Which Mobile Platforms Do You Want to Target?

If you want to target more than one platform, you have a number of choices. Clearly, the Web offers a highly attractive solution for this requirement. Your target is the mobile browser. Hybrid also lends itself well to this approach because of its reliance upon the WebView.

Native, on the other hand, finds itself in a unique space. If you are reliant upon the vendor SDKs and platform-specific programming languages, you are essentially coupled to the platform. In the case of iOS, it’s Objective-C or Swift; for Android, it’s Java; and for Windows Phone, it’s C#.

Where Will Your App Be Distributed?

If you prefer to distribute your application via an app store, you must build a hybrid or native application. You cannot distribute Web sites through app stores; that’s what your browser’s address bar is for! Despite this restriction, whether you build a hybrid or native application, it’s highly recommended that you have a Web site available for your mobile application. This will be the first place your users will expect to go if/when they encounter problems.

Are You Looking to Utilize the Capabilities of the Mobile Device?

Web sites have a restricted set of abilities as opposed to hybrid and native applications. These restrictions are enforced by the browser, effectively sandboxing it away from the mobile operating system. Recent developments with mobile browsers have exposed more device capabilities through HTML5 such as the camera, geolocation, and others.

Despite these advancements, support for advanced functionality is quite limited. For example, media capture and streaming remains unsupported in various mobile browsers. Because limitations like this remain in mobile browsers, many developers are compelled to evaluate hybrid and native as alternatives. Both offer the ability for developers to access device APIs; in the case of hybrid, this ability is supported through plug-ins.

It’s often asserted that native is best suited for applications where graphics performance is paramount. Mobile games are a class of mobile application almost entirely reliant upon complex visual interactions on the screen. Even if a game operates flawlessly from a functional perspective, you should expect it to have a very low app store rating if it feels sluggish. For that reason, developers have long-argued against using hybrid to build games.

That stated, a number of solutions for hybrid mobile applications exist. These include HTML5 Canvas and WebGL, both of which are well-suited for building applications like games. Furthermore, technologies like these are more approachable for developers through libraries like Paper.js, EaselJS, and others. For developers building more traditional, line-of-business applications, there are frameworks such as Famo.us.

What Are the Technical Abilities of Your Development Team?

Another factor to consider when evaluating your development options for mobile is your team’s technical abilities. If you decide to build a native application, you will require developers who are experienced with the platform SDKs and programming languages of every platform you wish to target. On the other hand, Web and hybrid applications are built using Web technologies like HTML, CSS, and JavaScript. Having a team that can target multiple platforms with a single set of technologies is definitely something worth considering when evaluating your opinions.

The Verdict

Even though there are many situations where building hybrid mobile apps is a perfect solution, it’s imperative to recognize that hybrid isn’t the be-all, end-all approach to mobile application development. If you find yourself developing an app that needs numerous native features, or an app where performance is critical to its success, you may find the hybrid development model limiting.

The important thing to remember about hybrid mobile application development is that it’s not a single approach; rather, it’s a spectrum of options ranging between Web and native. Determining if it’s the right fit for you requires evaluating the options and asking the right questions.

About the Author

Author head shot John Bristowe (@JohnBristowe) is a Principal Developer Advocate with Progress and lives in Australia. John is also an experienced speaker and frequently presents at developer conferences and events. Prior to joining Telerik, he was a Senior Developer Evangelist with Microsoft. You can find out more about John here.

The post Are Hybrid Mobile Apps Right for You? appeared first on CodeGuru.

]]>
Relative Merits of Three JavaScript Frameworks: AngularJS, ReactJS, and EmberJS https://www.codeguru.com/mobile/relative-merits-of-three-javascript-frameworks-angularjs-reactjs-and-emberjs/ Wed, 05 Oct 2016 07:15:00 +0000 https://www.codeguru.com/uncategorized/relative-merits-of-three-javascript-frameworks-angularjs-reactjs-and-emberjs/ By Phong Bui When you’re working towards creating a solid responsive design that works across multiple platforms, you need to choose the right client-side framework for best results. Anyone seeking a JavaScript framework for their project today is going to consider the big three: AngularJS, ReactJS, and EmberJS. But, how do you narrow down your […]

The post Relative Merits of Three JavaScript Frameworks: AngularJS, ReactJS, and EmberJS appeared first on CodeGuru.

]]>
By Phong Bui

When you’re working towards creating a solid responsive design that works across multiple platforms, you need to choose the right client-side framework for best results. Anyone seeking a JavaScript framework for their project today is going to consider the big three: AngularJS, ReactJS, and EmberJS. But, how do you narrow down your choice? Which framework is going to deliver what you need?

In this article, we’re going to delve into the pros and cons of each framework in turn and try to help you make the right choice for your project.

Background and Popularity

The first framework on the scene was AngularJS, which was first released in October, 2010. It is maintained by Google and enjoys a large, active community of developers and organizations. You’ll find it on the Web sites of ABC News, Intel, Walgreens, and others. Angular has 165,000 followers on Twitter.

First released in March, 2013, ReactJS is the youngest framework of our trio. It’s maintained by Facebook and a large community of individuals and corporations. You’ll find it used on Netflix, Feedly, Airbnb, and many other Web sites. React has 93,500 followers on Twitter.

EmberJS was first released in December 2011 and it also has a large active community, though it lacks the big-name backing of Angular and React. It can be found on Web sites like Groupon, Vine, and Chipotle. Ember has 35,200 followers on Twitter.

The relative popularity of each platform on Twitter broadly reflects our own client experience. Around 60% of our clients use Angular, about 30% use React, and the remaining 10% are using Ember.

Before we dig into the technical strengths and weaknesses of each platform, it’s worth noting that Google’s backing for Angular and Facebook’s backing for React make both of them safe bets. They won’t run into any funding issues or suffer from lack of support for the foreseeable future.

Now, let’s take each platform in turn and drill into the advantages and disadvantages, before suggesting some scenarios where they might be the right pick.

AngularJS

It looks as though Angular is the most popular choice, but the move to Angular 2.0 has been a bit disruptive. A lot of the community is still using Angular 1.x, and although Angular 2.0 offers many benefits, the transition is far from complete.

Advantages of Angular

  • MVC architecture
  • Easy-to-customize DOM
  • Two-way data bindings
  • Extendable HTML directories
  • Support for desktop and mobile applications
  • Built-in dependency injection
  • Support for server-side rendering
  • Easy to build and deploy with AngularCLI tool

Disadvantages of Angular

The big disadvantage with Angular 2.0 is the lack of documentation. The problem is complicated by the fact that the wealth of resources for Angular 1.x don’t really help because the framework has changed so much.

Angular Is Recommended

AngularJS is recommended for projects that need to support desktop and mobile. Also, because it is written in Microsoft’s TypeScript, it’s a good choice for large enterprises.

ReactJS

When Facebook created React, it was trying to find an efficient way to keep a consistent UI and it succeeded. It may be the newest kid on the block here, but it has made some innovative strides.

Advantages of React

  • Virtual DOM
  • One-way binding
  • Support for desktop and mobile applications
  • Support for server-side rendering
  • Fast performance

Disadvantages of React

The big disadvantage for React is the fact that it’s not really a full framework. You still need a third-party framework such as Flux or Redux to make a full MV* architecture.

React Is Recommended

ReactJS is recommended for projects that require high performance and simple libraries over a complete MV* framework.

EmberJS

Started with a focus on ambitious Web applications, Ember has some serious programming talent behind it, even if it does lack the backing of Google or Facebook. Ember 2.0 was released in August, 2015 and brought a raft of enhancements to the platform.

Advantages of Ember

  • MVC architecture
  • Two-way data bindings
  • Fits well with the RoR model and applications
  • Built-in dependency injection
  • Easy to build and deploy with EmberCLI tool
  • Quick to develop

Disadvantages of Ember

The relatively small community is a drawback for Ember and it’s also hard to code if you stray beyond its typical uses.

Ember Is Recommended

EmberJS is recommended for any projects that strictly follow the namespace/convention over configuration, especially Ruby on Rails projects.

How to Choose

There is no overall winner. The framework you choose depends on the project you’re working on. If you have the time, try them out and see what aligns most closely with your current requirements. Factor in any existing knowledge you might have to help you get a head start.

Although there are some unique selling points for each framework, the majority of the best new features and functions can be found in each of them. These are the three most popular frameworks for good reason.

About the Author

Phong Bui is the Vice President of Technology at KMS Technology, a software development and IT services firm based in Atlanta, GA and Ho Chi Minh City, Vietnam. He leads the R&D department. Phong started his career in 1998 as a software developer. Phong is a graduate of Ho Chi Minh City University with a bachelor’s degree in Information Technology. Contact him at phongbui@kms-technology.com.

*** This article was contributed. © All rights reserved Developer.com ***

The post Relative Merits of Three JavaScript Frameworks: AngularJS, ReactJS, and EmberJS appeared first on CodeGuru.

]]>
Building an Better Bot: Combining Microsoft Bot Framework and LUIS https://www.codeguru.com/mobile/building-an-better-bot-combining-microsoft-bot-framework-and-luis/ Mon, 01 Aug 2016 07:15:00 +0000 https://www.codeguru.com/uncategorized/building-an-better-bot-combining-microsoft-bot-framework-and-luis/ Introduction The first article in this series, “Microsoft Bot Framework: Let’s Get Chatty!,” took a look at the Microsoft Bot Framework and how to set up the channels of communication. The second article, “Turning Natural Language into Meaning with LUIS (Natural Language Understanding),” focused on natural language recognition using LUIS and organizing the conversation into […]

The post Building an Better Bot: Combining Microsoft Bot Framework and LUIS appeared first on CodeGuru.

]]>
Introduction

The first article in this series, “Microsoft Bot Framework: Let’s Get Chatty!,” took a look at the Microsoft Bot Framework and how to set up the channels of communication. The second article, “Turning Natural Language into Meaning with LUIS (Natural Language Understanding),” focused on natural language recognition using LUIS and organizing the conversation into some basic dialogs. This article explores how to bring your bot more places and offers up some approaches to making sure your users love your bot!

IVR Magic

The Bot Framework also supports interactive voice response via the Skype channel. When you use this channel, Skype’s service takes on the work of translating the voice to text, recognizing when the user is done speaking, and passing along the text to your bot. When you reply, Skype also takes on the text-to-speech chores to reply to the end user. The combination of the bot framework, LUIS, and interactive voice response could lead to a revolution in capability for IVR systems.

To take full advantage of the voice-specific capabilities of the framework, you will need to use the Calling API. In a chat window, messages are passed back and forth only when complete. In a voice interaction, it takes time to speak phrases and there are interruptions. Using the Calling API lets you handle these voice-specific nuances of the platform.

Going Cross Platform

The Microsoft Bot Framework supports more channels out-of-the-box than any of the other bot frameworks out there. It supports Facebook, GroupMe, Kik, Skype, Slack, Telegram, SMS, Email, and more. Despite this impressive diversity of channels, it’s not everything you would want to connect to your bot. Alexa from Amazon is very popular and you may want to add voice controls to your mobile app, for example. The good news is that Microsoft’s Bot Framework is flexible enough for you to add new custom capabilities like this.

Adding support to a custom app is very simple and straightforward. Within the Bot Framework. it is simple as using the Direct Line API they have included to route messages to and from your existing bot.

Supporting the Alexa platform is more challenging due to the differences in the interface. Alexa does both the voice-to-text and the meaning recognition via its skills toolkit. The core concepts are the same, even if it names them a little differently. Alexa uses the terms intent and utterances the same as LUIS does, but instead of having Entities, it has slots.

Manually setting up all of the same utterances, intents, and slots in Alexa to match the work you’ve done in LUIS would be a very laborious undertaking. Fortunately, Amazon does have a mechanism to upload intents as JSON files. As an added bonus, LUIS supports the ability to export its configuration into JSON files. It shouldn’t come as a surprise that they are different file formats. This means you will need to write a translation routine to export your LUIS model into a format that can be read by Alexa.

Once you have your intents uploaded to Alexa, you can build some simple wrapper services matching what Alexa’s SDK that route to your bot’s endpoints. It’s a less elegant solution than just being able to configure a new channel inside of the bot framework, but it is an example of a way to use the bot framework as a universal platform that can support channels it wasn’t originally designed for.

Don’t Be Human

Bots should never pretend to be flesh and blood human beings. First, people tend to get angry when they discover they are talking to a computer instead of a person. It feels like a betrayal. Second, people speak differently to a bot compared to how they speak to a person.

When you feel like you’re talking to a real person, you tend to talk in stories. For example, if you were calling to report an outage on your Internet connection, you might say:

YOU: “I was playing Overwatch, my team was winning too, and the Internet just cut out. I already tried resetting the router.”

Language recognition programs such as LUIS would struggle with this sentence because it would need to eliminate the unnecessary information to focus on the two key facts it cares about: The user is experiencing an outage and they have already reset the router.

If you know you’re speaking with an automated system, you would choose simpler statements without the background stories.

BOT: “I’m ISP Bot. How can I help you today?”

YOU: “My Internet isn’t working”

BOT: “Can you reset the router?”

YOU: “Already did, still not working”

In this case, the user can still interact using natural language but, because they know they are talking to a bot, telling it a backstory isn’t likely.

Have Some Personality

Because your bot isn’t trying to be human, you have the freedom to make it be whatever you want. If you’re a university, your bot could be your team’s mascot, for example. This is a unique opportunity to inject more of your brand’s personality into the customer experience than you could practically do with people handling the chats.

There are other benefits to giving your bot a special personality. By choosing a personality that doesn’t pretend to be “Carol in Customer Service,” it should be clear to the user they are talking to a bot without explicitly labeling your bot as a bot.

Conclusion

Microsoft’s Bot Framework is surprisingly extensible. You can easily adapt this platform to be your company’s natural language interface across all devices and channels, including voice communication. Your bot is a unique opportunity to provide a new channel for your customers and inject some of your brand’s personality into the mix.

About the Author

David Talbot is the director of Architecture & Strategy at a leading digital bank. He has almost two decades of innovation across many startups and has written extensively on technology.

The post Building an Better Bot: Combining Microsoft Bot Framework and LUIS appeared first on CodeGuru.

]]>
A Tab Control in Xamarin https://www.codeguru.com/mobile/a-tab-control-in-xamarin/ Fri, 07 Aug 2015 07:15:00 +0000 https://www.codeguru.com/uncategorized/a-tab-control-in-xamarin/ One of the biggest problems in mobile UI design is limited screen real estate. An effective technique for optimizing space involves using tabs that allow the user to flip from one set of controls to another while maintaining the context of the current page. Xamarin Forms provides the TabbedPage for this purpose. The TabbedPage is […]

The post A Tab Control in Xamarin appeared first on CodeGuru.

]]>
One of the biggest problems in mobile UI design is limited screen real estate. An effective technique for optimizing space involves using tabs that allow the user to flip from one set of controls to another while maintaining the context of the current page. Xamarin Forms provides the TabbedPage for this purpose.

The TabbedPage is the natural go-to when you want to implement multiple tabs in your application. It’s easy to implement a stand-alone page that provides navigation to other sub-pages without leaving the parent page. And, as Xamarin is quick to point out, the final look on various platforms is native to that platform: For iOS, icons, and text in a bar along the bottom. For Android, desktop-like tabs along the top.

However, issues can arise quickly as you try to integrate the TabbedPage into your project. If you are using a navigation page and opening content pages within it, there are issues you have to contend with related to having a navigation sub-page to itself be a container for sub-pages.

There’s also the native-look situation. Although the automatic adoption of the native platform paradigm for tabs is a neat trick, it isn’t always what you want. If you have specific ideas about the interface you are creating and how it should look and act, you may be frustrated at the lack of customization and the completely different look on the two platforms. Although it’s true that a different, native look for each platform is sometimes preferable, often it’s not. If you are developing business applications for the mobile platform, you might find that having a similar user interface across all platforms is the best way to go. Your marketing department may be eager to assure that the branding and other UI elements are always the same. And it certainly simplifies support/help-desk troubleshooting.

Options?

After reviewing the components available on the Xamarin site and elsewhere, I didn’t find any good options for a tab solution that worked on both Android and iOS. Likewise, no luck reviewing forum posts for alternatives. So, I did what any good developer would do: I built it myself!

Benefits

The solution I provide in this article is called BetterTabControls. It has a number of benefits:

  • It’s self-contained, so it can be easily referenced and used from any project.
  • It’s implemented as a set of standard controls on a page, not a specific type of parent/sub-page arrangement.
  • The user interface for each tab is collected in one place so you don’t have to hop among different files to see what the page will look like.
  • It provides a set of controls that do all the work for you. Just drop them in, define their look, and populate the tabs.
  • The controls themselves inherit from standard controls and provide all the properties and methods of their underlying type. This gives you the ultimate in flexibility in layout and style.
  • The controls can be instantiated in code or used through standard XAML syntax.
  • There are no platform-specific renderers (more on this later).

Using BetterTabControls

I’ll first show you how to use BetterTabControls. Then, if you like, you can take the code and use it in your own application without reading further. However, for those interested, I’ll go on after this section to show how the controls were built and how they work.

The first step is to add a reference in your application to the BetterTabControls project. (The PCL also can be compiled and the DLL referenced, if you prefer.)

Then, add the controls to your page. In this example, I’ll assume you’re using XAML. Instantiating in code works very much the same. This simple page puts BetterTabControls to work.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage 
      xmlns_x="http://schemas.microsoft.com/winfx/2009/xaml"
      xmlns_TabCtrls="clr-namespace:BetterTabControls;
         assembly=BetterTabControls"
      x_Class="App2.Page2"

      BackgroundColor="White"
      Title="  Time Sheet">


   <StackLayout Orientation="Vertical"
                VerticalOptions="FillAndExpand"
                HorizontalOptions="FillAndExpand">

      <Label
         Text="Select the appropriate tab to view by project,
            week or day."
         TextColor="Black" VerticalOptions="Center"
         HorizontalOptions="Center" />

      <TabCtrls:BetterTabs x_Name="ProjectsDaysTabs"
               Orientation="Vertical"
            SelectedTabIndex="1"
            SelectedColor="Lime" UnselectedColor="Green"
            VerticalOptions="FillAndExpand"
            HorizontalOptions="FillAndExpand">

         <TabCtrls:BetterTabButtons Orientation="Horizontal">
            <TabCtrls:BetterTabButton x_Name="ProjectsTabButton"
               Text="Projects"
               BorderRadius = "1" BorderWidth = "2" HeightRequest="35"
               WidthRequest = "75" FontSize="13" TextColor="Black"/>
            <TabCtrls:BetterTabButton x_Name="WeeksTabButton" Text="Weeks"
               BorderRadius = "1" BorderWidth = "2" HeightRequest="35"
               WidthRequest = "75" FontSize="13" TextColor="Black"/>
            <TabCtrls:BetterTabButton x_Name="DaysTabButton" Text="Days"
               BorderRadius = "1" BorderWidth = "2" HeightRequest="35"
               WidthRequest = "75" FontSize="13" TextColor="Black"/>
         </TabCtrls:BetterTabButtons>

         <TabCtrls:BetterTab x_Name="ProjectsTab" IsVisible="True"
               VerticalOptions="FillAndExpand"
               HorizontalOptions="FillAndExpand"
               BackgroundColor="Pink">

            <Label Text="Projects Tab" HorizontalOptions="Center"
                  TextColor="Black" />

         </TabCtrls:BetterTab>

         <TabCtrls:BetterTab x_Name="WeeksTab" IsVisible="False"
               VerticalOptions="FillAndExpand"
               HorizontalOptions="FillAndExpand"
               BackgroundColor="Yellow">

            <Label Text="Weeks Tab" HorizontalOptions="Center"
                  TextColor="Black"/>

         </TabCtrls:BetterTab>

         <TabCtrls:BetterTab x_Name="DaysTab" IsVisible="False"
               VerticalOptions="FillAndExpand"
               HorizontalOptions="FillAndExpand"
               BackgroundColor="Aqua">

            <Label Text="Days Tab" HorizontalOptions="Center"
                  TextColor="Black"/>

         </TabCtrls:BetterTab>

      </TabCtrls:BetterTabs>
   </StackLayout>
</ContentPage>

When this page is displayed, it looks like what’s shown in Figure 1.

Xam1
Figure 1: The Time Sheet’s tabs

When you click the Projects tab button, you see the contents of Figure 2.

Xam2
Figure 2: The Time Sheet’s Projects tab

Earlier, I touted the freedom to customize the look/feel of this approach. Please don’t take this application as an example of the styling possibilities. The artistic prowess demonstrated is clearly underwhelming!

Organization

Notice the organization of the controls within the page.

<TabCtrls:BetterTabs>
   <TabCtrls:BetterTabButtons>
      <TabCtrls:BetterTabButton>
      <TabCtrls:BetterTabButton>
      <TabCtrls:BetterTabButton>
   <TabCtrls:BetterTab>
   <TabCtrls:BetterTab>
   <TabCtrls:BetterTab>

All the tab-related controls are in the parent <TabCtrls:BetterTabs>. Within that is a collection of buttons called <TabCtrls:BetterTabButtons>. The buttons are of type <TabCtrls:BetterTabButton>. (The singular/plural distinction is important!) Finally, the <TabCtrls:BetterTab> elements, which contain the contents of each tab, are also within the parent (but not grouped into their own parent as with the buttons).

There’s only one important thing to know: The button elements and the tab elements are each an ordered list and the first button is associated with the first tab, the second with the second, and so on. Obviously, there must be the same number of buttons as tabs.

Tab Control Properties Available

Each tab control simply extends an existing Xamarin Forms control, adding its own properties and code. Here are the base classes for each:

Control Parent Control
BetterTabs StackLayout
BetterTabButtons StackLayout
BetterTabButton Button
BetterTab StackLayout

This means that any properties you’d set on a StackLayout—such as orientation, horizontal/vertical options, background color, visibility, and so forth—are available with BetterTabs, BetterTabButtons, and BetterTab. Likewise with BetterTabButton for Button properties.

In addition to the standard properties, there are a couple added to BetterTabs so you can specify tab-related information.

  • SelectedTabIndex: An integer value between 0 and the highest numbered tab (in this example, the tabs are numbered 0, 1, and 2). This determines which tab will be selected when the page is first displayed.
  • SelectedColor and UnselectedColor: The color applied to the background of the selected tab button and those that aren’t selected.

That’s all you need to know! You can organize your controls as you like anywhere within the page. You can even put the tab buttons below the tab contents.

Coding the Controls

Now, I’ll go into the code behind the controls. It isn’t rocket science, but I think it’s a useful tool and a good example of the ease of inheriting and extending existing controls and then coordinating them to work together.

Custom Controls without Custom Renderers

Xamarin Forms’ controls, in general, are lacking in variety and richness. It’s a lowest-common-denominator solution—providing only features that are fully supported on all platforms. The controls and features will grow in time, but today the answer to the limitations is always the same: custom controls and usually custom renderers.

The trouble is that, to create a custom renderer, you have to have a strong understanding of all the native platform UI paradigms. And, if you haven’t discovered it for yourself already, each platform’s UI requires its own significant learning curve.

But, there are times when you can create custom controls without resorting to custom renderers. You can inherit from existing Xamarin Forms controls and then extend them with your own properties, methods, and event code. This is the approach I’ve taken here to implement BetterTabControls.

BetterTabButton: Click to Change Tabs

There are four controls, but two of them are not extended in any way: BetterTabButtons, which is just a container for the set of tab buttons, and BetterTab, which is simply a container for all the UI elements the user wants on a given tab.

The first extended control is BetterTabButton. Its code is shown in the following samplee.

using System;
   using Xamarin.Forms;

namespace BetterTabControls
{
   public class BetterTabButtons : StackLayout {}

   public class BetterTabButton : Button
   {

      public BetterTabButton()
      {
         Clicked += ThisTabButtonClicked;
      }

      public void ThisTabButtonClicked(object s, EventArgs e)
      {
         BetterTabs prnt = validParentBetterTabs();
         if (prnt == null) return;

         prnt.SelectedTabButton = this;
      }

      private BetterTabs validParentBetterTabs()
      {
         // Work your way up to the grandparent; parent should be
         // BetterTabButtons and grandparent should be BetterTabs
         if (Parent != null && Parent.Parent != null &&
            Parent.Parent.GetType() == typeof (BetterTabs))
            return ((BetterTabs) Parent.Parent);
         else
         {
            throw new Exception(
               "Grandparent of a BetterTabButton " +
               "must be a BetterTabs");
         }
      }
   }
}

When the user clicks a tab button, the parent of the parent is checked—it should be a BetterTabs. If not, an exception is thrown. Otherwise, the SelectedButton property is set to this button. This has the effect of changing the look of the buttons and setting the associated tab to being visible, as you’ll see in BetterTabs.

BetterTabs: Where It All Happens

BetterTabs acts as the coordinator and implementer of the intelligence here.

using System;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;

namespace BetterTabControls
{
   public class BetterTab : StackLayout { }

   public class BetterTabs : StackLayout
   {
      private Color _selectedColor = Color.White;

      public Color SelectedColor {
         get { return _selectedColor; }
         set { _selectedColor = value; }
      }

      private Color _unselectedColor = Color.Silver;

      public Color UnselectedColor {
         get { return _unselectedColor; }
         set { _unselectedColor = value;
      }

The trivial BetterTab is declared first. BetterTabs first declares the SelectedColor and UnselectedColor, providing defaults of white and sliver.

Next are the TabButtons and Tabs properties.

            internal List<BetterTabButton> TabButtons
            {
               get
               {
                  BetterTabButtons tabButtons =
                     (BetterTabButtons)Children.
                     First(c => c.GetType() ==
                        typeof (BetterTabButtons));
                  var buttonEnumerable =
                     tabButtons.Children.Select(c =>
                        (BetterTabButton) c);
                  var buttonList =
                     buttonEnumerable.Where(c => c.GetType() ==
                        typeof (BetterTabButton)).ToList();
                  return buttonList;
               }
            }

             internal List<BetterTab> Tabs
             {
                get
                {
                   var childList =
                      Children.Where(c => c.GetType() ==
                         typeof(BetterTab));
                   var tabList =
                      childList.Select(c => (BetterTab) c).ToList();
                   return tabList;
                }
            }

These properties are intended for use only within the control library, so their access is internal. They are also read-only, so only get is implemented. They provide references to the tab buttons and tabs, but no separate list is maintained as a private backing variable. Instead, LINQ queries are performed on the children and grandchildren, selecting the appropriately typed elements and converting the result to a List. This will simplify accessing this information wherever it’s needed.

The selected methods are next.

            private int _selectedTabIndex;
            public int SelectedTabIndex
            {
               get { return _selectedTabIndex; }
               set
               {
                  _selectedTabIndex = value;

                  if(Tabs.Count > 0)
                     SelectionUIUpdate();
               }
            }

            public BetterTabButton SelectedTabButton {
               get { return TabButtons[_selectedTabIndex]; }
               set
               {
                  var tabIndex = TabButtons.FindIndex(t =>
                     t == value);
                  if (tabIndex == -1)
                     throw new Exception(
                        "SelectedTabButton assigned a button " +
                        "that isn't among the children  of "+
                        "BetterTabButtons.");

                  if(tabIndex != _selectedTabIndex)
                     SelectedTabIndex = tabIndex;
               }
            }

            public BetterTab SelectedTab
            {
               get { return Tabs[_selectedTabIndex]; }
            }

The selected tab is always identified by its index number in _selectedTabIndex. It may be set/accessed via the SelectedTabIndex property, as was done in the preceding XAML to specify the initially-selected tab. In addition, the user interface is updated, when appropriate. Why do I check Tabs.Count()? Because this property setter is triggered while the page is being rendered—and before the child objects are instantiated. I’ll handle updating the interface for that situation in a moment, in the OnParentSet() method.

When a tab button is clicked, it doesn’t know what index is assigned to it from the parent. It could calculate that, but it’d make more sense to do that here in the parent. That’s why the SelectedTabButton property was created. When it’s assigned, the setter obtains the index of the assigned button and sets the SelectedTabIndex.

Finally, it is sometimes helpful to obtain the selected tab—the one holding the UI that’s currently displayed on the page. Although this is easy to get, a property is provided to make it a bit easier.

Next, I needed to do a few things after all the tab controls are instantiated. And, fortunately, there’s a convenient function override available for that.

            protected override void OnParentSet()
            {
               base.OnParentSet();

               if (tabButtons.Count != tabs.Count)
               {
                  throw new Exception(
                     "The number of tab buttons and the " +
                     "number of tabs to not match.");
               }

               SelectionUIUpdate();
            }

As the name implies, this function occurs when (actually, after) the Parent property is set for this control. If you check to see how many children there are for BetterTabs in the BetterTabs constructor, it’ll tell you zero. However, when OnParentSet() is triggered, all the children are instantiated and available.

The first thing I do here is verify that the number of tab buttons and the number of tabs match.

Then, I call the SelectionUIUpdate() function, which is the last one in BetterTabs.cs.

            private void SelectionUIUpdate()
            {
               foreach (var btn in TabButtons)
                  btn.BackgroundColor = UnselectedColor;
               SelectedTabButton.BackgroundColor =
                  SelectedColor;


            foreach (var tb in Tabs)
               tb.IsVisible = false;
            SelectedTab.IsVisible = true;
         }
   }
}

The intent here is to update the UI based on the selected tab. All the tab buttons’ colors are set to the “unselected” color. Then, the selected tab button color is set to the “selected” color. Finally, all the tabs are made invisible and the SelectedTab is made visible.

Conclusion

I hope these controls are useful to you. And, I hope the code has provided a little insight into creating custom Xamarin Forms controls (without custom renderers) and how to get them working together.

The post A Tab Control in Xamarin appeared first on CodeGuru.

]]>
Using Hotspot Authentication API in Windows Phone 8.1 https://www.codeguru.com/mobile/using-hotspot-authentication-api-in-windows-phone-8-1/ Wed, 11 Mar 2015 07:15:00 +0000 https://www.codeguru.com/uncategorized/using-hotspot-authentication-api-in-windows-phone-8-1/ Introduction The Windows Phone 8.1 platform provides programmatic access to support Hotspot authentication via APIs in the Windows.Networking.NetworkOperators namespace. In this article, we will learn how to use these APIs to perform Hotspot authentication. Wireless Internet Service Provider roaming, called WISPr, is a protocol that allows users to roam among wireless Internet service providers. Mobile […]

The post Using Hotspot Authentication API in Windows Phone 8.1 appeared first on CodeGuru.

]]>
Introduction

The Windows Phone 8.1 platform provides programmatic access to support Hotspot authentication via APIs in the Windows.Networking.NetworkOperators namespace. In this article, we will learn how to use these APIs to perform Hotspot authentication.

Wireless Internet Service Provider roaming, called WISPr, is a protocol that allows users to roam among wireless Internet service providers. Mobile operators can implement WISPr protocol to allow devices to seamlessly log in to hotspots without the need for the user to interact with a captive portal.

Let us take a quick look at the classes/APIs of interest to build Hotspot authentication in our application.

  • HotspotAuthenticationContext class: This class provides the authentication context that contains details of the current authentication attempt and provides methods to perform the authentication.
  • HotspotAuthenticationContext.IssueCredentialsAsync method: This method asynchronously provides credentials for Hotspot authentication. This method is only available to mobile operator apps and Windows Store given privileged access by mobile network operators.
  • HotspotAuthenticationContext.WirelessNetworkId property: This property gets the SSID of the WLAN access point. This property is only available to mobile operator apps and Windows Store given privileged access by mobile network operators.
  • HotspotAuthenticationContext.NetworkAdapter property: This property gets the network interface that is connected to the WLAN access point of the Hotspot. This property is only available to mobile operator apps and Windows Store-given privileged access by mobile network operators.

WISPr imposes no requirements for “Windows Phone” access points. Windows Phone does not provide native WISPr authentication support, unlike Windows, which supports authentication via the HotSpotAuthenticationContext.IssueCredentialsAsync API. Hence, Windows Phone apps will need to implement the HotSpotAuthenticationContext.IssueCredentialsAsync API in the app and call the HotSpotAuthenticationContext.SkipAuthentication method. Unlike Windows Store applications, Windows Phone applications have only WirelessNetworkId and NetworkAdapter as valid properties of a HotspotAuthenticationContext object.

Building an application that does Hotspot authentication requires the application to be blessed by the mobile carrier because it needs provisioning information that only the mobile carrier can provide.

Hands On

Let us create a simple application to use To use the Hotspot Authentication APIs.

Create a new Visual Studio 2013 project by using the Windows Phone Blank App template. In the default page created, add a few controls, as follows:

Hotspot1
Figure 1: Adding controls to the default page

The XAML code behind is presented here:

<Page
   x_Class="App10.MainPage"
   
   xmlns_x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns_local="using:App10"
   xmlns_d="http://schemas.microsoft.com/expression/
      blend/2008"
   xmlns_mc="http://schemas.openxmlformats.org/
      markup-compatibility/2006"
   mc_Ignorable="d"
   Background="{ThemeResource
      ApplicationPageBackgroundThemeBrush}">

   <Grid>
      <Button x_Name="buttonProvision" Content="Provision"
         HorizontalAlignment="Left" Margin="130,69,0,0"
         VerticalAlignment="Top" />
      <TextBlock HorizontalAlignment="Left" Margin="130,600,0,0"
         TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"
         Height="30" Width="238"/>
      <TextBlock x_Name="textBlockStatus" HorizontalAlignment="Left"
         Margin="130,600,0,0" TextWrapping="Wrap"
         VerticalAlignment="Top" Height="30" Width="238"
         ScrollViewer.HorizontalScrollBarVisibility="Auto"/>
      <TextBlock HorizontalAlignment="Left" Margin="42,600,0,0"
         TextWrapping="Wrap" Text="Status" VerticalAlignment="Top"/>
      <Button x_Name="buttonAuthenticateThroughBackground"
         Content="Authenticate through background task"
         HorizontalAlignment="Left" Margin="28,186,0,0"
         VerticalAlignment="Top" Width="340" />
      <Rectangle Fill="#FFF4F4F5" HorizontalAlignment="Left"
         Height="222" Margin="28,326,0,0" Stroke="Black"
         VerticalAlignment="Top" Width="340" Opacity="0.25"/>
      <Button x_Name="buttonAuthenticate" Content="Authenticate"
         HorizontalAlignment="Left" Margin="130,414,0,0"
         VerticalAlignment="Top" RenderTransformOrigin="0.695,0.172"
         Width="131" />
      <Button x_Name="buttonSkip" Content="Skip"
         HorizontalAlignment="Left" Margin="130,457,0,0"
         VerticalAlignment="Top" Width="131" />
      <Button x_Name="buttonAbort" Content="Abort"
         HorizontalAlignment="Left" Margin="130,500,0,0"
         VerticalAlignment="Top" Width="131" />
      <CheckBox x_Name="checkBoxForegroundApp" Content="ForegroundApp"
         HorizontalAlignment="Left" Margin="84,362,0,0"
         VerticalAlignment="Top" />

   </Grid>
</Page>

Next, we update the application manifest file to declare the background task that the application will execute.

Right-click the Project name in Solution Explorer and click Properties.

Hotspot2
Figure 2: Selecting Properties

Click the “Package Manifest…” button and navigate to the Declarations tab.

Hotspot3
Figure 3: The Declarations tab

Add a BackgroundTask from the Available Declarations drop-down and click Add. Select “System Event” under the properties section and specify an entry point as a class (which we will later define) in the Entry point field.

Next, we will create a file that contains the Provisioning Data for a Hotspot. Note that the structure of this file is well defined and has to be copiedas-is.

Add a new XML file, called ProvisioningData.xml, to the solution with the following contents.

<?xml version="1.0" encoding="utf-8"?>
<CarrierProvisioning
   >
   <Global>
      <!-- Adjust the Carrier ID to fit your own ID.
           Refer to the MSDN documentation about Carrier ID's. -->
      <CarrierId>{11111111-1111-1111-1111-111111111111}</CarrierId>
      <!-- Adjust the Susbscriber ID.
           Refer to the MSDN documentation about Subscriber ID's. -->
      <SubscriberId>1234567890</SubscriberId>
   </Global>
   <WLANProfiles>
      <WLANProfile >
         <!-- Adjust the profile name to have a human readable
              network name. By default this equals the SSID. -->
         <name>Contoso Wi-Fi</name>
         <SSIDConfig>
            <SSID>
               <!-- Adjust the SSID name to fit the SSID
                    of the hotspot. -->
               <name>contosowifi</name>
            </SSID>
         </SSIDConfig>
         <MSM>
            <security>
               <authEncryption>
                  <authentication>open</authentication>
                  <encryption>none</encryption>
                  <useOneX>false</useOneX>
               </authEncryption>
               <HotspotProfile >
                  <ExtAuth>
                     <!-- Adjust the extension ID to match the
                          package family name of the application
                          running the background task handler. -->
                     <ExtensionId>7a043ce1-b464-41d5-9805-
                        76694351be64_h2fgybhm3had8</ExtensionId>
                  </ExtAuth>
               </HotspotProfile>
            </security>
         </MSM>
      </WLANProfile>
   </WLANProfiles>
</CarrierProvisioning>

The Extension ID is the same ID we will notice in the Application Manifest as “Package Family Name” under the Packaging tab.

Hotspot4
Figure 4: The Application Manifest is “Package Family Name” under the Packaging tab

Now, we will implement a helper class for storing and retrieving the configuration.

Add a new class, called “Config”, to the project. For simplicity, we will hard code a few properties and provide properties for capturing the name of the background helper tasks and authentication token.

//Config.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace App10
{
   public class Config
   {
      public static string AuthenticationHost
      {
         get { return "signin.contoso.com"; }
      }

      public static string UserName
      {
         get { return "username"; }
      }

      public static string Password
      {
         get { return "PassW@rd"; }
      }

      public static string ExtraParameters
      {
         get { return ""; }
      }

      // This flag is set by the foreground app to toggle
      // authentication to be done by the background task handler.
      public static bool AuthenticateThroughBackgroundTask
      {
         get
         {
            object value;
            if (ApplicationData.Current.LocalSettings.Values.
                  TryGetValue("background", out value) &&
               value is bool)
               return (bool)value;
               return true;  // default value
         }

         set { ApplicationData.Current.LocalSettings.Values
            ["background"] = value; }
      }

      // This item is set by the background task handler to pass
      // an authentication event token to the foreground app.
      public static string AuthenticationToken
      {
         get
         {
            object value;
            if (ApplicationData.Current.LocalSettings.Values.
                  TryGetValue("token", out value) &&
               value is string)
               return value as string;
            return "";
         }

         set { ApplicationData.Current.LocalSettings.Values
            ["token"] = value; }
      }
   }
}

Next, we implement the Background authentication task. Add another class, called BackgroundAuthenticationTask.cs, to the project:

//BackgroundAuthenticationTask.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Data.Xml.Dom;
using Windows.Networking.NetworkOperators;
using Windows.UI.Notifications;

namespace App10
{
   class BackgroundAuthenticationTask : IBackgroundTask
   {
      private const string _foregroundAppId =
         "HotspotAuthenticationApp.App";
      private BackgroundTaskDeferral _deferral;

      public void Run(IBackgroundTaskInstance taskInstance)
      {
         // Do the background task activity.
         // First, get the authentication context.

         var details = taskInstance.TriggerDetails as
            HotspotAuthenticationEventDetails;

         HotspotAuthenticationContext context;
         if (!HotspotAuthenticationContext.
               TryGetAuthenticationContext
            (details.EventToken, out context))
         {
            // Event is not of interest. Abort.
            return;
         }

         byte[] ssid = context.WirelessNetworkId;

         // Get configuration from application storage.


         // Check if authentication is handled by foreground app.
         if (!Config.AuthenticateThroughBackgroundTask)
         {
            // Pass event token to application
            Config.AuthenticationToken = details.EventToken;

            // TriggerAttentionRequired function throws
            // NotImplementedException on phone, we use
            // regular Toast Notification to notify user about
            // the authentication, Tapping on the notification
            // will launch the application where user can
            // complete the authentication.
            var toastXml = ToastNotificationManager.GetTemplateContent
               (ToastTemplateType.ToastText01);
               toastXml.GetElementsByTagName("text")[0].
               AppendChild(toastXml.CreateTextNode("Auth by foreground"));
            IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
            ((XmlElement)toastNode).SetAttribute("launch",
               "AuthByForeground");

            dynamic toast = new ToastNotification(toastXml);
            Type typeofToastNotification = toast.GetType();
            PropertyInfo tagProperty =
               typeofToastNotification.GetRuntimeProperty("Tag");
            PropertyInfo groupProperty =
               typeofToastNotification.GetRuntimeProperty("Group");
            if (tagProperty != null) toast.Tag = "AuthByForeground";
            if (groupProperty != null) toast.Group = "HotspotAuthAPI";

            var notification =
               ToastNotificationManager.CreateToastNotifier();
            notification.Show(toast);

            return;
         }

         // Handle authentication in background task.

         // Before calling an asynchronous API from the background task,
         // get the deferral object from the task instance.
         _deferral = taskInstance.GetDeferral();

         // Finally, call SkipAuthentication to indicate that we
         // are not doing native WISPr authentication.
         // This call also serves the purpose of indicating a
         // successful authentication.
         context.SkipAuthentication();

         _deferral.Complete();
      }
   }
}

In this class, we have code that is invoked when the background task is called. We also have created logic to display a Toast Notification.

Now, we are ready to wire up the UI to user actions.

In the code behind for MainPage (MainPage.xaml.cs), we will add the following variables to the class.

public sealed partial class MainPage : Page
{
   string taskName = "AuthenticationBackgroundTask";
   string backgroundEntryTaskPoint =
      "HotspotAuthenticationTask.AuthenticationTask";
   HotspotAuthenticationContext authenticationContext;
   public const string BackgroundTaskEntryPoint =
      "HotspotAuthenticationTask.AuthenticationTask";
   public const string BackgroundTaskName =
      "AuthenticationBackgroundTask";

   private bool HasRegisteredBackgroundTaskHandler = false;

   public ForegroundAuthenticationDelegate
      ForegroundAuthenticationCallback;

   CoreDispatcher coreDispatcher =
      Windows.UI.Xaml.Window.Current.CoreWindow.Dispatcher;

   // A delegate type for hooking up foreground
      // authentication notifications.
   public delegate void ForegroundAuthenticationDelegate
      (object sender, EventArgs e);

   public MainPage()

Next, we implement the click event handler for the Provision button.

private void buttonProvision_Click(object sender,
   RoutedEventArgs e)
{
   BackgroundAccessStatus status =
      BackgroundExecutionManager.RequestAccessAsync().AsTask().
      GetAwaiter().GetResult();

   if (status == BackgroundAccessStatus.Denied)
   {
      textBlockStatus.Text =
         "Access denied while trying Async Access";
      return;
   }

   var taskBuilder = new BackgroundTaskBuilder();

   // Create a new NetworkOperatorHotspotAuthentication trigger.
   var trigger = new NetworkOperatorHotspotAuthenticationTrigger();

   // Associate the NetworkOperatorHotspotAuthentication trigger
   // with the background task builder.
   taskBuilder.SetTrigger(trigger);

    // Specify the background task to run when the trigger fires.
   taskBuilder.TaskEntryPoint = this.backgroundEntryTaskPoint;

   // Name the background task.
   taskBuilder.Name = this.taskName;

   // Register the background task.
   var task = taskBuilder.Register();

   buttonProvision.IsEnabled = false;


}

Next, we add an event handler for Background task completion.

public async void OnBackgroundTaskCompleted(IBackgroundTaskRegistration
   sender, BackgroundTaskCompletedEventArgs e)
   {
      // Update the UI with progress reported by the background task.
      await coreDispatcher.RunAsync(CoreDispatcherPriority.Normal,
      new DispatchedHandler(()  =>
      {
         if ((sender != null) && (e != null))
         {
            // Update the UI with the completion status of the
            // background task.
            // The Run method of the background task sets this status.
            if (sender.Name == BackgroundTaskName)
            {
            textBlockStatus.Text = "Background task completed";


            // Signal callback for foreground authentication
            if (!Config.AuthenticateThroughBackgroundTask &&
               ForegroundAuthenticationCallback != null)
            {
               ForegroundAuthenticationCallback(this, null);
            }
         }

      }
   }));
}

We now can implement the click event handler for the “Authenticate through Background” button.

private void buttonAuthenticateThroughBackground_Click(object
      sender, RoutedEventArgs
   {
      Config.AuthenticateThroughBackgroundTask = true;
      if (!HasRegisteredBackgroundTaskHandler)
      {
         foreach (var cur in BackgroundTaskRegistration.AllTasks)
         {
            if (cur.Value.Name == BackgroundTaskName)
            {
               cur.Value.Completed +=
                  new BackgroundTaskCompletedEventHandler
                  (OnBackgroundTaskCompleted);
               HasRegisteredBackgroundTaskHandler = true;
               break;
            }
         }
      }
      return;
   }

Finally, we implement the methods for the activities for the Foreground app that attempt authentication.

private void buttonAuthenticate_Click(object sender,
   RoutedEventArgs e)
   {
      buttonAuthenticate.IsEnabled = false;

      // For Windows phone, we just skip authentication
      // because native WISPr is not supported.
      // Here you can implement custom authentication.
      authenticationContext.SkipAuthentication();
      textBlockStatus.Text = "Authentication skipped";
      buttonAuthenticate.IsEnabled = true;
   }


   private void checkBoxForegroundApp_Checked(object sender,
      RoutedEventArgs e)
      {
         if (checkBoxForegroundApp.IsChecked == true)
         {
            string token = Config.AuthenticationToken;
            if (token == "")
            {
               return;   // no token found
            }
            if (!HotspotAuthenticationContext.
               TryGetAuthenticationContext
               (token, out authenticationContext))
            {
               textBlockStatus.Text =
                  "TryGetAuthenticationContext failed";
               return;
            }

            buttonAuthenticate.IsEnabled = true;
            buttonSkip.IsEnabled = true;
            buttonAbort.IsEnabled = true;
         }
      }

   private void buttonSkip_Click(object sender,
      RoutedEventArgs e)
   {
      authenticationContext.SkipAuthentication();
      textBlockStatus.Text = "Authentication skipped";
      Config.AuthenticationToken = "";
      buttonAuthenticate.IsEnabled = false;
      buttonSkip.IsEnabled = false;
      buttonAbort.IsEnabled = false;
   }

   private void buttonAbort_Click(object sender,
      RoutedEventArgs e)
   {
      authenticationContext.AbortAuthentication(false);
      textBlockStatus.Text = "Authentication aborted";
      buttonAuthenticate.IsEnabled = false;
      buttonSkip.IsEnabled = false;
      buttonAbort.IsEnabled = false;
   }

Our application is now code-ready. However, it will not work because it needs to have certain data from mobile operators. Here are the steps once we have the data.

    1. Modify the Provisioning Metadata XML file to match your hotspot.
      Open provisioningData.xml and modify the following fields:
      • CarrierProvisioning\Global\CarrierID
      • CarrierProvisioning\Global\SubscriberID: This is the IMSI (International Mobile Subscriber Identity)
      • CarrierProvisioning\WLANProfiles\ WLANProfile\name: Name of your service point
      • CarrierProvisioning\WLANProfiles\ WLANProfile\SSIDConfig\SSID\name: Configured SSID of your hotspot
      • CarrierProvisioning\WLANProfiles\ WLANProfile\MSM\security\HotspotProfile\ExtAuth\ExtensionId: Available from Visual Studio App manifest
    2. Authenticate access to the Provisioning Agent APIs:
      • Open a PowerShell console.
      • Type the following command to import the Provisioning tools:
Import-Module "<path_to_Win8_sdk>\bin\<arch>\
   ProvisioningTestHelper.psd1"
      • Create and install a test Extended Validation certificate:
Install-TestEVCert -CertName <Certificate Name>
      • Use the new certificate to sign the provisioning file:
ConvertTo-SignedXml -InputFile <complete path to the input XML file>
   -OutputFile <complete path to the output XML file>
   -CertName <name of the certificate used to sign the xml>
    • Replace ProvisioningData.xml with the signed file.
  1. Provide crendentials for your test access point by updating the information in Config.cs if you have hard-coded values.

Summary

In this article, we learned about building a Windows Phone app that uses Hotspot Authentication APIs. I hope you have found this information useful. You can find more information at https://msdn.microsoft.com/en-us/library/windows/apps/br212049.aspx.

About the Author

Vipul Patel is a technology geek based in Seattle. He can be reached at vipul.patel@hotmail.com. You can visit his LinkedIn profile at https://www.linkedin.com/pub/vipul-patel/6/675/508.

The post Using Hotspot Authentication API in Windows Phone 8.1 appeared first on CodeGuru.

]]>