.NET Tracker - OXYGEN-MARKET/oxygen-market.github.io GitHub Wiki

HOME > SNOWPLOW TECHNICAL DOCUMENTATION > Trackers > .NET Tracker

This page refers to version 1.0.0 of the Snowplow .NET Tracker. For previous releases up to 0.1.2, please see here.

Contents

1. Overview

The Snowplow .NET Tracker allows you to track Snowplow events from your .NET websites and desktop applications. It's split into two libraries:

Snowplow.Tracker

This is a fully functional .NET Standard 1.4 tracking library - it'll work on any platform that supports .NET Standard 1.4+ (including .NET 461+).

Snowplow.Tracker.PlatformExtensions

This is a Portable Class Library (PCL) wrapper around the core Snowplow.Tracker library that extends functionality in platform specific ways, for example to provide geo-location information when tracking users in a Xamarin mobile application. If you're using Xamarin we encourage you to use this library.

Back to top

1.1 Snowplow Demo Application

The Xamarin demo application can be deployed on Android and iOS. Simply launch the Snowplow.Demo.App.sln solution file with Visual Studio and deploy to either emulators or actual test devices. The .NET Core Console demo application can also be loaded with Visual Studio using Snowplow.Demo.Console.sln.

Back to top

2. Initialization

Assuming you have completed the .NET Tracker Setup for your project, you are now ready to initialize the .NET Tracker.

Back to top

2.1 Importing the library

Add the following using lines to the top of your .cs scripts to access the Tracker:

using Snowplow.Tracker.Emitters;
using Snowplow.Tracker.Endpoints;
using Snowplow.Tracker.Logging;
using Snowplow.Tracker.Models;
using Snowplow.Tracker.Models.Events;
using Snowplow.Tracker.Models.Adapters;
using Snowplow.Tracker.Queues;
using Snowplow.Tracker.Storage;

You should now be able to setup the Tracker!

Back to top

2.2 Creating a tracker

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

To use the Tracker in your code simply instantiate the Tracker interface with the following:

// Create logger
var logger = new ConsoleLogger();

// Controls the sending of events
var endpoint = new SnowplowHttpCollectorEndpoint(emitterUri, method: method, port: port, protocol: protocol, l: logger);

// Controls the storage of events
// NOTE: You must dispose of storage yourself when closing your application!
var storage = new LiteDBStorage("events.db");

// Controls queueing events
var queue = new PersistentBlockingQueue(storage, new PayloadToJsonString());

// Controls pulling events of the queue and pushing them to the sender
var emitter = new AsyncEmitter(endpoint, queue, l: logger);

// Contains information about who you are tracking
var subject = new Subject().SetPlatform(Platform.Mob).SetLang("EN");

Tracker.Tracker.Instance.Start(emitter: emitter, subject: subject, trackerNamespace: "some namespace", appId: "some appid", l: logger);

This starts a global singleton Tracker which can be accessed anywhere via the Tracker.Tracker.Instance.{{ method }} chain.

For more information please review the Tracker and Emitter specific sections.

Back to top

3. Tracker

The Tracker object is responsible for co-ordinating the saving and sending of events as well as managing the optional Session object.

Back to top

3.1 Constructor

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

Argument Name Description Required? Default
emitter The Emitter object you create Yes Null
subject The Subject that defines a user No Null
clientSession The Session object you create No Null
trackerNamespace The name of the tracker instance No Null
appId The application ID No Null
base64Encoded If we base 64 encode json values No True
synchronous If loading into storage is done in sync No True
desktopContextDelegate Function to get the desktop context No Null
mobileContextDelegate Function to get the mobile context No Null
geoLocationContextDelegate Function to get the geo-location context No Null
logger The logger to use within the application No Null

A full Tracker construction should look like the following:

var logger = new ConsoleLogger();
var endpoint = new SnowplowHttpCollectorEndpoint(emitterUri, method: method, port: port, protocol: protocol, l: logger);
var storage = new LiteDBStorage("events.db");
var queue = new PersistentBlockingQueue(storage, new PayloadToJsonString());
var emitter = new AsyncEmitter(endpoint, queue, l: logger);
var subject = new Subject().SetPlatform(Platform.Mob).SetLang("EN");
var session = new ClientSession("client_session.dict", l: logger);

