Connect(); 2016

Volume 31 Number 12

[Connect(); Mobile DevOps]

Exploring Visual Studio Mobile Center

By Thomas Dohmke; 2016

Mobile devices are now at the center of the technology ecosystem. Many people feel they can’t live without their phones, tablets, and laptops, and use them to organize information for both their personal and their professional lives. The business world is reacting to this, and every company today is bent on transforming itself into a mobile business. In order to be successful and thrive, companies will have to support not just one mobile app, but a multi-app mobile strategy. This has come to be called the appification of the modern business—the proliferation of targeted, highly optimized apps designed for a particular group of users or for specific tasks. In an appified world, development teams have to deliver more apps with more value to customers, while the mobile platforms that run these apps are continuously evolving and the number of devices is constantly growing. The biggest apps are installed on more than 1 billion devices, with thousands of device configurations based on criteria such as screen size, language, locale or network provider.

To tackle those challenges, Microsoft offers an end-to-end solution based on three pillars: Visual Studio and Xamarin allow you to create mobile and desktop apps for all major platforms. Microsoft Azure provides powerful and flexible cloud services that make it easy to start or extend existing infrastructure assets and manage data between server and client experiences. Finally, the Mobile DevOps process helps you manage the application lifecycle and allows you to automate integration, testing, delivery and monitoring of your app. The current version of this Mobile DevOps stack consists of multiple integrated, but otherwise disparate, tools such as Visual Studio Team Services (VSTS), Xamarin Test Cloud and Hockey­App. Microsoft has learned a lot from offering these products in the past few years, including how developers can adopt Mobile DevOps practices faster and with less friction.

In this article, I am proud to announce the public preview of our product, combining all features into a single platform: Visual Studio Mobile Center.

The Mobile Application Lifecycle

DevOps practices can cover the whole development process, but they’re not an all-or-nothing commitment. Similar to a set of command-line tools, each practice can be used alone, but you get additional value by combining multiple practices. This is exactly how Mobile Center was designed. It starts with a great onboarding experience for developers, including an API-first design, which allows you to use Mobile Center completely through its REST API or command-line interface (CLI). Each feature solves a specific problem and is usable on its own.

With Build, you can take your source code in any Git repository and create an installable app package automatically with every commit or push. Best of all, you don’t need to provision any agents or external machines that run macOS to build your iOS apps. Mobile Center takes care of this and will compile your iOS and Android app right from the source code, with no manual setup on your side.

Once the build process is finished, you want to run your tests on real devices. Test Cloud offers more than 400 unique device configurations to validate your app’s behavior. Tests can be written in C# (UITest), Ruby (Calabash), or Java (Appium), and are automatically executed after a build succeeds.

When all tests are green, your app needs to get into the hand of testers—which is exactly what the Distribute feature offers. Enter a set of e-mails—called Distribution Groups—and your users can install the app directly on their phones, much as they’d download an app from the app store. Mobile Center Build, Test and Distribute work together seamlessly, so each of your code commits gets the maximum level of validation. And none of these features require any modification of your code.

The next step is to add monitoring to the app. Whether it’s automated testing, manual testing, a demo for a customer, or the launch of a new release in the App Store, the collection of usage and diagnostic data is vital for the success of your app. By adding the Mobile Center SDK, you can collect Crashes and leverage Analytics to assess quality issues, learn how and where customers are using your app, and ultimately improve ratings and reviews by responding to their requests.

The SDK also enables two other features: Identity and Tables. Identity is the quickest way to authenticate your app’s users with their Google, Facebook, Twitter or Microsoft account. Tables lets you build a cloud store for viewing, adding or modifying app data—even when there’s no network connection.

Figure 1 shows how these features enable the mobile appli­cation lifecycle.

The Mobile Application Lifecycle with Visual Studio Mobile Center
Figure 1 The Mobile Application Lifecycle with Visual Studio Mobile Center

Getting Started

Signing up for Mobile Center is really easy. If you already have a HockeyApp account, your existing e-mail and password will continue to work and sync between both systems. If not, you could create a new account through the registration form, but instead I want to show you the quickest flow to getting started: Connect with GitHub. If you live on GitHub as I do, you won’t need to enter your GitHub password—you’ll immediately see the authentication page shown in Figure 2. Simply approve access and you’ll land on the Mobile Center dashboard with a fully enabled account. No e-mail confirmation, credit card or other setup steps needed.

