Skip to content

The hassle-free way to add Segment analytics to your C# written app (.Net/Xamarin/Unity).

License

Notifications You must be signed in to change notification settings

segmentio/Analytics-CSharp

Repository files navigation

Analytics-CSharp

🎉 Flagship 🎉

This library is one of Segment’s most popular Flagship libraries. It is actively maintained by Segment, benefitting from new feature releases and ongoing support.

Nuget openupm

The hassle-free way to add Segment analytics to your .Net app (Unity/Xamarin/.Net). Analytics helps you measure your users, product, and business. It unlocks insights into your app's funnel, core business metrics, and whether you have product-market fit.

Analytics-CSharp is supported across the following platforms:

  • net/.net core/.net framework
  • mono
  • universal windows platform
  • xamarin
    • ios
    • mac
    • android
  • unity
    • ios
    • android
    • pc, mac, linux

NOTE: Migrating from Analytics.NET and Analytics.Xamarin? See our migration guide here

BREAKING CHANGES ALERT: if you are upgrading from 1.+ to 2.+, check out the breaking changes list here.

Getting Started

To get started with the Analytics-CSharp library:

  1. Create a Source in Segment.

    1. Go to Connections > Sources > Add Source.
    2. Search for Xamarin or Unity or .NET and click Add source.
  2. Add the Analytics dependency to your project. Analytics-CSharp is distributed via NuGet. Check other installation options here.

    dotnet add package Segment.Analytics.CSharp --version <LATEST_VERSION>
    

    For Unity, it is distributed via OpenUPM. Read more about it here.

    openupm add com.segment.analytics.csharp
    
  3. Initialize and configure the client.

        // NOTE: to make Analytics stateless/in-memory,
        // add `InMemoryStorageProvider` to the configuration
        var configuration = new Configuration("<YOUR WRITE KEY>",
                flushAt: 20,
                flushInterval: 30);
        var analytics = new Analytics(configuration);


    These are the options you can apply to configure the client:

Option Name Description
writeKey required This is your Segment write key.
flushAt Default set to 20.
The count of events at which Segment flushes events.
flushInterval Default set to 30 (seconds).
The interval in seconds at which Segment flushes events.
defaultSettings Default set to {}.
The settings object used as fallback in case of network failure.
autoAddSegmentDestination Default set to true.
This automatically adds the Segment Destination plugin. You can set this to false if you want to manually add the Segment Destination plugin.
apiHost Default set to api.segment.io/v1.
This sets a default API Host to which Segment sends events.
cdnHost Default set to cdn-settings.segment.com/v1.
This set a default cdnHost to which Segment fetches settings.
analyticsErrorHandler Default set to null.
This set an error handler to handle errors happened in analytics
storageProvider Default set to DefaultStorageProvider.
This set how you want your data to be stored.
DefaultStorageProvider is used by default which stores data to local storage. InMemoryStorageProvider is also provided in the library.
You can also write your own storage solution by implementing IStorageProvider and IStorage
httpClientProvider Default set to DefaultHTTPClientProvider.
This set a http client provider for analytics use to do network activities. The default provider uses System.Net.Http for network activities.
flushPolicies Default set to null.
This set custom flush policies to tell analytics when and how to flush. By default, it converts flushAt and flushInterval to CountFlushPolicy and FrequencyFlushPolicy. If a value is given, it overwrites flushAt and flushInterval.

Tracking Methods

Once you've installed the mobile or server Analytics-CSharp library, you can start collecting data through Segment's tracking methods:

info "" For any of the different methods described, you can replace the properties and traits in the code samples with variables that represent the data collected.

Identify

The Identify method lets you tie a user to their actions and record traits about them. This includes a unique user ID and any optional traits you know about them like their email, name, address. The traits option can include any information you want to tie to the user. When using any of the reserved traits, be sure the information reflects the name of the trait. For example, email should always be a string of the user's email address.

analytics.Identify("user-123", new JsonObject {
    ["username"] = "MisterWhiskers",
    ["email"] = "[email protected]",
    ["plan"] = "premium"
});

Track

The Track method lets you record the actions your users perform. Every action triggers an event, which also has associated properties that the track method records.

analytics.Track("View Product", new JsonObject {
    ["productId"] = 123,
    ["productName"] = "Striped trousers"
});

Screen

The Screen method lets you record whenever a user sees a screen in your mobile app, along with optional extra information about the page being viewed.

You'll want to record a screen event whenever the user opens a screen in your app. This could be a view, fragment, dialog or activity depending on your app.

Not all integrations support screen, so when it's not supported explicitly, the screen method tracks as an event with the same parameters.

analytics.Screen("ScreenName", new JsonObject {
    ["productSlug"] = "example-product-123"
});

Page

The Page method lets you record whenever a user sees a page in your web app, along with optional extra information about the page being viewed.

