Disclaimer: this is an automatic aggregator which pulls feeds and comments from many blogs of contributors that have contributed to the Mono project. The contents of these blog entries do not necessarily reflect Xamarin's position.

August 18

Native Android Facebook Authentication with Azure App Service

Authentication is critical to applications success. Look at your app, and I bet the very first things that your users will do is sign up or log in to their account. This will probably, in turn, leverage some form of social authentication. Each social authentication provider is a little bit different, and some, such as Facebook, offer a native SDK to simplify the login process and offer additional functionality specific to their service. Previously, we looked at how to integrate the Facebook SDK for iOS to offer a native login experience and how to integrate with Azure Mobile Apps, part of Azure App Service. Today, I’ll show you how to log in with the Android Facebook SDK to simplify the login process on Android and with Xamarin.Forms.

Why use Native SDKs?

Azure Mobile Apps offers a simple LoginAsync method that will invoke a secure login process leveraging Chrome Custom Tabs. However, this still requires users to type in their existing user name and password, even if they already have the provider’s application installed on their device. Leveraging the native SDK for Facebook, Google, or Microsoft enables a secure and streamlined experience and provides native user interface controls that make your users feel safe when logging in.

Signing up for Facebook Auth

Before we even begin to integrate Facebook authentication into our app, we must register a new application on the Facebook Developer site.

Next, we’ll want to add a proper oAuth redirect, which can be done by adding a “Facebook Login” product:

For this application, we’ll be using Azure App Service, which means we can specify a redirect URL such as:

https://[AppServiceApplicationURL]/.auth/login/facebook/callback

You can learn more about configuring this by reading through the Azure App Service Authentication with Facebook documentation.

Getting Started

With our Facebook application set up, we can now start integrating the Facebook Android SDK, which is available from NuGet, into our application. This is the Xamarin.Android binding to the official SDK provided by Facebook, which allows us to use all of the features available to Java and Kotlin developers.

When installing this NuGet, it’s important for us to ensure that we have installed the latest Android Support Libraries as well, as they are a dependency.

Configuring Our App

There’s a bit of additional setup that we must perform before implementing the login process. We can add the Facebook App Id that we received and our app’s name inside of our string resources:

<string name="app_name">Coffee Cups</string>
<string name="app_id">605355546285789</string>

The Facebook SDK will look for this metadata that we can expose using assembly flags. I tend to add these into my AssemblyInfo.cs file along with permissions that are required:

[assembly: MetaData("com.facebook.sdk.ApplicationId", Value = "@string/app_id")]
[assembly: MetaData("com.facebook.sdk.ApplicationName", Value = "@string/app_name")]
[assembly: Permission(Name = Android.Manifest.Permission.Internet)]
[assembly: Permission(Name = Android.Manifest.Permission.WriteExternalStorage)]

Registering Our Android App with Facebook

We can add a new platform of Android in the Facebook Developer site under Settings, so Facebook has additional information about our application. This will require our package name, class name, and key hashes.

Our package name comes directly from the AndroidManifest.xml. The class name can be set manually on the Main Activity such as:

[Activity (Label = "Coffee Cups", Icon = "@drawable/icon",
        Name = "com.refractored.coffeecups.MainActivity",
        MainLauncher = true,
        ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]

Finally they key hashes can be found using the Android Keystore Signature tool for Visual Studio. For now, we can just use the default debug keystore, however, we would want to use the keystore that we use to sign our application with before publishing the app to the app store.

Adding a Facebook Login Button

Now, it’s time for us to finally add in a login button to kick off the entire process. If you’re developing a Xamarin.Android application using a native Android user interface, you can simply insert the LoginButton that comes from the Facebook SDK:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:facebook="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFF">
        <com.facebook.login.widget.LoginButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:layout_gravity="center_horizontal"
            facebook:com_facebook_confirm_logout="false"
            facebook:com_facebook_tooltip_mode="never_display" />
</LinearLayout>

Xamarin.Forms Custom Control

If you’re using Xamarin.Forms, we must write a very small custom control. First, in our shared code, create a FacebookLoginButton that we can access in our XAML:

public class FacebookLoginButton : Xamarin.Forms.View
{
}

This can then be added into any page of our application:

</code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:controls="clr-namespace:CoffeeCups.View;assembly:CoffeeCups"
             x:Class="CoffeeCups.View.LoginPage">
    <ContentPage.Content>
        <StackLayout HorizontalOptions="CenterAndExpand"
                     VerticalOptions="CenterAndExpand"
                     Padding="8">
            <Label Text="Login for Coffee!"
                   VerticalOptions="Center"/>
            <controls:FacebookLoginButton/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Then we can write a small custom renderer that will display the native login button:

using CoffeeCups.View;
using Xamarin.Forms;
using CoffeeCups.Droid;
using Xamarin.Forms.Platform.Android;
using Xamarin.Facebook.Login.Widget;
[assembly: ExportRenderer(typeof(FacebookLoginButton), typeof(FacebookLoginButtonRenderer))]
namespace CoffeeCups.Droid
{
    public class FacebookLoginButtonRenderer : ViewRenderer<FacebookLoginButton, LoginButton>
    {
        LoginButton facebookLoginButton;
        protected override void OnElementChanged(ElementChangedEventArgs<FacebookLoginButton> e)
        {
            base.OnElementChanged(e);
            if(Control == null || facebookLoginButton == null)
            {
                facebookLoginButton = new LoginButton(Forms.Context);
                SetNativeControl(facebookLoginButton);
            }
        }
    }
}

Since we’re using the native Facebook SDK, when the users log in they will see the native Facebook login pop up, or, if they have the Facebook app installed, they can immediately log in with one button click:

Handling the Login Process

When the user logs in, we must handle the actual login events if it was successful, canceled, or if an error occurred. In our MainActivity, or whatever Activity the login button is shown on, we can implement a simple interface, IFacebookCallback, to handle these events.

class FacebookCallback<TResult> : Java.Lang.Object, IFacebookCallback where TResult : Java.Lang.Object
{
    public Action HandleCancel { get; set; }
    public Action<FacebookException> HandleError { get; set; }
    public Action<TResult> HandleSuccess { get; set; }
    public void OnCancel()
    {
        HandleCancel?.Invoke();
    }
    public void OnError(FacebookException error)
    {
        HandleError?.Invoke(error);
    }
    public void OnSuccess(Java.Lang.Object result)
    {
        HandleSuccess?.Invoke(result.JavaCast<TResult>());
    }
}

Now, we can initialize the Facebook SDK, register for login callbacks, and handle them properly:

ICallbackManager callbackManager;
protected override void OnCreate (Bundle bundle)
{
   //Standard OnCreate Intialization
    FacebookSdk.SdkInitialize(ApplicationContext);
    callbackManager = CallbackManagerFactory.Create();
    var loginCallback = new FacebookCallback<LoginResult>
    {
        HandleSuccess = loginResult =>
        {
            var facebookToken = AccessToken.CurrentAccessToken.Token;
            //Login here
        },
        HandleCancel = () =>
        {
            //Handle Cancel
        },
        HandleError = loginError =>
        {
            //Handle Error
        }
    };
    LoginManager.Instance.RegisterCallback(callbackManager, loginCallback);
    //Finish or load Xamarin.Forms app here
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);
    callbackManager.OnActivityResult(requestCode, (int)resultCode, data);
}