Tracker.Tracker.Instance.Start(emitter: emitter, subject: subject, clientSession: session, trackerNamespace: "some namespace", appId: "some appid", encodeBase64: true, l: logger);

The Tracker.Start(...) and Tracker.Stop() methods take full responsibility for starting and stopping the threads required for processing everything asynchronously. Do not use any other Start and Stop functions other than the ones directly for the Tracker to prevent unknown behaviours.

WARNING: The LiteDBStorage object must be disposed of manually after stopping the Tracker so you will need to maintain a reference to this object.

NOTE: The Subject variables can all be altered directly from the Tracker via replicated setter methods.

Back to top

3.2 Functions

The Tracker contains several critical functions that must be used to start Tracking.

Back to top

3.2.1 Start(...)

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

This function must be called before any events will start being stored or sent. This is due to the fact that we do not want to start any background processing from the constructors so it is left up to the developer to choose when to start everything up.

If you attempt to access the Tracker singleton before Starting it an exception will be thrown.

This function:

  • Starts the background emitter thread
  • Starts the background session check timer (Optional)

Once this is run everything should be in place for asynchronous event tracking.

Back to top

3.2.2 Stop()

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

If you need to halt the Tracker from tracking events you can run this function. This will bring all event processing, sending and collection to a halt and nothing will be started again until Start(...) is fired again.

WARNING: If you are using Client Sessionization stopping and then restarting the Tracker will result in the session index incrementing.

Back to top

3.2.3 Track(IEvent)

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

This is the function used for Tracking all events. You can pass any of these event types to this function.

Tracker.Tracker.Instance.Track(IEvent newEvent);

Back to top

4. Emitter

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

The Emitter object is responsible for sending and storing all events.

We have one emitter available currently:

  • AsyncEmitter : Fully asynchronous operation which uses threads to perform all of its operations.

The Emitter however depends on four other objects being built:

  • IEndpoint
  • IStorage
  • IPersistentBlockingQueue
  • IPayloadToString

Back to top

4.1 Emitter Constructor

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

Argument Name Description Required? Default
endpoint The endpoint object configured for sending events Yes Null
queue The queue to be used to push and pop events from Yes Null
sendLimit The amount of events to get from the queue at a time No 100
stopPollIntervalMs The amount of time to wait before checking for more events No 300
sendSuccessMethod An optional callback function which will report event success and failure counts No Null
deviceOnlineMethod An optional delegate function which will be used to check if the device is online No Null
logger The logger to use within the application No Null

A full Emitter construction should look like the following:

var endpoint = new SnowplowHttpCollectorEndpoint(emitterUri, method: method, port: port, protocol: protocol, l: logger);
var storage = new LiteDBStorage("events.db");
var queue = new PersistentBlockingQueue(storage, new PayloadToJsonString());

AsyncEmitter emitter = new AsyncEmitter(endpoint, queue, l: logger);

NOTE: The send limit can impact performance greatly as it determines how often we need to perform I/O to the disk and how big the POSTed event batches can be.

WARNING: If you are sending events via GET note that each event is sent as its own task, so this has the potential to launch 100 outbound tasks in parallel. It is recommended to lower this range if using GET to 10-15 as a maximum.

Back to top

4.2 Endpoint Constructor

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

This is a container for information about how to reach your collector.

Argument Name Description Required? Default
host The collector uri to send events to Yes Null
protocol The protocol to use when sending events (HTTP / HTTPs) No HttpProtocol.HTTP
port If the collector is not on port 80 No Null
method The method to use when sending (GET / POST) No HttpMethod.GET
postMethod Custom method for sending events via POST No Null
getMethod Custom method for sending events via GET No Null
byteLimitPost Maximum byte limit when sending a POST request No 40000
byteLimitGet Maximum byte limit when sending a GET request No 40000
logger The logger to use within the application No Null

We have one endpoint available currently:

  • SnowplowHttpCollectorEndpoint

A full Endpoint construction should look like the following:

SnowplowHttpCollectorEndpoint endpoint = new SnowplowHttpCollectorEndpoint("com.acme-collector", protocol: HttpProtocol.HTTPS, method: HttpMethod.GET, l: logger);

NOTE: If any individual event exceeds the byte limits set then this event will be sent - but it will be assumed to have succeeded. This is to prevent constanstly attempting to send overly large events.

