segmentio / Analytics-CSharp

The hassle-free way to add Segment analytics to your C# written app (.Net/Xamarin/Unity).
MIT License
21 stars 8 forks source link

[Question] Setting Context #68

Closed joshjbradley closed 1 year ago

joshjbradley commented 1 year ago

Hello,

Looking at migrating from from Analytics.Net and wondering how to set the context object when making a Track call. In Analytics.Net we were able to do this when calling the the Track method by applying the context fields to the Options object for example

options.SetContext(new Context()
{
    ["traits"] = traits
});

_analytics.Track(cdpId, "MyEvent", properties, options);

This does not seem to be on option with Analytics-CSharp it seems the way to do it now would be to use a custom plugin, is that correct?

wenxi-zeng commented 1 year ago

hey @joshjbradley, that is correct. you'll have to do it via a plugin like the following:

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

    public override RawEvent Execute(RawEvent incomingEvent)
    {
        RawEvent modified = incomingEvent;

        // toggle on/off integration
        modified.Integrations["Appsflyer"] = true;

        // update AnalyticsContext
        modified.Context["traits"] = new JsonObject();

        return modified;
    }
}

since context is meant for all events, so it makes sense to do it via a plugin. if it's for one shot, it's better to put it on properties. please let us know your use case if you feel this does not solve your problem.

wenxi-zeng commented 1 year ago

or you could use the following plugin to attach options differently for each event:

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

    public override RawEvent Execute(RawEvent incomingEvent)
    {
        if (incomingEvent is not TrackEvent modified || modified.Properties["traits"] == null)
        {
            return incomingEvent;
        }

        modified.Context["traits"] = modified.Properties["traits"];
        modified.Properties.Remove("traits");

        return modified;
    }
}

and then track it as following:

analytics.Add(new UpdateContextPlugin());
analytics.Track("MyEvent", new JsonObject
{
    ["traits"] = new JsonObject()
});