Saltar al contenido principal
Con el SDK de C# de Kameleoon, puede ejecutar experimentos del lado del servidor y activar feature flags en servidores de aplicaciones .NET. Es sencillo integrar nuestro SDK en su aplicación web, y su uso de memoria y red es bajo. Primeros pasos: Para obtener ayuda para comenzar, consulte la guía del desarrollador. Métodos del SDK: Para la documentación de referencia completa de los métodos del SDK de C#, consulte la sección referencia. Changelog: Última versión del SDK de C#: 4.19.0 changelog.

Guía del desarrollador

Primeros pasos

This guide is designed to help you integrate our SDK into your C# applications.

Kit de inicio

Para facilitarle el comienzo, Kameleoon proporciona un kit de inicio y una aplicación de demostración para probar el SDK. El kit de inicio incluye una aplicación totalmente configurada con ejemplos que muestran cómo se pueden utilizar los métodos del SDK en una aplicación. El kit de inicio, la aplicación de demostración y las instrucciones detalladas están disponibles en Starter kit for .NET

Instalación del cliente C#

Puede utilizar el gestor de paquetes NuGet, .NET CLI o Paket para instalar el cliente de C#.
Install-Package KameleoonClient -Version 4.17.0

Configuración adicional

Create a .properties configuration file to provide credentials and customize the SDK’s behavior. You can also download a sample configuration file. Save this file in the default path /etc/kameleoon/client-csharp.conf. If you place the file 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:
ClaveDescripciónValor predeterminado
clientId / client_id (obligatorio)Necesario para la autenticación con el servicio de Kameleoon. Para encontrar su client_id, consulte la documentación de credenciales de API.
clientSecret / client_secret (obligatorio)Necesario para la autenticación con el servicio de Kameleoon. Para encontrar su client_secret, consulte la documentación de credenciales de API.
sessionDurationMinute / session_duration_minute (opcional)Designa el intervalo de tiempo predefinido durante el cual Kameleoon almacena al visitante y sus datos asociados en memoria (RAM). Tenga en cuenta que aumentar la duración de la sesión incrementa la cantidad de RAM que debe asignarse para almacenar los datos del visitante.30 minutos
refreshIntervalMinute / refresh_interval_minute (opcional)Especifica el intervalo de actualización, en minutos, con el que el SDK obtiene la configuración de los experimentos activos y los feature flags. El valor determina el tiempo máximo necesario para propagar los cambios, como activar o desactivar feature flags o lanzar experimentos, a sus servidores de producción. Adicionalmente, ofrecemos un modo streaming que utiliza server-sent events (SSE) para enviar nuevas configuraciones al SDK automáticamente y aplicar las nuevas configuraciones en tiempo real, sin ningún retraso.60 minutos
defaultTimeoutMillisecond / default_timeout_millisecond (opcional)Especifica el tiempo de espera, en milisegundos, para las solicitudes de red desde el SDK. Establezca el valor en 30 segundos o más si no dispone de una conexión estable. Algunos métodos tienen un parámetro adicional que puede utilizar para anular el tiempo de espera predeterminado para ese método en particular. Si no especifica el tiempo de espera para un método de forma explícita, el SDK utiliza este valor predeterminado.10000 milisegundos
trackingIntervalMilliseconds / tracking_interval_millisecond (opcional)Especifica el intervalo para las solicitudes de seguimiento en milisegundos. Todos los visitantes que Kameleoon haya evaluado para cualquier feature flag o cuyos datos se hayan vaciado se incluyen en esta solicitud de seguimiento, que el SDK realiza una vez por intervalo. El valor mínimo es 1000 ms, que también es el predeterminado, y el valor máximo es 5000 ms.1000 milisegundos
environment / environment (opcional)Entorno desde el cual se debe utilizar la configuración del feature flag. El valor puede ser production, staging o development. Consulte el artículo de gestión de entornos para más detalles.production
topLevelDomain / top_level_domain (obligatorio en modo híbrido)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.null
proxyHost / proxy_host (opcional)Establece el host proxy para todas las llamadas de salida al servidor realizadas por el SDK.null
networkDomain / network_domain (opcional)Custom domain used by SDKs for outgoing requests, often for proxying. Must be a valid domain (e.g., example.com or sub.example.com). Invalid formats default to Kameleoon’s value.null

Inicialización del cliente Kameleoon

After you’ve installed the SDK and configured your credentials and SDK behavior, create the Kameleoon client in your application code. Por ejemplo:
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
        networkDomain: "example.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
}
Un IKameleoonClient es un objeto singleton que conecta su aplicación con la plataforma Kameleoon. Incluye todos los métodos y funcionalidades que necesita para ejecutar un experimento. As a developer, you must ensure your app uses the correct logic for A/B testing with Kameleoon. It’s best to exclude a visitor from the experiment if you haven’t launched it yet. Excluding is simple because this fits with the default logic for variations.

Activación de un feature flag

Asignación de un ID único a un usuario
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. Si está usando Kameleoon en modo híbrido, llamar al método GetVisitorCode() garantiza que el ID único (visitor code) se comparta entre el archivo de aplicación engine.js (anteriormente llamado kameleoon.js) y el SDK.
Recuperación de la configuración de un flag
Para implementar un feature flag en su código, primero debe crear el feature flag en su cuenta de Kameleoon. 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. El método GetVariation() gestiona tanto los feature flags simples con estados ON/OFF como los flags más complejos con múltiples variaciones. El método recupera la variación adecuada para el usuario comprobando las reglas de la funcionalidad, asignando la variación y devolviéndola en función del featureKey y el visitorCode. El método IsFeatureActive() puede utilizarse si desea recuperar la configuración de un feature flag simple que solo tiene un estado ON u OFF, a diferencia de los feature flags más complejos con múltiples variaciones u opciones de segmentación. 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. De forma predeterminada, 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. Si desea saber más sobre how tracking works, view this article
Adición de puntos de datos para segmentar a un usuario o filtrar / desglosar visitas en informes
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 collected on other devices or to access past user data (collected client-side when using Kameleoon in Hybrid mode), use the GetRemoteVisitorData() method. This method asynchronously fetches data from the servers. It is important to 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. Para obtener más información sobre las condiciones de segmentación disponibles, consulte el artículo detallado sobre este tema. Además, los puntos de datos que añade al perfil del visitante estarán disponibles al analizar sus experimentos, lo que le permite filtrar y desglosar sus resultados por factores como el dispositivo y el navegador. El modo híbrido de Kameleoon recopila automáticamente una variedad de puntos de datos en el lado del cliente, lo que facilita desglosar sus resultados en función de estos puntos de datos previamente recopilados. Consulte la lista completa aquí. Si necesita realizar el seguimiento de puntos de datos adicionales más allá de los que se recopilan automáticamente, puede utilizar la funcionalidad de Custom Data de Kameleoon. Custom Data le permite capturar y analizar información específica relevante para sus experimentos. No olvide llamar al método Flush() para enviar los datos recopilados a los servidores de Kameleoon para su análisis.
Para asegurarse de que sus resultados sean precisos, se recomienda filtrar los bots utilizando el tipo de dato UserAgent.
Seguimiento de conversiones de objetivos
Cuando un usuario completa una acción deseada (como realizar una compra), se registra como una conversión. Para hacer seguimiento de las conversiones, utilice el método TrackConversion() y proporcione los parámetros requeridos visitorCode y goalId. La solicitud de seguimiento de conversiones se enviará junto con la siguiente solicitud de seguimiento programada, que el SDK envía a intervalos regulares (definidos por tracking_interval_millisecond). Si prefiere enviar la solicitud de inmediato, utilice el método Flush() con el parámetro instant=true.
Envío de eventos a soluciones de analítica
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. El método GetEngineTrackingCode() recupera el código de seguimiento único necesario para enviar eventos de exposición a su solución de analítica. El uso de este método le permite registrar eventos y enviarlos a la plataforma de analítica que desee.