Back to top

4.3 Storage Constructor

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

Argument Name Description Required? Default
path The file path to store the database file at Yes Null

We have one storage target available currently:

  • LiteDBStorage

A full Storage construction should look like the following:

LiteDBStorage storage = new LiteDBStorage("events.db");

NOTE: When using the Tracker within Xamarin you will need to fetch a correct path for internal storage. Some example code for fetching this path:

// Android
public string GetLocalFilePath(string filename)
{
  string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
  return Path.Combine(path, filename);
}

// iOS
public string GetLocalFilePath(string filename)
{
  string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
  string libFolder = Path.Combine(docFolder, "..", "Library", "Databases");

  if (!Directory.Exists(libFolder))
  {
    Directory.CreateDirectory(libFolder);
  }

  return Path.Combine(libFolder, filename);
}

Back to top

4.4 Queue Constructor

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

Argument Name Description Required? Default
storage The storage object to use with the queue Yes Null
payloadToString Serializer for Payload objects Yes Null

We have one queue available currently:

  • PersistentBlockingQueue

A full queue construction should look like the following:

PersistentBlockingQueue queue = new PersistentBlockingQueue(storage, new PayloadToJsonString());

Back to top

4.5 Payload Serializer Constructor

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

We have one payload serializer available currently:

  • PayloadToJsonString

A full queue construction should look like the following:

PayloadToJsonString serializer = new PayloadToJsonString();

This controls how we queue information for internal use.

Back to top

5. Subject

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

You may have additional information about your application's environment, current user and so on, which you want to send to Snowplow with each event.

The Subject class has a set of Set...() methods to attach extra data relating to the user to all tracked events:

Here are some examples:

Subject s1 = new Subject();
s1.SetUserId("Kevin Gleason");
s1.SetLang("en-gb");
s1.SetScreenResolution(1920, 1080);

Back to top

5.1 Set user ID with SetUserId

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

You can set the user ID to any string:

s1.SetUserId( "{{USER ID}}" )

Example:

s1.SetUserId("alexd")

Back to top

5.2 Set screen resolution with SetScreenResolution

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

If your C# code has access to the device's screen resolution, then you can pass this in to Snowplow too:

s1.SetScreenResolution( {{WIDTH}}, {{HEIGHT}} )

Both numbers should be positive integers; note the order is width followed by height. Example:

s1.SetScreenResolution(1366, 768)

Back to top

5.3 Set viewport dimensions with SetViewport

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

If your C# code has access to the viewport dimensions, then you can pass this in to Snowplow too:

s1.SetViewport( {{WIDTH}}, {{HEIGHT}} )

Both numbers should be positive integers; note the order is width followed by height. Example:

s1.SetViewport(300, 200)

Back to top

5.4 Set color depth with SetColorDepth

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

If your C# code has access to the bit depth of the device's color palette for displaying images, then you can pass this in to Snowplow too:

s.SetColorDepth( {{BITS PER PIXEL}} )

The number should be a positive integer, in bits per pixel. Example:

s.SetColorDepth(32)

Back to top

5.5 Set timezone with SetTimezone

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

This method lets you pass a user's timezone in to Snowplow:

s.SetTimezone( {{TIMEZONE}} )

The timezone should be a string:

s.SetTimezone("Europe/London")

Back to top

5.6 Set the language with SetLang

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

This method lets you pass a user's language in to Snowplow:

s.SetLang( {{LANGUAGE}} )

The language should be a string:

s.SetLang('en')

Back to top

5.7 SetIpAddress

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

This method lets you pass a user's IP Address in to Snowplow:

s.SetIpAddress( {{IP ADDRESS}} )

The IP address should be a string:

s.SetIpAddress("127.0.0.1");

Back to top

5.8 SetUseragent

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

This method lets you pass a useragent in to Snowplow:

s.SetUseragent( {{USERAGENT}} )

The useragent should be a string:

s.SetUseragent("Agent Smith");

Back to top

5.9 SetNetworkUserId

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

This method lets you pass a Network User ID in to Snowplow:

s.SetNetworkUserId( {{NUID}} )

The network user id should be a string:

s.SetNetworkUserId("network-id");

Back to top

5.10 SetDomainUserId

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

This method lets you pass a Domain User ID in to Snowplow:

s.SetDomainUserId( {{DUID}} )

