Segment.Analytics.CSharp 1.0.4

There is a newer version of this package available.
See the version list below for details.
dotnet add package Segment.Analytics.CSharp --version 1.0.4                
NuGet\Install-Package Segment.Analytics.CSharp -Version 1.0.4                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Segment.Analytics.CSharp" Version="1.0.4" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Segment.Analytics.CSharp --version 1.0.4                
#r "nuget: Segment.Analytics.CSharp, 1.0.4"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Segment.Analytics.CSharp as a Cake Addin
#addin nuget:?package=Segment.Analytics.CSharp&version=1.0.4

// Install Segment.Analytics.CSharp as a Cake Tool
#tool nuget:?package=Segment.Analytics.CSharp&version=1.0.4                

Analytics-CSharp

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: This project is currently only available in Pilot phase and is covered by Segment's First Access & Beta Preview Terms. We encourage you to try out this new library. Please provide feedback via Github issues/PRs, and feel free to submit pull requests.

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.

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

    Analytics-CSharp is distributed via NuGet. Check other installation options here.

  3. Initialize and configure the client.

        // NOTE: persistentDataPath is different on different platform
        // for Xamarin use: Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
        // for Unity use: Application.persistentDataPath
        var configuration = new Configuration("<YOUR WRITE KEY>",
                persistentDataPath: "<PATH TO STORE DATA>",
                flushAt: 1,
                flushInterval: 10);
        var analytics = new Analytics(configuration);
    

    <br>These are the options you can apply to configure the client:

Option Name Description
writeKey required This is your Segment write key.
persistentDataPath requried This is the path where Segment stores your data. <br> for Xamarin use: Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData). <br> for Unity use: Application.persistentDataPath
apiHost Default set to api.segment.io/v1. <br> This sets a default API Host to which Segment sends events.
autoAddSegmentDestination Default set to true. <br> This automatically adds the Segment Destination plugin. You can set this to false if you want to manually add the Segment Destination plugin.
defaultSettings Default set to {}. <br> The settings object used as fallback in case of network failure.
flushAt Default set to 20. <br> The count of events at which Segment flushes events.
flushInterval Default set to 30 (seconds). <br> The interval in seconds at which Segment flushes events.
exceptionHandler set a an exception handler to handle errors happened in async methods within the analytics scope

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"] = "hello@test.com",
    ["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"
});

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"] = "hello@test.com",
    ["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()

Compatibility

This library targets .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.
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on Segment.Analytics.CSharp:

Package Downloads
Mediacom.Common.Code

Common code libraries

SIL.DesktopAnalytics

Wrapper around segment.com's Analytics.net specifically for desktop apps (instead of servers).

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.5.0 11,880 9/27/2024
2.4.2 59,916 6/12/2024
2.4.1 4,039 5/14/2024
2.4.0 3,590 5/3/2024
2.3.5 3,440 4/22/2024
2.3.4 13,297 3/4/2024
2.3.3 3,515 2/8/2024
2.3.2 371 1/30/2024
2.3.1 18,703 10/6/2023
2.3.1-alpha.2 80 10/6/2023
2.3.1-alpha.1 77 10/6/2023
2.3.0 2,772 9/22/2023
2.3.0-alpha.2 86 9/20/2023
2.3.0-alpha.1 1,172 8/11/2023
2.2.0 15,981 6/22/2023
2.1.1 3,428 5/15/2023
2.1.0 919 4/27/2023
2.0.0 1,260 3/21/2023
2.0.0-alpha1 578 3/9/2023
2.0.0-alpha.3 98 3/17/2023
2.0.0-alpha.2 81 3/9/2023
2.0.0-alpha.1 87 3/9/2023
1.0.4 2,998 11/17/2022
1.0.3 885 10/17/2022