Experimentación entre dispositivos

Para dar soporte a los visitantes que acceden a una aplicación desde varios dispositivos, Kameleoon permite sincronizar los datos del visitante previamente recopilados entre cada uno de sus dispositivos y reconciliar su historial de visitas entre dispositivos mediante la experimentación entre dispositivos. Los casos de estudio y la información detallada sobre cómo Kameleoon gestiona los datos entre dispositivos están disponibles en el artículo sobre experimentación entre dispositivos.

Sincronización de datos personalizados entre dispositivos

Aunque la sincronización de mapeo personalizado se utiliza para alinear los datos del visitante entre dispositivos, no siempre es necesaria. A continuación se presentan dos escenarios en los que no se requiere la sincronización de mapeo personalizado: Mismo ID de usuario en todos los dispositivos If the same user ID is used consistently across all devices, synchronization is handled automatically without a custom mapping sync. It is enough to call the GetRemoteVisitorData() method when you want to sync the data collected between multiple devices. Instancias multi-servidor con IDs consistentes In complex setups involving multiple servers (for example, distributed server instances), where the same user ID is available across servers, synchronization between servers (with GetRemoteVisitorData()) is sufficient without additional custom mapping sync. Customers who need additional data can refer to the GetRemoteVisitorData() method description for further guidance. In the below code, it is assumed that the same unique identifier (in this case, the visitorCode, which can also be referred to as userId) is used consistently between the two devices for accurate data retrieval.
Si desea sincronizar los datos recopilados en tiempo real, debe elegir el ámbito Visitor para sus datos personalizados.
Device A
// 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);
Device B
// Before working with the data, call the `GetRemoteVisitorData` method.
await kameleoonClient.GetRemoteVisitorData(visitorCode);

// After calling the method, the SDK on Device B will have access to CustomData of Visitor scope as defined on Device A.
// So, "your data" will be available for targeting and tracking the visitor.

Uso de datos personalizados para la fusión de sesiones

La experimentación entre dispositivos permite combinar el historial de un visitante en cada uno de sus dispositivos (reconciliación de historial). La reconciliación de historial permite fusionar diferentes sesiones de un visitante en una sola. Para reconciliar el historial de visitas, utilice CustomData para proporcionar un identificador único del visitante. Para más información, consulte la documentación dedicada. After cross-device reconciliation is enabled, calling GetRemoteVisitorData() with the parameter userId retrieves all known data for a given user. Las sesiones con el mismo identificador siempre verán la misma variación en un experimento. En la vista Visitor de las páginas de resultados de su experimento, estas sesiones aparecerán como un único visitante. La configuración del SDK garantiza que las sesiones asociadas siempre vean la misma variación del experimento. Sin embargo, existen algunas limitaciones en cuanto a la asignación de variaciones entre dispositivos. Estas limitaciones se describen aquí. Siga la guía de activación de la reconciliación de historial entre dispositivos para configurar sus datos personalizados en la plataforma Kameleoon. Posteriormente, puede usar el SDK de forma normal. Los siguientes métodos pueden ser útiles en el contexto de la fusión de sesiones:
  • GetRemoteVisitorData() with added UniqueIdentifier(true) - to retrieve data for all linked visitors.
  • TrackConversion() or Flush() with added UniqueIdentifier(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.
A continuación se muestra un ejemplo de cómo usar datos personalizados para la fusión de sesiones.
// In this example, `91` represents the index of the Custom Data
// configured as a unique identifier in Kameleoon.
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);

// Additionally, the linked visitors will share all fetched remote visitor data.
await kameleoonClient.GetRemoteVisitorData(userId);
En este ejemplo, la aplicación tiene una página de inicio de sesión. Como el ID de usuario es desconocido en el momento del inicio de sesión, se utiliza un identificador de visitante anónimo generado por el método GetVisitorCode(). Después de que el usuario inicia sesión, el visitante anónimo se asocia con el ID de usuario y se utiliza como identificador único del visitante.

Uso de una clave de bucketing personalizada

De forma predeterminada, Kameleoon utiliza un ID de visitante anónimo y único (visitorCode) para asignar usuarios a las variaciones de los feature flags. Este ID se genera y almacena habitualmente en el dispositivo del usuario (en una cookie del navegador para los SDKs del lado del cliente y del lado del servidor, y en almacenamiento persistente para los SDKs móviles). Sin embargo, en determinados escenarios puede necesitar asegurarse de que todos los usuarios de la misma organización vean la misma variante de un feature flag. La opción Custom Bucketing Key le permite anular este comportamiento predeterminado proporcionando su propio identificador personalizado para el bucketing. Esta anulación garantiza que la lógica de asignación de Kameleoon utilice la clave que usted especifique en lugar del visitorCode predeterminado.

Casos de uso

El uso de una clave de bucketing personalizada es esencial para mantener la consistencia y precisión en las asignaciones de sus feature flags, especialmente en estas situaciones:
  • Experimentos a nivel de cuenta u organización: Para productos B2B o escenarios en los que desea asignar a todos los usuarios de la misma organización a la misma variación, puede utilizar un identificador como accountId. Las claves de bucketing personalizadas son cruciales para probar mediante A/B funcionalidades que afecten a todo un equipo o empresa.
Al implementar una clave de bucketing personalizada, garantiza una mayor consistencia y precisión en sus experimentos, lo que se traduce en resultados más fiables y en una mejor experiencia de usuario.

Detalles técnicos

Cuando configura una clave de bucketing personalizada para un feature flag, proporciona a Kameleoon un identificador específico de los datos de su aplicación:
kameleoonClient.AddData(visitorCode, new CustomData(index, "newVisitorCode"));
  • Providing the custom key: You provide your custom identifier to the Kameleoon SDK using the AddData() method. In this method, you will pass your chosen custom bucketing key as a CustomData object. Here, newVisitorCode refers to the identifier you wish to use for your bucketing (for example, the new userId or accountId).
Para que la clave de bucketing personalizada funcione correctamente, también debe definirse y configurarse para el feature flag durante el proceso de creación o edición del flag. Sin esta configuración correspondiente, el bucketing del SDK no aplicará su clave personalizada. Para obtener instrucciones detalladas sobre cómo configurar esto en Kameleoon, consulte este artículo.
  • Bucketing logic: Once a custom bucketing key is provided through the AddData() method, all hash calculations for assigning users to variations will use this newVisitorCode (your custom key) instead of the default visitorCode. Using the newVisitorCode means that the bucketing decision is tied to your custom identifier, ensuring consistent assignments across various contexts where that identifier is present.
  • Seguimiento de datos y analítica: Es crucial tener en cuenta que, aunque el newVisitorCode (su clave personalizada) se utiliza para las decisiones de bucketing, todos los datos posteriores (eventos de seguimiento y conversiones, por ejemplo) se envían y se asocian con el visitorCode original. Esta separación garantiza que su analítica refleje con precisión los recorridos e interacciones individuales de los usuarios dentro del contexto más amplio de su experimento, incluso cuando el bucketing se realiza a un nivel superior (como una cuenta) o a través de varios dispositivos/sesiones. Sus datos originales del visitante permanecen intactos para una elaboración de informes completa.

Requisitos técnicos

