C# SDK
Introduction
Welcome to the developer documentation for the Kameleoon C# SDK! Our SDK gives you the possibility of running experiments on your back-end .NET application server. Integrating our SDK into your web-application is easy, and its footprint (in terms of memory and network usage) is low.
You can refer to the SDK reference
to check out all possible features of the SDK. Also make sure you check out our Getting started tutorial
which we have prepared to walk you through the installation and implementation.
Latest version of the C# SDK: 3.2.0 (changelog).
Getting started
This guide is designed to help you integrate our SDK in a few minutes and start running experiments in your C# applications. This tutorial will explain the setup of a simple A/B test to change the number of recommended products based on different variations.
Creating an experiment
First, you must create an experiment in the Kameleoon back-office so that our platform is aware of the new A/B test you're planning to implement on your side. Make sure that server-side type is chosen as shown below:
Upon successful creation of the experiment, you will need to get its ID to use in the SDK as an argument to the triggerExperiment()
method.
Installing the SDK
Installing the C# client from a package manager
// NuGet Package Manager
Install-Package KameleoonClient -Version 3.2.0
// .NET CLI
dotnet add package KameleoonClient --version 3.2.0
// Packet CLI
paket add KameleoonClient --version 3.2.0
There are several ways to install the C# SDK, which are listed to the right. You can either use NuGet Package manager, .NET CLI or Packet CLI.
Additional configuration
You should provide credentials for the C# SDK via a configuration file, which can also be used to customize the SDK behavior. A sample configuration file can be obtained here. We suggest to install this file to the default path of /etc/kameleoon/client-csharp.conf
, but you can also put it in another location and passing the path as an argument to the KameleoonClientFactory.Create()
method. With the current version of the C# SDK, those are the available keys:
- client_id: a
client_id
is required for authentication to the Kameleoon service. - client_secret: a
client_secret
is required for authentication to the Kameleoon service. - actions_configuration_refresh_interval: this specifies the refresh interval, in minutes, of the configuration for experiments and feature flags (the active experiments and feature flags are fetched from the Kameleoon servers). It means that once you launch an experiment, pause it, or stop it the changes can take (at most) the duration of this interval to be propagated in production to your servers. If not specified, the default interval is 60 minutes.
- visitor_data_maximum_size: this specifies the maximum amount of memory that the map holding all the visitor data (in particular custom data) can take (in MB). If not specified, the default size is 500MB.
- default_timeout: this specifies the timeout, in milliseconds for network requests of SDK. It is recommended to set the value to 30 seconds or more if you do not have a stable connection. The default value is 15 seconds. Some methods have their own parameters for timeouts, but if you do not specify them explicitly, this value is used.
- environment: an option specifying which feature flag configuration will be used, by default each feature flag is split into production, staging, development. If not specified, will be set to default value of production. More information
To learn more about the client_id
and client_secret
, as well as how to obtain them, refer to the API credentials article. Note that the Kameleoon C# SDK
uses the Automation API and follows the OAuth 2.0 client credentials flow.
Initializing the Kameleoon client
using Kameleoon;
string siteCode = "a8st4f59bj";
IKameleoonClient kameleoonClient = KameleoonClientFactory.Create(siteCode);
IKameleoonClient kameleoonClient = KameleoonClientFactory.Create(siteCode, "/etc/kameleoon/client-csharp.conf");
After installing the SDK into your application, configuring the correct credentials (in /etc/kameleoon/client-csharp.conf
) and setting up a server-side experiment on Kameleoon's back-office, the next step is to create the Kameleoon client in your application code.
The code on the right gives a clear example. A KameleoonClient is a singleton object that acts as a bridge between your application and the Kameleoon platform. It includes all the methods and properties you will need to run an experiment.
It's the responsability of the developer to ensure proper logic of its application code within the context of A/B testing via Kameleoon. A good practice is to always assume that the current visitor can be left out of the experiment because the experiment has not yet been launched. This is actually easy to do, because this corresponds to the implementation of the default / reference variation logic, which should be done in any case. The code samples on the next paragraph show examples of such an approach.
Triggering an experiment
using Kameleoon;
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, "example.com");
int recommendedProductsNumber;
try {
int variationID;
try {
variationID = kameleoonClient.TriggerExperiment(visitorCode, 75253);
}
catch (KameleoonException.NotTargeted e) {
/*
The user did not trigger the experiment, as the associated targeting segment
conditions were not fulfilled. He should see the reference variation.
*/
variationID = 0;
}
catch (KameleoonException.NotActivated e) {
/*
The user triggered the experiment, but did not activate it. Usually, this happens
because the user has been associated with excluded traffic.
*/
variationID = 0;
}
catch (KameleoonException.ExperimentConfigurationNotFound e) {
// The user will not be counted into the experiment, but should see the reference variation
variationID = 0;
}
if (variationID == 0) {
// This is the default / reference number of products to display
recommendedProductsNumber = 5;
}
else if (variationID == 148382) {
// We are changing number of recommended products for this variation to 10
recommendedProductsNumber = 10;
}
else if (variationID == 187791) {
// We are changing number of recommended products for this variation to 8
recommendedProductsNumber = 8;
}
/*
Here you should have code to generate the HTML page back to the client,
where recommendedProductsNumber will be used.
*/
}
catch (Exception e) {
}
Running an A/B experiment on your C# application means bucketing your visitors into several groups (one per variation). The SDK takes care of this bucketing (and the associated reporting) automatically.
Triggering an experiment by calling the TriggerExperiment()
method will register a random variation for a given visitorCode. If this visitorCode is already associated with a variation (most likely a returning visitor that has already been exposed to the experiment previously), then it will return the previous variation associated with a given experiment.
Obtaining a Kameleoon visitorCode for the current HTTP request is an important step of the process. You should use the provided GetVisitorCode()
helper method for this (details available on the reference documentation).
The triggerExperiment()
method will quite often throw out exceptions. You should generally treat an exception as if the user was bucketed into the reference. Some possible common exceptions:
- When the experiment has not yet been launched on the Kameleoon platform (but the code implementing the experiment on the Java application's side is already deployed), this results in a KameleoonException.ExperimentConfigurationNotFound exception.
- If you used targeting on your experiment, the KameleoonException.NotTargeted exception will be thrown to indicate that the current visitor is not targeted.
The TriggerExperiment()
method will make an asynchronous call to our servers for tracking purposes, but the association of a variation with the visitorCode for this experiment (this operation is also called the bucketing of the visitors) will be made directly in the SDK code. Thus the method will instantly return the variationID.
Every change of the deviation (traffic repartition between variations) for the experiment will trigger a mandatory reallocation
.
This will happen even if you did not select the "Reallocation" checkbox in the traffic management interface.
A reallocation means that all visitors that had been previously exposed to the experiment will be again bucketed, and thus can be assigned to a new, different variation.
Depending on your particular experiment, this can have some impact on the user experience and on the results of the test. We do NOT recommend changing the deviation for server side experiments at all if possible.
Read more about reallocation in this article.
Implementing variation code
private int recommendedProductsNumber;
if (variationID == 0) {
// This is the default / reference number of products to display
recommendedProductsNumber = 5;
}
else if (variationID == 148382) {
// We are changing number of recommended products for this variation to 10
recommendedProductsNumber = 10;
}
else if (variationID == 187791) {
// We are changing number of recommended products for this variation to 8
recommendedProductsNumber = 8;
}
To execute different code paths depending on the variation assigned to the visitor, you will need the list of all the experiment's variation IDs. You can find these variation IDs (as well as the experiment ID) by opening the experiment in the back-office interface. By convention, the reference (original variation) always has an ID equal to 0.
Once you have the IDs of the different variations, you can implement a different action for each variation, and one of the code paths will be executed, based on the associated variationID for the current visitor. Generally, this can be done using a simple if / else or switch mechanism. In our example, we just change the number of recommended products with two different variations.
Tracking conversion
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, "example.com");
int goalID = 123456;
kameleoonClient.TrackConversion(visitorCode, goalID);
After you are done with triggering an experiment, the next step is usually to start tracking conversions. This is done to measure performance characteristics according to the goals that make sense for your business.
For this purpose, use the TrackConversion()
method of the SDK as shown in the example. You need to pass the visitorCode and goalID parameters so we can correctly track conversion for this particular visitor.
Obtaining results
Once your implementation is in place on the server side (experiment triggering, variations handling, and conversion tracking), it is time to launch the experiment on the Kameleoon platform. You do this in the same way as for a front-end test. Basic operations such as starting, pausing and stopping the experiment work exactly in the same way.
After the experiment is launched, first results will be available on our standard results page in the back-office after a duration of 30 minutes. This is because (as is the case with front-end testing) visits are considered over after 30 minutes of inactivity. Inactivity in this context means the absence of calls sent to the Kameleoon back-end servers (such calls are made via TriggerExperiment()
, TrackConversion()
or Flush()
methods).
Technical considerations
Kameleoon made an important architectural design decision with its SDK technology, namely that every SDK must comply with a zero latency policy. In practice, this means that any blocking remote server call is banned, as even the fastest remote call would add a 20ms latency to your application. And if for any reason our servers are slower to reply than usual (unfortunately, this can happen), this delay can quickly increase to hundreds of milliseconds, seconds... or even completely block the load of the web page for the end user. We believe that web performance is of paramount importance in today's world and we don't think adding server-side A/B testing or feature flagging capabilities should come at the cost of an increased web page rendering time. For this reason, we guarantee that the use of our SDKs has absolutely no impact on the performance of the host platform.
However, having a zero latency policy does impose some constraints. The main one is that user data about your visitor should be kept locally, and not fetched from a remote server. For instance, if you set a custom data for a given visitor, we must store this somehow in your server / infrastructure, not on our (remote) side.
In the case of the C# SDK, this is implemented via a map of visitor data (where keys are the visitorCodes) directly on RAM. So if you use new CustomData()
and then kameleoonClient.AddData()
methods, the information will be stored in the application's RAM (the one hosting the SDK, usually an application server). The map is regularly cleaned (old visitors data is erased) so it should usually not grow too big in size, unless you have a very big traffic and use lots of custom data.
To be able to control how much maximum RAM the SDK can use with this map, you can use the visitor_data_maximum_size configuration parameter. The default value is 500MB, meaning the additional RAM overhead of the SDK will not be more than 500MB on your host server (if you use Custom Data, if you don't it will be much lower).
Since the visitor data is kept in RAM, it is obviously lost if you restart your application server. This is usually not an issue, as important custom data is usually fetched from persistent database and then tagged on the current visitor. A reboot should thus only affect the Kameleoon custom data of the sessions active when the reboot occured.
Reference
This is a full reference documentation of the C# SDK.
If this is your first time working with the C# SDK, we strongly recommend you go over our Getting started tutorial
to integrate the SDK and start experimenting in a few minutes.
Kameleoon.KameleoonClientFactory
Create
IKameleoonClient kameleoonClient = KameleoonClientFactory.Create(siteCode);
// With a custom configurationFilePath
IKameleoonClient kameleoonClient = KameleoonClientFactory.Create(siteCode, false, "/var/lib/kameleoon/client-csharp.conf");
The starting point for using the SDK is the initialization step. All interaction with the SDK is done through an object of the KameleoonClient class, therefore you need to create this object via KameleoonClientFactory Create()
static method.
Arguments
Name | Type | Description |
---|---|---|
siteCode | string | Code of the website you want to run experiments on. This unique code id can be found in our platform's back-office. 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. |
clientID | string | This parameter is used for OAUth 2.0 authentication to our service. This field is optional, as it can be provided via the configuration file. However, it must either be supplied by the configuration file or by this method, else a KameleoonException.CredentialsNotFound exception will be thrown. |
clientSecret | string | This parameter is used for OAUth 2.0 authentication to our service. This field is optional, as it can be provided via the configuration file. However, it must either be supplied by the configuration file or by this method, else a KameleoonException.CredentialsNotFound exception will be thrown. |
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.CredentialsNotFound | Exception indicating that the requested credentials were not provided (either via the configuration file, or via parameters on the method). |
KameleoonException.EmptySiteCode | Exception indicating that the specified site code is empty string which is invalid value. |
Kameleoon.IKameleoonClient
GetVisitorCode
using static Kameleoon;
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, "example.com");
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, "example.com", defaultVisitorCode);
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, "example.com", Guid.NewGuid().ToString());
Previously named: ObtainVisitorCode
- deprecated since SDK version 3.0.0
and will be removed in a future release.
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 we check if a kameleoonVisitorCode cookie or query parameter associated with the current HTTP request can be found. If so, we will use this as the visitor identifier.
If no cookie / parameter is found in the current request, we either randomly generate a new identifier, or use the defaultVisitorCode argument as identifier if it is passed. This allows our customers to use their own identifiers as visitor codes, should they wish to. This can have the added benefit of matching Kameleoon visitors with their own users without any additional look-ups in a matching table.
In any case, the server-side (via HTTP header) kameleoonVisitorCode cookie is set with the value. Then this identifier value is finally returned by the method.
For more information, refer to this article.
If you provide your own visitorCode
, its uniqueness must be guaranteed on your end - the SDK cannot check it. Also note that the length of visitorCode
is limited to 255 characters. Any excess characters will throw an exception.
Arguments
Name | Type | Description |
---|---|---|
Request | Microsoft.AspNetCore.Http.Request | The current Request object should be passed as the first parameter. This field is mandatory. |
Response | Microsoft.AspNetCore.Http.Response | The current Response object should be passed as the second parameter. This field is mandatory. |
topLevelDomain | string | Your current top level domain for the concerned site (this information is needed to set the corresponding cookie accordingly, on the top level domain). 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. |
TriggerExperiment
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, "example.com");
int experimentID = 75253;
int variationID;
try {
variationID = kameleoonClient.TriggerExperiment(visitorCode, experimentID);
}
catch (KameleoonException.NotTargeted e) {
/*
The user did not trigger the experiment, as the associated targeting segment
conditions were not fulfilled. He should see the reference variation.
*/
variationID = 0;
}
catch (KameleoonException.NotActivated e) {
/*
The user triggered the experiment, but did not activate it. Usually, this happens
because the user has been associated with excluded traffic.
*/
variationID = 0;
}
catch (KameleoonException.ExperimentConfigurationNotFound e) {
/*
This experiment was not found in the SDK configuration. The user will not be counted
into the experiment, but should see the reference variation.
*/
variationID = 0;
}
catch (Exception e) {
// This is generic Exception handler which will handle all exceptions
Console.WriteLine("Exception occured");
}
To trigger an experiment, call the TriggerExperiment()
method of our SDK.
This method takes visitorCode and experimentID as mandatory arguments to register a variation for a given user.
If such a user has never been associated with any variation, the SDK returns a randomly selected variation. If a user with a given visitorCode is already registered with a variation, it will detect the previously registered variation and return the variationID.
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.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | Unique identifier of the user. This field is mandatory. |
experimentID | int | ID of the experiment you want to expose to a user. This field is mandatory. |
Return value
Type | Description |
---|---|
int | ID of the variation that is registered for a given visitorCode. By convention, the reference (original variation) always has an ID equal to 0. |
Exceptions Thrown
Type | Description |
---|---|
KameleoonException.NotTargeted | Exception indicating that the current visitor / user did not trigger the required targeting conditions for this experiment. The targeting conditions are defined via Kameleoon's segment builder. |
KameleoonException.NotActivated | Exception indicating that the current visitor / user triggered the experiment (met the targeting conditions), but did not activate it. The most common reason for that is that part of the traffic has been excluded from the experiment and should not be tracked. |
KameleoonException.ExperimentConfigurationNotFound | Exception indicating that the requested experiment ID has not been found in the internal configuration of the SDK. This is usually normal and means that the experiment has not yet been started on Kameleoon's side (but code triggering / implementing variations is already deployed on the web-application's side). |
IsFeatureActive
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, "example.com");
string featureKey = "new_checkout";
bool hasNewCheckout = false;
try {
hasNewCheckout = kameleoonClient.IsFeatureActive(visitorCode, featureKey);
}
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.FeatureConfigurationNotFound 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
}
Previously named: ActivateFeature
- deprecated since SDK version 3.1.0
and will be removed in a future release.
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.
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. |
Return value
Type | Description |
---|---|
bool | Value of the feature that is registered for a given visitorCode. |
Exceptions Thrown
Type | Description |
---|---|
KameleoonException.NotTargeted | Exception indicating that the current visitor / user did not trigger the required targeting conditions for this feature. The targeting conditions are defined via Kameleoon's segment builder. |
KameleoonException.FeatureConfigurationNotFound | 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). |
GetFeatureVariationKey
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, "example.com");
string featureKey = "new_checkout";
string variationKey = "";
try {
variationKey = kameleoonClient.GetFeatureVariationKey(visitorCode, featureKey);
} catch (KameleoonException.FeatureConfigurationNotFound e) {
// The error is happened, feature flag isn't found in current configuraiton
}
switch (variationKey) {
case "on":
// Main variation key is selected for visitorCode
break;
case "alternative_variation":
// Alternative variation key
break;
default:
// Default variation key
break;
}
To get feature variation key, call the GetFeatureVariationKey()
method of our SDK.
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.
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. |
Return value
Type | Description |
---|---|
string | Variation key of the feature flag that is registered for a given visitorCode. |
Exceptions Thrown
Type | Description |
---|---|
KameleoonException.FeatureConfigurationNotFound | 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). |
GetFeatureVariable
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.FeatureConfigurationNotFound e) {
// The error is happened, feature flag isn't found in current configuraiton
}
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.
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. |
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.FeatureConfigurationNotFound | 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). |
GetVariationAssociatedData
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, "example.com");
int experimentID = 75253;
try {
int variationID = kameleoonClient.TriggerExperiment(visitorCode, experimentID);
JObject jsonObject = kameleoonClient.GetVariationAssociatedData(variationID);
string firstName = jsonObject.getString("firstName");
}
catch (KameleoonException.VariationConfigurationNotFound e) {
// The variation is not yet activated on Kameleoon's side, ie the associated experiment is not online
}
catch (Exception e) {
// This is generic Exception handler which will handle all exceptions
Console.WriteLine("Exception occured");
}
Previously named: ObtainVariationAssociatedData
- deprecated since SDK version 3.0.0
and will be removed in a future release.
To retrieve JSON data associated with a variation, call the GetVariationAssociatedData()
method of our SDK. The JSON data usually represents some metadata of the variation, and can be configured on our web application interface or via our Automation API.
This method takes the variationID as a parameter and will return the data as a JObject
instance. It will throw an exception (KameleoonException.VariationConfigurationNotFound
) if the variation ID is wrong or corresponds to an experiment that is not yet online.
We decided to use the Newtonsoft.Json
package as a JSON provider / library. This adds a dependency to our SDK.
Arguments
Name | Type | Description |
---|---|---|
variationID | int | ID of the variation you want to obtain associated data for. This field is mandatory. |
Return value
Type | Description |
---|---|
Newtonsoft.Json.Linq.JObject | Data associated with this variationID. |
Exceptions Thrown
Type | Description |
---|---|
KameleoonException.VariationConfigurationNotFound | Exception indicating that the requested variation ID has not been found in the internal configuration of the SDK. This is usually normal and means that the variation's corresponding experiment has not yet been activated on Kameleoon's side. |
ObtainFeatureVariable
string featureKey = "myFeature";
string variableKey = "myVariable";
string data;
try {
data = (string) kameleoonClient.ObtainFeatureVariable(featureKey, variableKey);
}
catch (KameleoonException.FeatureConfigurationNotFound e) {
// The feature is not yet activated on Kameleoon's side
}
catch (Exception e) {
// This is generic Exception handler which will handle all exceptions.
Console.WriteLine("Exception occurred");
}
To retrieve a feature variable, call the ObtainFeatureVariable()
method of our SDK. A feature variable can be changed easily via our web application.
This method takes two input parameters: featureKey and variableKey. It will return the data as a System.Object
instance. Usually it should be casted to the expected type (the one defined on the web interface). It will throw an exception (KameleoonException.FeatureConfigurationNotFound
) if the requested feature has not been found in the internal configuration of the SDK.
We decided to use the Newtonsoft.Json
package as a JSON provider / library. This adds a dependency to our SDK.
Arguments
Name | Type | Description |
---|---|---|
featureID or featureKey | int or string | ID or Key of the feature you want to obtain to a user. This field is mandatory. |
variableKey | string | Key of the variable. This field is mandatory. |
Return value
Type | Description |
---|---|
object | Data associated with this variable for this feature flag. This can be a int, double, string, bool or Newtonsoft.Json.Linq.JObject (depending on the type defined on the web interface). |
Exceptions Thrown
Type | Description |
---|---|
KameleoonException.FeatureConfigurationNotFound | 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. |
GetFeatureAllVariables
string featureKey = "myFeature";
try {
var allVariables = kameleoonClient.GetFeatureAllVariables(featureKey);
}
catch (KameleoonException.FeatureConfigurationNotFound e) {
// The feature is not yet activated on Kameleoon's side
}
catch (Exception e) {
// This is generic Exception handler which will handle all exceptions.
Console.WriteLine("Exception occurred");
}
Previously named: ObtainFeatureAllVariables
- deprecated since SDK version 3.0.0
and will be removed in a future release.
To retrieve the all feature variables, call the GetFeatureAllVariables()
method of our SDK. A feature variable can be changed easily via our web application.
This method takes one input parameter: featureKey. It will return the data with the Dictionary<string, object>
type, as defined on the web interface. It will throw an exception (KameleoonException.FeatureConfigurationNotFound
) 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. |
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.FeatureConfigurationNotFound | 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. |
TrackConversion
using Kameleoon;
using Kameleoon.Data;
string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, "example.com");
int goalID = 83023;
kameleoonClient.AddData(visitorCode, new Browser(Browser.Browsers.CHROME));
kameleoonClient.AddData(
visitorCode,
new PageView("http://url.com", "title", new int[] {3}),
new Interest(2)
);
kameleoonClient.AddData(visitorCode, new Conversion(32, 10f, false));
kameleoonClient.TrackConversion(visitorCode, goalID);
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.
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. |
AddData
kameleoonClient.AddData(new Browser(Browser.Browsers.CHROME));
kameleoonClient.AddData(
visitorCode,
new PageView("https://url.com", "title", new int[] {3}),
new Interest(0)
);
kameleoonClient.AddData(visitorCode, new Conversion(32, 10f, false));
To associate various data with the current user, we can use the AddData()
method. This method requires the visitorCode as a first parameter, and then accepts several additional parameters. Those additional parameters represent the various Data Types allowed in Kameleoon.
Note that the AddData()
method doesn't return any value and doesn't interact with the Kameleoon back-end servers by itself. Instead, the declared data is saved for future sending via the Flush()
method described in the next paragraph. This reduces the number of server calls made, as data is usually grouped into a single server call triggered by the execution of Flush()
.
The TriggerExperiment()
and TrackConversion()
methods also send out previously associated data, just like the Flush()
method.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | Unique identifier of the user. This field is mandatory. |
dataTypes | IData | Custom data types which may be passed separated by a comma. |
Flush
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 Interest(0)
);
kameleoonClient.AddData(visitorCode, new Conversion(32, 10f, false));
kameleoonClient.Flush(visitorCode);
Data associated with the current user via AddData()
method is not sent immediately to the server. It is stored and accumulated until it is sent automatically by the TriggerExperiment()
or TrackConversion()
methods, or manually by the Flush()
method. This allows the developer to control exactly when the data is flushed to our servers. For instance, if you call the AddData()
method a dozen times, it would be a waste of ressources to send data to the server after each AddData()
invocation. Just call Flush()
once at the end.
The Flush()
method doesn't return any value. This method is non-blocking as the server call is made asynchronously.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | Unique identifier of the user. This field is mandatory. |
GetExperimentList
var experimentIds = kameleoonClient.GetExperimentList()
Previously named: ObtainExperimentList
- deprecated since SDK version 3.0.0
and will be removed in a future release.
Returns a list of experiment IDs currently available for the SDK
Return value
Type | Description |
---|---|
List<int> | List of experiment's IDs |
GetExperimentListForVisitor
var experimenListIds = kameleoonClient.GetExperimentListForVisitor(visitorCode) // onlyAllocated == true by default
var experimenListIds = kameleoonClient.GetExperimentListForVisitor(visitorCode, false)
Previously named: ObtainExperimentListForVisitorCode
- deprecated since SDK version 3.0.0
and will be removed in a future release.
This method takes two input parameters: visitorCode and onlyActive. If onlyActive
parameter is true
result contains only active experiments, otherwise it contains all targeted experiments to specific visitorCode
. Returns a list of experiment IDs currently available for specific visitorCode
according to the onlyActive
option
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | Unique identifier of the user. This field is mandatory. |
onlyAllocated | bool | The value is true by default, result contains only active for the user experiments. Set false for fetching all targeted experiment IDs. This field is optional. |
Return value
Type | Description |
---|---|
List<int> | List of experiment IDs available for specific visitorCode according to the onlyActive option |
GetFeatureList
const featureFlagIds = kameleoonClient.GetFeatureList()
Previously named: ObtainFeatureList
- deprecated since SDK version 3.0.0
and will be removed in a future release.
Returns a list of feature flag IDs currently available for the SDK
Return value
Type | Description |
---|---|
List<int> | List of feature flag IDs |
GetActiveFeatureListForVisitor
var onlyActive = true
var featureListIds = kameleoonClient.GetActiveFeatureListForVisitor(visitorCode)
Previously named: ObtainFeatureListForVisitorCode
- deprecated since SDK version 3.0.0
and will be removed in a future release.
This method takes two input parameters: visitorCode and onlyActive. If onlyActive
parameter is true
result contains only active feature flags, otherwise it contains all targeted feature flags to specific visitorCode
. Returns a list of feature flag IDs currently available for specific visitorCode
according to the onlyActive
option
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 |
GetRemoteData
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
}
Previously named: RetrieveDataFromRemoteSource
- deprecated since SDK version 3.1.0
and will be removed in a future release.
The GetRemoteData()
method 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 / users.
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 2000 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 |
UpdateConfigurationHandler
kameleoonClient.UpdateConfigurationHandler(async delegate () {
// Configuration was updated
});
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. |
GetEngineTrackingCode
string engineTrackingCode = kameleoonClient.GetEngineTrackingCode(visitorCode);
// 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.
Kameleoon offers built-in integrations with various analytics solutions, such as Mixpanel, GA4, Segment... To ensure that you can track and analyze your server-side experiments, Kameleoon provides a method GetEngineTrackingCode()
that allows you to automatically send exposure events to the analytics solution you are using. For more information on how to implement this method, please refer to the following documentation.
To benefit from this feature, you will need to implement both the C# SDK and our Kameleoon JavaScript tag. 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.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | The user's unique identifier. This field is mandatory. |
Return value
Type | Description |
---|---|
string | JavasScript code to be inserted in your page |
Kameleoon.Data.IData
Browser
kameleoonClient.AddData(visitorCode, new Browser(Browser.Browsers.CHROME));
Name | Type | Description |
---|---|---|
browser | enum | List of browsers: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER. This field is mandatory. |
PageView
kameleoonClient.AddData(
visitorCode,
new PageView("https://url.com", "title", new int[] {3})
);
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.
https://help.kameleoon.com/create-acquisition-channel
Conversion
kameleoonClient.AddData(visitorCode, new Conversion(32, 10f, false));
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. |
CustomData
kameleoonClient.AddData(visitorCode, new CustomData(1, "some custom value"));
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 on our Back-Office, 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.
Device
kameleoonClient.AddData(visitorCode, new Device(Device.Type.DESKTOP));
Name | Type | Description |
---|---|---|
device | Device.Type | List of devices: PHONE, TABLET, DESKTOP. This field is mandatory. |
UserAgent
kameleoonClient.AddData(visitorCode, new UserAgent("Your User Agent"));
Name | Type | Description |
---|---|---|
value | string | The User-Agent value that will be sent with tracking requests. This field is mandatory. |