Signing up for Mobile Center with GitHub
Figure 2 Signing up for Mobile Center with GitHub

Once your account is connected to GitHub, you’re only a few steps away from your first build. Create your app by simply entering the name, then pick your Git repository and branch via the Build menu as shown in Figure 3. Mobile Center will automatically detect your project type, so you don’t have to manually add or configure build steps. Behind the scenes, the build pipeline provisions a virtual machine to compile the app, runs all unit tests and signs the app package for distribution.

Selecting a GitHub repository for Build
Figure 3 Selecting a GitHub repository for Build

When the build process completes, you can download the app package file for local installation, execute automated tests on real devices using the Mobile Center Test, or you can continue with the Distribute feature to ship the app to your testers. Each member of your distribution group will receive an e-mail notification to install the app. Simply open the e-mail on the phone and install the app from the browser.

Adding the SDK

For Crashes and Analytics, you need to add the Mobile Center SDK to your project. The SDK is designed with a modular architecture that lets you integrate only those features you want in your app. Let’s start with an example for an iOS app. First, add the following import statements to the top of the AppDelegate.swift file:

import MobileCenter
import MobileCenterCrashes
import MobileCenterAnalytics

The MobileCenterCore is required for all features, while the other two can be omitted if you don’t want the Crashes or Analytics features. Next, start the SDK in the didFinishLaunchingWithOptions method:

MSMobileCenter.start("{Your App Secret}", withServics:[MSAnalytics.self,
  MSCrashes.self])

The App Secret is a GUID that can be taken from the app’s management page in Mobile Center. Instead of typing those four lines, you can simply copy them from the app’s overview page, as shown in Figure 4.

Getting Started with the Mobile Center SDK
Figure 4 Getting Started with the Mobile Center SDK

The setup looks very similar on Android:

import com.microsoft.azure.mobile.MobileCenter;
import com.microsoft.azure.mobile.crashes.Crashes;
import com.microsoft.azure.mobile.analytics.Analytics;
// ...
MobileCenter.start(getApplication(), "{Your App Secret}", Analytics.class,
  Crashes.class);

By enabling the Crashes module, the SDK will automatically start catching unhandled exceptions on iOS and Android, as well as low-level crashes on iOS. To generate a test crash, you can add the following line to a button handler on iOS:

MSCrashes.generateTestCrash()

The same call is available for Android:

Crashes.generateTestCrash();

After a crash, the SDK stores the log file in the device’s local storage. When the user opens the application again, all pending crash logs will be posted to the Mobile Center back end and processed there. If you build your iOS app with the Mobile Center Build feature, the stack trace in the crash log will be automatically symbolicated, which means all memory addresses are converted into class and method names, file names, and line numbers. If you used a different build server or build your iOS app on your local Mac, you’ll see the new crash logs in the Incoming menu first. You can then upload the matching dSYM files to start the symbolication process.

By enabling the Analytics module, the SDK will automatically track sessions, device properties such as OS version, model, or manufacturer, and user properties like language or region, and Mobile Center will show them on the Audience page (see Figure 5).

Mobile Analytics on the Audience Page
Figure 5 Mobile Analytics on the Audience Page

You can track your own custom events and properties with the following line on iOS:

MSAnalytics.trackEvent("Video clicked",
  withProperties: ["FileName" : "RickRoll.mp4"])

On Android, the properties are specified in a HashMap:

Map<String,String>properties=new HashMap<String,String>();
properties.put("FileName", "RickRoll.mp4");
Analytics.trackEvent("Video clicked", properties);

All telemetry, crashes, events, and properties are collected anonymously and stored securely in the Azure Cloud, giving you full control over the data your app gathers. To enable an even higher level of trust, the Mobile Center SDK is fully open source and available on github.com/Microsoft for iOS (/MobileCenter-SDK-iOS), Android (/MobileCenter-SDK-Android) and Xamarin (/MobileCenter-SDK-Xamarin). I encourage you to review its source code and file bugs and contribute with pull requests.