Para utilizar eficazmente una clave de bucketing personalizada:
  • The key must be a string.
  • Debe ser única para la entidad que pretende agrupar (por ejemplo, si utiliza un userId, el ID de cada usuario debe ser único).
  • La clave debe estar disponible para el SDK en el momento exacto en que se evalúa la decisión del feature flag para ese usuario o solicitud.

Condiciones de segmentación

Los SDKs de Kameleoon admiten una variedad de condiciones de segmentación predefinidas que puede usar para segmentar a los usuarios en sus campañas. Para ver la lista de condiciones que admite este SDK, consulte usar el historial de visitas para segmentar a los usuarios. También puede utilizar sus propios datos externos para segmentar a los usuarios.

Registro de eventos

El SDK genera registros que reflejan diversos procesos internos y problemas.

Niveles de registro

El SDK admite la configuración para limitar el registro mediante un nivel de log.
// The `None` log level does not allow logging.
Kameleoon.Logging.KameleoonLogger.LogLevel = Kameleoon.Logging.LogLevel.None;

// The `Error` log level only allows logging issues that may affect the SDK's primary behavior.
Kameleoon.Logging.KameleoonLogger.LogLevel = Kameleoon.Logging.LogLevel.Error;

// The `Warning` log level allows logging issues which may require additional 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 logging general information on the SDK's internal processes.
// It extends the `Warning` log level.
Kameleoon.Logging.KameleoonLogger.LogLevel = Kameleoon.Logging.LogLevel.Info;

// The `DEBUG` level logs additional details about the SDK’s internal processes and extends the `INFO` level
// with more granular. diagnostic output.
// This information is not intended for end-user interpretation but can be sent to our support team
// to assist with internal troubleshooting.
Kameleoon.Logging.KameleoonLogger.LogLevel = Kameleoon.Logging.LogLevel.Debug;

Gestión personalizada de los registros

El SDK escribe sus registros en la salida de la consola de forma predeterminada. Este comportamiento puede anularse.
El filtrado por nivel de log se realiza de forma independiente de la lógica de gestión de los registros.
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();

Referencia

This is the full reference documentation of the C# SDK.

Inicialización

Create()

To start using the SDK, you need to initialize it. Your app interacts with the SDK through the KameleoonClient class found in Kameleoon.IKameleoonClient. You can create this object using the static method Kameleoon.KameleoonClientFactory Create().
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
        networkDomain: "example.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
}
Argumentos
NameTypeDescriptionDefault
siteCode (obligatorio)stringEs la clave única del proyecto de Kameleoon que está utilizando con el SDK.
configurationFilePath (opcional)stringRuta al archivo de configuración del SDK./etc/kameleoon/client-csharp.conf
kameleoonConfig (opcional)KameleoonClientConfigObjeto de configuración del SDK que puede pasar en lugar de utilizar un archivo de configuración.null
Valor de retorno
TypeDescription
IKameleoonClientAn instance of the KameleoonClient class, that will be used to manage your experiments and feature flags.
Excepciones lanzadas
TypeDescription
KameleoonException.ConfigCredentialsInvalidException indicating that the requested credentials were not provided in the configuration file or as arguments on the method.
KameleoonException.SiteCodeIsEmptyExcepción que indica que el site code especificado es una cadena vacía, lo que no es un valor válido.

WaitInit()

WaitInit() awaits the initialization of the Kameleoon client. Este método le permite verify that the client has successfully initialized before you proceed with other operations.
using static Kameleoon;

try {
    await kameleoonClient.WaitInit();
} catch (Exception exception) {
    //  indicates that client could not be initialized due to the thrown exception.
}
Valor de retorno
TypeDescription
TaskLa tarea se completará cuando el cliente se haya inicializado correctamente.
Excepciones lanzadas
TipoDescripción
ExceptionExcepción que indica que el cliente no se ha inicializado correctamente y todavía no puede utilizarse.

Feature flags y variaciones

IsFeatureActive()

  • 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro track)
This method was previously called ActivateFeature, which was removed in SDK version 4.0.0.
To activate a feature toggle, call the IsFeatureActive method. Este método requiere un visitorCode y un featureKey (o featureID) para comprobar si un usuario puede acceder a una funcionalidad específica. If the user has never been linked to this feature, the SDK will randomly decide whether to activate it, returning either true (the user can access the feature) or false (the user cannot). If the user with the given visitorCode is already linked to this feature, the system will return the previous value of the featureFlag. Asegúrese de incluir un manejo de errores adecuado en su código, como se muestra en el ejemplo, para capturar cualquier error potencial. Si especifica un visitorCode, el método IsFeatureActive() lo usa como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitorCode y establece el parámetro isUniqueIdentifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
Kameleoon uses tracking to count sessions and visitors when you call certain methods, such as IsFeatureActive(), GetVariation() or GetVariations().Use el valor predeterminado true para el parámetro track cuando exponga a los visitantes a una variación y necesite contarlos. Establezca el parámetro track en false solo si llama a estos métodos antes de exponer a los visitantes.Por ejemplo, if you call GetVariations() to retrieve all variations before you expose visitors, set the track parameter to false. This setting prevents Kameleoon from prematurely counting a session. You can then trigger tracking later when you explicitly expose the visitor.Kameleoon sends tracking data every second by default. You can configure this interval up to five seconds using the tracking interval configuration option. Kameleoon groups tracking events into a single session as long as the interval between events is less than 30 minutes. If more than 30 minutes elapse between tracking events, Kameleoon counts the events as separate sessions. A visit appears in your reports 30 minutes after the last recorded event in the session.
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.FeatureNotFound e) {
  // Feature toggle not yet activated on Kameleoon's side - we consider the feature inactive.
  hasNewCheckout = false;
}
catch (Exception e) {
  // This is a generic Exception handler which will handle all exceptions.
  Console.WriteLine("Exception occured");
}
if (hasNewCheckout)
{
  // Implement new checkout code here.
}
The IsFeatureActive() method evaluates the served variant, not the master flag state. If you exclude rules, the method uses the Then, for everyone else serve default state. If you select Off for this default state, the method always returns false even when the master feature flag is On.
Argumentos
NombreTipoDescripción
visitorCodestringIdentificador único del usuario. Este campo es obligatorio.
featureKeystringClave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio.
isUniqueIdentifier (Obsoleto)boolParámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es false. The field is optional.
trackboolAn optional parameter to enable or disable tracking of the feature evaluation (true by default).
Valor de retorno
TypeDescription
boolValue of the feature that is registered for a given visitorCode.
Excepciones lanzadas
TipoDescripción
KameleoonException.VisitorCodeInvalidExcepción que indica que el visitor code especificado no es válido. (Está vacío o tiene más de 255 caracteres).
KameleoonException.FeatureNotFoundException 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).

GetVariation()

  • 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro track)