You'll want to record a page event whenever the user opens a page in your app. This could be a webpage, view, fragment, dialog or activity depending on your app.

Not all integrations support page, so when it's not supported explicitly, the page method tracks as an event with the same parameters.

analytics.Page("PageName", new JsonObject {
    ["productSlug"] = "example-product-123"
});

Group

The Group method lets you associate an individual user with a group— whether it's a company, organization, account, project, or team. This includes a unique group identifier and any additional group traits you may have, like company name, industry, number of employees. You can include any information you want to associate with the group in the traits option. When using any of the reserved group traits, be sure the information reflects the name of the trait. For example, email should always be a string of the user's email address.

analytics.Group("user-123", new JsonObject {
    ["username"] = "MisterWhiskers",
    ["email"] = "[email protected]",
    ["plan"] = "premium"
});

Plugin Architecture

Segment's plugin architecture enables you to modify and augment how the analytics client works. From modifying event payloads to changing analytics functionality, plugins help to speed up the process of getting things done.

Plugins are run through a timeline, which executes in order of insertion based on their entry types. Segment has these 5 entry types:

Type Details
Before Executes before event processing begins.
Enrichment Executes as the first level of event processing.
Destination Executes as events begin to pass off to destinations.
After Executes after all event processing completes. You can use this to perform cleanup operations.
Utility Executes only with manual calls such as Logging.

Fundamentals

There are 3 basic types of plugins that you can use as a foundation for modifying functionality. They are: Plugin, EventPlugin, and DestinationPlugin.

Plugin

Plugin acts on any event payload going through the timeline.

For example, if you want to add something to the context object of any event payload as an enrichment:

class SomePlugin : Plugin
{
    public override PluginType Type => PluginType.Enrichment;

    public override RawEvent Execute(RawEvent incomingEvent)
    {
        incomingEvent.Context["foo"] = "bar";
        return incomingEvent;
    }
}

EventPlugin

EventPlugin is a plugin interface that acts on specific event types. You can choose the event types by only overriding the event functions you want.

For example, if you only want to act on track & identify events:

class SomePlugin : EventPlugin
{
    public override PluginType Type => PluginType.Enrichment;

    public override IdentifyEvent Identify(IdentifyEvent identifyEvent)
    {
        // code to modify identify event
        return identifyEvent;
    }

    public override TrackEvent Track(TrackEvent trackEvent)
    {
        // code to modify track event
        return trackEvent;
    }
}

DestinationPlugin

The DestinationPlugin interface is commonly used for device-mode destinations. This plugin contains an internal timeline that follows the same process as the analytics timeline, enabling you to modify and augment how events reach a particular destination.

For example, if you want to implement a device-mode destination plugin for Amplitude, you can use this:

class AmplitudePlugin : DestinationPlugin
{
    public override string Key =>
        "Amplitude"; // This is the name of the destination plugin, it is used to retrieve settings internally

    private Amplitude amplitudeSDK: // This is an instance of the partner SDK

    public AmplitudePlugin()
    {
        amplitudeSDK = Amplitude.instance;
        amplitudeSDK.initialize(applicationContext, "API_KEY");
    }

    /*
    * Implementing this function allows this plugin to hook into any track events
    * coming into the analytics timeline
    */
    public override TrackEvent Track(TrackEvent trackEvent)
    {
        amplitudeSDK.logEvent(trackEvent.Event);
        return trackEvent;
    }
}

Advanced concepts

  • configure(Analytics): Use this function to setup your plugin. This implicitly calls once the plugin registers.
  • update(Settings): Use this function to react to any settings updates. This implicitly calls when settings update. You can force a settings update by calling analytics.checkSettings().
  • DestinationPlugin timeline: The destination plugin contains an internal timeline that follows the same process as the analytics timeline, enabling you to modify/augment how events reach the particular destination. For example if you only wanted to add a context key when sending an event to Amplitude:
class AmplitudeEnrichment : Plugin
{
    public override PluginType Type => PluginType.Enrichment;

    public override RawEvent Execute(RawEvent incomingEvent)
    {
        incomingEvent.Context["foo"] = "bar";
        return incomingEvent;
    }
}


var amplitudePlugin = new AmplitudePlugin(); // add amplitudePlugin to the analytics client
analytics.Add(amplitudePlugin);
amplitudePlugin.Add(new AmplitudeEnrichment()); // add enrichment plugin to amplitude timeline

Adding a plugin

Adding plugins enable you to modify your analytics implementation to best fit your needs. You can add a plugin using this:

var yourPlugin = new SomePlugin()
analytics.Add(yourPlugin)

Though you can add plugins anywhere in your code, it's best to implement your plugin when you configure the client.

Here's an example of adding a plugin to the context object of any event payload as an enrichment:

class SomePlugin : Plugin
{
    public override PluginType Type => PluginType.Enrichment;

