Using Application Insights with Cordova Apps in Visual Studio

Abstract

When developing a mobile application, native or hybrid, we require a certain way to monitor and track different activities and events in the application. Developers need to detect issues, solve problems and continuously improve the application code. Marketers, on the other hand, want different kind of metrics. For instance, they want to know how many people are using the application on a daily basis, what features they are using and how they are interacting with the application.

Background

Application Insights is a set of services that provide actionable insight into a production application. It monitors your application to detect issues, diagnose crashes and discover how it is being used. It works with both web and stand-alone apps on a wide variety of platforms: .NET or J2EE, hosted on-premises or in the cloud; device apps on Windows, iOS, Android, OSX and other platforms. At the time of writing, Application Insights is still in Preview (for the other platforms).

10-perf

What About Cordova Apps?

By looking at the documentation, we realize that Application Insights SDK supports JavaScript apps. Woohoo!

too easy

Create the Resource First

Adding an Application Insights resource to your Azure account is pretty straightforward. You can follow the detailed steps in the documentation. You will need to add a new Developer Service and then select the Application Insights resource. Give it any name you list, but select the Application Type as “other” since that is not an ASP.NET application.

0 application insights create

 

Creating the service would take a moment, but you can see the progress if you pin it to your Dashboard.

0.1 - application insights

Add the Application Insights service to Cordova

You will need to create an Apache Cordova application in Visual Studio 2015 (You could also use VS 2013). You can use the Empty project template provided if you’d like. If you are uncomfortable creating the app by yourself, you can follow the detailed steps in this article. Once you have the application running, you are ready to add Application Insights.

Cordova Tools in Visual Studio allows you to add Connected Services to your application such as Azure, Salesforce, and Office 365 (Other services will be added in the future). Let’s right click on the project and then open the wizard by clicking on Add -> Connected Service…

1- add connected services

Avoid Excessive Excitement

Yak it’s not a pleasant sight… Unfortunately, at the time of writing, Application Insights is still not available as a Connected Service for Cordova applications.

2- project not supported

Panic Not! There Must Be Another Way

Since Application Insights has a JavaScript SDK, it is legitimate to imagine that there is an alternative. Luckily, folks at Microsoft are working on a Cordova plugin. Let’s go ahead and add it to our project.

3- add custom plugin

4- add custom plugin

By reviewing the source code of the plugin, we learn a great deal about how it was implemented. We also realize that it is reliant on another plugin which is available in the Plugins list. That is the Device plugin.

6- add device plugin

Configure the Plugin

In order to connect to the Azure account, we need the Instrumentation Key from the Application Insights service settings.

5- get instrumentation key

Looking at the www folder on the plugin’s web page, we understand that there are different ways that we can assign the Instrumentation Key. Here’s a snippet from the code

var appInsightsConfig = {
    // To override this stub there is a three ways
    // * pass --variable INSTRUMENTATION_KEY=<your_key> to `cordova plugin add` command
    //      - THIS DOESN'T WORK YET DUE TO ISSUE WITH CORDOVA-LIB
    //
    // * add <preference name="instrumentation_key" value="<your_key>"> to config.xml at the root of project
    // * update this file manually
    instrumentationKey: "PASTE_YOUR_KEY_HERE_!!!",
    // Need to specify this explicitly, because default value doesn't provide URL scheme
    endpointUrl: "https://dc.services.visualstudio.com/v2/track"
};

I find adding the key to the config.xml the most convenient method. You will need to edit the file with a Text editor as opening it in Visual Studio results in opening the GUI.

5- add instrumentation key

Ok, Where’s the Code?

Let us use the API now to track a custom event, an exception and a page view.

    function onDeviceReady() {
        // Handle the Cordova pause and resume events
        document.addEventListener('pause', onPause.bind(this), false);
        document.addEventListener('resume', onResume.bind(this), false);

        // TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.

        // When and if device plugin is initialized, set up the device context
        if (device && appInsights && appInsights.context && appInsights.context.device) {
            appInsights.context.device.osversion = device.version;
            appInsights.context.device.os = device.platform;
            appInsights.context.device.model = device.model;
            appInsights.context.device.id = device.uuid;
        }

        initEvents();
    };
    function onTrackEventClick(e) {
        // This will send a custom-defined event to your appInsights account
        var eventData = { ButtonId: "trackSingleEvent", Timestamp: new Date() };
        appInsights.trackEvent('click', eventData);
    }

    function onThrowExceptionClick(e) {
        // This will send an exception information to your appInsights account
        try {
            // Do some logic here which may
            throw new Error("Sample Error");
        } catch (err) {
            // Catch an error and send it to appInsights
            appInsights.trackException(err);
        }
    }

    function onTrackPageViewClick() {
        appInsights.trackPageView();
    }

Let’s Build!

At this moment, we feel comfortable running the application as we have it all configured (or we think we do). Let us use Ripple and launch the application in the browser. We should see the following:

6- run

Clicking on one of the buttons resulted in a very unexpected error. Yes, it fails. The connection is refused. Ripple fails us, one more time. Thinking that the simulator was blocking the request, I added the whitelist plugin with the right meta tag. That had no positive effect.

error

OK Ripple, There Won’t Be Hatred

When I get uncommon exceptions in the Web Simulator, I often like to go the slow track, and test it on either a virtual or an actual physical device. Connecting an Android phone to my computer and deploying the application took only a few minutes. If you are unfamiliar with that process, I encourage you to read my previous articles for Android and iOS.

By inspecting the device in Chrome, I saw no errors in the console. Looking at my Azure Portal, I confirmed that the application worked this time.

9- success 10- success

Since App Insights is meant to be used in a production environment I need not to worry about the Simulator. I can simply add an exception for that environment to make sure my code does not break.

Summary

By integrating Application Insights monitoring capabilities into your Cordova applications, you will be able to deliver better quality code and more usable features. Application Insights Connected Service is still not available for Cordova apps, but there is an alternative through the use of Cordova plugins.

You can download the sample application from our Github repo.

1 Comment
  • Ioannis Kalfas
    August 13, 2016

    In VS15, i am also following all steps that you describe. The only difference is that you have to enter the instrumentation key, at the time of the plugin installation. However, i get an “Invalid instrumentation key” message, no matter what. Any suggestions?

Leave a Reply

Your email address will not be published. Required fields are marked *