Recupera la Variation asignada a un visitante dado para un feature flag específico. Este método toma un visitorCode and featureKey as mandatory arguments. The track argument is optional and defaults to true. Devuelve la Variation asignada al visitante. Si el visitante no está asociado con ninguna regla de feature flag, el método devuelve la Variation predeterminada para el feature flag dado. Asegúrese de implementar un manejo de errores adecuado en su código para gestionar las posibles excepciones.
La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección “Then, for everyone else…” de la interfaz de administración.
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 occurred; the feature flag isn't found in the current configuration.
} catch (KameleoonException.FeatureEnvironmentDisabled e)
{
  // The feature flag is disabled for the environment.
} catch (KameleoonException.VisitorCodeInvalid 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;
}
Argumentos
NameTypeDescriptionDefault
visitorCode (obligatorio)stringIdentificador único del visitante.
featureKey (obligatorio)stringClave de la funcionalidad que desea exponer a un visitante.
track (opcional)boolParámetro opcional para habilitar o deshabilitar el seguimiento de la evaluación de la funcionalidad.true
Valor de retorno
TipoDescripción
VariationAn assigned Variation to a given visitor for a specific feature flag.
Excepciones lanzadas
TipoDescripción
VisitorCodeInvalidExcepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters.
FeatureNotFoundExcepción que indica que la clave de funcionalidad solicitada no se encontró en la configuración interna del SDK. Esto suele significar que el feature flag no está activado en la aplicación de Kameleoon (pero el código que implementa la funcionalidad ya está desplegado en la aplicación).
FeatureEnvironmentDisabledExcepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development).

GetVariations()

  • 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro track)
Recupera un map de objetos Variation asignados a un visitante dado para todos los feature flags. Este método itera sobre todos los feature flags disponibles y devuelve la Variation asignada para cada flag asociado con el visitante especificado. It takes visitorCode as a mandatory argument, while onlyActive and track are optional.
  • If onlyActive is set to true, the method GetVariations() will return feature flags variations provided the user is not bucketed with the off variation.
  • El parámetro track controla si el método realizará el seguimiento de las asignaciones de variación. De forma predeterminada, it is set to true. Si se establece en false, el seguimiento estará deshabilitado.
El map devuelto consta de claves de feature flags como claves y su Variation correspondiente como valores. Si no se asigna ninguna variación para un feature flag, el método devuelve la Variation predeterminada para ese flag. Se debe implementar un manejo de errores adecuado para gestionar las posibles excepciones.
La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección “Then, for everyone else…” de la interfaz de administración.
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
}
Argumentos
NameTypeDescriptionDefault
visitorCode (obligatorio)stringIdentificador único del visitante.
onlyActive (opcional)boolParámetro opcional que indica si se deben devolver las variaciones para los feature flags activos (true) o todos (false).false
track (opcional)boolParámetro opcional para habilitar o deshabilitar el seguimiento de la evaluación de la funcionalidad.true
Valor de retorno
TipoDescripción
IReadOnlyDictionary<string, Variation>Map que contiene los objetos Variation asignados de los feature flags utilizando las claves de las funcionalidades correspondientes.
Excepciones lanzadas
TipoDescripción
VisitorCodeInvalidExcepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters.

GetFeatureList()

This method was previously named ObtainFeatureList(), which was removed in SDK version 4.0.0.
Devuelve una lista de claves de feature flags disponibles actualmente en el SDK.
const featureFlagIds = kameleoonClient.GetFeatureList()
Valor de retorno
TipoDescripción
List<string>List of feature flag keys

SetForcedVariation()

El método permite you to programmatically assign a specific Variation to a user, bypassing the standard evaluation process. Esto es especialmente valioso para experimentos controlados donde la lógica de evaluación habitual no es necesaria o debe omitirse. It can also be helpful in scenarios like debugging or custom testing. Cuando se establece una variación forzada, esta anula la lógica de evaluación en tiempo real de Kameleoon. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set forceTargeting=false instead.
Simulated variations always take precedence in the execution order. If a simulated variation calculation is triggered, it will be fully processed and completed first.
A forced variation is treated the same as an evaluated variation. It is tracked in analytics and stored in the user context like any standard evaluated variation, ensuring consistency in reporting. El método puede lanzar excepciones bajo ciertas condiciones (por ejemplo, parámetros no válidos, contexto del usuario o problemas internos). Proper exception handling is essential to ensure that your application remains stable and resilient.
It’s important to distinguish forced variations from simulated variations:
  • Forced variations: Are specific to an individual experiment.
  • Simulated variations: Affect the overall feature flag result.
const int experimentId = 9516;
try
{
    // Forcing the variation "on" in the experiment 9516 for the visitor
    kameleoonClient.SetForcedVariation(visitorCode, experimentId, "on");

    // Forcing the variation "on" while preserving segmentation and targeting conditions during the experiment
    kameleoonClient.SetForcedVariation(visitorCode, experimentId, "on", false);

    // Resetting the forced variation for the experiment 9516 for the visitor
    kameleoonClient.SetForcedVariation(visitorCode, experimentId, null);
}
catch (KameleoonException ex)
{
    // Handling the exception
}
Argumentos
NameTypeDescriptionDefault
visitorCode (obligatorio)stringIdentificador único del visitante.
experimentId (obligatorio)intExperiment Id que será segmentado y seleccionado durante el proceso de evaluación.
variationKey (obligatorio)stringVariation Key correspondiente a una Variation que debe forzarse como valor devuelto para el experimento. Si el valor es null, la variación forzada se restablecerá.
forceTargeting (opcional)boolIndica si la segmentación para el experimento debe forzarse y omitirse (true) o aplicarse como en el proceso de evaluación estándar (false).true
Excepciones lanzadas
TipoDescripción
VisitorCodeInvalidExcepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters.
FeatureExperimentNotFoundExcepción que indica que el experiment id solicitado no se encontró en la configuración interna del SDK. Esto suele ser normal y significa que el experimento correspondiente a la regla todavía no se ha activado del lado de Kameleoon.
FeatureVariationNotFoundExcepción que indica que la variation key (id) solicitada no se ha encontrado en la configuración interna del SDK. Esto suele ser normal y significa que el experimento correspondiente a la variación todavía no se ha activado del lado de Kameleoon.
En la mayoría de los casos, solo es necesario gestionar el error básico KameleoonException, como se muestra en el ejemplo. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including Exception.

EvaluateAudiences()

  • 📨 Envía datos de seguimiento a Kameleoon
Este método evalúa a los visitantes con respecto a todos los segmentos disponibles de Audiences Explorer y realiza el seguimiento de los que coinciden. EvaluateAudiences() should be called after all relevant visitor data has been set or updated, and just before getting a feature variation or checking a feature flag. Este enfoque garantiza que el visitante se evalúe con los datos más recientes disponibles, lo que permite una asignación precisa de audiencia basada en todos los criterios. After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.
try
{
    kameleoonClient.EvaluateAudiences(visitorCode);
}
catch (KameleoonException ex)
{
    // Handling the exception
}
Argumentos
NombreTipoDescripción
visitorCode (obligatorio)stringIdentificador único del visitante.
Excepciones lanzadas
TipoDescripción
VisitorCodeInvalidExcepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters.
En la mayoría de los casos, solo es necesario gestionar el error básico KameleoonException, como se muestra en el ejemplo. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including Exception.

GetDataFile()

DataFile dataFile = kameleoonClient.GetDataFile();
Valor de retorno

Datos del visitante

GetVisitorCode()

This method was previously called ObtainVisitorCode, which was removed in SDK version 4.0.0.
To get the Kameleoon visitorCode for the current visitor, use the GetVisitorCode() method. This method is crucial in environments where front-end and back-end systems must consistently identify users. Here’s how it works:
  1. Check for a kameleoonVisitorCode cookie or query parameter in the current Solicitud HTTP. If you find one, use that as the visitor identifier and skip the next step.
  2. If you don’t find a cookie or parameter, either randomly create a new identifier or use the defaultVisitorCode argument if it’s provided. Doing so lets you use your identifiers as visitor codes, making connecting Kameleoon visitors to your own users easier without needing extra look-ups.
  3. Set the server-side kameleoonVisitorCode cookie using the identifier value. El método devuelve this identifier value.
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.
The GetVisitorCode() method allows you to set simulated variations for a visitor. Cuando las cookies (de una request o document) contienen la clave kameleoonSimulationFFData, se omite el proceso de evaluación estándar. En su lugar, el método devuelve directamente una Variation basada en los datos proporcionados.Puede aplicar simulaciones de dos formas:
  • Automatically (recommended): If using Kameleoon Web Experimentation or the SDK in Hybrid mode, the cookie is created automatically when simulating a variant’s display using the Simulation Panel.
  • Manualmente: Establezca la cookie kameleoonSimulationFFData manualmente.
It’s important to distinguish simulated variations from forced variations:
  • Simulated variations: Affect the overall feature flag result.
  • Forced variations: Are specific to an individual experiment.
⚙️ Manual setupAsegúrese de que la cookie kameleoonSimulationFFData siga este formato:
  • kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simula la variación con varId del experimento expId para el featureKey indicado.
  • kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simula la variación predeterminada (definida en la sección Then, for everyone else in Production, serve) para el featureKey indicado.
⚠️ To ensure proper functionality, the cookie value must be encoded as a URI component using a method such as encodeURIComponent.
try
{
    string visitorCode = kameleoonClient.GetVisitorCode(Request, Response);

    string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, defaultVisitorCode);
}
catch (VisitorCodeInvalid e)
{
    //  Handle exception
}
Argumentos
NombreTipoDescripción
RequestMicrosoft.AspNetCore.Http.HttpRequest / System.Web.HttpRequestThe current Request object should be passed as the first parameter. Este campo es obligatorio.
ResponseMicrosoft.AspNetCore.Http.HttpResponse / System.Web.HttpResponseThe current Response object should be passed as the second parameter. Este campo es obligatorio.
defaultVisitorCodestringThis 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.
Valor de retorno
TipoDescripción
stringA visitorCode that will be associated with this particular user and should be used with most of the methods of the SDK.
Excepciones lanzadas
TypeDescription
KameleoonException.VisitorCodeInvalidExcepción que indica que el visitor code proporcionado no es válido (está vacío o tiene más de 255 caracteres).

AddData()

El método AddData() añade datos de segmentación al almacenamiento para que otros métodos puedan utilizar los datos para decidir si segmentar o no al visitante actual. El método AddData() no devuelve ningún valor y no interactúa por sí mismo con los servidores backend de Kameleoon. En su lugar, todos los datos declarados se guardan para su transmisión futura mediante el método Flush(). Este enfoque reduce el número de llamadas al servidor, ya que los datos se agrupan habitualmente en una única llamada al servidor que desencadena el Flush(). El método TrackConversion() también envía cualquier dato previamente asociado, al igual que Flush(). Lo mismo aplica para los métodos GetVariation() y GetVariations() si se desencadena una regla de experimentación.
Cada visitante solo puede tener una instancia de datos asociados para la mayoría de los tipos de datos. However, CustomData is an exception. Visitors can have one instance of associated CustomData per index.
// Add a single data item (tracked by default)
kameleoonClient.AddData(new Browser(Browser.Browsers.CHROME));

// Add multiple data items (tracked by default)
kameleoonClient.AddData(
    visitorCode,
    new PageView("https://url.com", "title", new int[] {3}),
    new UserAgent("UserAgent")
);

// Add multiple data items stored locally for targeting only (not sent to the Kameleoon Data API)
kameleoonClient.AddData(
    visitorCode,
    false,
    new PageView("https://url.com", "title", new int[] {3}),
    new UserAgent("UserAgent")
);
Argumentos
NombreTipoDescripciónValor predeterminado
visitorCode (obligatorio)stringIdentificador único del visitante.
track (opcional)boolEspecifica si los datos añadidos son aptos para el seguimiento. Cuando se establece en false, los datos se almacenan localmente y se utilizan solo para la evaluación de segmentación; no se envían a la Data API de Kameleoon.true
data (obligatorio)params IData[]Colección de tipos de datos de Kameleoon.
Excepciones
TipoDescripción
VisitorCodeInvalidExcepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters.

Flush()

  • 📨 Envía datos de seguimiento a Kameleoon
The Flush() method collects the Kameleoon data linked to the visitor. It then sends a tracking request along with all the previously added data using the AddData method, which has not yet been sent using one of these methods. Flush() is non-blocking as the server call is made asynchronously. Flush() lets you 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. Si especifica un visitorCode, el método Flush() lo usa como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitorCode y establece el parámetro isUniqueIdentifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
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 tracking method)

kameleoonClient.Flush(true, visitorCode); // Instant tracking

// if you operate with unique ID
kameleoonClient.AddData(visitorCode, new UniqueIdentifier(true));
kameleoonClient.Flush(visitorCode);
Argumentos
NombreTipoDescripción
instantboolBoolean flag indicating whether the data should be sent instantly (true) or according to the scheduled tracking interval (false). Este campo es opcional.
visitorCodestringIdentificador único del usuario. Este campo es obligatorio.
isUniqueIdentifier (Obsoleto)boolParámetro opcional para indicar si el visitorCode es un identificador único. Se debe proporcionar el visitorCode y no ser null para aplicar isUniqueIdentifier a un visitante; de lo contrario, será ignorado. If not provided, el valor predeterminado es false. The field is optional.

GetRemoteData()

This method was previously named RetrieveDataFromRemoteSource, which was removed in SDK version 4.0.0.
GetRemoteData() is a method that lets you fetch data for a specific siteCode (set in KameleoonClientFactory.create()) from a remote Kameleoon server using a key you provide. Our Data API stores this data on our servers, which are designed to efficiently handle large amounts of data. Keep in mind that because this method involves a server call, it works asynchronously.
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
}
Argumentos
NombreTipoDescripción
keystringThe key that the data you try to get is associated with. Este campo es obligatorio.
timeoutint?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.
Valor de retorno
TipoDescripción
JObjectData associated with retrieving data for specific key.
Excepciones lanzadas
TypeDescription
ExceptionException indicating that the request timed out or retrieved data can’t be parsed with JObject.Parse method.

GetRemoteVisitorData()

GetRemoteVisitorData() is a method that retrieves Kameleoon visit data for a specific user using their VisitorCode. It works in the background and stores this data for other methods to make targeting decisions. This data is important for several reasons:
  • It helps you use information collected from different devices.
  • It allows you to access a user’s history, such as previously visited pages from earlier visits.
  • It lets you use data only available on the client side, such as datalayer variables and goals that only track conversions on the front-end.
