HockeyApp: Creating a bridge to the cloud

HockeyApp is an awesome tool when it comes to crash reporting, user metrics, beta app distribution and collecting user feedback. The SDK is very easy to integrate and there also is tooling available to integrate HockeyApp in your CI/CD pipeline.

In 2016, when Microsoft announced (Visual Studio) Mobile Center, it also became clear that HockeyApp will become part of this new full-fledged platform for mobile development. Therefor Microsoft is now focussing on integrating HockeyApp in Mobile Center and HockeyApp itself isn’t getting new features.

If you are currently at the point where you need to choose a tool for crash reporting and user metrics, and you don’t want to use the preview of Mobile Center, HockeyApp is probably still the way to go. One great advantage of HockeyApp is that when Mobile Center becomes general available, the migration will be seamless. Also if you want to analyze and visualize your event data in ways other than are currently available in HockeyApp, you are able to create a bridge to Azure Application Insights. This will allow you to create your own dashboards and get fine-grained control of your data and metrics. You can even export to your own data storage through Application Insights! For now it’s only possible to export events and traces, but exporting crashes is on the roadmap for Mobile Center.

Application Insights
Application Insights is an extensible analytics platform that helps you monitoring your performance and metrics. When connecting HockeyApp to Azure Application Insights the raw data of logged events and traces will become available for querying. Based on these queries you’ll be able to create your own dashboards!

Setting up the connection between HockeyApp and Application Insights is pretty straightforward:

  1. First, create a API in your HockeyApp account settings:
  2. When the API key is created, you need to create a resource in the Azure portal. The Application Insights resource can be found in the Developer Tools category. After selecting Application Insights, the form will show up and ASP.net web application will be selected as default application type. After selecting “HockeyApp bridge app”, the form will change and show the required fields for a HockeyApp bridge. First of all you need to paste the (previously created) API key in the “Token” field. Azure will automatically load your apps from HockeyApp, so you only have to choose an app and fill in the other fields. If you ever created an Azure resource this should be fairly easy.
  3. After clicking Create, you’re all set! Yes, it’s really that easy!
    To see your data you can simply open Application Insights from the Azure portal or navigate directly to https://analytics.applicationinsights.io/ and log in with your Microsoft account.

When your bridge app collected some data, you will be able to start analyzing and visualizing by creating queries. Queries can be created with the Analytics query language, which might be a bit tricky in the beginning, but the documentation will help you get started. To give you a feeling of what it looks like, this query will return all events from the US:

 customEvents | where client_CountryOrRegion == "United States" 

By default the data is visualized in a table, but with a few clicks you can transform this into a beautiful chart. You can even customize these visualizations to suit your needs!

Related links:

Talking Bluetooth (Low Energy) with Xamarin

With the rising popularity of IoT (Internet of Things), it becomes more common that you need to communicate with hardware. In most cases you can accomplish this with network connectivity, but you might want to consider Bluetooth Low Energy (BLE) as well. As the name suggests, BLE uses a lot less energy in comparison to classic Bluetooth. Less energy consumption means that it’s possible to use smaller (and portable) batteries what might be very useful for IoT devices. When deciding if BLE suites your needs, you should take a few things in consideration:

  • Bandwidth: Bluetooth is less suitable for transmitting large sets of data, especially BLE.
  • Costs: in comparison to network adapters, bluetooth is more affordable.
  • Range: the range of your device really depends on the bluetooth device and version that is used by the hardware and the smartphone/tablet. The environment might also impact the range. At a maximum you can reach 100 meters, but the average will be around 15 meters.
  • Power consumption: you can use BLE to save energy, but this will limit the throughput. If you are transferring small packages this might be interesting. The classic way of bluetooth communication is also less consuming than network connectivity.

Instead of writing the bluetooth code for every platform, you can choose to use a plugin that provides an abstraction layer so it’s possible to access BLE from shared code. At the time of writing, I find Bluetooth LE Plugin for Xamarin the best pick for the job. The plug-in is easy to implement and is continuously getting updates. If you want to use classic bluetooth you might want to look into some other plugins. in this post I will focus on Bluetooth LE Plugin for Xamarin.

When working with BLE, there are 3 (most important) different bluetooth abstraction layers:

  • Services: A service contains one or more characteristics. For example, you could have a service called “Heart Rate service” that includes characteristics such as “heart rate measurement.” Each service has it’s unique pre-defined 16-bit or 128-bit UUID.
  • Characteristics: A characteristic is some kind of endpoint for a specific part of the service. Just like a service, the characteristic also has a UUID. Characteristics support a range of different interactions: read, write, notify, indicate, signedWrite, writableAuxilliaries, broadcast.
  • DescriptorsDescriptors are defined attributes that describe a characteristic value. For example, a descriptor might specify a human-readable description, an acceptable range for a characteristic’s value, or a unit of measure that is specific to a characteristic’s value.

