C# SDK
Welcome to the developer documentation for the Kameleoon C# SDK! Use our SDK to run experiments on your back-end .NET application server. It is easy to integrate our SDK into your web-application, and its memory and network usage are low.
Getting started: For help getting started, see the developer guide.
SDK methods: For the full reference documentation of the C# SDK methods, see the reference section.
Changelog: Latest version of the C# SDK: 4.8.1 changelog.
Developer guide
Getting started
This guide is designed to help you integrate our SDK into your C# applications.
Starter kit
If you're just getting started with Kameleoon, we provide a starter kit and demo application to test the SDK and learn how it works. The starter kit includes a fully configured app with examples demonstrating how you might use the SDK methods in your app. You can find the starter kit, the demo application and detailed instructions on how to use it at Starter kit for .NET
Install the C# client
You can use the NuGet, .NET CLI, or Paket package manager to install the C# client.
- NuGet Package Manager
- .NET CLI
- Paket CLI
Install-Package KameleoonClient -Version 4.8.0
dotnet add package KameleoonClient --version 4.8.0
paket add KameleoonClient --version 4.8.0
Additional configuration
Create a .properties
configuration file to provide credentials and customize the SDK behavior. You can also download a sample configuration file. Save this file in the default path /etc/kameleoon/client-csharp.conf
. If you place it in another location, you'll need to pass the path as an argument to KameleoonClientFactory.Create()
. With the current version of the C# SDK, these are the available keys.
The following table shows the available properties that you can set:
Key | Description |
---|---|
client_id | Required for authentication to the Kameleoon service. To find your client_id , see the API credentials documentation. |
client_secret | Required for authentication to the Kameleoon service. To find your client_secret , see the API credentials documentation. |
session_duration_minute | Designates the time interval (in minutes) that Kameleoon stores the visitor and their associated data in memory (RAM). Note that increasing the session duration increases the amount of RAM that needs to be allocated to store visitor data. The default session duration is 30 minutes. |
refresh_interval_minute | Specifies the refresh interval, in minutes, that the SDK fetches the configuration for the active experiments and feature flags. The value determines the maximum time it takes to propagate changes, such as activating or deactivating feature flags or launching experiments, to your production servers. If left unspecified, the default interval is set to 60 minutes. Additionally, we offer a streaming mode that uses server-sent events (SSE) to push new configurations to the SDK automatically and apply new configurations in real-time, without any delays. |
default_timeout_millisecond | Specifies the timeout, in milliseconds, for network requests from the SDK. Set the value to 30 seconds or more if you do not have a stable connection. The default value is 10000 ms. Some methods have an additional parameter that you can use to override the default timeout for that particular method. If you do not specify the timeout for a method explicitly, the SDK uses this default value. |
tracking_interval_millisecond | Specifies the interval for tracking requests, in milliseconds. All visitors who were evaluated for any feature flag or had data flushed will be included in this tracking request, which is performed once per interval. The minimum value is 100 ms and the maximum value is 1000 ms, which is also the default value. |
environment | Environment from which a feature flag’s configuration is to be used. The value can be production , staging , development . The default environment value is production . See the managing environments article for details. |
top_level_domain | The current top-level domain for your website. Use the format example.com . Don't include https:// , www , or other subdomains. Kameleoon uses this information to set the corresponding cookie on the top-level domain. This field is mandatory. |
proxy_host | Sets the proxy host for all outgoing server calls made by the SDK. |
Initialize the Kameleoon client
After you've installed the SDK into your application and configured your credentials and SDK behavior, create the Kameleoon client in your application code. For example:
using Kameleoon;
string siteCode = "a8st4f59bj";
try {
// Read from default configuration path: "/etc/kameleoon/client-csharp.conf"
IKameleoonClient kameleoonClient = KameleoonClientFactory.Create(siteCode);
} catch (KameleoonException.SiteCodeIsEmpty e) {
// indicates that provided site code is empty
} catch (KameleoonException.ConfigCredentialsInvalid exception) {
// indicates that provided clientId / clientSecret are not valid
}
try {
IKameleoonClient kameleoonClient = KameleoonClientFactory.Create(siteCode, "custom/file/path/client-csharp.conf");
} catch (KameleoonException.SiteCodeIsEmpty e) {
// indicates that provided site code is empty
} catch (KameleoonException.ConfigCredentialsInvalid exception) {
// indicates that provided clientId / clientSecret are not valid
}
try {
KameleoonClientConfig config = new KameleoonClientConfig(
clientId: "<clientId>", // mandatory
clientSecret: "<clientId>", // mandatory
refreshIntervalMinute: 60, // in minutes, optional (60 minutes by default)
sessionDurationMinute: 30, // in minutes, optional (30 minutes by default)
defaultTimeoutMillisecond: 10_000, // in milliseconds, optional (10000 ms by default)
trackingIntervalMilliseconds: 1000, // in milliseconds, optional (1000 ms by default)
environment: "development", // optional
topLevelDomain: "example.com", // mandatory if you use hybrid mode (engine or web experiments)
proxyHost: "proxy.host.com", // optional
);
IKameleoonClient kameleoonClient = KameleoonClientFactory.Create(siteCode, config);
} catch (KameleoonException.SiteCodeIsEmpty e) {
// indicates that provided site code is empty
} catch (KameleoonException.ConfigCredentialsInvalid exception) {
// indicates that provided clientId / clientSecret are not valid
}
A IKameleoonClient
is a singleton object that acts as a bridge between your application and the Kameleoon platform. It includes all the methods and properties you need to run an experiment.
It's your responsibility as the app developer to ensure your application code uses the correct logic within the context of A/B testing via Kameleoon. It's a best practice to assume that you can exclude the current visitor from the experiment if the experiment has not yet been launched. This is easy to do, because this practice corresponds to the default and reference variation logic.
Activating a feature flag
Assigning a unique ID to a user
To assign a unique ID to a user, you can use the GetVisitorCode()
method. If a visitor code doesn’t exist (from the request headers cookie), the method generates a random unique ID or uses a defaultVisitorCode
that you would have generated. The ID is then set in a response headers cookie.
If you are using Kameleoon in Hybrid mode, calling the GetVisitorCode()
method ensures that the unique ID (visitor code) is shared between the application file (kameleoon.js) and the SDK.
Retrieving a flag configuration
To implement a feature flag in your code, you must first create the feature flag in your Kameleoon account.
To determine the status or variation of a feature flag for a specific user, you should use the GetVariation()
or IsFeatureActive()
method to retrieve the configuration based on the featureKey
.
The GetVariation()
method handles both simple feature flags with ON/OFF states and more complex flags with multiple variations. The method retrieves the appropriate variation for the user by checking the feature rules, assigning the variation, and returning it based on the featureKey
and visitorCode
.
The IsFeatureActive()
method can be used if you want to retrieve the configuration of a simple feature flag that has only an ON or OFF state, as opposed to more complex feature flags with multiple variations or targeting options.
If your feature flag has associated variables (such as specific behaviors tied to each variation) GetVariation()
also enables you to access the Variation
object, which provides details about the assigned variation and its associated experiment. This method checks whether the user is targeted, finds the visitor’s assigned variation, and saves it to storage. When track=true
, the SDK will send the exposure event to the specified experiment on the next tracking request, which is automatically triggered based on the SDK’s tracking_interval_millisecond
. By default, this interval is set to 1000 milliseconds (1 second).
The GetVariation()
method allows you to control whether tracking is done. If track=false
, no exposure events will be sent by the SDK. This is useful if you prefer not to track data through the SDK and instead rely on client-side tracking managed by the Kameleoon engine, for example. Additionally, setting track=false
is helpful when using the GetVariations()
method, where you might only need the variations for all flags without triggering any tracking events. If you want to know more about how tracking works, view this article
Adding data points to target a user or filter / breakdown visits in reports
To target a user, ensure you've added relevant data points to their profile before retrieving the feature variation or checking if the flag is active. Use the AddData()
method to add these data points to the user's profile.
To retrieve data points that have been collected on other devices or to access past data points about a user (which would have been collected client-side if you are using Kameleoon in Hybrid mode), use the GetRemoteVisitorData()
method. This method asynchronously fetches data from our servers. However, it is important you call GetRemoteVisitorData()
before retrieving the variation or checking if the feature flag is active, as this data might be required to assign a user to a given variation of a feature flag.
To learn more about available targeting conditions, read our detailed article on the subject.
Additionally, the data points you add to the visitor profile will be available when analyzing your experiments, allowing you to filter and break down your results by factors like device and browser. Kameleoon Hybrid mode automatically collects a variety of data points on the client-side, making it easy to break down your results based on these pre-collected data points. See the complete list here.
If you need to track additional data points beyond what's automatically collected, you can use Kameleoon's Custom Data feature. Custom Data allows you to capture and analyze specific information relevant to your experiments. Don't forget to call the Flush()
method to send the collected data to Kameleoon servers for analysis.
To ensure your results are accurate, it's recommended to filter out bots by using the UserAgent
data type.
Tracking goal conversions
When a user completes a desired action (such as making a purchase), it is recorded as a conversion. To track conversions, use the TrackConversion()
method and provide the required visitorCode
and goalId
parameters.
The conversion tracking request will be sent along with the next scheduled tracking request, which the SDK sends at regular intervals (defined by tracking_interval_millisecond
). If you prefer to send the request immediately, use the Flush()
method with the parameter instant=true
.
Sending events to analytics solutions
To track conversions and send exposure events to your customer analytics solution, you must first implement Kameleoon in Hybrid mode. Then, use the GetEngineTrackingCode()
method.
The GetEngineTrackingCode()
method retrieves the unique tracking code required to send exposure events to your analytics solution. Using this method allows you to record events and send them to your desired analytics platform.
Cross-device experimentation
To support visitors who access your app from multiple devices, Kameleoon allows you to synchronize previously collected visitor data across each of the visitor's devices and reconcile their visit history across devices through cross-device experimentation.
Synchronizing custom data across devices
If you want to synchronize your Custom Data across multiple devices, Kameleoon provides a custom data synchronization mechanism.
To synchronize visitor data across multiple devices, Kameleoon provides a native synchronization mechanism. To use this feature, you need to create a Kameleoon custom data and set as a value the visitor identifier that uniquely identifies this user across multiple devices (internal user ID). The custom data should be configured as follows:
- Scope: Visitor
- Option "Use this custom data as a unique identifier for cross-device matching" turned ON.
After the custom data is set up, calling GetRemoteVisitorData()
makes the latest data accessible on any device.
See the following example of data synchronization between two devices:
// In this example Custom data with index `90` was set to "Visitor" scope on Kameleoon Platform.
const int VisitorScopeCustomDataIndex = 90;
kameleoonClient.AddData(visitorCode, new CustomData(VisitorScopeCustomDataIndex, "your data"));
kameleoonClient.Flush(visitorCode);
// Before working with the data, call the `GetRemoteVisitorData` method.
await kameleoonClient.GetRemoteVisitorData(visitorCode);
// After that the SDK on Device B will have an access to CustomData of Visitor scope defined on Device A.
// So "your data" will be available for targeting and tracking for the visitor.
Using custom data for session merging
Cross-device experimentation allows you to combine a visitor's history across each of their devices (history reconciliation). One of the powerful features that history reconciliation provides is the ability to merge different visitors sessions into one. To reconcile visit history, you can use CustomData
to provide a unique identifier for the visitor.
Follow the activating cross-device history reconciliation guide to set up your custom data on the Kameleoon platform
When your custom data is set up, you can use it in your code to merge a visitor's sessions.
Sessions with the same identifier will always see the same experiment variation and will be displayed as a single visitor in the Visitor view of your experiment's result pages.
The SDK configuration ensures that associated sessions always see the same variation of the experiment.
Afterwards, you can use the SDK normally. The following methods that may be helpful in the context of session merging:
GetRemoteVisitorData()
with addedUniqueIdentifier(true)
- to retrieve data for all linked visitors.TrackConversion()
orFlush()
with addedUniqueIdentifier(true)
data - to track some data for specific visitor that is associated with another visitor.
As the custom data you use as the identifier must be set to Visitor scope, you need to use cross-device custom data synchronization to retrieve the identifier with the GetRemoteVisitorData()
method on each device.
Here's an example of how to use custom data for session merging.
// In this example, `91` represents the index of the Custom Data
// configured as a unique identifier on Kameleoon Platform.
const int MappingIndex = 91;
const string FeatureKey = "ff123";
// 1. Before the visitor is authenticated
// Retrieve the variation for an unauthenticated visitor.
// Assume `anonymousVisitorCode` is the randomly generated ID for that visitor.
Variation anonymousVariation = kameleoonClient.GetVariation(anonymousVisitorCode, FeatureKey);
// 2. After the visitor is authenticated
// Assume `userId` is the visitor code of the authenticated visitor.
kameleoonClient.AddData(anonymousVisitorCode, new CustomData(MappingIndex, userId));
kameleoonClient.Flush(anonymousVisitorCode, instant=true);
// Indicate that `userId` is a unique identifier.
kameleoonClient.AddData(userId, new UniqueIdentifier(true));
// 3. After the visitor has been authenticated
// Retrieve the variation for the `userId`, which will match the anonymous visitor code's variation.
Variation userVariation = kameleoonClient.GetVariation(userId, FeatureKey);
bool isSameVariation = userVariation.Key == anonymousVariation.Key; // true
// The `userId` and `anonymousVisitorCode` are now linked and tracked as a single visitor.
kameleoonClient.TrackConversion(userId, 123, 10.0);
// Also, the linked visitors will share all fetched remote visitor data.
await kameleoonClient.GetRemoteVisitorData(userId);
In this example, we have an application with a login page. Since we don't know the user ID at the moment of login, we use an anonymous visitor identifier generated by the GetVisitorCode()
method. After the user logs in, we can associate the anonymous visitor with the user ID and use it as a unique identifier for the visitor.
Targeting conditions
The Kameleoon SDKs support a variety of predefined targeting conditions that you can use to target users in your campaigns. For the list of conditions this SDK supports, see use visit history to target users.
You can also use your own external data to target users.
Logging
The SDK generates logs to reflect various internal processes and issues.
Log levels
The SDK supports configuring limiting logging by a log level.
// The `None` log level allows no logging.
Kameleoon.Logging.KameleoonLogger.LogLevel = Kameleoon.Logging.LogLevel.None;
// The `Error` log level allows to log only issues that may affect the SDK's main behaviour.
Kameleoon.Logging.KameleoonLogger.LogLevel = Kameleoon.Logging.LogLevel.Error;
// The `Warning` log level allows to log issues which may require an attention.
// It extends the `Error` log level.
// The `Warning` log level is a default log level.
Kameleoon.Logging.KameleoonLogger.LogLevel = Kameleoon.Logging.LogLevel.Warning;
// The `Info` log level allows to log general information on the SDK's internal processes.
// It extends the `Warning` log level.
Kameleoon.Logging.KameleoonLogger.LogLevel = Kameleoon.Logging.LogLevel.Info;
// The `Debug` log level allows to log extra information on the SDK's internal processes.
// It extends the `Info` log level.
Kameleoon.Logging.KameleoonLogger.LogLevel = Kameleoon.Logging.LogLevel.Debug;
Custom handling of logs
The SDK writes its logs to the console output by default. This behaviour can be overridden.
Logging limiting by a log level is performed apart from the log handling logic.
class CustomLogger : Kameleoon.Logging.ILogger
{
private readonly Microsoft.Extensions.Logging.ILogger inner;
public CustomLogger(Microsoft.Extensions.Logging.ILogger inner)
{
this.inner = inner;
}
// `Log` method accepts logs from the SDK
public void Log(Kameleoon.Logging.LogLevel level, string message)
{
// Custom log handling logic here. For example:
switch (level)
{
case Kameleoon.Logging.LogLevel.Error:
Microsoft.Extensions.Logging.LoggerExtensions.LogError(inner, message);
break;
case Kameleoon.Logging.LogLevel.Warning:
Microsoft.Extensions.Logging.LoggerExtensions.LogWarning(inner, message);
break;
case Kameleoon.Logging.LogLevel.Info:
Microsoft.Extensions.Logging.LoggerExtensions.LogInformation(inner, message);
break;
case Kameleoon.Logging.LogLevel.Debug:
Microsoft.Extensions.Logging.LoggerExtensions.LogDebug(inner, message);
break;
}
}
}
// Log level filtering is applied separately from log handling logic.
// The custom logger will only accept logs that meet or exceed the specified log level.
// Ensure the log level is set correctly.
Kameleoon.Logging.KameleoonLogger.LogLevel = Kameleoon.Logging.LogLevel.Debug; // Optional, defaults to `LogLevel.Warning`.
Kameleoon.Logging.KameleoonLogger.Logger = new CustomLogger();
Reference
This is the full reference documentation of the C# SDK.
Initialization
Create()
The starting point for using the SDK is the initialization step. All of your app's interaction with the SDK is done through an instance of the KameleoonClient
class in Kameleoon.IKameleoonClient
. Create this object using the Kameleoon.KameleoonClientFactory Create()
static method.
Arguments
Name | Type | Description |
---|---|---|
siteCode | string | This is a unique key of the Kameleoon project you are using with the SDK. This field is mandatory. |
configurationFilePath | string | Path to the SDK configuration file. This field is optional and set to /etc/kameleoon/client-csharp.conf by default. |
kameleoonConfig | KameleoonClientConfig | Configuration SDK object that you can pass instead of using a configuration file. This field is optional. |
Return value
Type | Description |
---|---|
IKameleoonClient | An instance of the KameleoonClient class, that will be used to manage your experiments and feature flags. |
Exceptions thrown
Type | Description |
---|---|
KameleoonException.ConfigCredentialsInvalid | Exception indicating that the requested credentials were not provided in the configuration file or as arguments on the method. |
KameleoonException.SiteCodeIsEmpty | Exception indicating that the specified site code is empty string which is invalid value. |
Example code
using Kameleoon;
string siteCode = "a8st4f59bj";
try {
// Read from default configuration path: "/etc/kameleoon/client-csharp.conf"
IKameleoonClient kameleoonClient = KameleoonClientFactory.Create(siteCode);
} catch (KameleoonException.SiteCodeIsEmpty e) {
// indicates that provided site code is empty
} catch (KameleoonException.ConfigCredentialsInvalid exception) {
// indicates that provided clientId / clientSecret are not valid
}
try {
IKameleoonClient kameleoonClient = KameleoonClientFactory.Create(siteCode, "custom/file/path/client-csharp.conf");
} catch (KameleoonException.SiteCodeIsEmpty e) {
// indicates that provided site code is empty
} catch (KameleoonException.ConfigCredentialsInvalid exception) {
// indicates that provided clientId / clientSecret are not valid
}
try {
KameleoonClientConfig config = new KameleoonClientConfig(
clientId: "<clientId>", // mandatory
clientSecret: "<clientId>", // mandatory
refreshIntervalMinute: 60, // in minutes, optional (60 minutes by default)
sessionDurationMinute: 30, // in minutes, optional (30 minutes by default)
defaultTimeoutMillisecond: 10_000, // in milliseconds, optional (10000 ms by default)
trackingIntervalMilliseconds: 1000, // in milliseconds, optional (1000 ms by default)
environment: "development", // optional
topLevelDomain: "example.com", // mandatory if you use hybrid mode (engine or web experiments)
proxyHost: "proxy.host.com" // optional
);
IKameleoonClient kameleoonClient = KameleoonClientFactory.Create(siteCode, config);
} catch (KameleoonException.SiteCodeIsEmpty e) {
// indicates that provided site code is empty
} catch (KameleoonException.ConfigCredentialsInvalid exception) {
// indicates that provided clientId / clientSecret are not valid
}
WaitInit()
WaitInit()
awaits the initialization of the Kameleoon client. This method allows you to check if the client has been successfully initialized before proceeding with other operations.
Return value
Type | Description |
---|---|
Task | The task will complete when the client has been successfully initialized. |
Exceptions thrown
Type | Description |
---|---|
Exception | Exception indicating that client is not initialized properly and cannot be used yet. |
Example code
using static Kameleoon;
try {
await kameleoonClient.WaitInit();
} catch (Exception exception) {
// indicates that client could not be initialized due to the thrown exception.
}
Feature flags and variations
IsFeatureActive()
- 📨 Sends Tracking Data to Kameleoon (depending on the
track
parameter)
This method was previously named ActivateFeature
, which was removed in SDK version 4.0.0
.
To activate a feature toggle, call the IsFeatureActive
method of our SDK.
This method takes a visitorCode and featureKey (or featureID) as mandatory arguments to check if the specified feature will be active for a given user.
If such a user has never been associated with this feature flag, the SDK returns a boolean value randomly (true if the user should have this feature or false if not). If a user with a given visitorCode is already registered with this feature flag, it will detect the previous featureFlag value.
You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.
If you specify a visitorCode
, the IsFeatureActive()
method uses it as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitorCode
and set the isUniqueIdentifier
parameter to true
, the SDK links the flushed data with the visitor associated with the specified identifier.
The parameter isUniqueIdentifier
is deprecated. Please use UniqueIdentifier
instead.
The isUniqueIdentifier
can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode
that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | Unique identifier of the user. This field is mandatory. |
featureKey | string | Key of the feature you want to expose to a user. This field is mandatory. |
isUniqueIdentifier (Deprecated) | bool | An optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is false . The field is optional. |
track | bool | An optional parameter to enable or disable tracking of the feature evaluation (true by default). |
Return value
Type | Description |
---|---|
bool | Value of the feature that is registered for a given visitorCode. |
Exceptions thrown
Type | Description |
---|---|
KameleoonException.VisitorCodeInvalid | Exception indicating that the specified visitor code is not valid. (It is either empty or longer than 255 characters). |
KameleoonException.FeatureNotFound | Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side). |
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, "example.com");
string featureKey = "new_checkout";
bool hasNewCheckout = false;
try {
hasNewCheckout = kameleoonClient.IsFeatureActive(visitorCode, featureKey);
// disabling tracking
hasNewCheckout = kameleoonClient.IsFeatureActive(visitorCode, featureKey, track: false);
}
catch (KameleoonException.NotTargeted e) {
/*
The user did not trigger the feature, as the associated targeting segment
conditions were not fulfilled. The feature should be considered inactive.
*/
hasNewCheckout = false;
}
catch (KameleoonException.FeatureNotFound e) {
// Feature toggle not yet activated on Kameleoon's side - we consider the feature inactive
hasNewCheckout = false;
}
catch (Exception e) {
// This is generic Exception handler which will handle all exceptions.
Console.WriteLine("Exception occured");
}
if (hasNewCheckout)
{
// Implement new checkout code here
}
GetVariation()
- 📨 Sends Tracking Data to Kameleoon (depending on the
track
parameter)
Retrieves the Variation
assigned to a given visitor for a specific feature flag.
This method takes a visitorCode
and featureKey
as mandatory arguments. The track
argument is optional and defaults to true
.
It returns the assigned Variation
for the visitor. If the visitor is not associated with any feature flag rules, the method returns the default Variation
for the given feature flag.
Ensure that proper error handling is implemented in your code to manage potential exceptions.
The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It's represented as the variation in the "Then, for everyone else..." section in a management interface.
const string featureKey = "new_checkout";
Variation variation;
try
{
variation = kameleoonClient.GetVariation(visitorCode, featureKey);
// disabling tracking
variation = kameleoonClient.GetVariation(visitorCode, featureKey, false);
} catch (KameleoonException.FeatureNotFound e)
{
// The error has happened, the feature flag isn't found in current configuration
} catch (KameleoonException.FeatureEnvironmentDisabled e)
{
// The feature flag is disabled for the environment
} catch (KameleoonException.VisitoCodeInvalid e)
{
// The visitor code you passed to the method is invalid and can't be accepted by SDK
}
// Fetch a variable value for the assigned variation
string title = variation.Variables["title"].Value;
switch (variation.Key)
{
case "on":
// Main variation key is selected for visitorCode
break;
case "alternative_variation":
// Alternative variation key
break;
default:
// Default variation key
break;
}
Arguments
Name | Type | Description | Default |
---|---|---|---|
visitorCode (required) | string | Unique identifier of the user. | |
featureKey (required) | string | Key of the feature you want to expose to a user. | |
track (optional) | boolean | An optional parameter to enable or disable tracking of the feature evaluation. | true |
Return value
Type | Description |
---|---|
Variation | An assigned variation to a given visitor for a specific feature flag. |
Exceptions thrown
Type | Description |
---|---|
VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |
FeatureNotFound | Exception indicating that the requested feature key wasn't found in the internal configuration of the SDK. This usually means that the feature flag is not activated in the Kameleoon app (but code implementing the feature is already deployed on your application). |
FeatureEnvironmentDisabled | Exception indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development). |
GetVariations()
- 📨 Sends Tracking Data to Kameleoon (depending on the
track
parameter)
Retrieves a map of Variation
objects assigned to a given visitor across all feature flags.
This method iterates over all available feature flags and returns the assigned Variation
for each flag associated with the specified visitor. It takes visitorCode
as a mandatory argument, while onlyActive
and track
are optional.
- If
onlyActive
is set totrue
, the methodGetVariations()
will return feature flags variations provided the user is not bucketed with theoff
variation. - The
track
parameter controls whether or not the method will track the variation assignments. By default, it is set totrue
. If set tofalse
, the tracking will be disabled.
The returned map consists of feature flag keys as keys and their corresponding Variation
as values. If no variation is assigned for a feature flag, the method returns the default Variation
for that flag.
Proper error handling should be implemented to manage potential exceptions.
The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It's represented as the variation in the "Then, for everyone else..." section in a management interface.
IReadOnlyDictionary<string, Types.Variation> variations;
try
{
variations = kameleoonClient.GetVariations(visitorCode);
// only active variations
variations = kameleoonClient.GetVariations(visitorCode, true);
// disable tracking
variations = kameleoonClient.GetVariations(visitorCode, track: false);
}
catch (VisitorCodeInvalid e)
{
// Handle exception
}
Arguments
Name | Type | Description | Default |
---|---|---|---|
visitorCode (required) | string | Unique identifier of the user. | |
onlyActive (optional) | boolean | An optional parameter indicating whether to return variations for active (true ) or all (false ) feature flags. | false |
track (optional) | boolean | An optional parameter to enable or disable tracking of the feature evaluation. | true |
Return value
Type | Description |
---|---|
IReadOnlyDictionary<string, Variation> | Map that contains the assigned Variation objects of the feature flags using the keys of the corresponding features. |
Exceptions thrown
Type | Description |
---|---|
VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |
GetFeatureVariationKey()
- 📨 Sends Tracking Data to Kameleoon
To get feature variation key, call GetFeatureVariationKey()
.
This method is deprecated and will be removed in SDK version 5.0.0
. Use GetVariation()
instead.
This method takes a visitorCode
and featureKey
as mandatory arguments to get variation key for a given user.
If such a user has never been associated with this feature flag, the SDK returns a variation key randomly (according to the feature flag rules). If a user with a given visitorCode
is already registered with this feature flag, it will detect the previous variation key value. If the user does not match any of the rules, the default value will be returned, which we can define in your customer's account.
You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.
If you specify a visitorCode
, the GetFeatureVariationKey()
method uses it as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitorCode
and set the isUniqueIdentifier
parameter to true
, the SDK links the flushed data with the visitor associated with the specified identifier.
The parameter isUniqueIdentifier
is deprecated. Please use UniqueIdentifier
instead.
The isUniqueIdentifier
can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode
that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | Unique identifier of the user. This field is mandatory. |
featureKey | string | Key of the feature you want to expose to a user. This field is mandatory. |
isUniqueIdentifier (Deprecated) | bool | An optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is false . The field is optional. |
Return value
Type | Description |
---|---|
string | Variation key of the feature flag that is registered for a given visitorCode. |
Exceptions thrown
Type | Description |
---|---|
KameleoonException.FeatureNotFound | Exception indicating that the requested feature key has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side). |
KameleoonException.FeatureEnvironmentDisabled | Exception indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development). |
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, "example.com");
string featureKey = "new_checkout";
string variationKey = "";
try {
variationKey = kameleoonClient.GetFeatureVariationKey(visitorCode, featureKey);
} catch (KameleoonException.FeatureNotFound e) {
// The feature is not yet activated on Kameleoon's side
} catch (KameleoonException.FeatureEnvironmentDisabled e) {
// The feature flag is disabled for the environment
}
switch (variationKey) {
case "on":
// Main variation key is selected for visitorCode
break;
case "alternative_variation":
// Alternative variation key
break;
default:
// Default variation key
break;
}
GetFeatureList()
This method was previously named ObtainFeatureList()
, which was removed in SDK version 4.0.0
.
Returns a list of feature flag keys currently available for the SDK.
Return value
Type | Description |
---|---|
List<string> | List of feature flag keys |
Example code
const featureFlagIds = kameleoonClient.GetFeatureList()
GetActiveFeatureListForVisitor()
This method is deprecated and will be removed in SDK version 5.0.0
. Use GetActiveFeatures
instead.
This method was previously named ObtainFeatureListForVisitorCode()
, which was removed in SDK version 4.0.0
.
This method takes a single visitorCode
parameter. Return only the active feature flags for the specified visitor.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | Unique identifier of the user. This field is mandatory. |
Return value
Type | Description |
---|---|
List<string> | List of active feature flag IDs available for specific visitorCode |
Example code
var featureListIds = kameleoonClient.GetActiveFeatureListForVisitor(visitorCode)
Variables
GetFeatureVariable()
- 📨 Sends Tracking Data to Kameleoon
This method is deprecated and will be removed in SDK version 5.0.0
. Use GetVariation()
instead.
To get variable of variation key associated with a user, call the GetFeatureVariable()
method of our SDK.
This method takes a visitorCode
, featureKey
and variableKey
as mandatory arguments to get a variable of variation key for a given user.
If such a user has never been associated with this feature flag, the SDK returns a variable value of variation key randomly (according to the feature flag rules). If a user with a given visitorCode is already registered with this feature flag, it will detect the variable value for previous associated variation. If the user does not match any of the rules, the variable of default value will be returned.
You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.
If you specify a visitorCode
, the GetFeatureVariable()
method uses it as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitorCode
and set the isUniqueIdentifier
parameter to true
, the SDK links the flushed data with the visitor associated with the specified identifier.
The parameter isUniqueIdentifier
is deprecated. Please use UniqueIdentifier
instead.
The isUniqueIdentifier
can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode
that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | Unique identifier of the user. This field is mandatory. |
featureKey | string | Key of the feature you want to expose to a user. This field is mandatory. |
variableKey | string | Key of the variable you want to get a value. This field is mandatory. |
isUniqueIdentifier (Deprecated) | bool | An optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is false . The field is optional. |
Return value
Type | Description |
---|---|
object | Value of variable of variation that is registered for a given visitorCode for this feature flag. Possible types: bool, int, double, string, JObject, JArray |
Exceptions thrown
Type | Description |
---|---|
KameleoonException.FeatureNotFound | Exception indicating that the requested feature key has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web application's side). |
KameleoonException.FeatureEnvironmentDisabled | Exception indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development). |
KameleoonException.FeatureVariableNotFound | Exception indicating that the requested variable wasn't found. Check that the variable's key in the Kameleoon app matches the one in your code. |
KameleoonException.VisitorCodeInvalid | Exception indicating that the specified visitor code is not valid. (It is either empty or longer than 255 characters). |
Example code
var visitorCode = kameleoonClient.GetVisitorCode(req, res, "example.com");
const string featureKey = "feature_key";
const string variableKey = "var"
try {
var variableValue = kameleoonClient.GetFeatureVariable(visitorCode, featureKey, variableKey);
// Your custom code depending of variableValue
} catch (KameleoonException.FeatureNotFound e) {
// The feature is not yet activated in the Kameleoon app
} catch (KameleoonException.FeatureEnvironmentDisabled e) {
// The feature flag is disabled for the environment
} catch (KameleoonException.FeatureVariableNotFound e) {
// Requested variable not defined in the Kameleoon app
}
GetActiveFeatures()
This method is deprecated and will be removed in SDK version 5.0.0
. Use GetVariations()
instead.
GetActiveFeatures
method retrieves information about the active feature flags that are available for the specified visitor code.
The Kameleoon.Types.Variation.Id
and Kameleoon.Types.Variation.ExperimentId
properties of returned variations are optional. If not specified, the default value is Kameleoon.Types.Variation.UndefinedId
.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | Unique identifier of the visitor you want to retrieve active feature flags for. This field is mandatory. |
Return value
Type | Description |
---|---|
IReadOnlyDictionary<string, Kameleoon.Types.Variation> | A dictionary that contains the assigned variations of the active features using the active feature IDs as keys. |
Exceptions thrown
Type | Description |
---|---|
KameleoonException.VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |
Example code
IReadOnlyDictionary<string, Kameleoon.Types.Variation> activeFeatures = GetActiveFeatures(visitorCode);
GetFeatureVariationVariables()
- This method is deprecated and will be removed in SDK version
5.0.0
. UseGetVariation()
instead. - This method was previously named
GetFeatureAllVariables()
, which was removed in SDK version4.0.0
.
Call this method to retrieve all feature variables for a feature. You can modify feature variables in the Kameleoon app.
This method takes two input parameters: featureKey
and variationKey
. It will return the data with the Dictionary<string, object>
type, as defined on the web interface. It will throw an exception (KameleoonException.FeatureNotFound
) if the requested feature has not been found in the internal configuration of the SDK.
Arguments
Name | Type | Description |
---|---|---|
featureKey` | string | Identificator key of the feature you need to obtain. This field is mandatory. |
variationKey` | string | Key of the variation you want to obtain. This field is required. |
Return value
Type | Description |
---|---|
Dictionary<string, object> | Data associated with this feature flag. The values of can be a number, string, boolean or object (depending on the type defined on the web interface). |
Exceptions thrown
Type | Description |
---|---|
KameleoonException.FeatureNotFound | Exception indicating that the requested feature has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side. |
KameleoonException.FeatureEnvironmentDisabled | Exception indicating that the feature flag is disabled for the visitor's current environment (for example, production, staging, or development). |
KameleoonException.FeatureVariationNotFound | Exception indicating that the requested variation ID wasn't found in the internal configuration of the SDK. This usually means that the variation's corresponding experiment is not activated in the Kameleoon app. |
Example code
string featureKey = "myFeature";
try {
var allVariables = kameleoonClient.GetFeatureVariationVariables(featureKey, variationKey);
} catch (KameleoonException.FeatureNotFound e) {
// The feature is not yet activated in the Kameleoon app
} catch (KameleoonException.FeatureEnvironmentDisabled e) {
// The feature flag is disabled for the environment
} catch (KameleoonException.FeatureVariationNotFound e) {
// The variation is not activated in the Kameleoon app (the associated experiment is not online)
} catch (Exception e) {
// This is generic Exception handler which will handle all exceptions.
Console.WriteLine("Exception occurred");
}
Visitor data
GetVisitorCode()
This method was previously named ObtainVisitorCode
, which was removed in SDK version 4.0.0
.
The GetVisitorCode()
helper method should be called to obtain the Kameleoon visitorCode for the current visitor. This is especially important when using Kameleoon in a mixed front-end and back-end environment, where user identification consistency must be guaranteed. The implementation logic is described here:
First, check if a kameleoonVisitorCode cookie or query parameter associated with the current HTTP request exists. If so, use this as the visitor identifier and skip the next step.
If no cookie or parameter is found in the current request, either randomly generate a new identifier, or use the defaultVisitorCode argument as identifier if it is passed. This allows you to use your own identifiers as visitor codes, if desired. This can help you match Kameleoon visitors with your own users without any additional look-ups in a matching table.
Set the server-side kameleoonVisitorCode cookie (via HTTP header) with the identifier value. This identifier value is then returned by the method.
If you provide your own visitorCode
, make sure it is unique! Also note that the length of visitorCode
is limited to 255 characters. Using an identifier with too many characters will result in an exception.
Arguments
Name | Type | Description |
---|---|---|
Request | Microsoft.AspNetCore.Http.HttpRequest / System.Web.HttpRequest | The current Request object should be passed as the first parameter. This field is mandatory. |
Response | Microsoft.AspNetCore.Http.HttpResponse / System.Web.HttpResponse | The current Response object should be passed as the second parameter. This field is mandatory. |
defaultVisitorCode | string | This parameter will be used as the visitorCode if no existing kameleoonVisitorCode cookie is found on the request. This field is optional, and by default a random visitorCode will be generated. |
Return value
Type | Description |
---|---|
string | A visitorCode that will be associated with this particular user and should be used with most of the methods of the SDK. |
Example code
using static Kameleoon;
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response);
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, defaultVisitorCode);
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, Guid.NewGuid().ToString());
AddData()
The AddData()
method adds targeting data to storage so other methods can use the data to decide whether or not to target the current visitor.
The AddData()
method does not return any value and does not interact with Kameleoon back-end servers on its own. Instead, all the declared data is saved for future transmission using the Flush()
method. This approach reduces the number of server calls made, as the data is typically grouped into a single server call that is triggered the Flush()
.
The TrackConversion()
method also sends out any previously associated data, just like the Flush()
. The same holds true for GetVariation()
and GetVariations()
methods if an experimentation rule is triggered.
Each visitor can only have one instance of associated data for most data types. However, CustomData
is an exception. Visitors can have one instance of associated CustomData
per index.
kameleoonClient.AddData(new Browser(Browser.Browsers.CHROME));
kameleoonClient.AddData(
visitorCode,
new PageView("https://url.com", "title", new int[] {3}),
new Conversion(32, 10f, false)
);
Arguments
Name | Type | Description |
---|---|---|
visitorCode (required) | string | Unique identifier of the user. |
data (required) | params IData[] | Collection of Kameleoon data types. |
Exceptions
Type | Description |
---|---|
VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |
Flush()
- 📨 Sends Tracking Data to Kameleoon
Flush()
takes the Kameleoon data associated with the visitor, then sends a tracking request along with all of the data that were added previously using the AddData
method, that has not yet been sent when calling one of these methods. Flush()
is non-blocking as the server call is made asynchronously.
Flush()
allows you to control when the data associated with a given visitorCode
is sent to our servers. For instance, if you call AddData()
a dozen times, it would be inefficient to send data to the server after each time AddData()
is invoked, so all you have to do is call Flush()
once at the end.
If you specify a visitorCode
, the Flush()
method uses it as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitorCode
and set the isUniqueIdentifier
parameter to true
, the SDK links the flushed data with the visitor associated with the specified identifier.
The parameter isUniqueIdentifier
is deprecated. Please use UniqueIdentifier
instead.
The isUniqueIdentifier
can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode
that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
Arguments
Name | Type | Description |
---|---|---|
instant | bool | Boolean flag indicating whether the data should be sent instantly (true ) or according to the scheduled tracking interval (false ). This field is optional. |
visitorCode | string | Unique identifier of the user. This field is mandatory. |
isUniqueIdentifier (Deprecated) | bool | An optional parameter for specifying if the visitorCode is a unique identifier. The visitorCode should be provided and not null to apply isUniqueIdentifier for a visitor, otherwise it will be ignored. If not provided, the default value is false . The field is optional. |
Example code
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, "example.com");
kameleoonClient.AddData(new Browser(Browser.Browsers.CHROME));
kameleoonClient.AddData(
visitorCode,
new PageView("https://url.com", "title", new int[] {3}),
new Conversion(32, 10f, false)
);
kameleoonClient.Flush(visitorCode); // Interval tracking (most performant way for tracking)
kameleoonClient.Flush(true, visitorCode); // Instant tracking
// if you operate with unique ID
kameleoonClient.AddData(visitorCode, new UniqueIdentifier(true));
kameleoonClient.Flush(visitorCode);
GetRemoteData()
This method was previously named RetrieveDataFromRemoteSource
, which was removed in SDK version 4.0.0
.
GetRemoteData()
allows you to retrieve data (according to a key passed as argument) for specified siteCode (specified in KameleoonClientFactory.create()
) stored on a remote Kameleoon server. Usually data will be stored on our remote servers via the use of our Data API. This method, along with the availability of our highly scalable servers for this purpose, provides a convenient way to quickly store massive amounts of data that can be later retrieved for each of your visitors.
Note that since a server call is required, this mechanism is asynchronous.
Arguments
Name | Type | Description |
---|---|---|
key | string | The key that the data you try to get is associated with. This field is mandatory. |
timeout | int? | Timeout (in milliseconds). This parameter specifies the maximum amount of time to wait for a result. This field is optional, if not provided, it will use the default value of 10000 milliseconds. |
Return value
Type | Description |
---|---|
JObject | Data associated with retrieving data for specific key. |
Exceptions thrown
Type | Description |
---|---|
Exception | Exception indicating that the request timed out or retrieved data can't be parsed with JObject.Parse method. |
Example code
var testValue = await kameleoonClient.GetRemoteData("test"); // default timeout
testValue = await kameleoonClient.GetRemoteData("test", 1000);
try {
testValue = await kameleoonClient.GetRemoteData("test");
} catch (Exception e) {
// Timeout or Json Parsing Exception
}
GetRemoteVisitorData()
GetRemoteVisitorData()
is an asynchronous method for retrieving Kameleoon Visits Data for the VisitorCode
from the Kameleoon Data API. The method adds the data to storage for other methods to use when making targeting decisions.
Data obtained using this method plays an important role when you want to:
- use data collected from other devices.
- access a user's history, such as previously visited pages during past visits.
- use data that is only accessible on the client-side, like datalayer variables and goals that only convert on the front-end.
Read this article for a better understanding of possible use cases.
By default, GetRemoteVisitorData()
automatically retrieves the latest stored custom data with Scope=Visitor
and attaches them to the visitor without the need to call the method AddData()
. It is particularly useful for synchronizing custom data between multiple devices.
The parameter isUniqueIdentifier
is deprecated. Please use UniqueIdentifier
instead.
The isUniqueIdentifier
can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode
that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
Using parameters in GetRemoteVisitorData()
The GetRemoteVisitorData()
method offers flexibility by allowing you to define various parameters when retrieving data on visitors. Whether you're targeting based on goals, experiments, or variations, the same approach applies across all data types.
For example, let's say you want to retrieve data on visitors who completed a goal "Order transaction". You can specify parameters within the GetRemoteVisitorData()
method to refine your targeting. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the PreviousVisitAmount
parameter to 5 and Conversions
to true.
The flexibility shown in this example is not limited to goal data. You can use parameters within the GetRemoteVisitorData()
method to retrieve data on a variety of visitor behaviors.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | The visitor code for which you want to retrieve the assigned data. This field is mandatory. |
addData | bool | A boolean indicating whether the method should automatically add retrieved data for a visitor. This field is optional. |
timeout | int? | Timeout (in milliseconds). This parameter specifies the maximum amount of time to wait for a result. This field is optional. If not provided, the default value is 10000 milliseconds. |
filter | Kameleoon.Types.RemoteVisitorDataFilter | Filter for specifying what data should be retrieved from visits, by default only CustomData is retrieved from the current and latest previous visit (new RemoteVisitorDataFilter(previousVisitAmount: 1, currentVisit: true, customData: true) or RemoteVisitorDataFilter.Default ). Other filters parameters are set to false . This filed is optional. |
isUniqueIdentifier (Deprecated) | bool | An optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is false . The field is optional. |
Here is the list of available Kameleoon.Types.RemoteVisitorDataFilter
options:
Name | Type | Description | Default |
---|---|---|---|
previousVisitAmount (optional) | int | Number of previous visits to retrieve data from. Number between 1 and 25 | 1 |
currentVisit (optional) | bool | If true, current visit data will be retrieved | true |
customData (optional) | bool | If true, custom data will be retrieved. | true |
pageViews (optional) | bool | If true, page data will be retrieved. | false |
geolocation (optional) | bool | If true, geolocation data will be retrieved. | false |
device (optional) | bool | If true, device data will be retrieved. | false |
browser (optional) | bool | If true, browser data will be retrieved. | false |
operatingSystem (optional) | bool | If true, operating system data will be retrieved. | false |
conversions (optional) | bool | If true, conversion data will be retrieved. | false |
experiments (optional) | bool | If true, experiment data will be retrieved. | false |
kcs (optional) | bool | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on. | false |
visitorCode (optional) | bool | If true, the visitorCode from the most recent visit should be retrieved and applied to the current visitor. Required for Cross-device experimentation. | true |
Return value
Type | Description |
---|---|
Task<IReadOnlyCollection<IData>> | Collection associated with a given visitor. |
Exceptions thrown
Type | Description |
---|---|
HttpRequestException | Exception indicating that the request was failed for any reason. |
Exception | Exception indicating that the request timed out or any other reason of failure. |
Example code
string visitorCode = "visitorCode";
// Visitor data will be fetched and automatically added for `visitorCode`
Task<IReadOnlyCollection<IData>> visitorData = kameleoonClient.GetRemoteVisitorData(visitorCode);
// If you only want to fetch data and add it yourself manually, set addData == `false`
Task<IReadOnlyCollection<IData>> visitorData = kameleoonClient.GetRemoteVisitorData(visitorCode, false);
// If you want to fetch custom list of data types
var filter = new RemoteVisitorDataFilter(25, customData: false, conversions: true, experiments: true);
var visitorData = kameleoonClient.getRemoteVisitorData(visitorCode, filter: filter);
try {
IReadOnlyCollection<IData> visitorData = await kameleoonClient.GetRemoteVisitorData(visitorCode);
// Your custom code
} catch (Exception e) {
// Catch exception
}
GetVisitorWarehouseAudience()
Retrieves all audience data associated with the visitor in your data warehouse using the specified visitorCode
and warehouseKey
. The warehouseKey
is typically your internal user ID. The customDataIndex
parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the warehouse targeting documentation for additional details. The method returns a CustomData
object, confirming that the data has been added to the visitor and is available for targeting purposes.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | A unique visitor identification string, can't exceed 255 characters length. |
customDataIndex | int | An integer representing the index of the custom data you want to use to target your BigQuery Audiences. |
warehouseKey | string | A unique key to identify the warehouse data (usually, your internal user ID). This field is optional. |
timeout | int? | Timeout (in milliseconds). This parameter specifies the maximum amount of time to wait for a result. This field is optional. If not provided, the default value is 10000 milliseconds. |
Return value
Type | Description |
---|---|
Task<CustomData> | A CustomData instance confirming that the data has been added to the visitor. |
Exceptions thrown
Type | Description |
---|---|
KameleoonException.VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (it is either empty or longer than 255 characters). |
HttpRequestException | Exception indicating that the request was failed for any reason. |
Exception | Exception indicating that the request timed out or any other reason of failure. |
Example code
Task<CustomData> warehouseAudienceDataTask = kameleoonClient.
GetVisitorWarehouseAudience(visitorCode, customDataIndex); // default timeout
Task<CustomData> warehouseAudienceDataTask = kameleoonClient.
GetVisitorWarehouseAudience(visitorCode, customDataIndex, timeout: 1000);
// If you need to specify warehouse key
Task<CustomData> warehouseAudienceDataTask = kameleoonClient.
GetVisitorWarehouseAudience(visitorCode, customDataIndex, warehouseKeyValue); // default timeout
Task<CustomData> warehouseAudienceDataTask = kameleoonClient.
GetVisitorWarehouseAudience(visitorCode, customDataIndex, warehouseKeyValue, 1000);
try
{
CustomData warehouseAudienceData = await warehouseAudienceDataTask;
// Your custom code
}
catch (Exception e)
{
// Catch exception
}
SetLegalConsent()
You must use this method to specify whether the visitor has given legal consent to use personal data. Setting the legalConsent
parameter to false
limits the types of data that you can include in tracking requests. This helps you adhere to legal and regulatory requirements while responsibly managing visitor data. You can find more information on personal data in the consent management policy.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | The user's unique identifier. This field is required. |
legalConsent | bool | A boolean value representing the legal consent status. true indicates the visitor has given legal consent, false indicates the visitor has never provided, or has withdrawn, legal consent. This field is required. |
response | Microsoft.AspNetCore.Http.HttpResponse / System.Web.HttpRequest | The HTTP response where values in the cookies will be adjusted based on the legal consent status. This field is optional. |
Exceptions thrown
Type | Description |
---|---|
KameleoonException.VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |
Example code
string visitorCode = kameleoonClient.GetVisitorCode(httpRequest, httpResponse);
kameleoonClient.SetLegalConsent(visitorCode, true, httpResponse);
Goals and third-party analytics
TrackConversion()
- 📨 Sends Tracking Data to Kameleoon
To track conversion, use the TrackConversion()
method. This method requires visitorCode
and goalId
to track conversion on this particular goal. In addition, this method also accepts revenue as a third optional argument to track revenue. The visitorCode usually is identical to the one that was used when triggering the experiment.
The TrackConversion()
method doesn't return any value. This method is non-blocking as the server call is made asynchronously.
If you specify a visitorCode
, the TrackConversion()
method uses it as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitorCode
and set the isUniqueIdentifier
parameter to true
, the SDK links the flushed data with the visitor associated with the specified identifier.
The parameter isUniqueIdentifier
is deprecated. Please use UniqueIdentifier
instead.
The isUniqueIdentifier
can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode
that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | Unique identifier of the user. This field is mandatory. |
goalId | int | ID of the goal. This field is mandatory. |
revenue | float | Revenue of the conversion. This field is optional. |
isUniqueIdentifier (Deprecated) | bool | An optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is false . The field is optional. |
Example code
using Kameleoon;
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, "example.com");
int goalID = 83023;
kameleoonClient.TrackConversion(visitorCode, goalID);
// if you operate with unique ID
kameleoonClient.AddData(visitorCode, new UniqueIdentifier(true));
kameleoonClient.TrackConversion(visitorCode, goalID);
GetEngineTrackingCode()
Kameleoon offers built-in integrations with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To ensure that you can track and analyze your server-side experiments, Kameleoon provides the method GetEngineTrackingCode()
to automatically send exposure events to the analytics solution you are using. The SDK builds a tracking code for your active analytics solution based on the experiments the visitor has triggered in the last 5 seconds. Please refer to our hybrid experimentation for more information on implementing this method.
You must implement both the C# SDK and our Kameleoon JavaScript tag to benefit from this feature. We recommend you implement the Kameleoon asynchronous tag, which you can install before your closing <body>
tag in your HTML page, as it will be only used for tracking purposes.
The following string will be returned:
window.kameleoonQueue = window.kameleoonQueue || [];
window.kameleoonQueue.push(['Experiments.assignVariation', experiment1ID, variation1ID]);
window.kameleoonQueue.push(['Experiments.trigger', experiment1ID, true]);
window.kameleoonQueue.push(['Experiments.assignVariation', experiment2ID, variation2ID]);
window.kameleoonQueue.push(['Experiments.trigger', experiment2ID, true]);
Here, experiment1ID
, experiment2ID
and variation1ID
, variation2ID
represent the specific experiments and variations that users have been assigned to.
string engineTrackingCode = kameleoonClient.GetEngineTrackingCode(visitorCode);
Arguments
Name | Type | Description |
---|---|---|
visitorCode (required) | string | Unique identifier of the user. |
Return value
Type | Desription |
---|---|
string | JavaScript code to be inserted in your page |
Events
UpdateConfigurationHandler()
The UpdateConfigurationHandler()
method allows you to handle the event when configuration has updated data. It takes one input parameter, handler. The handler that will be called when the configuration is updated using a real-time configuration event.
Arguments
Name | Type | Description |
---|---|---|
handler | Action | The handler that will be called when the configuration is updated using a real-time configuration event. |
Example code
kameleoonClient.UpdateConfigurationHandler(async delegate () {
// Configuration was updated
});
Data types
The following data types are available in Kameleoon.Data.IData
.
Data available in the SDK is not available for targeting and reporting in the Kameleoon app until you add the data. For example, by using the addData()
method.
See use visit history to target users for more information.
If you are using hybrid mode, you can call GetRemoteVisitorData()
to automatically fill all data that Kameleoon has collected previously.
Browser
The Browser
data set stored here can be used to filter experiment and personalization reports by any value associated with it.
kameleoonClient.AddData(visitorCode, new Browser(Browser.Browsers.CHROME));
kameleoonClient.AddData(visitorCode, new Browser(Browser.Browsers.SAFARI, 16));
Name | Type | Description |
---|---|---|
browser (required) | Browser.Browsers | List of browsers: CHROME , INTERNET_EXPLORER , FIREFOX , SAFARI , OPERA , OTHER . |
version (optional) | float? | Version of the browser, floating point number represents major and minor version of the browser |
PageView
Name | Type | Description |
---|---|---|
url | string | URL of the page viewed. This field is mandatory. |
title | string | Title of the page viewed. This field is mandatory. |
referrers | int[] | Referrers of viewed pages. This field is optional. |
The index (ID) of the referrer is available on our Back-Office, in the Acquisition channel configuration page. Be careful: this index starts at 0, so the first acquisition channel you create for a given site would have the ID 0, not 1.
kameleoonClient.AddData(
visitorCode,
new PageView("https://url.com", "title", new int[] {3})
);
Conversion
Name | Type | Description |
---|---|---|
goalID | int | ID of the goal. This field is mandatory. |
revenue | float | Conversion revenue. This field is optional. |
negative | bool | Defines if the revenue is positive or negative. This field is optional. |
kameleoonClient.AddData(visitorCode, new Conversion(32, 10f, false));
CustomData
Name | Type | Description |
---|---|---|
index | int | Index / ID of the custom data to be stored. This field is mandatory. |
value | string | Value of the custom data to be stored. This field is mandatory. |
The index (ID) of the custom data is available in the Kameleoon app, in the Custom data configuration page. Be careful: this index starts at 0, so the first custom data you create for a given site would have the ID 0, not 1.
kameleoonClient.AddData(visitorCode, new CustomData(1, "some custom value"));
Device
Name | Type | Description |
---|---|---|
device | Device.Type | List of devices: PHONE, TABLET, DESKTOP. This field is mandatory. |
kameleoonClient.AddData(visitorCode, new Device(Device.Type.DESKTOP));
UserAgent
Server-side experiments are more vulnerable to bot traffic than client-side experiments. To address this, Kameleoon uses the IAB/ABC International Spiders and Bots List to identify known bots and spiders. Kameleoon also uses the UserAgent
field to filter out bots and other unwanted traffic that could otherwise skew your conversion metrics. For more details, see the help article on bot filtering.
If you use internal bots, we suggest that you pass the value curl/8.0 of the userAgent to exclude them from our analytics.
Name | Type | Description |
---|---|---|
Value | string | The UserAgent value that will be sent with tracking requests. This field is mandatory. |
kameleoonClient.AddData(visitorCode, new UserAgent("Your User Agent"));
UniqueIdentifier
If you don't add UniqueIdentifier
for a visitor, visitorCode
is used as the unique visitor identifier, which is useful for Cross-device experimentation. When you add UniqueIdentifier
for a visitor, the SDK links the flushed data with the visitor associated with the specified identifier.
The UniqueIdentifier
can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode
that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
Name | Type | Description |
---|---|---|
value | bool | Parameter for specifying if the visitorCode is a unique identifier. This field is required. |
kameleoonClient.AddData(visitorCode, new UniqueIdentifier(true));
OperatingSystem
OperatingSystem
contains information about the operating system on the visitor's device.
Each visitor can only have one OperatingSystem
. Adding a second OperatingSystem
overwrites the first one.
Name | Type | Description |
---|---|---|
type | OperatingSystem.Type | List of operating systems: WINDOWS , MAC , IOS , LINUX , ANDROID and WINDOWS_PHONE . This field is required. |
kameleoonClient.addData(visitorCode, new OperatingSystem(OperatingSystem.Type.WINDOWS));
Cookie
Cookie
contains information about the cookie stored on the visitor's device.
Each visitor can only have one Cookie
. Adding second Cookie
overwrites the first one.
Name | Type | Description |
---|---|---|
cookies | IReadOnlyDictionary<string, string> | A string object map consisting of cookie keys and values. This field is required. |
Cookie cookie = new Cookie (new Dictionary<string, string>() {
{ "k1", "v1" },
{ "k2", "v2" },
});
kameleoonClient.addData(visitorCode, cookie);
Geolocation
Geolocation
contains the visitor's geolocation details.
- Each visitor can have only one
Geolocation
. Adding a secondGeolocation
overwrites the first one.
kameleoonClient.addData(visitorCode, new Geolocation("France", "Île-de-France", "Paris"));
Name | Type | Description |
---|---|---|
country (required) | string | The country of the visitor. |
region (optional) | string | The region of the visitor. |
city (optional) | string | The city of the visitor. |
postalCode (optional) | string | The postal code of the visitor. |
latitude (optional) | float | The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |
longitude (optional) | float | The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |
Returned Types
Variation
Variation
contains information about the assigned variation to the visitor (or the default variation, if no specific assignment exists).
Name | Type | Description |
---|---|---|
Key | string | The unique key identifying the variation. |
Id | int | The ID of the assigned variation (or Variation.UndefinedId if it's the default variation). |
ExperimentId | int | The ID of the experiment associated with the variation (or Variation.UndefinedId if default). |
Variables | IReadOnlyDictionary<string, Variable> | A dictionary containing the variables of the assigned variation, keyed by variable names. This could be an empty collection if no variables are associated. |
- The
Variation
object provides details about the assigned variation and its associated experiment, while theVariable
object contains specific details about each variable within a variation. - Ensure that your code handles the case where
Id
orExperimentId
may beVariation.UndefinedId
, indicating a default variation. - The
Variables
dictionary might be empty if no variables are associated with the variation.
Example code
// Retrieving the variation key
string variationKey = variation.Key;
// Retrieving the variation id
int variationId = variation.Id;
// Retrieving the experiment id
int experimentId = variation.ExperimentId;
// Retrieving the variables map
var variables = variation.Variables;
Variable
Variable
contains information about a variable associated with the assigned variation.
Name | Type | Description |
---|---|---|
Key | string | The unique key identifying the variable. |
Type | string | The type of the variable. Possible values: BOOLEAN, NUMBER, STRING, JSON, JS, CSS. |
Value | object | The value of the variable, which can be of the following types: bool, int, double, string, Newtonsoft.Json.Linq.JToken. |
Example code
// Retrieving the variables map
var variables = variation.Variables;
// Variable type can be retrieved for further processing
string type = variables["isDiscount"].Type;
// Retrieving the variable value by key
bool isDiscount = (bool)variables["isDiscount"].Value;
// Variable value can be of different types
string title = (string)variables["title"].Value;