Notice that we’re now able to get access to the Facebook access token, which will enable us to log in and make additional calls to the Facebook service.

Logging in to App Service

With this token, we can log in to our Azure App Service using the MobileServiceClient.

var facebookToken = AccessToken.CurrentAccessToken.Token;
var token = new JObject();
token["access_token"] = facebookToken;
var user  = await Client.LoginAsync(MobileServiceAuthenticationProvider.Facebook, token);

When we do this, we’ll get back a MobileServiceUser which contains a new token that’s unique to our App Service’s backend. It’s worth noting that this token is not the same as the Facebook token we sent, and it should be stored to re-hydrate the MobileServiceUser in the future.

Learn More

As we have seen here, it’s to our advantage to use the native authentication SDKs when possible in our application to streamline the login process for our users, which can be done with just a few lines of code. To learn more about Azure Mobile Apps as a backend for your mobile app, be sure to read through the great documentation including how to add other login providers to your mobile applications with custom URL schemes. Additionally, you can find my sample app Coffee Cup, which I used to demonstrated the concepts in this blog post, on GitHub.

The post Native Android Facebook Authentication with Azure App Service appeared first on Xamarin Blog.

August 17

Speech Central Makes it Easier to Browse the Internet Hands-Free

Labsii is a Serbian-based software development firm focused on creating better accessible, utility-driven apps for everyday tasks. Their Speech Central app allows users to use remote controls, such as those on headphones or Bluetooth commands, to browse the web, select articles they’d like to listen to in depth, and initiate text-to-speech capabilities. From freeing commuters trying to keep up with the latest headlines to helping families find and read the best recipes in the kitchen and assisting vision-impaired individuals, Speech Central strives to allow anyone to harness the wealth of information on the internet and stay up-to-date on topics that matter to them.

Initially launched as a Windows 8.1 app, Speech Central now covers nearly every platform that C# (and Xamarin) can reach. Today, Labsii’s founder and lead developer, Ivan Icin, joins us to share how he’s grown the company and user base to include Windows 10 UWP, Android,  iOS (including tvOS and watchOS), and Mac.

Tell us a little bit about your company and your role.

Labsii focuses on the consumer market. All of our apps have one common theme: great design and new interaction models that save time. We’re empowering people to do things not only differently, but better. 

Speech Central, one of our flagship apps, plays a huge part in our goal of providing value to our customers and making the world a better place. 

I’ve been developing software for almost 10 years, primarily using C# and .NET. My interest in apps started when I became a fan of the early stage Mozilla Firefox project and later actively contributed to its UI/UX. Around the same time, I started finding ways to improve internal processes at my “real job,” including learning SQL and C#. Those two stories merged when I founded Labsii.

Tell us about Speech Central.