    public override RawEvent Execute(RawEvent incomingEvent)
    {
        incomingEvent.Context["foo"] = "bar";
        return incomingEvent;
    }
}

var yourPlugin = new SomePlugin()
analytics.Add(yourPlugin)

Example projects using Analytics-CSharp

See how different platforms and languages use Analytics-CSharp in different example projects.

Utility Methods

The Analytics-CSharp utility methods help you work with plugins from the analytics timeline. They include:

There's also the Flush method to help you manage the current queue of events.

Add

The Add method lets you add a plugin to the analytics timeline.

class SomePlugin : Plugin
{
    public override PluginType Type => PluginType.Enrichment;

    public override RawEvent Execute(RawEvent incomingEvent)
    {
        incomingEvent.Context["foo"] = "bar";
        return incomingEvent;
    }
}

var somePlugin = new SomePlugin();
analytics.Add(somePlugin);

Find

The Find method lets you find a registered plugin from the analytics timeline.

var plugin = analytics.Find<SomePlugin>();

Remove

The Remove methods lets you remove a registered plugin from the analytics timeline.

analytics.remove(somePlugin);

Flush

The Flush method lets you force flush the current queue of events regardless of what the flushAt and flushInterval is set to.

analytics.Flush();

Reset

The reset method clears the SDK’s internal stores for the current user and group. This is useful for apps where users log in and out with different identities on the same device over time.

analytics.Reset()

Controlling Upload With Flush Policies

To more granularly control when events are uploaded you can use FlushPolicies. This will override any setting on flushAt and flushInterval, but you can use CountFlushPolicy and FrequencyFlushPolicy to have the same behaviour respectively.

A Flush Policy defines the strategy for deciding when to flush, this can be on an interval, on a certain time of day, after receiving a certain number of events or even after receiving a particular event. This gives you even more flexibility on when to send event to Segment.

To make use of flush policies you can set them in the configuration of the client:

    var configuration = new Configuration("<YOUR WRITE KEY>",
            flushPolicies: new List<IFlushPolicy>
            {
                new CountFlushPolicy(),
                new FrequencyFlushPolicy(),
                new StartupFlushPolicy()
            });
    var analytics = new Analytics(configuration);

That means only the first policy to reach ShouldFlush gets to trigger a flush at a time. In the example above either the event count gets to 5 or the timer reaches 500ms, whatever comes first will trigger a flush.

We have several standard FlushPolicies:

  • CountFlushPolicy triggers whenever a certain number of events is reached
  • FrequencyFlushPolicy triggers on an interval of milliseconds
  • StartupFlushPolicy triggers on client startup only

Adding or removing policies

One of the main advantages of FlushPolicies is that you can add and remove policies on the fly. This is very powerful when you want to reduce or increase the amount of flushes.

For example you might want to disable flushes if you detect the user has no network:

    // listen to network changes
    if (noNetwork) {
        // remove all flush policies to avoid flushing
        analytics.ClearFlushPolicies();

        // or disable analytics completely (including store events)
        analytics.Enable = false
    }
    else {
        analytics.AddFlushPolicy(new CountFlushPolicy(), new FrequencyFlushPolicy());
    }

Creating your own flush policies

You can create a custom FlushPolicy special for your application needs by implementing the IFlushPolicy interface. You can also extend the FlushPolicyBase class that already creates and handles the shouldFlush value reset.

A FlushPolicy only needs to implement 2 methods:

  • Schedule: Executed when the flush policy is enabled and added to the client. This is a good place to start background operations, make async calls, configure things before execution
  • UpdateState: Gets called on every event tracked by your client
  • Unschedule: Called when policy should stop running any scheduled flushes
  • Reset: Called after a flush is triggered (either by your policy, by another policy or manually)

They also have a ShouldFlush observable boolean value. When this is set to true the client will attempt to upload events. Each policy should reset this value to false according to its own logic, although it is pretty common to do it inside the Reset method.

class FlushOnScreenEventsPolicy : IFlushPolicy
{
    private bool _screenEventsSeen = false;

    public bool ShouldFlush() => _screenEventsSeen;

    public void UpdateState(RawEvent @event)
    {
        // Only flush when at least a screen even happens
        if (@event is ScreenEvent)
        {
            _screenEventsSeen = true;
        }
    }

    public void Reset()
    {
        _screenEventsSeen = false;
    }

    public void Schedule(Analytics analytics) {}

    public void Unschedule() {}
}

Handling Errors

You can handle analytics client errors through the analyticsErrorHandler option.

The error handler configuration requires an instance that implements IAnalyticsErrorHandler which will get called whenever an error happens on the analytics client. It will receive a general Exception, but you can check if the exception is a type of AnalyticsError and converts to get more info about the error. Checkout here to see a full list of error types that analytics throws.

You can use this error handling to trigger different behaviours in the client when a problem occurs. For example if the client gets rate limited you could use the error handler to swap flush policies to be less aggressive:

class NetworkErrorHandler : IAnalyticsErrorHandler
{
    private Analytics _analytics;

    public NetworkErrorHandler(Analytics analytics)
    {
        _analytics = analytics;
    }

    public void OnExceptionThrown(Exception e)
    {
        if (e is AnalyticsError error && error.ErrorType == AnalyticsErrorType.NetworkServerLimited)
        {
            _analytics.ClearFlushPolicies();
            // Add less persistent flush policies
            _analytics.AddFlushPolicy(new CountFlushPolicy(1000), new FrequencyFlushPolicy(60 * 60 * 1000));
        }
    }
}

Reporting errors from plugins

Plugins can also report errors to the handler by using the .ReportInternalError function of the analytics client, we recommend using the AnalyticsErrorType.PluginError for consistency, and attaching the exception with the actual exception that was hit:

    try
    {
        // do something;
    }
    catch (Exception e)
    {
        this.Analytics.ReportInternalError(AnalyticsErrorType.PluginError, e, "Error from plugin");
        Analytics.Logger.Log(LogLevel.Error, e);
    }

Listen to Analytics Logs

Besides error handling, you could also provide a static ISegmentLogger to help log and debug as well as error handling. The same log that is reported by ReportInternalError is also reported to this static logger. The static logger also receives more errors and exceptions because it does not require an Analytics instance available. Thus, it's also a good idea to use the logger as an addition to IAnalyticsErrorHandler.

Analytics.Logger = new SegmentLogger();

class SegmentLogger : ISegmentLogger
{
    public void Log(LogLevel logLevel, Exception exception = null, string message = null)
    {
        switch (logLevel)
        {
            case LogLevel.Warning:
            case LogLevel.Information:
            case LogLevel.Debug:
                Console.Out.WriteLine("Message: " + message);
                break;
            case LogLevel.Critical:
            case LogLevel.Trace:
            case LogLevel.Error:
                Console.Error.WriteLine("Exception: " + exception?.StackTrace);
                Console.Error.WriteLine("Message: " + message);
                break;
            case LogLevel.None:
            default:
                break;
        }
    }
}

Customize HTTP Client

The SDK allows you to have full control over the network components. You can easily swap out System.Net with your favorite network library by implementing IHTTPClientProvider and extending HTTPClient. Take a look at this example where the default http client is fully replaced by Unity's UnityWebRequest.

Proxying HTTP Calls

You can also redirect the HTTP calls to your own proxy server by implementing IHTTPClientProvider and extending DefaultHTTPClient:

class ProxyHttpClient : DefaultHTTPClient
{
    public ProxyHttpClient(string apiKey, string apiHost = null, string cdnHost = null) : base(apiKey, apiHost, cdnHost)
    {
    }

    public override string SegmentURL(string host, string path)
    {
        if (host.Equals(_apiHost))
        {
            return "Your proxy api url";
        }
        else
        {
            return "Your proxy cdn url";
        }
    }
}

class ProxyHttpClientProvider : IHTTPClientProvider
{
    public HTTPClient CreateHTTPClient(string apiKey, string apiHost = null, string cdnHost = null)
    {
        return new ProxyHttpClient(apiKey, apiHost, cdnHost);
    }
}

Customize Storage

The SDK also allows you to fully customize your storage strategy. It comes with two standard providers: DefaultStorageProvider that stores data to local disk and InMemoryStorageProvider that stores data all in memory. You can write up your own provider according to your needs, for example, store data to a database or to your own server directly, by implementing IStorage and IStorageProvider. Please refer to the implementation of Storage as example.

Json Library

The SDK supports .netstandard 1.3 and .netstandard 2.0 and auto assembles the internal Json library according to the target framework:

  • on .netstandard 1.3, the SDK uses Newtonsoft Json.NET
  • on .netstandard 2.0, the SDK uses System.Text.Json

Samples

For sample usages of the SDK in specific platforms, checkout the following:

Platform Sample
Asp.Net Setup with dependency injection
Asp.Net MVC Setup with dependency injection
Console Basic setups
Unity Singleton Analytics
Lifecycle plugin
Custom HTTPClient
Xamarin Basic setups
General Custom HTTP client
Custom Storage
Flush Policy
Custom Logger
Custom Error Handler

Compatibility

This library targets .NET Standard 1.3 and .NET Standard 2.0. Checkout here for compatible platforms.

Changelog

View the Analytics-CSharp changelog on GitHub.

Contributing

See the contributing guide to learn how to contribute to the repository and the development workflow.

Integrating with Segment

Interested in integrating your service with us? Check out our Partners page for more details.

Code of Conduct

Before contributing, please also see our code of conduct.

License

MIT License

Copyright (c) 2021 Segment

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.