Read this article for a better understanding of possible use cases.
De forma predeterminada, 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.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
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
}
Argumentos
NameTipoDescripción
visitorCodestringThe visitor code for which you want to retrieve the assigned data. Este campo es obligatorio.
addDataboolBooleano que indica si el método debe añadir automáticamente los datos recuperados para un visitante. Este campo es opcional.
timeoutint?Timeout (in milliseconds). This parameter specifies the maximum amount of time to wait for a result. Este campo es opcional. If not provided, el valor predeterminado es 10000 milliseconds.
filterKameleoon.Types.RemoteVisitorDataFilterFilter 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 (Obsoleto)boolParámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es false. The field is optional.
Valor de retorno
TipoDescripción
Task<IReadOnlyCollection<IData>>Collection associated with a given visitor.
Excepciones lanzadas
TypeDescription
HttpRequestExceptionException indicating that the request was failed for any reason.
ExceptionException indicating that the request timed out or any other reason of failure.
Using parameters in GetRemoteVisitorData()
El método GetRemoteVisitorData() ofrece flexibilidad al permitirle definir varios parámetros al recuperar datos de los visitantes. Ya sea que esté segmentando en función de objetivos, experimentos o variaciones, el mismo enfoque se aplica a todos los tipos de datos. Por ejemplo, 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. La flexibilidad mostrada en este ejemplo no se limita a los datos de objetivos. Puede usar parámetros dentro del método GetRemoteVisitorData() para recuperar datos sobre una variedad de comportamientos del visitante.
Here is the list of available Kameleoon.Types.RemoteVisitorDataFilter options:
NameTypeDescriptionDefault
previousVisitAmount (opcional)intNúmero de visitas previas de las que recuperar datos. Number between 1 and 251
currentVisit (opcional)boolIf true, current visit data will be retrievedtrue
customData (opcional)boolIf true, custom data will be retrieved.true
pageViews (opcional)boolIf true, page data will be retrieved.false
geolocation (opcional)boolIf true, geolocation data will be retrieved.false
device (opcional)boolIf true, device data will be retrieved.false
browser (opcional)boolIf true, browser data will be retrieved.false
operatingSystem (opcional)boolIf true, operating system data will be retrieved.false
conversions (opcional)boolIf true, conversion data will be retrieved.false
experiments (opcional)boolIf true, experiment data will be retrieved.false
kcs (opcional)boolIf true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on.false
visitorCode (opcional)boolIf true, the visitorCode from the most recent visit should be retrieved and applied to the current visitor. Required for Cross-device experimentation.true
cbs (opcional)boolIf true, Contextual Bandit score data will be retrieved.false

GetVisitorWarehouseAudience()

Este método recupera 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. El método devuelve a CustomData object, confirming that the data has been added to the visitor and is available for targeting purposes.
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
}
Argumentos
NombreTipoDescripción
visitorCodestringA unique visitor identification string, can’t exceed 255 characters length.
customDataIndexintEntero que representa el índice del dato personalizado que desea utilizar para segmentar sus BigQuery Audiences.
warehouseKeystringA unique key to identify the warehouse data (usually, your internal user ID). Este campo es opcional.
timeoutint?Timeout (in milliseconds). This parameter specifies the maximum amount of time to wait for a result. Este campo es opcional. If not provided, el valor predeterminado es 10000 milliseconds.
Valor de retorno
TipoDescripción
Task<CustomData>A CustomData instance confirming that the data has been added to the visitor.
Excepciones lanzadas
TypeDescription
KameleoonException.VisitorCodeInvalidExcepción que indica que el visitor code proporcionado no es válido (está vacío o tiene más de 255 caracteres).
HttpRequestExceptionException indicating that the request was failed for any reason.
ExceptionException indicating that the request timed out or any other reason of failure.

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 method 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.
string visitorCode = kameleoonClient.GetVisitorCode(httpRequest, httpResponse);
kameleoonClient.SetLegalConsent(visitorCode, true, httpResponse);
Argumentos
NameTipoDescripción
visitorCodestringIdentificador único del usuario. Este campo es obligatorio.
legalConsentboolValor booleano que representa el estado del consentimiento legal. true indicates the visitor has given legal consent, false indicates the visitor has never provided, or has withdrawn, legal consent. Este campo es obligatorio.
responseMicrosoft.AspNetCore.Http.HttpResponse / System.Web.HttpRequestThe HTTP response where values in the cookies will be adjusted based on the legal consent status. Este campo es opcional.
Excepciones lanzadas
TipoDescripción
KameleoonException.VisitorCodeInvalidExcepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters.
Comportamiento al revocar el consentimiento
Cuando llama a setLegalConsent() con consent=false, el SDK no elimina la cookie kameleoonVisitorCode. En su lugar, deja de prorrogar la fecha de expiración de la cookie, permitiendo que esta persista hasta que expire de forma natural. Si sus requisitos de cumplimiento exigen la eliminación inmediata del archivo de cookie al revocar el consentimiento, debe eliminarlo manualmente utilizando los métodos nativos de gestión de cookies de su framework. El SDK no eliminará el archivo automáticamente.

Objetivos y analítica de terceros

TrackConversion()

  • 📨 Envía datos de seguimiento a Kameleoon
Use este método para track a conversion for a specific goal and user. This method requires visitorCode and goalId. In addition, this method also accepts an optional revenue, negative and metadata arguments. The visitorCode is usually identical to the one that was used when triggering the experiment. El método TrackConversion() no devuelve ningún valor. Este método no es bloqueante, ya que la llamada al servidor se realiza de forma asíncrona.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
using Kameleoon;

string visitorCode = kameleoonClient.GetVisitorCode(Request, Response, "example.com");
int goalId = 83023;

kameleoonClient.TrackConversion(visitorCode, goalId);

// Add metadata
var cd = new CustomData(1, "metadata");
kameleoonClient.TrackConversion(visitorCode, goalId, metadata: cd)
Argumentos
NombreTipoDescripciónDefault
visitorCode (obligatorio)stringIdentificador único del visitante.
goalId (obligatorio)intID del objetivo.
revenue (opcional)float?Ingreso de la conversión.0
negative (opcional)boolDefine si el ingreso es positivo o negativo.false
metadata (opcional)params CustomData[]Le permite establecer valores específicos para los datos personalizados que se hayan definido como metadatos del objetivo en la aplicación de Kameleoon. Example: [CustomData{id: 5, value: "Payment Type"}, CustomData{id: 6, value: "Delivery Method"}]. In this example, 5 and 9 are the indexes of the custom data (5 = “Payment Type”, 9 = “Delivery Method”).new CustomData[0]
isUniqueIdentifier (deprecated)boolParámetro opcional para indicar si el visitorCode es un identificador único.false
metadata values are accessible through raw data exports and the results page.If the metadata parameter is provided, Kameleoon will use these specified values for the current conversion instead of what was previously collected using the AddData() method. If the parameter is omitted, Kameleoon will use the last tracked values for those CustomData prior to the conversion and within the same visit.Kameleoon will only consider the metadata values that are explicitly passed as parameters to the TrackConversion() method.En el siguiente ejemplo, Kameleoon will associate the conversion only with the custom data value explicitly provided as a parameter (here: index 5 with the value ‘Amex Credit Card’).
kameleoonClient.AddData(visitorCode, new CustomData(5, "Credit Card"), new CustomData(9, "Express Delivery"));
kameleoonClient.TrackConversion(visitorCode, 10, metadata: new CustomData(5, "Amex Credit Card"));
Excepciones
TipoDescripción
VisitorCodeInvalidExcepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters.

GetEngineTrackingCode()

Kameleoon integrates with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To track server-side experiments correctly, call the GetEngineTrackingCode() method after the visitor triggers an experiment. The SDK returns JavaScript queue commands for the experiments that the visitor triggered during the previous five seconds. When you insert this code into the page, Engine.js processes the commands and sends the exposure events through the active analytics integration. Consulte experimentación híbrida para más información sobre cómo implementar este método.
string engineTrackingCode = kameleoonClient.GetEngineTrackingCode(visitorCode);
  • To use this feature, implement both the C# SDK and Kameleoon Engine.js. Because Engine.js is used only for tracking in this flow, you can install the asynchronous tag before the closing </body> tag.
  • If you only want to track experiments in Kameleoon and do not need to send exposure events to third-party analytics tools, use the JavaScript / TypeScript SDK. This option works well for serverless edge compute platforms. The JavaScript / TypeScript SDK automatically tracks variations when you call getVisitorCode, as long as you add the corresponding experiment assignments to window.kameleoonQueue..
  • You can insert the returned tracking code directly into an HTML <script> tag.