Speech Central on iPhoneOur development started with a File Manager Desk & Archive desktop app (built with C#). We took what we learned from our experiences and launched Speech Central, then called “Share to Speech,” more than three years ago. It was originally a personal project; I wanted an app that would allow me to easily read internet articles and webpages aloud. We based the “1.0” user experience and design on my own experiences, needs, and wants. 

When we started, ours was the only app that offered this level of robust text-to-speech capabilities, and, while other similar apps have emerged, we’ve kept our edge by adding new interactions and convenient features that other apps don’t offer.

We’ve made many improvements and changes over the years, but our expansion to nearly all platforms has been the most important part of our evolution. Today, Speech Central is available for Windows (with the entire device family covered from phone to desktop), Android, iOS, Mac, watchOS, and tvOS.

What do your apps allow users to do?

Speech Central is the only app that delivers interactive web on-the-go. Most people access the web via a device screen, but you can’t really do that while running, driving, or moving through your daily activities. From the app interface, our users can quickly add favorite websites or blogs, upload their own documents, which we convert to audio files (desktop only), or search past articles / content to create “playlists” of interesting or must-read articles.

Some apps allow non-interactive web on-the-go, requiring users to fully prepare what they’re going to listen to by searching and saving specific articles before they head out. We remove that burden—our users just launch the app and listen to the fresh headlines using their headphone or Bluetooth controls to scan through their favorite news outlets, saved articles, and more, and then select what to listen to hands-free.

The internet is a great place, but, if you’re anything like me, you can easily lose time, especially when you use the standard browser. You might intend to check one simple thing, but spend a long time browsing unnecessary content. 

What were your goals?

First, we wanted to make something unique, something that had the potential to change how people interact with the internet. What if we made listening to the web and other content so convenient that it became people’s preferred way to consume news, documents, and other digital content?

Second, but just as important, we wanted to turn our ideas into a successful business.

We’ve achieved the first, and we’re well on our way to accomplishing the second.

Speech Central on Android

Why did you choose Xamarin?  

We started Speech Central with a Windows app, and we wanted to reuse our Windows app code to capitalize on our early success. If we were launching a new project, we’d choose Xamarin to quickly reach as many platforms as possible.

We’ve built some apps in Java and Swift, but they were fairly simple (Country Calling Code Fixer and Digty Clock).

We could develop Java and Swift apps in Android Studio and XCode, but those environments are less productive than Visual Studio. We’re a small team, and any productivity gains make a big difference. Thus, when it came time to expand Speech Central to other platforms, Visual Studio Tools for Xamarin was an easy choice.

Today, we do almost everything with .NET and Microsoft technology, from Visual Studio (on Windows and Mac) to Visual Studio Tools for Xamarin to Azure to HockeyApp to Visual Studio Team Services, and Visual Studio Mobile Center Preview.

What’s the most compelling or exciting aspect of your app

For our mobile users, interactive web is our key differentiator. On desktop, it’s our versatility: there’s something for everyone, from creating and listening to audio files to making web content accessible for visually impaired users to listening and sharing documents, e-books, and more.

Based on our analytics, no single use case is dominant, and that’s what we’re shooting for. 

How long did it take you to ship your apps, from design to deploy?

We decided to use Xamarin.Android, Xamarin.iOS, and Xamarin.Mac, which gave us full access to every element that a traditional Android or iOS app developer has in their toolkit. While we could have gotten slightly better code reuse from Xamarin.Forms, we still share a significant percentage of code across all of our desktop, mobile, wearable, and other connected device app versions.

We only have one full time developer (me), and it took us about a year to launch (including ramp time). Without Xamarin, it would have taken twice as long. Today, we release updates at least monthly, but often more frequently.

How do you use Microsoft Azure? 

We initially stored data in JSON format, and we transitioned Speech Central’s backend to Microsoft Azure several months ago to (1) begin testing syncing content across platforms and devices (we hadn’t even released on some platforms when we started the transition) and (2) future-proof our app, so when we want to make content sync available to users, it’ll be simple—we’ll just enable a login dialog inside the app.

In our experience, Microsoft Azure libraries have very good APIs to easily sync and retrieve app data.

How are using mobile DevOps / CI?

Speech Central on Apple WatchMobile quality starts with quality procedures and processes. Users are fickle and different kinds of users have different expectations. For example, when you launch something new, users may be somewhat forgiving about one or two small issues, but, especially over the last few years, this is becoming less and less the case. As competition increases, users will give up and look for an alternative at the first indication an app doesn’t meet their standards.

To deliver this level of quality, crash analytics play a major role. It’s impossible to avoid all bugs and crashes, no matter how much you test. This doesn’t mean that you shouldn’t comprehensively test your apps, but that you need a plan to deal with inevitable crashes.

Capturing and fixing issues requires robust crash analytics. We’ve used HockeyApp for quite some time, and I’ve started exploring Visual Studio Mobile Center, which, first off, is wonderfully designed in addition to delivering great crash logs that help us identify and resolve issues.

We’ve also used Visual Studio Team Services from the very start. If a new commit causes our tests to fail, we can dig into which changes are in the branch, troubleshoot, and easily revert to a secure, stable code backup. When we’re developing new features, we’re bound to run into times when something that worked in the last build now just doesn’t. It’s essential to quickly pinpoint which change caused the problem.

In addition to using HockeyApp and Visual Studio Mobile Center Preview for crash data, we also track user behavior to find ways to improve. As I mentioned, we designed the app based on my personal experiences and UI preferences. With HockeyApp, we’ve learned that my assumptions about our users aren’t always right.

For example, Speech Central includes many user commands, which we ordered based on how I’d like to use and navigate the app, making some controls easier to access than others. After looking at production usage analytics, we quickly realized that some commands were much more popular than we thought they’d be and rearranged shortcuts accordingly.

What have your users said about your app? 

We appreciate any praise about our overall app quality,  but it’s always most pleasing to hear how Speech Central is improving our users’ lives, whether it’s meeting a goal, being more efficient at work, or allowing someone with a disability to experience something never before possible.

We’ve also been reviewed and featured in many blogs. In one example, Windows Central tested our app over an extended period and wrote a great feature sharing their experiences (you can read the article here).

Have you accomplished your goals?

I believe that you should always have new goals, so it’s a never-ending process. We’ve accomplished so much, but we have many milestones that we’re still working toward—and even more that we don’t even know about yet.

What advice do you have for developers or organizations who are just starting mobile development? 

First, deeply understand your needs. Every choice has trade-offs, and you should select the option that benefits an individual project, not blindly follow any “rules” or advice. In my experience, others’ advice is often based on assumptions that may be true for most apps, but not necessarily for my projects.

For Xamarin specifically, the official guides from the Developer Center are a great place to start!
 
 
Visit xamarin.com/customers to learn how our customers across industries and geographies deliver amazing mobile apps, and visit xamarin.com/download to start building your own.

The post Speech Central Makes it Easier to Browse the Internet Hands-Free appeared first on Xamarin Blog.

August 15

Live Webinar: Take your .NET Skills from the Desktop to Android and iOS

Register today to join me for my upcoming webinar, Xamarin University Presents: Desktop Developer’s Guide to Mobile with Visual Studio Tools for Xamarin on Tuesday, August 29, to see how to extend your desktop expertise to the mobile world. As a long-time desktop developer, I’ll share my personal experiences and technical best practices, giving you step-by-step guidance to make the jump to native Android and iOS development.
 

Register

During the session, you’ll learn how to:

  • Use Visual Studio Tools for Xamarin and C# to design and build native apps for lots of devices and platforms
  • Map common desktop paradigms to mobile, including comparing desktop and mobile APIs
  • Optimize the UX / UI when porting your desktop app to a tablet or mobile device

You’ll also see sample code, get tips and tricks, and we’ll have Xamarin University instructors and mobile experts available to answer your questions live.

Register now to join us on August 29 at 9 am PT! Whether you’re a building commercial desktop apps, or apps for internal use, this session will give your mobile career a jumpstart.

 

We encourage all registrants to attend the webinar live, as we will be answering questions throughout the event. However, all registrants will receive a link to the recording, so please feel free to sign up even if you cannot join us that day.

The post Live Webinar: Take your .NET Skills from the Desktop to Android and iOS appeared first on Xamarin Blog.

August 14

Adding Storage to Mobile Apps with OneDrive for Business

Every app needs storage, whether it’s for storing a collection of the same type of records in Azure Mobile Service with Easy Tables, or a SQL Database exposed via Web Services. When the data is unstructured, NoSQL with Azure DocumentDB can be used. For scalability and high availability, Azure CosmosDb can be used in both the cases. In enterprise situations, however, where different types of documents need to be stored and shared with colleagues, the best solution is OneDrive for Business. OneDrive for Business is part of Office 365 and provides easy access across multiple Office 365 services. We learned previously how to integrate OneDrive for Business in mobile apps developed using Xamarin.

Since then, there have been changes to APIs and SDKs that have made this integration simpler. We’ll take a look at those changes in this blog post. You can find the repo for this post on GitHub.

Step 1: App Registration

To integrate OneDrive for Business with mobile apps, the app needs to be registered with the Azure Active Directory service. This will authenticate and authorize users while providing access to the resources. The process is the same as registering any other app with Azure Active Directory.

Visit https://apps.dev.microsoft.com/ and click on Add an app to get started. Name your app and continue, making sure you note the Application Id. Click on Add Platorm and select Native Application.

Ensure you define Delegated Permissions for the application to be able to access files stored on OneDrive for Business:

  • Files.Read
  • Files.Read.All
  • Files.Read.Selected
  • Files.ReadWrite
  • Files.ReadWrite.All
  • User.Read

Step 2: Calling APIs

Once the app is registered, create a Blank Xamarin.Forms application with the PCL code sharing strategy. Make sure that the profile selected for PCL is set to Profile7 by right-clicking the PCL project and selecting Properties > Build > General. Add two NuGet packages: Microsoft.Identity.Client and Microsoft.Graph.

Use the Microsoft Authentication Library (MSAL) to authenticate the user in the code-behind in App.xaml.cs.

using Microsoft.Identity.Client;
...
public static PublicClientApplication IdentityClientApp = null;
public static string ClientID = "4f91166f-c946-438f-8d07-33792251026d";
public static string[] Scopes = { "User.Read", "User.ReadBasic.All", "Files.Read", "Files.Read.All", "Files.ReadWrite", "Files.ReadWrite.All" };
public static UIParent UiParent = null;
public App()
{
   InitializeComponent();
   MainPage = new XamarinDrive.MainPage();
   IdentityClientApp = new PublicClientApplication(ClientID);
   MainPage = new NavigationPage(new MainPage());
}

After the authentication process is complete, create a GraphServiceClient object which will be responsible for further requests in the code-behind for MainPage.xaml.cs.

using Microsoft.Graph;
using Microsoft.Identity.Client;
...
private async Task CreateGraphClientAsync()
{
   try {
      Client = new GraphServiceClient("https://graph.microsoft.com/v1.0",
               new DelegateAuthenticationProvider(
               async (requestMessage) =&gt; {
                         var tokenRequest = await App.IdentityClientApp.AcquireTokenAsync(App.Scopes, App.UiParent).ConfigureAwait(false);
                         requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", tokenRequest.AccessToken);
                }));
                Me = await Client.Me.Request().GetAsync();
                Username.Text = $"Welcome {((User)Me).DisplayName}";
                return true;
       }
       catch (MsalException ex){
            await DisplayAlert("Error", ex.Message, "OK", "Cancel");
            return false;
       }
}

Using this GraphServiceClient and Graph Model, traverse through the Drive and get a list of items (files and folders) within the drive. Assign this list of items to the listview control in ListPage.xaml.cs.

using Microsoft.Graph;
...
var client = new GraphServiceClient("https://graph.microsoft.com/v1.0",
                new DelegateAuthenticationProvider(
                async (requestMessage) =&gt;
                {
                   var tokenRequest = await App.IdentityClientApp.AcquireTokenSilentAsync(App.Scopes, App.IdentityClientApp.Users.FirstOrDefault());
                   requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", tokenRequest.AccessToken);
                }));
var data = await client.Me.Drive.Root.Children.Request().GetAsync();
var list = data.ToList();
FileList.ItemsSource = list;

This list of DriveItems will then be displayed on ListPage using the binding with ListView. When a user clicks on an item inside List, the file will be opened as requested. This can be achieved with the OnItemTapped event.

var item = ((DriveItem) e.Item);
   if (item.Folder != null)
      await DisplayAlert("Type", "Selected Item is a Folder!", "Ok");
   else
      Xamarin.Forms.Device.OpenUri(new Uri(item.WebUrl));

Just like any Xamarin.Forms app is required to implement platform-specific functionality differently, follow the guide for each individual platform to implement authentication from here.

Step 3: Running the App

Run the app on a device or simulator and log in with your Office 365 credentials. The app will ask for appropriate permissions. Once those permissions are granted, the app will display the list of files.

Wrapping Up

OneDrive for Business, which is part of Office 365, allows users to store, share, and collaborate with different types of documents. Using Microsoft Graph Client Libraries and Microsoft Authentication Library, it’s easy to integrate various Office 365 services such as OneDrive. As usual, you can find the sample used in this blog post on GitHub.

The post Adding Storage to Mobile Apps with OneDrive for Business appeared first on Xamarin Blog.

August 11

Podcast: Contributing to Xamarin.Forms, C# 7, Input Validation, Android’s BottomNavigationView, and more!

In this episode of the Xamarin Podcast, James Montemagno and I cover the latest mobile .NET development news, including how to get started contributing to Xamarin.Forms, C# 7 tips & tricks, validating user input, Android’s BottomNavigationView, and new Xamarin releases. Be sure to download today’s episode from your favorite podcasting app!



Subscribe or Download Today

Keeping up with the latest in .NET, C#, and Xamarin is easier than ever with the Xamarin Podcast! Cohosts Pierce Boggan and James Montemagno cover topics relevant to Xamarin developers, from designing mobile apps to identity management. Be sure to subscribe to the Xamarin Podcast on iTunes, Google Play Music, Stitcher, or your favorite podcast app you use to ensure you don’t miss an episode.

The post Podcast: Contributing to Xamarin.Forms, C# 7, Input Validation, Android’s BottomNavigationView, and more! appeared first on Xamarin Blog.

August 10

Announcement: Clojure.spec implementation for Node.js

A few months ago I started implementing Speculaas, a Clojure.spec implementation for Node.js. This is the  announcement of a series of blog posts on this site in which I will show how to use this npm package for specification based testing of your code.

Have fun,

Maurits


August 9

Payit Brings Peer-to-Peer Payments to Mexico with Mobile DevOps and the Cloud

Payit’s mobile apps are revolutionizing how Mexican residents pay bills and request and send money among friends and family. Initially a web-only way to pay rent, the founding team quickly realized that their customers were paying each other using the platform and developed Mexico’s first peer-to-peer payment network (available on Android and iOS), removing the need for wire transfers, checks, or visits to the ATM.

Today, Miguel Cervantes, Payit CTO, tells us how Payit has grown from a one-man development team to a fast-moving organization with an automated, bi-weekly release cadence to continuously ship high quality, secure apps to their passionate expanding customer base.

Tell us a little bit about your company and role.

Payit app on iPhoneWe started Payit a couple of years ago to solve a big problem for Mexico’s residents: cash. Because of its geography and lack of infrastructure, Mexico has the biggest “cost” of cash transactions in the world. Consumers spend 2.3 billion pesos and 48 million hours simply accessing cash (getting to an ATM, waiting in line, and paying associated fees), and Mexico’s welfare program spends a significant portion of its funds in dispersion and logistics costs. Less than 30% of Mexico’s adult population has a debit account, but the vast majority have a smartphone (see Fletcher School’s Institute for Business in the Global Context (IBGC) – Tufts University report to learn more about the cost of cash in Mexico).

We’re serving two distinct audiences or situations where people heavily rely on cash, even living in the biggest cities: young adults, typically between 18–34, who frequently need to pay or request funds from friends (roommates, trips, small loans) and small business owners and shopkeepers who need to collect payments for goods. This “informal market” of business owners represents over half of the Mexican economy, but they’re historically largely cash-based.

With Payit, our goal is to revolutionize the way we do things, making them easier, better, and faster. We allow anyone with a smartphone to send or receive money, and we free business owners to accept any form of digital payment, from a simple credit or debit cards today to crypto currencies in the future.

I’m Payit’s CTO, and I have experience with numerous languages and frameworks: a little Obj-C and Java, as well as web languages such as JavaScript / VB Script, but most of my experience is in writing enterprise-level C# applications for desktop (none targeting mobile platforms). Since our development team is small, I’m actively coding with our developers on a daily basis.

Tell us about your app; has it evolved over time?

Before Payit, we were a software development company. As many developers know, this is an extremely cyclical business; sometimes you have tons of work, sometimes you don’t.

In one of those “sometimes not” phases, we decided to start a service to satisfy one of our own needs: making rent payment easier. After we released, we quickly realized that many people were sending money to each other, not just their landlords, and saw an opportunity to tackle a much bigger market and help our whole country.

Our app is simple; it allows people to securely pay and collect funds through their mobile phones. Users create a login using their cellphone number or Facebook account, link their bank accounts and debit cards, and can immediately start sending and requesting money, view payment requests, and more. Before finalizing a transaction, users must enter a unique PIN to ensure all of their transfers are approved and safe.

Why did you choose Xamarin?

I analyzed many technologies, basing my decision on four main criteria:

  • Security and Stability: As a bank-like app, we needed to ensure that the technology let us have world-class security and stability. With Xamarin (and C#), we have flawless access to the key chain/key store and all .NET encryption functionality. .NET allows us to use several kinds of encryption systems with ease, including RSA1024 and AES256 to secure our communications (in addition to the SSL certificate).
  • Performance and Productivity: We wanted performance both on the device in the form of a native experience, as well as in our own development processes. Xamarin.Forms gives us that fully native look and feel and reduces our release cycles.
  • Scalability: We looked for technology with an active, growing community and great documentation.
  • TCO: We’re a start-up and keeping our burn rate as low as possible is top of mind. One language (C#) ruling both the backend and the front end reduces our need to staff and train a huge development team. Our developers move from the backend to the front end with ease, and share their knowledge and code between both worlds.

At the end of the day, we found our solution in Xamarin, particularly Xamarin.Forms.

How did you get up to speed with mobile development?

Our team used C# for desktop apps, so our ramp-up was easier. Plus, since everything is C#, we could share snippets and experiences across the team to get things done quickly.

What is the most compelling or exciting aspect of your app.

Beyond enabling mobile payments for the first time in Mexico, what makes us different is our commitment to mobile quality and security for our customers and fellow citizens. 

We’ve taken care to create a fully native UX and invested in mobile DevOps processes. On the security side, we store all personal bank information, including credit cards and account numbers, on the device (with encrypted distributed key methods and additional security layers), not on our servers.

We know that it’s not a matter of if, but when, we’ll face hack attacks, and having this distribution ensures we don’t have a “gold mine” of users’ financial data on our servers. In our eyes, the best person to have your personal and sensitive information is you.

Describe your development process and team structure; how long did it take you to release, from design to deploy?

Payit app on Android

We have four developers, including myself: one dedicated to the app (to me, it’s amazing that we only need one!), one dedicated to the core backend, one to the bank backend, while I usually switch between the app and the backend. A junior developer who helps us gather statistics and business analytics for reporting and a UX designer round out the team.

On the development side, everything is C#. We use Visual Studio 2017 Tools for Xamarin, Windows Server 2012 R2, and SQL Server Management Studio. We virtualize our test environment with Hyper-V, and all of our user profile data is stored in Microsoft SQL Server (transactions, profiles, sessions, friends, and wall events). I’ve worked with many different databases (MySQL, Derby, and Oracle) and found Microsoft SQL Server most smoothly runs big queries with a lot of data. 

From writing T-SQL queries to the integration with Visual Studio and availability of tools like SQL Server Management Studio (especially the Profiler) for debugging ORM generated queries, any data we want is immediately available.

For our mobile apps, we handle bank transactions, so it’s imperative that the app is bug free and makes users feel safe, or we’ll immediately lose their trust. We released our first version in 2016, but it would have taken eons without Xamarin. At the beginning of the project, we were a one-man army (me!), and having multiple languages and multiple IDEs would have taken me years to learn, code, debug, and deploy. Today, we share 98% of our code across Android and iOS (we have a few custom renderers that use C# native APIs).

As I mentioned, we’ve invested in mobile DevOps processes, including Visual Studio Mobile Center Preview for CI, and we release a new build daily, with a beta candidate for our internal testers every Thursday. Our release frequency depends on what we want to achieve; after a big new release, we typically ship updates every two weeks.

With each production release, HockeyApp crash reports and statistics help us understand what’s happening with the app; if it’s running correctly, how many users are crash-free, which issues are happening most frequently, and so forth. We use this information to learn and consistently improve.

What have your users said about your app? 

We have 60K active users and everyone we talk to loves the app, but we’re happier that more than 70% of our users come from referrals.

Our users don’t just like our app, they’re so passionate about it they share it with their friends! For an app like ours, virality is critical.

What’s your team planning to build next? Why?

We have a lot planned. Our goals have always been extremely ambitious. We’ve achieved great milestones, but still have a lot of work to do.

We’re in the process of migrating our .NET Framework to .NET Core, and we’re researching the best Azure Machine Learning algorithms to replace our existing “State Machine AntiFraud System” (what we’ve named our in-house system, which limits us to simple rules). We want to combine our experience and expertise with Azure Machine Learning and Azure infrastructure to create a peer-to-peer specific antifraud system that learns from our users.

Going forward, we’d also like to incorporate chatbots and a more conversational UI.

What advice do you have for developers or organizations who are just starting mobile development?

“Cross-platformize” your projects! Don’t be afraid of cross-platform native solutions. For us, our path changes a lot day-to-day. Because we share so much code across platforms, we’re able to quickly address changes in our market and the needs of our users. 

As a new developer, you’ll save a lot of time and money by not learning platform-specific languages and, instead, focusing on reaching as many platforms as possible as quickly as possible. The future of app development is the ability to run on every single device, and the less code you have to write, the better.

Lastly, platform-specific look and feel (UX) matters: users will recognize native quality, or non-native quality, and this has large impacts on your engagement/retention.
 
 
Visit xamarin.com/download to get started and explore xamarin.com/customers to get inspired.

The post Payit Brings Peer-to-Peer Payments to Mexico with Mobile DevOps and the Cloud appeared first on Xamarin Blog.

August 8

Validation in Xamarin.Forms Enterprise Apps

animationWe released an eBook this past May on Enterprise Application Patterns using Xamarin.Forms. The eBook focuses on core patterns and architectural guidance for developing Xamarin.Forms enterprise apps that are easier to test, maintain, and evolve. Guidance is provided on how to implement the Model-View-ViewModel (MVVM) pattern, dependency injection, navigation, validation, and configuration management, while maintaining loose coupling. In addition, there’s also guidance on performing authentication and authorization with IdentityServer, accessing remote data from containerized microservices, and unit testing.

This blog post explores validation in Xamarin.Forms enterprise apps. There are, of course, many approaches that can be taken to validation. What’s presented here is the validation approach taken in the eShopOnContainers mobile app, which is extensible, easily unit testable, and supports data binding and property change notification.

Introduction

Any app that accepts input from users should ensure that the input is valid. An app could, for example, check for input that contains only characters in a particular range, is of a certain length, or matches a particular format. Without validation, a user can supply data that causes the app to fail. Validation enforces business rules, and prevents an attacker from injecting malicious data.

In the context of the Model-ViewModel-Model (MVVM) pattern, a view model or model will often be required to perform data validation and signal any validation errors to the view so that the user can correct them. The eShopOnContainers mobile app performs synchronous client-side validation of view model properties and notifies the user of any validation errors by highlighting the control that contains the invalid data, and by displaying error messages that inform the user of why the data is invalid. The following diagram shows the classes involved in performing validation in the eShopOnContainers mobile app:

View model properties that require validation are of type ValidatableObject<T>, and each ValidatableObject<T> instance has validation rules added to its Validations property. Validation is invoked from the view model by calling the Validate method of the ValidatableObject<T> instance, which retrieves the validation rules and executes them against the ValidatableObject<T> Value property. Any validation errors are placed into the Errors property of the ValidatableObject<T> instance, and the IsValid property of the ValidatableObject<T> instance is updated to indicate whether validation succeeded or failed.

Property change notification is provided by the ExtendedBindableObject class, and so an Entry control can bind to the IsValid property of the ValidatableObject<T> instance in the view model class to be notified of whether or not the entered data is valid.

Specifying Validation Rules

Validation rules are specified by creating a class that derives from the IValidationRule<T> interface, which is shown in the following code example:

public interface IValidationRule<T>
{
    string ValidationMessage { get; set; }
    bool Check(T value);
}

This interface specifies that a validation rule class must provide a boolean Check method that is used to perform the required validation, and a ValidationMessage property whose value is the validation error message that will be displayed if validation fails.

The following code example shows the IsNotNullOrEmptyRule<T> validation rule, which is used to perform validation of the username and password entered by the user on the LoginView when the eShopOnContainers mobile app is configured to use mock services:

public class IsNotNullOrEmptyRule<T> : IValidationRule<T>
{
    public string ValidationMessage { get; set; }
    public bool Check(T value)
    {
        if (value == null)
        {
            return false;
        }
        var str = value as string;
        return !string.IsNullOrWhiteSpace(str);
    }
}

The Check method returns a boolean indicating whether the value argument is null, empty, or consists only of whitespace characters.

Adding Validation Rules to a Property

In the eShopOnContainers mobile app, view model properties that require validation are declared to be of type ValidatableObject<T>, where T is the type of the data to be validated. The following code example shows an example of one such property:

public ValidatableObject<string> UserName
{
    get
    {
        return _userName;
    }
    set
    {
        _userName = value;
        RaisePropertyChanged(() => UserName);
    }
}

For validation to occur, validation rules must be added to the Validations collection of the ValidatableObject<T> instance, as demonstrated in the following code example:

private void AddValidations()
{
    _userName.Validations.Add(new IsNotNullOrEmptyRule<string> 
    { 
        ValidationMessage = "A username is required." 
    });
}

This method adds the IsNotNullOrEmptyRule<T> validation rule to the Validations collection of the ValidatableObject<T> instance, including a value for the ValidationMessage property, which specifies the validation error message that will be displayed if validation fails.

Triggering Validation

Validation can be triggered manually for a view model property. For example, this occurs in the eShopOnContainers mobile app when the user taps the Login button on the LoginView, when using mock services. The command delegate calls the MockSignInAsync method in the LoginViewModel, which invokes validation by executing the Validate method, which in turn invokes the ValidateUserName method:

private bool ValidateUserName()
{
    return _userName.Validate();
}

The ValidateUserName method performs validation of the username entered by the user on the LoginView, by invoking the Validate method on the ValidatableObject<T> instance. The following code example shows the Validate method from the ValidatableObject<T> class:

public bool Validate()
{
    Errors.Clear();
    IEnumerable<string> errors = _validations
        .Where(v => !v.Check(Value))
        .Select(v => v.ValidationMessage);
    Errors = errors.ToList();
    IsValid = !Errors.Any();
    return this.IsValid;
}

This method clears the Errors collection, and then retrieves any validation rules that were added to the object’s Validations collection. The Check method for each retrieved validation rule is executed, and the ValidationMessage property value for any validation rule that fails to validate the data is added to the Errors collection of the ValidatableObject<T> instance. Finally, the IsValid property is set, and its value is returned to the calling method, indicating whether validation succeeded or failed.

Validation is also automatically triggered whenever a bound property changes. For more information, see Triggering Validation when Properties Change.

Displaying Validation Errors

The eShopOnContainers mobile app notifies the user of any validation errors by highlighting the control that contains the invalid data with a red line, and by displaying an error message that informs the user why the data is invalid below the control containing the invalid data. The following screenshot shows part of the LoginView in the eShopOnContainers mobile app when a validation error is present:

Highlighting a Control that Contains Invalid Data

The LineColorBehavior attached behavior is used to highlight Entry controls where validation errors have occurred. The following code example shows how the LineColorBehavior attached behavior is attached to an Entry control:

<Entry Text="{Binding UserName.Value, Mode=TwoWay}">
    <Entry.Style>
        <OnPlatform x:TypeArguments="Style"
          iOS="{StaticResource EntryStyle}"
          Android="{StaticResource EntryStyle}"
          WinPhone="{StaticResource UwpEntryStyle}"/>
    </Entry.Style>
    ...
</Entry>

The Entry control consumes an explicit style, which is shown in the following code example:

<Style x:Key="EntryStyle"
       TargetType="{x:Type Entry}">
    ...
    <Setter Property="behaviors:LineColorBehavior.ApplyLineColor"
            Value="True" />
    <Setter Property="behaviors:LineColorBehavior.LineColor"
            Value="{StaticResource BlackColor}" />
    ...
</Style>

This style sets the ApplyLineColor and LineColor attached properties of the LineColorBehavior attached behavior on the Entry control. When the value of the ApplyLineColor attached property is set, or changes, the LineColorBehavior attached behavior executes the OnApplyLineColorChanged method, which adds or removes the EntryLineColorEffect class to the Entry‘s Effects collection. For more information about the EntryLineColorEffect class, see Highlighting a Control that Contains Invalid Data.

The Entry control also has a DataTrigger added to its Triggers collection. The following code example shows the DataTrigger:

<Entry Text="{Binding UserName.Value, Mode=TwoWay}">
    ...
    <Entry.Triggers>
        <DataTrigger 
            TargetType="Entry"
            Binding="{Binding UserName.IsValid}"
            Value="False">
            <Setter Property="behaviors:LineColorBehavior.LineColor" 
                    Value="{StaticResource ErrorColor}" />
        </DataTrigger>
    </Entry.Triggers>
</Entry>

This DataTrigger monitors the UserName.IsValid property, and if it’s value becomes false, it executes the Setter, which changes the LineColor attached property of the LineColorBehavior attached behavior to red.

Displaying Error Messages

The UI displays validation error messages in Label controls below each control whose data failed validation. The following code example shows the Label that displays a validation error message if the user has not entered a valid username:

<Label Text="{Binding UserName.Errors, Converter={StaticResource FirstValidationErrorConverter}"
       Style="{StaticResource ValidationErrorLabelStyle}" />

Each Label binds to the Errors property of the view model object that’s being validated. The Errors property is provided by the ValidatableObject<T> class, and is of type List<string>. Because the Errors property can contain multiple validation errors, the FirstValidationErrorConverter instance is used to retrieve the first error from the collection for display.

Summary

Enterprise Application Patterns using Xamarin.Forms focuses on core patterns and architectural guidance for developing Xamarin.Forms enterprise apps that are easier to test, maintain, and evolve. The eBook also ships with a sample application, the eShopOnContainers mobile app, which performs synchronous client-side validation of view model properties and notifies the user of any validation errors by highlighting the control that contains the invalid data, and by displaying error messages that inform the user why the data is invalid.

The post Validation in Xamarin.Forms Enterprise Apps appeared first on Xamarin Blog.

August 7

Exploring Android’s Bottom Navigation View

The debate over whether tabs should go on the top or the bottom of a screen has raged for nearly a decade. Android has always preferred to use tabs as a filtering mechanism on the top of a page, while iOS has used bottom tabs as the main source of navigation. Now, with the addition of the Bottom Navigation View in the Support Design library, Android developers have the choice of where their main navigation comes from in their applications.

Bottom navigation bars make it easy for your users to navigate through your top-level views with a single tap, compared the the navigation drawer that flies out from the side and has been a standard when there are a lot of different sections to an app. Today, I’ll walk through when it’s best to use bottom navigation in your app, how to implement it, and how to customize it to your liking.

The core experience of bottom navigation is designed for use on mobile phone devices that allows users to swap between pages easily. Some questions for if you should use bottom navigation are:

  • Does your app have 3–5 top-level pages?
  • Do your top-level pages need direct access?

If your application has more than five pages, it’s best to stick with the navigation drawer; if you have less than three, stick with standard top tabs.

Getting Started

To get started with the new Bottom Navigation View, we’ll want to make sure that we have our Android application updated with an AppCompat Activity and upgraded to the latest Support Libraries. With that, we can now install the Xamarin.Android.Support.Design NuGet package (current version 25.3.1) into our Android project at our set up.

Adding Tab/Menu Items

We must define the items that will be displayed before we add the BottomNavigationView control. This is controlled similarly to the NavigationDrawer, with a menu defined in xml. We can create a new menu folder in the Resources directory and add a new xml file. I created bottom_navigation_main.xml in Resources/menu/ and downloaded a few tab icons from the Android Asset Studio, which are 24dp x 24dp.



  
  
  

Adding a Bottom Navigation View

Bottom navigation works by replacing fragments when one of the items is selected. This means that our Android xml should also have a FrameLayout to swap in and out the fragments that will be displayed. Our xml will look something like this in its basic form:


    
    
      
  

We can define an elevation so the bottom navigation is lifted off the page with a nice drop shadow, and we define our items in the navigation view with the menu property that is referencing the menu we created earlier.

As we can see, the default will automatically apply our primary color and gray out the deselected items.

Handling Click Events

Now it’s time for us to actually handle the click events and set our content. In this example, I have three different fragments that simply load an Android xml file that displays the current index it’s on. We can create a simple method to replace the current fragment based on the ID that was set in the menu xml in our Main Activity:

void LoadFragment(int id)
{
    Android.Support.V4.App.Fragment fragment = null;
    switch (id)
    {
        case Resource.Id.menu_home:
            fragment = Fragment1.NewInstance();
            break;
        case Resource.Id.menu_audio:
            fragment = Fragment2.NewInstance();
            break;
        case Resource.Id.menu_video:
            fragment = Fragment3.NewInstance();
            break;
    }
    if (fragment == null)
        return;
    SupportFragmentManager.BeginTransaction()
        .Replace(Resource.Id.content_frame, fragment)
        .Commit();
}

Now we can load our xml, find the BottomNavigationView, and register for a NavigationItemSelected event:

BottomNavigationView bottomNavigation;
protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.main);
    var toolbar = FindViewById(Resource.Id.toolbar);
    if (toolbar != null)
    {
        SetSupportActionBar(toolbar);
        SupportActionBar.SetDisplayHomeAsUpEnabled(false);
        SupportActionBar.SetHomeButtonEnabled(false);
    }
    bottomNavigation = FindViewById(Resource.Id.bottom_navigation);
    bottomNavigation.NavigationItemSelected += BottomNavigation_NavigationItemSelected;
    // Load the first fragment on creation
    LoadFragment(Resource.Id.menu_home);
}
private void BottomNavigation_NavigationItemSelected(object sender, BottomNavigationView.NavigationItemSelectedEventArgs e)
{
    LoadFragment(e.Item.ItemId);
}

Adding Color

Google’s recommendation is to simply use the default white or black background color and primary tint of icons if your app is using default themes and your Toolbar is already tinted. If you wish to set the color of the bottom navigation, then it’s recommended to make the icon and text of the current action black or white. There are two additional properties, app:itemIconTint and app:itemTextColor, that can be set to handle this. Setting them directly to a specific color is what you probably think you want to do, but an immediate issue will present itself where it also sets the deselected state to the same color. For instance, if I set these three properties:

android:background="@color/primary"
app:itemIconTint="@android:color/white"
app:itemTextColor="@android:color/white"

To fix this, we just have to create a selector defined in our drawable folder that will set the color based on the state in a new xml file; I called mine nav_item_colors.xml:



  
  

Now, back in our BottomNavigationView, we can use the new selector colors:

android:background="@color/primary"
app:itemIconTint="@drawable/nav_item_colors"
app:itemTextColor="@drawable/nav_item_colors"

Absolutely lovely!

Learn More

To learn more about bottom navigation in Android, be sure to read through the Material Design Guidelines for all the “dos and don’ts” of using it. You can also grab a full sample and other samples of navigation from my GitHub repo.

The post Exploring Android’s Bottom Navigation View appeared first on Xamarin Blog.

Monologue

Monologue is a window into the world, work, and lives of the community members and developers that make up the Mono Project, which is a free cross-platform development environment used primarily on Linux.

If you would rather follow Monologue using a newsreader, we provide the following feed:

RSS 2.0 Feed

Monologue is powered by Mono and the Monologue software.

Bloggers