The domain user id should be a string:

s.SetDomainUserId("domain-id");

Back to top

5.11 SetPlatform

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

This method lets you set the Platform that the Tracker is running on:

s.SetPlatform( Platform.{{ option }} )

The Platform should be an enum:

s.SetPlatform(Platform.Mob);

Available platforms:

  • Web
  • Mob
  • Pc
  • Srv
  • App
  • Tv
  • Cnsl
  • Iot

Back to top

6. Session

The Session object is responsible for maintaining persistent data around user sessions over the life-time of an application.

Back to top

6.1 Constructor

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

Argument Name Description Required? Default
savePath The path to save persistent data into Yes Null
foregroundTimeout The time until a session expires in focus No 600 (s)
backgroundTimeout The time until a session expires in back No 300 (s)
checkInterval How often to validate the session timeout No 15 (s)
logger The logger to use within the application No Null

A full ClientSession construction should look like the following:

ClientSession session = new ClientSession ("save_file_path.xml");

The timeout's refer to the length of time the session remains active after the last event is sent. As long as events are sent within this limit the session will not timeout.

NOTE: When using the Tracker within Xamarin you will need to fetch a correct path for internal storage. Some example code for fetching this path:

// Android
public string GetLocalFilePath(string filename)
{
  string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
  return Path.Combine(path, filename);
}

// iOS
public string GetLocalFilePath(string filename)
{
  string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
  string libFolder = Path.Combine(docFolder, "..", "Library", "Databases");

  if (!Directory.Exists(libFolder))
  {
    Directory.CreateDirectory(libFolder);
  }

  return Path.Combine(libFolder, filename);
}

Back to top

6.2 Functions

Back to top

6.2.1 SetBackground(bool)

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

Will set whether or not the application is in the background. It is up to the developer to set this metric if they wish to have a different timeout for foreground and background.

NOTE: If a timeout occurs while the application has been backgrounded the SessionChecker will be stopped automatically. Session checking will resume on Foregrounding or on an event being tracked.

Back to top

7. Event Tracking

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

Snowplow has been built to enable you to track a wide range of events that occur when users interact with your websites and apps. We are constantly growing the range of functions available in order to capture that data more richly.

Events supported by the .NET Tracker at a glance:

Events *Description
Track(PageView) Track and record views of web pages
Track(ScreenView) Track the user viewing a screen within the application
Track(Structured) Track a Snowplow custom structured event
Track(Timing) Track a Timing with Category event
Track(Unstructured) Track a Snowplow custom unstructured event
Track(EcommerceTransaction) Track an ecommerce transaction and its items

Back to top

7. Event Types

Back to top

7.1.1 Track page views with Track(PageView)

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

You can use Track(PageView) to track a user viewing a web page within your app.

Arguments are:

Argument Description Required? Type
pageUrl The URL of the page Yes string
pageTitle The title of the page No string
referrer The address which linked to the page No string
customContexts Optional custom context No List<IContext>
trueTimestamp Optional true-timestamp No long
eventId Optional custom event id No string

Examples:

t1.Track(new PageView()
    .SetPageUrl("www.example.com")
    .SetPageTitle("example")
    .SetReferrer("www.referrer.com")
    .Build());

t1.Track(new PageView()
    .SetPageUrl("www.example.com")
    .SetPageTitle("example")
    .SetReferrer("www.referrer.com")
    .SetCustomContext(contextList)
    .SetTrueTimestamp(1423583655000)
    .SetEventId("uid-1")
    .Build());

Back to top

7.1.2 Track screen views with Track(ScreenView)

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

Use Track(ScreenView) to track a user viewing a screen (or equivalent) within your app. You must use either name or id. Arguments are:

Argument Description Required? Type
name Human-readable name for this screen No string
id Unique identifier for this screen No string
customContexts Optional custom context No List<IContext>
deviceCreatedTimestamp Optional device-created-timestamp No long
trueTimestamp Optional true-timestamp No long
eventId Optional custom event id No string

Examples:

t1.Track(new ScreenView()
    .SetName("HUD > Save Game")
    .SetId("screen23")
    .Build());

t1.Track(new ScreenView()
    .SetName("HUD > Save Game")
    .SetId("screen23")
    .SetCustomContext(contextList)
    .SetTrueTimestamp(1423583655000)
    .SetEventId("uid-1")
    .Build());

Back to top

7.1.3 Track structured events with Track(Structured)

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

Use Track(Structured) to track a custom event happening in your app which fits the Google Analytics-style structure of having up to five fields (with only the first two required):

Argument Description Required? Type
category The grouping of structured events which this action belongs to Yes string
action Defines the type of user interaction which this event involves Yes string
label A string to provide additional dimensions to the event data No string
property A string describing the object or the action performed on it No string
value A value to provide numerical data about the event No double
customContexts Optional custom context No List<IContext>
deviceCreatedTimestamp Optional device-created-timestamp No long
trueTimestamp Optional true-timestamp No long
eventId Optional custom event id No string

Examples:

t1.Track(new Structured()
    .SetCategory("shop")
    .SetAction("add-to-basket")
    .Build());

t1.Track(new Structured()
    .SetCategory("shop")
    .SetAction("add-to-basket")
    .SetLabel("Add To Basket")
    .SetProperty("pcs")
    .SetValue(2.00)
    .SetCustomContext(contextList)
    .SetTrueTimestamp(1423583655000)
    .SetEventId("uid-1")
    .Build());

Back to top

7.1.4 Track timing events with Track(Timing)

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

Use Track(Timing) to track an event related to a custom timing.

Argument Description Required? Type
category The category of the timed event Yes string
label The label of the timed event No string
timing The timing measurement in milliseconds Yes int
variable The name of the timed event Yes string
customContexts Optional custom context No List<IContext>
deviceCreatedTimestamp Optional device-created-timestamp No long
trueTimestamp Optional true-timestamp No long
eventId Optional custom event id No string

Examples:

t1.Track(new Timing()
    .SetCategory("category")
    .SetVariable("variable")
    .SetTiming(1)
    .Build());

t1.Track(new Timing()
    .SetCategory("category")
    .SetVariable("variable")
    .SetTiming(1)
    .SetLabel("label")
    .SetCustomContext(contextList)
    .SetTrueTimestamp(1423583655000)
    .SetEventId("uid-1")
    .Build());

Back to top

7.1.5 Track unstructured events with Track(SelfDescribing)

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

Custom unstructured events are a flexible tool that enable Snowplow users to define their own event types and send them into Snowplow.

When a user sends in a custom unstructured event, they do so as a JSON of name-value properties, that conforms to a JSON schema defined for the event earlier.

Use Track(SelfDescribing) to track a custom event which consists of a name and an unstructured set of properties. This is useful when:

  • You want to track event types which are proprietary/specific to your business (i.e. not already part of Snowplow), or
  • You want to track events which have unpredictable or frequently changing properties

The arguments are as follows:

Argument Description Required? Type
eventData The properties of the event Yes SelfDescribingJson
customContexts Optional custom context No List<IContext>
deviceCreatedTimestamp Optional device-created-timestamp No long
trueTimestamp Optional true-timestamp No long
eventId Optional custom event id No string

Example event json to track:

{
  "schema": "iglu:com.acme/save_game/jsonschema/1-0-0",
  "data": {
    "levelName": "Barrels o' Fun",
    "levelIndex": 23
  }
}

How to set it up?

// Create a Dictionary of your event data
Dictionary<string, object> eventDict = new Dictionary<string, object>();
eventDict.Add("levelName", "Barrels o' Fun");
eventDict.Add("levelIndex", 23);

// Create your event data
SelfDescribingJson eventData = new SelfDescribingJson("iglu:com.acme/save_game/jsonschema/1-0-0", eventDict);