<html lang="en">
  <body>
    <script>
      const engineTrackingCode = `
        window.kameleoonQueue = window.kameleoonQueue || [];
        window.kameleoonQueue.push(['Experiments.assignVariation', 123456, 7890, true]);
        window.kameleoonQueue.push(['Experiments.trigger', 123456, true]);
        window.kameleoonQueue.push(['Experiments.assignVariation', 234567, 8901, true]);
        window.kameleoonQueue.push(['Experiments.trigger', 234567, true]);
      `;
      const script = document.createElement('script');

      script.textContent = engineTrackingCode;
      document.body.appendChild(script);
    </script>

  </body>
</html>
En este ejemplo, 123456 y 234567 son IDs de experimento, y 7890 y 8901 son IDs de variación. En su implementación, el SDK genera estos valores en el código de seguimiento devuelto.
Argumentos
NombreTipoDescripción
visitorCode (obligatorio)stringIdentificador único del visitante.
Valor de retorno
TipoDescripción
stringCódigo JavaScript para insertar en la página.

Events

UpdateConfigurationHandler()

El método UpdateConfigurationHandler() le permite gestionar el evento cuando la configuración tiene datos actualizados. Toma un parámetro de entrada, handler. El manejador que se llamará cuando la configuración se actualice mediante un evento de configuración en tiempo real.
kameleoonClient.UpdateConfigurationHandler(async delegate () {
  // Configuration was updated
});
Argumentos
NombreTipoDescripción
handlerActionThe handler that will be called when the configuration is updated using a real-time configuration event.

Tipos de datos

Data available in the SDK is not available for targeting and reporting in the Kameleoon app until it is added; for example, by using the addData() method. See use visit history to target users for more information.
If you are in hybrid mode, you can call GetRemoteVisitorData() to automatically fill all data that Kameleoon collected previously.
Los siguientes tipos de datos están disponibles en Kameleoon.Data.IData.

Browser

El conjunto de datos Browser almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier valor asociado a él.
NombreTipoDescripción
browser (obligatorio)Browser.BrowsersList of browsers: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER.
version (opcional)float?Version of the browser, floating point number represents major and minor version of the browser
kameleoonClient.AddData(visitorCode, new Browser(Browser.Browsers.CHROME));

kameleoonClient.AddData(visitorCode, new Browser(Browser.Browsers.SAFARI, 16));

PageView

NombreTipoDescripción
urlstringURL of the page viewed. Este campo es obligatorio.
titlestringTitle of the page viewed. Este campo es obligatorio.
referrersint[]Referrers de las páginas vistas. Este campo es opcional.
The index (ID) of the referrer is available in 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

El conjunto de datos Conversion almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier objetivo asociado a él.
  • Each visitor can have multiple Conversion objects.
  • You can find the goalId in the Kameleoon app.
NombreTipoDescripciónDefault
goalId (obligatorio)intID del objetivo.
revenue (opcional)floatRevenue of the conversion0
negative (opcional)boolDefine si el ingreso es positivo o negativo.false
metadata (opcional)params CustomData[]Metadatos de la conversión.new CustomData[0]
kameleoonClient.AddData(visitorCode, new Conversion(32, 10f));

kameleoonClient.AddData(visitorCode, new Conversion(33, negative: true));

kameleoonClient.AddData(
    visitorCode,
    new Conversion(34, 5f, metadata: new CustomData(3, "metadata1", "md2"), new CustomData(5, "md3"))
);

CustomData

CustomData allows any type of data to be easily associated with each visitor. It can then be used as a targeting condition in segments or as a filter/breakdown in experiment reports. To learn more about custom data, please refer to this article.
NombreTipoDescripciónDefault
index/name (obligatorio)int/stringÍndice o nombre del dato personalizado. Either index or name must be provided to identify the data.
values (obligatorio)params string[]Values of the custom data to be stored.
overwrite (opcional)boolFlag para controlar explícitamente cómo se almacenan los valores y cómo aparecen en los informes. See moretrue
  • Each visitor is allowed only one CustomData for each unique index. Adding another CustomData with the same index will replace the existing one.
  • The custom data ‘index’ can be found in the Custom Data dashboard under the “INDEX” column.
  • To prevent the SDK from sending data with the selected index to Kameleoon servers for privacy reasons, enable the option: Use this data only locally for targeting purposes when creating custom data.
  • Adding a CustomData instance created with a name when the SDK instance configuration is not up to date or the name is not registered, will result in the data being ignored.
kameleoonClient.AddData(visitorCode, new CustomData(1, "value"));

// With several values
kameleoonClient.AddData(visitorCode, new CustomData(1, "value1", "value2"));

// To set the 'overwrite' flag to false
kameleoonClient.AddData(visitorCode, new CustomData(1, false, "value"));

// To use a name instead of the index
kameleoonClient.AddData(visitorCode, new CustomData("my-custom-data", "value"));

Device

NombreTipoDescripción
deviceDevice.TypeList of devices: PHONE, TABLET, DESKTOP. Este campo es obligatorio.
kameleoonClient.AddData(visitorCode, new Device(Device.Type.DESKTOP));

UserAgent

Server-side experiments are more likely to be affected by bot traffic than client-side experiments. Kameleoon uses the IAB/ABC International Spiders and Bots List to tackle this issue and recognize known bots and spiders. Kameleoon also uses the UserAgent field to filter out bots and other unwanted traffic that might distort your conversion metrics. Para más detalles, consulte our help article on bot filtering. Si utiliza bots internos, le sugerimos pasar el valor curl/8.0 del userAgent para excluirlos de nuestra analítica.
NombreTipoDescripción
ValuestringThe UserAgent value that will be sent with tracking requests. Este campo es obligatorio.
kameleoonClient.AddData(visitorCode, new UserAgent("Your User Agent"));

UniqueIdentifier

Si no añade UniqueIdentifier para un visitante, se utiliza visitorCode como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando añade UniqueIdentifier para un visitante, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado. isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
NombreTipoDescripción
valueboolParameter for specifying if the visitorCode is a unique identifier. Este campo es obligatorio.
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.
NombreTipoDescripción
typeOperatingSystem.TypeList of operating systems: WINDOWS, MAC, IOS, LINUX, ANDROID and WINDOWS_PHONE. Este campo es obligatorio.
kameleoonClient.addData(visitorCode, new OperatingSystem(OperatingSystem.Type.WINDOWS));
Cookie contains information about the cookie stored on the visitor’s device.
NombreTipoDescripción
cookiesIReadOnlyDictionary<string, string>Map de objetos string que consta de claves y valores de cookies. Este campo es obligatorio.
Each visitor can only have one Cookie. Adding a second Cookie overwrites the first one.
Cookie cookie = new Cookie (new Dictionary<string, string>() {
    { "k1", "v1" },
    { "k2", "v2" },
});
kameleoonClient.addData(visitorCode, cookie);

Geolocation

Geolocation contains the visitor’s geolocation details.
NombreTipoDescripción
country (obligatorio)stringThe country of the visitor.
region (opcional)stringThe region of the visitor.
city (opcional)stringThe city of the visitor.
postalCode (opcional)stringThe postal code of the visitor.
latitude (opcional)floatThe latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees.
longitude (opcional)floatThe longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees.
  • Each visitor can have only one Geolocation. Adding a second Geolocation overwrites the first one.
kameleoonClient.addData(visitorCode, new Geolocation("France", "Île-de-France", "Paris"));

ApplicationVersion