Back End Included

Most modern mobile apps utilize one or more online services to enable their full power, for example to sync a to-do list among multiple devices, to share data among multiple line-of-business apps, or to restrict features to authenticated users who bought a premium subscription. Mobile Center supports these scenarios by directly integrating with Azure App Service through the Tables and Identity features.

The first time you click on either menu item, you need to connect your Azure subscription. If you don’t have one yet, you can sign up for Azure for free on bit.ly/1MoL3Rb. Once your Azure account is linked to Mobile Center, you can create data tables right from the Tables overview page.

As an example, I create a table with the name “TodoItem” for a to-do app. To access the data in the table from an iOS app, I need to initialize the SDK as follows:

let client = MSClient(applicationURLString: "{Your App URL}")
let table = client.tableWithName("TodoItem")

As with the App Secret, the App URL should be replaced with the URL for your app from the configuration page in Mobile Center. Then I can query the MSTable object for all available items:

table.readWithCompletion { (result, error) in
  if let err = error {
    print("ERROR ", err)
  } else if let items = result?.items {
    for item in items {
      print("Todo Item: ", item["text"])
    }
  }
}

To filter the result, I can use an NSPredicate object and the readWithPredicate method, for example, to get only incomplete to-do items:

let predicate = NSPredicate(format: "complete == NO")
table.readWithPredicate(predicate) { (result, error) in
  // Handle item
}

Inserting a new item is done through an NSDictionary object and the insert method:

let newItem = ["text": "Write MSDN article", "complete": false]
table.insert(newItem) { (result, error) in
  if let err = error {
    print("ERROR ", err)
  } else if let item = result {
    print("New item ID: ", item["id"])
  }
}

The Azure App Service mobile back end automatically generates new columns based on the dictionary, including a unique id. I can also provide my own id as a key-value pair in the dictionary. Similar to insert, the methods update and delete allow me to modify data, for example, when a to-do item is completed, and delete them. And, of course, all this not only works for iOS apps, but for all supported platforms on Mobile Center.

With the code shown so far, all users of the app would access the same list of to-do items or, more generally, the same data across all devices. This is usually not desirable; typically, each user wants to manage his own to-do list. I can achieve this by adding the Identity feature to my app. Mobile Center supports five identity providers out of the box: Azure Active Directory, Facebook, Google, Microsoft Account and Twitter. An app can use any number of these identity providers to let users sign in with their preferred account. There are two options to integrate the feature:

With a provider SDK (the Facebook SDK, for example), users can sign in to an experience that integrates tightly with the OS on which the app is running. As part of the sign-in process, the app obtains a provider token that needs to be sent back to Azure App Service, which then validates the token and replaces it with a new App Service token. The app can also store the provider token for its own use; to access the Facebook Graph API, for example.

Without a provider SDK, you can use the following method in the Mobile Center SDK:

client.loginWithProvider("google", controller: self, animated: true) { (user, error) in
  // Load data
}

This will open a Web view to the provider and the user can sign in. The provider token is directly processed on the server side and the app never receives it. At the end of the flow, the Mobile Center SDK has an App Service token, which is automatically attached to all back-end requests and ensures that the app’s data is only accessible by the authenticated user.

Looking Ahead

All features described in this article are available now as a public preview for iOS and Android developers. Sign up for free on aka.ms/mobilecenter. Over the next few months, Microsoft will continuously deliver more features and value, including support for Windows developers, integration with VSTS and more back-end services such as offline data sync. Our goal is that Mobile Center becomes your one-stop shop for the lifecycle of your mobile and desktop apps: build, test, distribute, monitor, and connect to the cloud. My team and I are very excited about the next generation of Mobile DevOps from Microsoft and we hope you’ll join us on this journey.


Thomas Dohmke is a co-founder of HockeyApp, which was acquired by Microsoft in late 2014. Dohmke is the group program manager for Visual Studio Mobile Center and is responsible for driving the product vision and managing the team of program managers for each feature. Reach him via e-mail at thdohmke@microsoft.com or on Twittter: @ashtom.


Discuss this article in the MSDN Magazine forum