// Track your event with your custom event data
t1.Track(new SelfDescribing()
    .SetEventData(eventData)
    .Build();

// OR

t1.Track(new SelfDescribing()
    .SetEventData(eventData)
    .SetCustomContext(contextList)
    .SetTrueTimestamp(1423583655000)
    .SetEventId("uid-1")
    .Build();

For more on JSON schema, see the blog post.

Back to top

7.1.6 Track ecommerce transactions with Track(EcommerceTransaction)

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

Use Track(EcommerceTransaction) to track an ecommerce transaction.

Arguments:

Argument Description Required? Type
orderId ID of the eCommerce transaction Yes string
totalValue Total transaction value Yes double
affiliation Transaction affiliation No string
taxValue Transaction tax value No double
shipping Delivery cost charged No double
city Delivery address city No string
state Delivery address state No string
country Delivery address country No string
currency Transaction currency No string
items Items in the transaction Yes List<EcommerceTransactionItem>
customContexts Optional custom context No List<IContext>
deviceCreatedTimestamp Optional device-created-timestamp No long
trueTimestamp Optional true-timestamp No long
eventId Optional custom event id No string

The items argument is a List of individual EcommerceTransactionItem elements representing the items in the e-commerce transaction. Note that Track(EcommerceTransaction) fires multiple events: one transaction event for the transaction as a whole, and one transaction item event for each element of the items List.

Each transaction item event will have the same device created timestamp, true timestamp, orderId, and currency as the main transaction event.

Back to top

7.1.6.1 EcommerceTransactionItem

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

To instantiate a EcommerceTransactionItem in your code, simply use the following constructor signature:

EcommerceTransactionItem item = new EcommerceTransactionItem ()
      .SetSku ("sku")
      .SetPrice (10.2)
      .SetQuantity (1)
      .SetName ("name")
      .SetCategory ("category")
      .Build ()

These are the fields that can appear as elements in each EcommerceTransactionItem element of the transaction item's List:

Field Description Required? Type
sku Item SKU Yes string
price Item price Yes double
quantity Item quantity Yes int
name Item name No string
category Item category No string
customContexts Optional custom context No List<IContext>
eventId Optional custom event id No string

Example of tracking a transaction containing two items:

// Create some Transaction Items
EcommerceTransactionItem item1 = new EcommerceTransactionItem ()
    .SetSku ("item_sku_1")
    .SetPrice (10.2)
    .SetQuantity (1)
    .SetName ("item_name_1")
    .SetCategory ("item_category")
    .Build ();

EcommerceTransactionItem item2 = new EcommerceTransactionItem()
    .SetSku("item_sku_2")
    .SetPrice(1.00)
    .SetQuantity(1)
    .SetName("item_name_2")
    .SetCategory("item_category")
    .Build();

// Add these items to a List
List<EcommerceTransactionItem> items = new List<EcommerceTransactionItem>();
items.Add(item1);
items.Add(item2);

// Now Track the Transaction by using this list of items as an argument
tracker.Track(new EcommerceTransaction()
    .SetOrderId("order_id_1")
    .SetTotalValue(300.00)
    .SetAffiliation("my_affiliate")
    .SetTaxValue(30.00)
    .SetShipping(10.00)
    .SetCity("Boston")
    .SetState("Massachusetts")
    .SetCountry("USA")
    .SetCurrency("USD")
    .SetItems(items)
    .Build());

Back to top

7.2 Custom Contexts

Custom contexts are Self Describing Jsons with extra descriptive information that can be optionally attached to any Snowplow event with SetCustomContexts(...). We provide several builders for Snowplow custom contexts as well as a generic builder if you wish to define and send your own custom contexts!

For ease of development you are also able to extend the IContext interface or the AbstractContext class for your own contexts if you so wish.

All of these contexts will need to be combined into a List<IContext> before being attachable to Snowplow Events.

Back to top

7.2.1 DesktopContext

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

The following arguments can be used in a DesktopContext:

Field Description Required? Type
osType The Operating System Type Yes string
osVersion The Version of the Operating System Yes string
osServicePack Service Pack information No string
osIs64Bit If the OS is 32 or 64 bit No bool
deviceManufacturer Who made the device No string
deviceModel What is the device model No string
processorCount How many cores does the device have No int

An example of a DesktopContext construction:

DesktopContext context = new DesktopContext ()
    .SetOsType("OS-X")
    .SetOsVersion("10.10.5")
    .SetOsServicePack("Yosemite")
    .SetOsIs64Bit(true)
    .SetDeviceManufacturer("Apple")
    .SetDeviceModel("Macbook Pro")
    .SetDeviceProcessorCount(4)
    .Build ();

Back to top

7.2.2 MobileContext

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

The following arguments can be used in a MobileContext:

Field Description Required? Type
osType The Operating System Type Yes string
osVersion The Version of the Operating System Yes string
deviceManufacturer Who made the device Yes string
deviceModel What is the device model Yes string
carrier The name of the carrier No string
networkType The type of network No NetworkType
networkTechnology The networks technlogy No string
openIdfa An OpenIDFA UUID No string
appleIdfa An Apple IDFA UUID No string
appleIdfv An Apple IDFV UUID No string
androidIdfa An Android IDFA UUID No string

An example of a MobileContext construction:

MobileContext context = new MobileContext ()
    .SetOsType("iOS")
    .SetOsVersion("9.0")
    .SetDeviceManufacturer("Apple")
    .SetDeviceModel("iPhone 6S+")
    .SetCarrier("FREE")
    .SetNetworkType(NetworkType.Mobile)
    .SetNetworkTechnology("LTE")
    .Build ();

Back to top

7.2.3 GeoLocationContext

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

The following arguments can be used in a GeoLocationContext:

Field Description Required? Type
latitude The user latitude Yes double
longitude The user longitude Yes double
latitudeLongitudeAccuracy The user lat-long accuracy No double
altitude The user altitude No double
altitudeAccuracy The user alt accuracy No double
bearing The user bearing No double
speed The user speed No double
timestamp A timestamp in ms No long

An example of a GeoLocationContext construction:

GeoLocationContext context = new GeoLocationContext ()
    .SetLatitude(123.564)
    .SetLongitude(-12.6)
    .SetLatitudeLongitudeAccuracy(5.6)
    .SetAltitude(5.5)
    .SetAltitudeAccuracy(2.1)
    .SetBearing(3.2)
    .SetSpeed(100.2)
    .SetTimestamp(1234567890000)
    .Build ();

Back to top

7.2.4 GenericContext

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

The GenericContext is a simple builder with three functions:

  • SetSchema(string) : Sets the Context Schema Path
  • Add(string, object) : Adds a single key-pair value to the data packet of this context
  • AddDict(string, object) : Adds a dictionary of key-pair values to the data packet

You must set a schema string or a RuntimeException will be thrown.

An example of a GenericContext construction:

GenericContext context = new GenericContext()
    .SetSchema("iglu:com.acme/acme_context/jsonschema/1-0-0")
    .Add("context", "custom")
    .Build();

Back to top

7.3 SelfDescribingJson

Using Snowplow.Tracker (.NET Standard) or Snowplow.Tracker.PlatformExtensions (PCL)

A SelfDescribingJson is used as a wrapper around a Dictionary<string, object>. After creating the Dictionary you want to wrap you can create a SelfDescribingJson using the following:

// Data as a Dictionary
Dictionary<string, object> data = new Dictionary<string, object>();
data.Add("Event", "Data")

// We then create a new SelfDescribingJson
SelfDescribingJson json = new SelfDescribingJson("iglu:com.acme/example/jsonschema/1-0-0", data);

This object is now ready to be Tracked within an SelfDescribing Event.

You can create a SelfDescribingJson with the following arguments:

Argument Description Required? Type
schema JsonSchema that describes the data Yes string
data Data that will be validated by the schema No Dictionary<string,object>

Back to top

8. Platform Specific Functions

To support multiple platforms we provide several utility functions for fetching platform specific information.

Back to top

8.1 GetMobileContext

PlatformExtensions only

Platforms:

  • Xamarin.Android API 15+
  • Xamarin.iOS 8+

NOTE: These mobile contexts do not currently fetch any advertising identifiers.

Back to top

8.2 GetGeoLocationContext

PlatformExtensions only

Platforms:

  • Xamarin.Android API 15+
  • Xamarin.iOS 8+

NOTE: To make the GeoLocation context work on iOS you will need to add the following to your Info.plist:

<key>UIBackgroundModes</key>
<array>
  <string>location</string>
</array>
<key>NSLocationAlwaysUsageDescription</key>
<string></string>

When you send your first event a prompt will be fired asking the user for permission to use their location.

Back to top

8.3 GetDesktopContext

PlatformExtensions only

Platforms:

  • .NET Framework 4.6.1+

Back to top

8.4 GetLocalFilePath

PlatformExtensions only

Platforms:

  • Xamarin.Android API 15+
  • Xamarin.iOS 8+

Back to top

8.5 IsDeviceOnline

PlatformExtensions only

Platforms:

  • Xamarin.Android API 15+
  • Xamarin.iOS 8+
  • .NET Framework 4.6.1+

Back to top

⚠️ **GitHub.com Fallback** ⚠️