Skip to content

Commit 32bac14

Browse files
authored
Merge pull request #4623 from segmentio/DOC-679
Analytics-CSharp Library (Public Beta) [DOC-679]
2 parents cad618e + fcc047b commit 32bac14

File tree

6 files changed

+579
-5
lines changed

6 files changed

+579
-5
lines changed

src/_data/sidenav/strat.yml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,3 +225,11 @@ sections:
225225
title: Analytics-Node.js Classic
226226
- path: /connections/sources/catalog/libraries/server/node/migration/
227227
title: Analytics-Node.js Migration Guide
228+
229+
- slug: csharp
230+
section_title: Analytics-CSharp Documentation
231+
section:
232+
- path: /connections/sources/catalog/libraries/server/csharp/
233+
title: Analytics-CSharp
234+
- path: /connections/sources/catalog/libraries/server/csharp/migration-guide/
235+
title: Analytics-CSharp Migration Guide
Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
11
---
22
title: 'Unity Source'
3-
hidden: true
4-
published: false
5-
---
3+
---

src/connections/sources/catalog/libraries/mobile/xamarin/index.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ sourceTitle: 'Xamarin'
44
sourceCategory: 'Mobile'
55
id: wcssVcPJrc
66
---
7-
Our [Xamarin](http://xamarin.com/) Portable Class Library ([PCL](http://developer.xamarin.com/guides/cross-platform/application_fundamentals/pcl/)) is the best way to integrate analytics into your Xamarin application. It lets you record analytics data from your C#, F#, and .NET code, and supports `PCL Profile 4.0 - Profile136`, which targets the following platforms:
7+
Segment's [Xamarin](http://xamarin.com/) Portable Class Library ([PCL](http://developer.xamarin.com/guides/cross-platform/application_fundamentals/pcl/)) is the best way to integrate analytics into your Xamarin application. It lets you record analytics data from your C#, F#, and .NET code, and supports `PCL Profile 4.0 - Profile136`, which targets the following platforms:
88

99
- .NET Framework 4 or later
1010
- Windows Phone 8 or later
@@ -17,7 +17,10 @@ Our [Xamarin](http://xamarin.com/) Portable Class Library ([PCL](http://develope
1717

1818
The library issues requests that hit our servers, and then we route your data to any analytics service you enable on our destinations page. This library is open-source, so you can [check it out on GitHub](https://github.com/segmentio/Analytics.Xamarin).
1919

20-
**Note:** Since Xamarin requires our library to be portable to different builds, we can only enable server-side destinations, as opposed to bundling select native SDKs like we do for iOS and Android. Look for the "Server" icon when selecting destinations. For tools for which we offer both bundled and server-side destinations, like Mixpanel, Amplitude, and Google Analytics, our Xamarin library will only be able to use their server-side functionality.
20+
**Note:** Since Xamarin requires Segment's library to be portable to different builds, Segment can only enable server-side destinations, as opposed to bundling select native SDKs like we do for iOS and Android. Look for the "Server" icon when selecting destinations. For tools for which we offer both bundled and server-side destinations, like Mixpanel, Amplitude, and Google Analytics, Segment's Xamarin library will only be able to use their server-side functionality.
21+
22+
> info "Analytics-CSharp (C#)"
23+
> With Analytics-CSharp, you can add Segment analytics to your C# based app which includes Xamarin. The [Analytics-CSharp library](/docs/connections/sources/catalog/libraries/server/csharp/) is currently in beta and is governed by Segment’s [First Access and Beta terms](https://www.twilio.com/legal/tos){:target="_blank"}. If you'd like to migrate to use Analytics-CSharp, see the [Analytics-CSharp migration guide](/docs/connections/sources/catalog/libraries/server/csharp/migration-guide/).
2124
2225
## Getting Started
2326

Lines changed: 331 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,331 @@
1+
---
2+
title: Analytics for CSharp (C#)
3+
strat: csharp
4+
id:
5+
redirect_from:
6+
- '/connections/sources/catalog/libraries/mobile/unity'
7+
---
8+
9+
With Analytics-CSharp, you can add Segment analytics to your C# based app which includes Unity, Xamarin, .NET. Analytics-CSharp 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. The Analytics-CSharp library is open-source [on GitHub](https://github.com/segmentio/analytics-csharp){:target="_blank"}.
10+
11+
> info ""
12+
> This library is currently in beta and is governed by Segment’s [First Access and Beta terms](https://www.twilio.com/legal/tos){:target="_blank"}.
13+
14+
### Supported platforms
15+
These platforms support Analytics-CSharp:
16+
* .NET/.NET core/.NET framework
17+
* Mono
18+
* Universal Windows platform
19+
* Xamarin
20+
* iOS
21+
* Mac
22+
* Android
23+
* Unity
24+
* iOS
25+
* Android
26+
* PC, Mac, Linux
27+
28+
## Getting started
29+
30+
> info ""
31+
> If you'd like to migrate to Analytics-CSharp from a different library, follow the steps in the [Analytics-CSharp migration guide](/docs/connections/sources/catalog/libraries/server/csharp/migration-guide/).
32+
33+
To get started with the Analytics-CSharp library:
34+
35+
1. Create a Source in Segment.
36+
1. Go to **Connections > Sources > Add Source**.
37+
2. Search for *Xamarin, Unity, or .NET* (whichever source you want to use) and click **Add Source**. **Note:** There is no CSharp source. To use Analytics-CSharp, use either Xamarin, Unity, or .NET as your source.
38+
2. Add the Analytics dependency to your project.
39+
40+
```git
41+
dotnet add package Segment.Analytics.CSharp --version <LATEST_VERSION>
42+
```
43+
<br>**Note:** Analytics-CSharp is distributed through NuGet. Check out other installation options [here](https://www.nuget.org/packages/Segment.Analytics.CSharp/){:target="_blank"}. For Unity, Analytics-Chsharp is distributed through [OpenUPM](https://openupm.com/packages/com.segment.analytics.csharp/?subPage=readme){:target="_blank"}.
44+
45+
3. Initialize and configure the client.
46+
47+
```c#
48+
// NOTE: to make Analytics stateless/in-memory,
49+
// add `InMemoryStorageProvider` to the configuration
50+
var configuration = new Configuration("<YOUR WRITE KEY>",
51+
flushAt: 1,
52+
flushInterval: 10);
53+
var analytics = new Analytics(configuration);
54+
```
55+
56+
These are the options you can apply to configure the client:
57+
58+
Option Name | Description
59+
----------- | -----------
60+
`writeKey` *required* | This is your Segment write key.
61+
`apiHost` | The default is set to `api.segment.io/v1`. <br> This sets a default API Host to which Segment sends events.
62+
`autoAddSegmentDestination` | The default is 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.
63+
`defaultSettings` | The default is set to `{}`. <br> The settings object used as fallback in case of network failure.
64+
`flushAt` | The default is set to `20`. <br> The count of events at which Segment flushes events.
65+
`flushInterval` | The default is set to `30` seconds. <br> The interval in seconds at which Segment flushes events.
66+
`exceptionHandler` | Use to set an exception handler to handle errors happened in async methods within the analytics scope.
67+
`storageProvider` | Use to set how you want your data to be stored. <br> `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`.
68+
69+
## Tracking Methods
70+
71+
Once you've installed the Analytics-CSharp library, you can start collecting data through Segment's tracking methods:
72+
- [Identify](#identify)
73+
- [Track](#track)
74+
- [Screen](#screen)
75+
- [Page](#page)
76+
- [Group](#group)
77+
78+
> info ""
79+
> 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.
80+
81+
### Identify
82+
The [Identify](/docs/connections/spec/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.
83+
84+
```c#
85+
analytics.Identify("user-123", new JsonObject {
86+
["username"] = "MisterWhiskers",
87+
["email"] = "[email protected]",
88+
["plan"] = "premium"
89+
});
90+
```
91+
92+
### Track
93+
The [Track](/docs/connections/spec/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.
94+
95+
```c#
96+
analytics.Track("View Product", new JsonObject {
97+
["productId"] = 123,
98+
["productName"] = "Striped trousers"
99+
});
100+
```
101+
102+
### Screen
103+
The [Screen](/docs/connections/spec/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.
104+
105+
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.
106+
107+
Not all integrations support screen. When it's not supported explicitly, the screen method tracks as an event with the same parameters.
108+
109+
```c#
110+
analytics.Screen("ScreenName", new JsonObject {
111+
["productSlug"] = "example-product-123"
112+
});
113+
```
114+
115+
### Page
116+
The [Page](/docs/connections/spec/page/) method lets you record whenever a user sees a page in your web app, along with optional extra information about the page.
117+
118+
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.
119+
120+
Not all integrations support page. When it's not supported explicitly, the page method tracks as an event with the same parameters.
121+
122+
```c#
123+
analytics.Page("PageName", new JsonObject {
124+
["productSlug"] = "example-product-123"
125+
});
126+
```
127+
128+
### Group
129+
The [Group](/docs/connections/spec/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.
130+
131+
```c#
132+
analytics.Group("user-123", new JsonObject {
133+
["username"] = "MisterWhiskers",
134+
["email"] = "[email protected]",
135+
["plan"] = "premium"
136+
});
137+
```
138+
## Plugin Architecture
139+
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.
140+
141+
Plugins are run through a timeline, which executes in order of insertion based on their entry types. Segment has these 5 entry types:
142+
143+
| Type | Details |
144+
|---------------| ---------------------------------------------------------------------------------------------- |
145+
| `Before` | Executes before event processing begins. |
146+
| `Enrichment` | Executes as the first level of event processing. |
147+
| `Destination` | Executes as events begin to pass off to destinations. |
148+
| `After` | Executes after all event processing completes. You can use this to perform cleanup operations. |
149+
| `Utility` | Executes only with manual calls such as Logging. |
150+
151+
### Fundamentals
152+
There are 3 basic types of plugins that you can use as a foundation for modifying functionality. They are: [`Plugin`](#plugin), [`EventPlugin`](#eventplugin), and [`DestinationPlugin`](#destinationplugin).
153+
154+
#### Plugin
155+
`Plugin` acts on any event payload going through the timeline.
156+
157+
For example, if you want to add something to the context object of any event payload as an enrichment:
158+
159+
```c#
160+
class SomePlugin : Plugin
161+
{
162+
public override PluginType Type => PluginType.Enrichment;
163+
public override RawEvent Execute(RawEvent incomingEvent)
164+
{
165+
incomingEvent.Context["foo"] = "bar";
166+
return incomingEvent;
167+
}
168+
}
169+
```
170+
171+
#### EventPlugin
172+
`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.
173+
174+
For example, if you only want to act on `track` & `identify` events:
175+
176+
```c#
177+
class SomePlugin : EventPlugin
178+
{
179+
public override PluginType Type => PluginType.Enrichment;
180+
public override IdentifyEvent Identify(IdentifyEvent identifyEvent)
181+
{
182+
// code to modify identify event
183+
return identifyEvent;
184+
}
185+
public override TrackEvent Track(TrackEvent trackEvent)
186+
{
187+
// code to modify track event
188+
return trackEvent;
189+
}
190+
}
191+
```
192+
193+
#### DestinationPlugin
194+
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.
195+
196+
For example, if you want to implement a device-mode destination plugin for Amplitude, you can use this:
197+
198+
```c#
199+
class AmplitudePlugin : DestinationPlugin
200+
{
201+
public override string Key =>
202+
"Amplitude"; // This is the name of the destination plugin, it is used to retrieve settings internally
203+
private Amplitude amplitudeSDK: // This is an instance of the partner SDK
204+
public AmplitudePlugin()
205+
{
206+
amplitudeSDK = Amplitude.instance;
207+
amplitudeSDK.initialize(applicationContext, "API_KEY");
208+
}
209+
/*
210+
* Implementing this function allows this plugin to hook into any track events
211+
* coming into the analytics timeline
212+
*/
213+
public override TrackEvent Track(TrackEvent trackEvent)
214+
{
215+
amplitudeSDK.logEvent(trackEvent.Event);
216+
return trackEvent;
217+
}
218+
}
219+
```
220+
221+
### Advanced concepts
222+
223+
- `configure(Analytics)`: Use this function to set up your plugin. This implicitly calls once the plugin registers.
224+
- `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()`.
225+
- `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`:
226+
227+
```c#
228+
class AmplitudeEnrichment : Plugin
229+
{
230+
public override PluginType Type => PluginType.Enrichment;
231+
public override RawEvent Execute(RawEvent incomingEvent)
232+
{
233+
incomingEvent.Context["foo"] = "bar";
234+
return incomingEvent;
235+
}
236+
}
237+
var amplitudePlugin = new AmplitudePlugin(); // add amplitudePlugin to the analytics client
238+
analytics.Add(amplitudePlugin);
239+
amplitudePlugin.Add(new AmplitudeEnrichment()); // add enrichment plugin to amplitude timeline
240+
```
241+
242+
## Adding a plugin
243+
Adding plugins enable you to modify your analytics implementation to best fit your needs. You can add a plugin using this:
244+
245+
```c#
246+
var yourPlugin = new SomePlugin()
247+
analytics.Add(yourPlugin)
248+
```
249+
250+
Though you can add plugins anywhere in your code, it's best to implement your plugin when you configure the client.
251+
252+
Here's an example of adding a plugin to the context object of any event payload as an enrichment:
253+
254+
```c#
255+
class SomePlugin : Plugin
256+
{
257+
public override PluginType Type => PluginType.Enrichment;
258+
public override RawEvent Execute(RawEvent incomingEvent)
259+
{
260+
incomingEvent.Context["foo"] = "bar";
261+
return incomingEvent;
262+
}
263+
}
264+
var yourPlugin = new SomePlugin()
265+
analytics.Add(yourPlugin)
266+
```
267+
268+
### Example projects using Analytics-CSharp
269+
See how other platforms and languages use Analytics-CSharp in different [example projects](https://github.com/segmentio/Analytics-CSharp/tree/main/Samples){:target="_blank"}.
270+
271+
## Utility Methods
272+
The Analytics-CSharp utility methods help you work with plugins from the analytics timeline. They include:
273+
- [Add](#add)
274+
- [Find](#find)
275+
- [Remove](#remove)
276+
- [Reset](#reset)
277+
278+
There's also the [Flush](#flush) method to help you manage the current queue of events.
279+
280+
### Add
281+
The Add method lets you add a plugin to the analytics timeline.
282+
283+
```c#
284+
class SomePlugin : Plugin
285+
{
286+
public override PluginType Type => PluginType.Enrichment;
287+
public override RawEvent Execute(RawEvent incomingEvent)
288+
{
289+
incomingEvent.Context["foo"] = "bar";
290+
return incomingEvent;
291+
}
292+
}
293+
var somePlugin = new SomePlugin();
294+
analytics.Add(somePlugin);
295+
```
296+
297+
### Find
298+
The Find method lets you find a registered plugin from the analytics timeline.
299+
300+
```c#
301+
var plugin = analytics.Find<SomePlugin>();
302+
```
303+
304+
### Remove
305+
The Remove methods lets you remove a registered plugin from the analytics timeline.
306+
307+
```c#
308+
analytics.remove(somePlugin);
309+
```
310+
311+
### Flush
312+
The Flush method lets you force flush the current queue of events regardless of what the `flushAt` and `flushInterval` is set to.
313+
314+
```c#
315+
analytics.Flush();
316+
```
317+
318+
### Reset
319+
The `reset` method clears the SDKs 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.
320+
321+
```c#
322+
analytics.Reset()
323+
```
324+
325+
## Compatibility
326+
This library targets `.NET Standard 2.0`. See the [list of compatible platforms](https://docs.microsoft.com/en-us/dotnet/standard/net-standard?tabs=net-standard-2-0){:target="_blank"}.
327+
328+
## Changelog
329+
[View the Analytics-CSharp changelog on GitHub](https://github.com/segmentio/analytics-csharp/releases){:target="_blank"}.
330+
331+

0 commit comments

Comments
 (0)