Now, let’s dive into some code samples! To give you a taste of what the plugin has in store for you, some snippets:

Scan for BLE devices (advertisements)
The Adapter class makes it possible to detect devices in the surrounding area. You can simply get an instance of the adapter and start scanning with the following code:

 var adapter = CrossBluetoothLE.Current.Adapter;
adapter.DeviceDiscovered += (s,a) =+ deviceList.Add(a.Device);
await adapter.StartScanningForDevicesAsync(); 

Connect to device
When you’ve found the device you want to connect to, you are able to initiate a connection with the device. After connecting successfully to a device you are able to get the available characteristics and start sending requests or start retrieving notifications from the device. When the bluetooth device doesn’t receive any requests for a specific period (may differ per device), it will disconnect to save battery power. After getting a device instance (with the previous sample), it’s fairly easy to setup a connection:

 try
{
    await _adapter.ConnectToDeviceAsync(device);
}
catch(DeviceConnectionException e)
{
// ... could not connect to device
}

Note: a device scan is only necessary when connecting to the device for the first time. It’s also possible to initiate a connection based on the UUID of the device.

Get services, characteristics, descriptors
As described above, a service is the first abstraction layer. When an instance of a service is resolved, the characteristics of this specific service can be requested. The same goes for a characteristic and his descriptors. On a characteristic you can request the descriptors.

The different abstraction layers can be requested in a similar way, GetAll or GetById:

// Get All services and getting a specific service
var services = await connectedDevice.GetServicesAsync();
var service = await connectedDevice.GetServiceAsync(Guid.Parse("ffe0ecd2-3d16-4f8d-90de-e89e7fc396a5"));

// Get All characteristics and getting a specific characteristic
var characteristics = await service.GetCharacteristicsAsync();
var characteristic = await service.GetCharacteristicAsync(Guid.Parse("37f97614-f7f7-4ae5-9db8-0023fb4215ca"));

// Get All descriptors and getting a specific descriptor
var descriptors = await characteristic.GetDescriptorsAsync();
var descriptor = await characteristic.GetDescriptorAsync(Guid.Parse("6f361a84-eeac-404c-ae48-e65b9cba6af8"));

Send write command
After retrieving an instance of the characteristic you’re able to interact with it. Writing bytes for example:

await characteristic.WriteAsync(bytes);

Send read command
You can also request information from a characteristic:

var bytes = await characteristic.ReadAsync();

Pretty easy, right? To get you started, you can find an example project on the Bluetooth LE Plugin GitHub page. Although this seems pretty simple,  I’ve experienced some difficulties in making it rock solid. Some tips to improve your code:

  • Run bluetooth code on main thread.
  • Don’t scan for devices and send commands simultaneously, also don’t send multiple commands simultaneously. A characteristic can only execute one request at a time.
  • Adjust ScanMode to suit your use case.
  • Don’t store instances of characteristics or services.

Related links:

Microsoft Build: The future of Xamarin

On the second day of the Microsoft Build conference, during the Keynote, Microsoft had some awesome announcements related to Mobile development. In a following session James Montemagno and Miguel De Icaza got into more detail and even showed more epic new features. As always to two put on a great show while presenting!

Together with my colleague Marco, I’ll cover announcements made at the Microsoft Build conference in a series of blogposts. You can also read these posts on his blog.

Xamarin Live Player
When Xamarin Live Player (XLP) was announced during the Build keynote, most of the audience was pleasantly surprised. Until now developing on Windows for iOS was a serious hassle because it required a Mac to compile the app. This setup works well when you have an expensive Mac and a fast and reliable network, but in a lot of scenarios these builds take up a lot of time.

With XLP you don’t need a Mac build host anymore! You just install the Xamarin Live Player app from the App Store or Play Store, pair your device in Visual Studio and boom! You’re ready to debug on the device. Just select your device (annotated with “Player”) en hit run:

Besides the build improvements XLP has more to offer! You can also modify your Xamarin.Forms or Xamarin.Classic app while debugging so you can easily test changes to your app without stopping and restarting the debug process.
This will really speed up the development! To achieve this you first have to open the view you want to debug live. For now a Xamarin.Forms Xaml and iOS storyboards are supported, when XLP becomes GA all types of views should be supported. After opening your view file, you can run the with Visual Studio by clicking “Run -> Live Run Current View” on Mac or “Tools -> Xamarin Live Player -> Live Run Current View” on Windows.

