Building a Universal Windows Platform (UWP) Application (Part 5) – Analytics with Visual Studio Application Insights
As many of you developers out there are aware, sometimes you have to build or bring with you a number of application infrastructure items before you can even get started with the core application logic. For example, you might need some helpers, services and base classes that make your job easier or allow you to start with your base patterns, such as, MVC, MVVM, etc.
So, I have decided to create a series of posts that build up a bunch of common, important parts of an application that you might want to have in place before you even start developing your core functionality. I have discussed a number of topics in my previous posts:
Building a Universal Windows Platform (UWP) Application, Part 1 – Using Template10
Building a Universal Windows Platform (UWP) Application, Part 2 – T4 and Strings
Building a Universal Windows Platform (UWP) Application, Part 3 – Multilingual Support
Building a Universal Windows Platform (UWP) Application, Part 4 – Logging w/ MetroLog
If you haven’t already read the previous posts, I recommend you do since they all build on each other.
In part 5 of this series, I thought that maybe before we start writing any application code, we might want to add a service that allows us to analyze and get insight into how our application gets used. There are several analytics packages out there, but I thought I would take a brief look at Visual Studio Application Insights.
My goal is to create a service that allows us to use this service, along with the ability to add others. I won’t only show you how to gather the data with the service, but briefly show you how you can view the data to help you make decision about your software. For example, “What screens do people visit most frequently?”
How does that sound? Excited? Well, let’s get started…
Visual Studio Application Insights
Since I don’t want to spend a ton of time going into describing what Visual Studio Application Insights is, I will take a quick snapshot of their home page and give you a link to it for further reference and research.
I will, however, attempt to show you how to wire Visual Studio Application Insights up for your application. So, the first thing we will do is go out to our Azure portal. If you don’t have an account with Azure, you should get one. Here is a link to the Azure if you haven’t signed up yet. It is simple and all you need is a Microsoft account. Click this link to learn more and create an account.
Once you have an Azure account, let’s go to the portal.
Once you have logged in, you should be taken to your dashboard that looks something similar to the following:
Now, we want to add a new resource by click on the + New.
From here, enter Application Insights into the search box and select Application Insights from the list.
You should now see the results to the search, select Application Insights…
Once you select Application Insights, you will be presented with a brief description with some useful links. From here, select Create.
You will now be prompted for application information. Enter a Name, select Other for Application Type, select your Subscription type, for now, create a new Resource Group and give it a Name, select your Location, select Pin to dashboard and then select Create.
Once it is created, you should see something like the following:
For now, let’s not do anything else with the portal. We will come back and look at it in a little bit.
Open our previous solution into Visual Studio, right click on the project and select Manage NuGet Packages…
From the NuGet screen, select Browse, type in Application Insights into the search field, select Microsoft.ApplicationInsights, select the Latest stable 2.1.0 version (or whatever the latest is at the time you read this post) and then select Install.
You will see the following prompt, select OK:
Accept the License agreement for Visual Studio Application Insights after installing:
Once it completes, look and your references and you should have a reference to Microsoft.ApplicationInsights.
Okay, now with the reference in place, let’s create a new Folder called AnalyticsServices in our Services folder. You can do this by right clicking on the Services folder, selecting Add and selecting New Folder.
Now, let’s add two class files to the folder called AnalyticsService.cs and IAnalyticsService.cs. To add a class file, right click on the AnalyticsServices folder, select Add and select Class…
Sweet, now for the coding magic. Open IAnalyticsService.cs and replace the code with the following:
So, the first thing you will notice in the interface are two methods: SetupTelemetry() and FlushTelemetry(). These will be used to initialize and clean up the service. The rest of the methods are used for tracking page views, tracing and custom events. Notice that for the custom events there are options to include metrics and properties for that event.
Let’s look at the class that implements the interface,
Open AnalyticsService.cs. Let’s walk through the class. First, notice that there are a couple of properties. Instance is for our singleton service. The next is the TelemetryClient object defined by Application Insights and used in our service called ApplicationInsightsClient.
Next, there are two methods used to setup and flush remaining data for the Telemetry Client: SetupTelemetry() and FlushTelemetry(). There are a few of things to note in the SetupTelemetry() method. Notice that a userId is passed into the method. These, as well as other important information, are set on the client object and will be used for each call to the Visual Studio Application Insights Azure service. Note, the only property that you need to set is InstrumentationKey, the rest are optional. So, you don’t even need to include the userId in your code. I chose to use it to show you that there are several properties that can be set depending on the information you need to analyze.
Now let’s look at the remaining calls.
Each method tracks slightly different information: Pages, Exceptions, Tracing and Events. Here is a summary of each:
- TrackPage() – used to track your pages (screens). It accepts a string reference to the page.
- TrackException() – used to track exceptions for analysis. It accepts an Exception that you wish to log.
- TrackTrace() – used to track log messages. It accepts a string message.
- TrackEvent() – used to track events (actions) within your application. For example, maybe you want to track when a user clicks a specific button or updates certain data. TrackEvent() has a number of overloads that allow you to not only create an event, but also include various properties and/or other metrics about an event. You will see more of this later in the blog.
NOTE: There are other API methods that you can use, but these are some basic ones.
Okay, now, let’s add some code to our project that uses some of this functionality. First, we need to call the SetupTelemetry() method. Where should we put it? Well, my suggestion would be when the application object is created, in the constructor.
First, let’s open App.xaml.cs.
Next, add the SetupTelemetry() call at the end of the method.
Now, you can add analytics statements to all your code. But, first, let’s override two methods in the application object: OnResuming() and OnSuspendingAsync().
From here, we will add our call to make sure that the messages are flushed before the app is suspended.
Now, let’s add the event method calls to keep track of what the application is doing. First, let’s add a call to the OnInitializeAsync() method.
Next, let’s add statements to both OnResuming() and OnSuspendingAsync() methods.
Open MainPage.xaml.cs and create the override for OnNavigatedTo(). In this method, let’s place a TrackPage() event so that we know that they navigated to the MainPage. For us, that is the main page for the application and will navigate to it automatically. Here is what the code would look like:
Ok, we can now build and run the application. In order to get the OnResuming() and OnSuspendingAsync() to fire their events, you can use the Debug Location toolbar. You can turn this toolbar on by simply right-clicking and selecting it in the context menu.
Once you select this toolbar, while your application is running, you will have the following options available to you. To view them, select Lifecycle Events toolbar item and then select Suspend, Resume or Suspend and Shutdown.
Once you have selected and played with a few of these lifecycle events, let’s jump back to our Azure Portal and go to the Applications Insights service that we created earlier. From our overview screen blade, select Metrics Explorer.
You should see the Metrics Explorer blade. First, select Edit in the first graph.
Now, in the Chart details blade, select Page views from the Usage list.
Once you do this, you should see your chart in the Metrics Explorer blade change to show you the number of page views your application has performed in the last 24 hours (default).
Let’s do the same thing with the bottom chart. Select Edit and select Events in the Charts details blade.
You should see something like the following:
It is seriously that easy to view the number of page views and events published from within your application. I want to show you one more thing. If you click on the Page Views chart, you will be taken to a Search blade that allows you to search and view the page events captured using the TrackPage() method in our service.
Imagine if you have TrackPage() events in every page of your application. In this blade, you could search for the MainPage and see all the times the user navigated to that page. Image all the analysis you could start doing to find out how users are working in your application. Don’t forget, you could create an event for almost anything. So, maybe you track the page, but maybe you also track the times a user clicks on a button, etc.
If you want to go deeper into the event that was captured, simple click on the event and see the information associated with it. You can see in the following example, we set the User Id value when we called SetupTelemetry(), so that every call that comes back has a user Id associated with it, as well as other important information.
If you wanted to look at the events we fired using TrackEvent() from our service, you would click on the Events chart and see the list of latest events.
Click on one of the events, and you see more details. Notice it has the Suspending name we gave it from the call we made in OnSuspendingAsync() event in our application.
Also, if you wanted to include more properties and/or metrics, you could do that by calling one of the other methods in our service to include dictionaries to represent those values. I won’t show you that now, but you should try it out. It is possible to track almost everything in your application.
So, to summarize what we accomplished in this blog post:
- Created an Azure Portal Applications Insight service for our application using Visual Studio Application Insights.
- We created the service to capture Page and Event calls within our application using the Azure service.
- Demonstrated how to quickly see the results of our captures within the Azure Portal so we can make better decision about the features that are currently in the application as well as future features to come.
In part 6 of this series, I will add integration with HockeyApp and show you how easy it is to deploy your application for others to try and/or test. There will also be some analytics provided with HockeyApp and we will take a quick look at that as well.
I hope you enjoyed this post. If so, please share it with others.
Part 1 – Building a Universal Windows Platform (UWP) Application (Part 1) – Using Template10
Part 2 – Building a Universal Windows Platform (UWP) Application (Part 2) – T4 and Strings
Part 3 – Building a Universal Windows Platform (UWP) Application (Part 3) – Multilingual Support
Part 4 – Building a Universal Windows Platform (UWP) Application (Part 4) – Logging w/ MetroLog