ApplicationVersion represents the semantic version number of your application.
A visitor can have only one ApplicationVersion. Adding a second instance will overwrite the first one.
NombreTipoDescripción
version (opcional)stringThe mobile application version. This field must follow semantic versioning. Accepted formats are major, major.minor, or major.minor.patch.
client.AddData(visitorCode, new ApplicationVersion("10")) // major

client.AddData(visitorCode, new ApplicationVersion("10.20")) // major.minor

client.AddData(visitorCode, new ApplicationVersion("10.20.30")) // major.minor.patch

Returned Types

DataFile

El DataFile contiene los detalles de configuración del SDK. It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
NombreTipoDescripción
FeatureFlagsIReadOnlyDictionary<string, FeatureFlag>A map of FeatureFlag objects, keyed by feature flag keys.
DateModifiedlongThe timestamp (in milliseconds) indicating when the DataFile was last modified.
// Retrieves the map of feature flags from the DataFile.
// The map is keyed by feature flag identifiers, with each value being a FeatureFlag object.
IReadOnlyDictionary<string, FeatureFlag> featureFlags = dataFile.FeatureFlags;

// Retrieves the last modification timestamp of the DataFile.
// The value is a long representing milliseconds since the Unix epoch.
long dateModified = dataFile.DateModified;

Variation

Variation contains information about the assigned variation to the visitor (or the default variation if no specific assignment exists).
NombreTipoDescripción
KeystringThe unique key identifying the variation.
IdintThe ID of the assigned variation (or Variation.UndefinedId if it’s the default variation).
ExperimentIdintThe ID of the experiment associated with the variation (or Variation.UndefinedId if default).
VariablesIReadOnlyDictionary<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 the Variable object contains specific details about each variable within a variation.
  • Ensure that your code handles the case where Id or ExperimentId may be Variation.UndefinedId, indicating a default variation.
  • The Variables dictionary might be empty if no variables are associated with the variation.
// 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.
NombreTipoDescripción
KeystringThe unique key identifying the variable.
TypestringThe type of the variable. Possible values: BOOLEAN, NUMBER, STRING, JSON, JS, CSS.
ValueobjectThe value of the variable, which can be of the following types: bool, int, double, string, Newtonsoft.Json.Linq.JToken.
// 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;

Deprecated methods

Estos métodos están obsoletos y se eliminarán en la versión 5.0.0 del SDK.

GetFeatureVariationKey()

  • 📨 Envía datos de seguimiento a Kameleoon
To get feature variation key, call GetFeatureVariationKey().
Use GetVariation() instead.
Este método requiere un visitorCode y un featureKey (o featureID) para comprobar si un usuario puede acceder a una funcionalidad específica. If the user has never been linked to this feature, the SDK will randomly decide whether to activate it, returning either true (they can access the feature) or false (they cannot). If the user with the given visitorCode is already linked to this feature, the system will return the previous value of the featureFlag. Asegúrese de incluir un manejo de errores adecuado en su código, como se muestra en el ejemplo, para capturar cualquier error potencial. Si especifica un visitorCode, el método GetFeatureVariationKey() lo usa como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitorCode y establece el parámetro isUniqueIdentifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
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;
}
Argumentos
NombreTipoDescripción
visitorCodestringIdentificador único del usuario. Este campo es obligatorio.
featureKeystringClave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio.
isUniqueIdentifier (Obsoleto)boolParámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es false. The field is optional.
Valor de retorno
TipoDescripción
stringVariation key of the feature flag that is registered for a given visitorCode.
Excepciones lanzadas
TipoDescripción
KameleoonException.FeatureNotFoundException 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.FeatureEnvironmentDisabledExcepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development).

GetActiveFeatureListForVisitor()

  • Use GetActiveFeatures instead.
  • This method was previously called ObtainFeatureListForVisitorCode(), which was removed in SDK version 4.0.0.
Este método toma un single visitorCode parameter. Return only the active feature flags for the specified visitor.
var featureListIds = kameleoonClient.GetActiveFeatureListForVisitor(visitorCode)
Argumentos
NameTipoDescripción
visitorCodestringIdentificador único del usuario. Este campo es obligatorio.
Valor de retorno
TipoDescripción
List<string>List of active feature flag IDs available for specific visitorCode

GetFeatureVariable()

  • 📨 Envía datos de seguimiento a Kameleoon
Use GetVariation() instead.
To get variable of variation key associated with a user, call the GetFeatureVariable() method of our SDK. Este método requiere un visitorCode y un featureKey (o featureID) para comprobar si un usuario puede acceder a una funcionalidad específica. If the user has never been linked to this feature, the SDK will randomly decide whether to activate it, returning either true (they can access the feature) or false (they cannot). If the user with the given visitorCode is already linked to this feature, the system will return the previous value of the featureFlag. Asegúrese de incluir un manejo de errores adecuado en su código, como se muestra en el ejemplo, para capturar cualquier error potencial. Si especifica un visitorCode, el método GetFeatureVariable() lo usa como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitorCode y establece el parámetro isUniqueIdentifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
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 on 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
}
Argumentos
NombreTipoDescripción
visitorCodestringIdentificador único del usuario. Este campo es obligatorio.
featureKeystringClave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio.
variableKeystringKey of the variable you want to get a value. Este campo es obligatorio.
isUniqueIdentifier (Obsoleto)boolParámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es false. The field is optional.
Valor de retorno
TipoDescripción
objectValue of variable of variation that is registered for a given visitorCode for this feature flag. Possible types: bool, int, double, string, JObject, JArray
Excepciones lanzadas
TipoDescripción
KameleoonException.FeatureNotFoundException 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.FeatureEnvironmentDisabledExcepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development).
KameleoonException.FeatureVariableNotFoundException 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.VisitorCodeInvalidExcepción que indica que el visitor code especificado no es válido. (Está vacío o tiene más de 255 caracteres).

GetActiveFeatures()

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, el valor predeterminado es Kameleoon.Types.Variation.UndefinedId.
IReadOnlyDictionary<string, Kameleoon.Types.Variation> activeFeatures = GetActiveFeatures(visitorCode);
Argumentos
NameTypeDescription
visitorCodestringUnique identifier of the visitor you want to retrieve active feature flags for. Este campo es obligatorio.
Valor de retorno
TipoDescripción
IReadOnlyDictionary<string, Kameleoon.Types.Variation>A dictionary that contains the assigned variations of the active features using the active feature IDs as keys.
Excepciones lanzadas
TypeDescription
KameleoonException.VisitorCodeInvalidExcepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters.

GetFeatureVariationVariables()

  • Use GetVariation() instead.
  • This method was previously called GetFeatureAllVariables(), which was removed in SDK version 4.0.0.
Llame a este método para recuperar todas las variables de funcionalidad de una funcionalidad. Puede modificar las variables de funcionalidad en la aplicación Kameleoon. Este método toma two input parameters: featureKey and variationKey. It returns 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 SDK’s internal configuration.
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 a generic Exception handler which will handle all exceptions.
  Console.WriteLine("Exception occurred");
}
Argumentos
NombreTipoDescripción
featureKeystringIdentificator key of the feature you need to obtain. Este campo es obligatorio.
variationKeystringClave de la variación que desea obtener. Este campo es obligatorio.
Valor de retorno
TipoDescripción
Dictionary<string, object>Datos asociados con este feature flag. The values of can be a number, string, boolean or object (depending on the type defined on the web interface).
Excepciones lanzadas
TipoDescripción
KameleoonException.FeatureNotFoundException 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.FeatureEnvironmentDisabledException indicating that the feature flag is disabled for the visitor’s current environment (for example, production, staging, or development).
KameleoonException.FeatureVariationNotFoundException 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.