XLP is still in preview and after some testing we are still experiencing a few difficulties. If you want to give XLP a try, you’re probably best of using the examples provided by James Montemagno.

Fastlane
If you’ve ever developed an app for iOS you probably felt the pain of having to provision your app in the Apple Developer Portal. Although there is a good (and very long) read on how to accomplish this, you don’t want to waste any time on this. This is where Fastlane comes to the rescue. With Fastlane tools installed you are able to provision your app with a few clicks in Visual Studio! Fastlane also comes in handy when releasing your app to the Stores. It handles all tedious tasks, like generating screenshots, dealing with code signing, and releasing your application.

Xaml standard 1.0
During the Build Conference Microsoft also introduced a new standard for XAML, called XAML Standard 1.0. The standard will describe a specification for cross-platform user interfaces for both UWP and Xamarin.Forms. As for now, XAML Standard is in a very early stage and Microsoft encourages developers to contribute to their specification. 1.0 should become available later this year.

Bindings simplified
Xamarin was already supporting usage of native libraries with Android binding and iOS binding projects. Because of the complex nature of binding projects, Xamarin released the CocoaPods Importer which will simplify importing CocoaPods with a few clicks. With this importer you can easily transform a CocoaPods library to a .NET library.

iOS Extensions
When you’ve created extensions for your app, these extensions will run in a separate process. Therefor the Xamarin runtime was included for every extension. With the latest version of Xamarin, the runtime is only included once for all your extensions. This will result in a smaller app size and improved performance. The latest version of Visual Studio also allows multi-process debugging, that will come in handy when debugging your app combined with your extensions.

AOT for Mac and Android, Hybrid mode
The compilation process of Xamarin.Android and Xamarin.iOS apps was quite different until now. One big difference was that Android was compiled Just In Time, iOS was compiled Ahead Of Time. After the compilation of iOS apps, the LVVM optimizes the generated code to get high performance. Xamarin announced to also start supporting AOT for Android and Mac apps, that will result in better performance. When you compile AOT you might lose some flexibility (for example: no dynamic code loading), and therefor Xamarin also introduced an Hybrid mode. The Hybrid mode will work for platforms that support AOT as well as JIT. It will compile AOT, but also add the bits needed for JIT.

Embedinator-4000

Embedinator-4000​
While the Xamarin platform mostly focuses on writing code in C# and compiling this to a native application, the Embedinator takes a bit of a different approach. The Embedinator makes it possible to write your code in C# and then compile this into a framework library for Java, Swift, Objective-C or C/C++. Therefor you can easily share your C# code with truly native apps. Miguel De Icaza promised that more languages will be added. As for now, the Embedinator can be used from command line, in the future this will be integrated in Visual Studio.

SkiaSharp
SkiaSharp is a cross-platform 2D graphics API for .NET platforms based on Google’s Skia Graphics Library (which is used by apps like Google Chrome). Xamarin announced that it will be supporting Android, iOS, Mac, UWP, tvOS and Windows. Also support for SVG files is added in the latest release. James showed an awesome demo of The Kimono designer which is build on top of SkiaSharp.

Xamarin.IoT
The latest alpha of Xamarin also contains support for Linux based IoT devices! It will add a new project template for Xamarin.IoT and allow you to deploy and debug your IoT app remotely. Debugging will work similar to debugging Xamarin applications. The IoT Hub SDK will make it easy to communicate with your Azure IoT Hub. The library supports communication with MQTT and AMQP message queues.

Mobile Center
Microsoft is putting a lot of effort in making Mobile Center a full fletched CI/CD solution. With the latest release they added support for UWP and the ability to send push notifications to Android or iOS applications. Mobile Center is still in preview, but is expected to become GA later this year.

Project Rome for iOS
Last year Microsoft announced Project Rome SDK for Android. This year at the Build conference Microsoft also announced the iOS SDK. Project Rome creates a bridge between the different platforms for a seamless user experience. The SDK allows developers to start and control apps over platforms and devices.

If you have any comments or want to share your experience, don’t hesitate to contact me on Twitter.

Related links:

 

Xamarin: UITest backdoor

When running your UI tests, locally or in Xamarin Test Cloud, you sometimes want to execute code in your app from your tests. You might for instance want to setup some mock implementations instead of making actual API calls, or you might want to trigger some OS specific code from your tests. In these scenario’s backdoors come in handy!

Backdoors itself are not very complex, but it opens up a lot of possibilities with UI tests. In the past I used backdoors to:

  • Setup authentication for tests
  • Create a specific state in your app to run your tests in.
  • Set mock implementations from my UI tests.
  • Trigger deeplink

And I can think of a lot more useful scenario’s. You can create a backdoor with the following code:

iOS
In your AppDelegate class you need to create an method that returns NSString, is public,  is annotated with Export attribute and takes an NSString as parameter. For example:

public class AppDelegate : UIApplicationDelegate
{
 [Export("myBackdoorMethod:")] // notice the colon at the end of the method name
 public NSString MyBackdoorMethod(NSString value)
 {
 // In through the backdoor - do some work.
 }
}

Android
On Android you need to create a method in your MainActivity that is public, returns string/void, is annotated with Export attribute and takes an string/int/bool as parameter:

public class MainActivity : Activity
{
    [Export("MyBackdoorMethod")]
    public void MyBackdoorMethod(string value)
    {
        // In through the backdoor - do some work.
    }
}

Invoking the backdoor from your UI tests:

if (app is Xamarin.UITest.iOS.iOSApp)
{
    app.Invoke("myBackdoorMethod:", "exampleString");
}
else
{
    app.Invoke("MyBackdoorMethod", "exampleString");
}

Note: The signature of the backdoor methods is very important as the Backdoors – Xamarin docs mention.

If you want to switch out your actual implementations for mocks, the use of compiler flags (combined with build configurations) might be more suited. You can read more on this over here.

Related links:

Build configurations and compiler flags

If you have developed some Xamarin applications in the past, you might have stumbled on the excessive range of configuration options you can choose from. The settings you’re using in development may be very different from your Release settings. For example; you don’t want to include debug information in the app that will be published to the App Stores. It will increase the app size enormously and expose technical info about your app that might be useful to malicious people.

Besides the difference of Release and Debug configurations, you sometimes need a extra set of configurations. Visual Studio allows you to create additional build configurations:

Configuration Manager
Configuration Manager
Build configurations
Build configurations

Compiler flags / Conditional compilation symbols

Per build configuration you can also specify a set of compiler flags. Compiler flags on itself don’t have any impact on your app, but you can use these flags in your code. By default the build configuration called Debug, has a compiler flag called “Debug”. In your code you can check if this flag is set (and therefor Debug configuration is active) and execute some Debug code. A common scenario is to Log additional information when the Debug flag is set.

Compiler flags
Setting compiler flags

Using compiler flag in code:

#if Debug
	InitializeUiTests();
#endif

Related links:

Xamarin: The magic of Fody weaving

When creating Xamarin apps a lot of people choose to go with the MVVM pattern. There are a lot of beautiful frameworks out there to make the life of an MVVM developer easier, but sometimes you just want to do it the hard way and write it yourself.

If you ever created an Xamarin app using the MVVM pattern (without any framework) and data binding, you may have noticed there is a lot of boilerplate code to notify property changes. As your ViewModels grow, this becomes a nightmare!

Fody.PropertyChanged to the rescue!
Fody is an extensible library that adds an post build task to the MSBuild pipeline. With this task it manipulates the generated IL code, depending on what add-ins you are using. Add-ins can be build on the Fody core. One of the add-ins is Fody.PropertyChanged. As you might guess, this add-in generates the code for notifying changes in a ViewModel. The add-in will look for properties in classes that implement INotifyPropertyChanged or properties/classes annotated with the [ImplementPropertyChanged] attribute.

Example class PersonViewModel:

[ImplementPropertyChanged]
public class PersonViewModel
{
public string GivenNames { get; set; }
public string FamilyName { get; set; }

public string FullName
{
get
{
return string.Format("{0} {1}", GivenNames, FamilyName);
}
}
}

After applying Fody magic it will become:

public class PersonViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

string givenNames;
public string GivenNames
{
get { return givenNames; }
set
{
if (value != givenNames)
{
givenNames = value;
OnPropertyChanged("GivenNames");
OnPropertyChanged("FullName");
}
}
}

string familyName;
public string FamilyName
{
get { return familyName; }
set
{
if (value != familyName)
{
familyName = value;
OnPropertyChanged("FamilyName");
OnPropertyChanged("FullName");
}
}
}

public string FullName
{
get
{
return string.Format("{0} {1}", GivenNames, FamilyName);
}
}

public virtual void OnPropertyChanged(string propertyName)
{
var propertyChanged = PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

Fody.PropertyChanged has another killer feature called Fody NotificationInterception which makes it possible to execute some code before propertyChanged gets triggered. This feature can be for example used for logging purpose or to make sure you are calling propertyChanged on the main thread. See related links for more info.

If you want to give Fody.PropertyChanged (or any other Fody add-in) a try, just install the NuGet package and you’re good to go!

Note:
Fody requires your release builds to contain debug symbols. You can enable this in your project settings by setting Build->compiler->debug information to “Symbols only”.

Fody-release

Related links: