-
Notifications
You must be signed in to change notification settings - Fork 33
Documentation
At the highest level, here is how it works:
- Within our SDK, each measurement is sent to Google Analytics as a set of parameter value pairs. You can think of these as an instance of the Hit class, which contains a collection of key-value pairs and a time-stamp to be sent as a measurement.
- This set of parameters is most often built using the HitBuilder class. HitBuilder is a fluent API that provides convenient functions for building your parameters. Even with the simplest measure, like an event, it is more convenient to collect the data like this:
var data = HitBuilder.CreateCustomEvent("level", "completed", "level5", 32).Build();
Compared to building the collection manually, like this:
Dictionary<string, object> hit = new Dictionary<string, object>();
hit.Add("t", "event"); //type of interaction
hit.Add("ec", "level"); // event category
hit.Add("ea", "completed"); // event action
hit.Add("el" , "level5"); // event label
hit.Add("ev", 32); //event value
- Once you have aggregated the all the key-value-pairs for this Hit, you pass the data to the Send() method in your Tracker instance and this Tracker dispatches it to the server.
//sending the data we got from our prior CreateCustomEvent call
tracker.Send ( data );
- Tracker is the logical entity sending the data; but the underlying work to dispatch the request is done by the AnalyticsManager. AnalyticsManager provides infrastructure to Tracker(s): it can handle system-wide configuration details, it also implements the proper dispatching of the data, and it also provides the events for tracking the status of each measurement sent event. Here is a canonical sample of using AnalyticsManager and Tracker.
//Below is an example of common configuration options exposed by AnalyticsManager
//Automaticaly catch unhandled exceptions and send them to analytics server
AnalyticsManager.Current.ReportUncaughtExceptions = true;
//automatically handle suspend/resume (sends data on suspend)
AnalyticsManager.Current.AutoAppLifetimeMonitoring = true;
// prevent http caching by appending a unique param every time.
AnalyticsManager.Current.BustCache = true;
//After you have your defaults w/ Analytics Manager,
//Create a tracker
var tracker = GoogleAnalytics.AnalyticsManager.Current.CreateTracker("<PropertyId>");
- When sending all these measurement data, you also want to send information about the OS or the hardware your app is running on, PlatformInfoProvider takes care of this. You might not need to interact much with this class, but it is there supporting the AnalyticsManager.
In a nutshell, that is how our object model works. Let's now discuss the different kinds of interactions, and some of the shared,higher level features in the SDK.
Through out this journey, keep in mind that Google has ample documentationon all the features, the best practices, etc.
When reading the docs, consider our object model is most similar to the Android SDK, and we use the measurement protocol.
#Interactions The measurement protocol supports the following hit types: 'pageview', 'screenview', 'event', 'transaction', 'item', 'social', 'exception', 'timing'.
Screens in Google Analytics represent content users are viewing within your app. The equivalent concept in web analytics is a pageview. Measuring screen views allows you to see which content is being viewed most by your users, and how are they are navigating between different pieces of content.
A screen view consists of a single field:
- Screen Name [string, required]
Screen view data is used primarily in the following Google Analytics reports:
- Screens report
- Engagement Flow
- Goal Flow
There is two slightly different ways to send a screen view:
// Approach #1
//This sends a screen view of a page called "TransientDialog"
tracker.Send(HitBuilder.CreateScreenView("TransientDialog").Build());
/* if we were to send a custom event next, using the code below, it would
NOT include the TransientDialog parameter as it applied only to the screen view hit*/
// tracker.Send(HitBuilder.CreateCustomEvent("category", "action", "label", 0).Build());
// Approach #2
tracker.ScreenName = "SharedUntilOverridden";
//This sends a screen view. In this case, the name is "SharedUntilOverridden".
tracker.Send(HitBuilder.CreateScreenView().Build());
/* With this approach, the screen name comes from the Tracker.ScreenName property.
Since ScreenName is still set in the Tracker when we send the event below,
this new event would include the screen name parameter.
It is a good way to always send the context of the screen the user is in */
// tracker.Send(HitBuilder.CreateCustomEvent("category", "action", "label", 0).Build());
Events are a useful way to collect data about a user's interaction with interactive components of your app, like button presses or the use of a particular item in a game.
An event consists of four fields that you can use to describe a user's interaction with your app content:
- Category [string, required]
- Action [string, required]
- Label [string, optional]
- Value [long, optional]
Here is how you build a custom event hit:
tracker.Send(HitBuilder.CreateCustomEvent("ui", "click", "age_button", 7).Build());
Social interaction measurement allows you to measure a user's interactions with various social network sharing and recommendation widgets embedded in your app.
A social hit includes the following fields:
- social network [string, required]
- social action [string, required]
- social target [string, optional]
Here is how to send a social interaction:
var hit = HitBuilder.CreateSocialInteraction("twitter", "follow", "@jaimerodriguez");
tracker.Send( hit.Build());
Measuring user timings provides a native way to measure a period of time in Google Analytics. This can be useful to measure resource load times, for example.
A timing consists of the following fields:
- category [string, required]
- value [long, required, see details below for time-scale]
- name [string, required]
- label [string, optional]
Here is how to send a user timing:
TimeSpan ts = TimeSpan.FromSeconds(2.2);
tracker.Send(HitBuilder.CreateTiming("load", "MainPage", ts).Build());
Note: The SDK uses [TimeSpan structure](https://msdn.microsoft.com/library/windows/apps/br225996). For C#, this maps to **System.TimeSpan**, and should be seamless, as you don't deal with Duration. For C++, the **Windows.Foundation.TimeSpan** Duration is measured in 100 nanosecond ticks, so 1 second is represented as 10000000.
For JavaScript, timespan.duration is in milliseconds intervals, so 1 second is represented as {duration: 1000}.
These slight differences are imposed by the platform, we don't control it in the SDK.
Enhanced commerce enables the measurement of user interactions with products across the user's shopping experience, which include product impressions, product clicks, viewing product details, adding a product to a shopping cart, initiating the checkout process, transactions, and refunds.
Here is an example of a measurement for a user viewing a product impression:
var product = new GoogleAnalytics.Ecommerce.Product()
{
Id = "Product12345" ,
Category = "Computer",
Name = "Surface Pro Tablet",
Price = 1299.99 ,
};
var hit = HitBuilder.CreateScreenView( "Search Results");
hit.AddProduct(product);
tracker.Send(hit.Build());
Enhanced commerce can also track actions, which are instances of ProductAction. You can add actions to interactions using HitBuilder _**SetProductAction **_method.
Actions and impressions can also be combined into a single hit. To learn more all these, please refer to Google Analytics enhanced commerce documentation
Crash and exception measurement allows you to measure the number and types of handled and unhandled exceptions that occur in your app. An exception in Google Analytics consists of these fields:
- Description [string, optional]
- isFatal [boolean, required]
With our SDK, you can report handled and unhandled exceptions. For handled exceptions, just follow your logic and build a hit following the same patterns we have been using:
try
{
//do something here that throws
} catch ( Exception ex )
{
tracker.Send(HitBuilder.CreateException(ex.Message, false).Build());
}
To report unhandled exceptions (in C# and C++ projects), just set ReportUncaughtExceptions = true; in your instance of AnalyticsManager:
AnalyticsManager.Current.ReportUncaughtExceptions = true;
When an unhandled exception occurs, AnalyticsManager will catch it, fill the description field with the stacktrace and report it as fatal. From there, it gets passed to your application's UnhandledException handlers.
Note: Automatic unhandled exception tracking does not work in JavaScript projects. Use manual exception reporting in this case.
Now that you are familiar with the interaction types, here is a few other important configuration parameters
You can enable client-side sampling to limit the number of hits sent to Google Analytics. If your app has a large number of users or otherwise sends a large volume of data to Google Analytics, enabling sampling will help ensure un-interrupted reporting.
To limit the number of hits, set SampleRate
in the Tracker
object. 100 means no items should be excluded, 50 means half should be excluded, and 0 means all items should be excluded.
Note: To avoid reporting inconsistencies, each of your app views (profiles) should contain data collected at the same sampling rate. If different versions of your app use different sampling rates, you'll need to configure view (profile) filters using the app version dimension to keep the data from each version of your app separate.
A session represents a single period of user interactions. By default, Google Analytics will group hits that are received within 30 minutes of one another into the same session, so you should not have anything for most scenarios.
If you manually want to start a session, you can use HitBuilder SetNewSession on any hit:
var hit = HitBuilder.CreateScreenView("loginSuccess").SetNewSession( );
tracker.Send(hit.Build());
##Debugging
AnalyticsManager has an **isDebug ** property that allows you to send your hits to the Measurement Protocol Validation Server. When you send the hits to the validation server, you get detailed responses that will tell you whether a hit was valid, and when it is invalid, you get a detailed parserMessage that helps you troubleshoot.
Our default samples use this technique and shows you how to listen to AnalyticsManager HitSent, HitMalformed, and HitFailed events to interpret all the responses.
This project is supported by the .NET Foundation