Fs class

The Fs class represents the SDK. It facilitates the initialization process and creation of new visitors.

start method

Start the flagship SDK

  • static void Start(string envId, string apiKey, [FlagshipConfig config = null])

Arguments:

NameTypeDescription
envIdstringEnvironment id provided by Flagship.
apiKeystringApi authentication key provided by Flagship.
configFlagshipConfigCustom flagship configuration. see configuration attribute

Example:

// Use the Flagship package
using Flagship.Main;
// ...

Fs.Start("ENV_ID", "API_KEY");

newVisitor method

Initialize the builder for visitor creation, and Return a VisitorBuilder instance.

  • static VisitorBuilder NewVisitor(string visitorId, bool hasConsented)

Arguments:

NameTypeDescription
visitorIdstringUnique visitor identifier. If null is given, the SDK will generat one by default.
hasConsentedbool Required
Specifies if the visitor has consented for personal data usage.
When set to false, some features will be deactivated and the cache will be deactivated and cleared.

Example:

using Flagship.Main;

//...

var visitor = Fs.NewVisitor("<VISITOR_ID>", true)
  .WithContext(new Dictionary<string, object> {
    ["isVIP"] = true,
    ["country"] = "NL",
    ["loginProvider"] = "Google"
    })
  .Build();

close method

This method batches and sends all collected hits. It should be called when your application (script) is about to terminate or in the event of a crash to ensures that all collected data is sent and not lost.

  • static Task Close()

Config property

Return the current config used by the SDK. see configuration

  • static FlagshipConfig Config { get; }

Visitor property

Return the last visitor created and saved or return undefined if no visitor has been saved. see newVisitor.

  • static Visitor Visitor { get; }

Status property

Return current status of Flagship SDK.Status of the SDK.

  • static FSSdkStatus Status { get; }

FlagshipConfig class

This class represents the configuration for the Flagship SDK. It provides methods to set and retrieve various configuration options.

DecisionApiConfig class

Initialize the SDK to start in Decision-Api mode

When the SDK is running in DecisionApi mode, the campaign assignments and targeting validation take place server-side in the flagship infrastructure. In this mode, each call to the fetchFlags method to refresh the flags will make an HTTP request.

Example:

// Use the Flagship package
using Flagship.Main;
// ...

Fs.Start("ENV_ID", "API_KEY", new DecisionApiConfig { 
                LogManager = new sentryCustomLog(),
                LogLevel = Flagship.Enums.LogLevel.ALL,
                Timeout = TimeSpan.FromSeconds(2),
            });

BucketingConfig class

Initialize the SDK to start in Bucketing-mode.

In Bucketing mode, the SDK downloads all campaign configurations in a single bucketing file. This allows the SDK to compute variation assignments on the client-side. The bucketing file is cached and only re-downloaded when campaign configurations are updated from the Flagship interface. Learn more

Example:

// Use the Flagship package
using Flagship.Main;
// ...

Fs.Start("ENV_ID", "API_KEY", new BucketingConfig { 
                LogManager = new sentryCustomLog(),
                LogLevel = Flagship.Enums.LogLevel.ALL,
                Timeout = TimeSpan.FromSeconds(2),
                PollingInterval = TimeSpan.FromSeconds(2)
            });

Configuration options

Here are all available options you can set on the SDK:

AttributeTypeDefaultDescription
TimeoutTimeSpan2sRequired
Specify timeout for api request.
Note: timeout can't be lower than 0 second.
LogLevelFlagship.Enums.LogLevelFlagship.Enums.LogLevel.ALLRequired
Set the maximum log level to display
seeLogLevel
LogManagerFlagship.Logger.IFsLogManagerObjectRequired
Specify a custom implementation of LogManager in order to receive logs from the SDK.
Note: The object must fill Interface IFsLogManager
PollingIntervalTimeSpan2sRequired
Specify delay between two bucketing polling when SDK is running on Bucketing mode.
Note: If 0 is given, it should poll only once at start time.
VisitorCacheImplementationFlagship.Cache.IVisitorCacheImplementationundefinedOptional
Define an object that implement the interface IVisitorCacheImplementation, to handle the visitor cache. see cache-manager
HitCacheImplementationFlagship.Cache.IHitCacheImplementationundefinedOptional
Define an object that implement the interface IHitCacheImplementation, to handle the visitor cache. see cache-manager
DisableCachebooleanfalseRequired
if it's set to true, hit cache and visitor cache will be disabled otherwise will be enabled. see cache-manager
OnSdkStatusChangedFlagship.Delegate.StatusChangedDelegateundefinedOptional
Define an event to be callback when the SDK status has changed.
see arguments.
TrackingManagerConfigFlagship.Config.ITrackingManagerConfigObjectDefine options to configure hit batching
trackingMangerConfig
OnVisitorExposedFlagship.Delegate.OnVisitorExposedDelegateundefinedOptional
Define an event to be callback each time a Flag has been exposed to a visitor.
see arguments
DisableDeveloperUsageTrackingbooleanfalse Determines whether to disable the collection of analytics data.

LogLevel

Flagship.Enums.LogLevel is an enum defined the level of log to receive

KeyValueTypeDescription
NONE0intLogging will be disabled.
EMERGENCY1intOnly emergencies will be logged
ALERT2intOnly alerts and above will be logged.
CRITICAL3intOnly critical and above will be logged.
ERROR4intOnly errors and above will be logged.
WARNING5intOnly warnings and above will be logged.
NOTICE6intOnly notices and above will be logged.
INFO7intOnly info logs and above will be logged.
DEBUG8intOnly debug logs and above will be logged.
ALL9intEverything will be logged.

IFsLogManager

The aims of Flagship.Logger.IFsLogManager Interface is to define methods that an object must have in order to receive Flagship SDK logs.

interface IFsLogManager
    {
         void Emergency(string message, string tag);
         void Alert(string message, string tag);
         void Critical(string message, string tag);
         void Error(string message, string tag);
         void Warning(string message, string tag);
         void Notice(string message, string tag);
         void Info(string message, string tag);
         void Debug(string message, string tag);
         void Log(LogLevel level, string message, string tag);
    }

Example:

ArgumentTypeDescription
messagestringGet a description of the log
tagstringGet the function that triggered the log
levelnumberGet the log level.

Note:only for log method see LogLevel

OnSdkStatusChanged

The Flagship.Delegate.StatusChangedDelegate delegate has one argument:

ArgumentTypeDescription
statusFlagship.Enums.FSSdkStatusStatus of the SDK. seeFSSdkStatus

OnVisitorExposed

The OnVisitorExposedDelegate delegate has 2 arguments :

ParameterTypeDescription
exposedVisitorIExposedVisitorAn interface to get information about the visitor to whom the flag has been exposed. see detail
exposedFlagIExposedFlagAn interface to get information about the flag that has been exposed.see detail

Here is an example on how to use this callback:

Example with Mixpanel integration
Example with Segment integration


TrackingManagerConfig class

Represents the configuration for the tracking manager.

The Tracking Manager’s batch processing reduces network traffic, prevents hit loss through caching, and resends any failed hits.

Configuration options

List of available options for the tracking manager:

KeyTypeDefault valueDescription
CacheStrategyFlagship.Enums.CacheStrategyPERIODIC_CACHINGDefine the strategy that will be used for hit caching
see cacheStrategy
PoolMaxSizenumber100 Define the maximum number of hits the pool must reach to automatically batch all hits in the pool and send them.

Note:

- Must be greater than 5 otherwise default value will be used
- Having a large PoolMaxSize can lead to performance issues
BatchIntervalsTimeSpan10s Define a regular interval of time to trigger batch processing

Note:

- The process will batch all hits from the pool whether PoolMaxSize is reached or not
- Must be between 1sec and 14400s (4hours). Otherwise default value will be applied

CacheStrategy

Flagship.Enums.CacheStrategy is an enum defining the different caching strategies

KeyTypevalueDescription
CONTINUOUS_CACHINGnumber0When a hit is emitted, it will first be cached in database using IHitCacheImplementation and added into the pool, then after batching and sending, it will be flushed from database using IHitCacheImplementation.

Note:

- It is Recommended for client-side applications and should be used when your application is running in an environment where the probability of data loss is high.
- Keep in mind that this strategy can do a lot of database I/O depending on how many hits your visitor can send.
PERIODIC_CACHINGnumber1When a hit is emitted, it will be added into the pool, then after batching and sending, all remained database hits will be flushed, then the entire pool will be cached using IHitCacheImplementation for both actions.

Note:

- It is recommended for server-side applications and should be used when your application sends a lot of hits and the probability of data loss is low.
- The number of I/Os in the database is low.

Example:

// Use the Flagship package
using Flagship.Main;
// ...

Fs.Start("ENV_ID", "API_KEY",
    new DecisionApiConfig
    {
        TrackingMangerConfig = new TrackingManagerConfig
        {
            CacheStrategy = Flagship.Enums.CacheStrategy.CONTINUOUS_CACHING,
            PoolMaxSize = 100,
            BatchIntervals = TimeSpan.FromSeconds(10)
        }
    });

VisitorBuilder class

VisitorBuilder is a fluent interface builder api managing Visitor creation.

SetIsAuthenticated method

Specify whether the Visitor is authenticated or anonymous.

  • VisitorBuilder SetIsAuthenticated(bool isAuthenticated)

Argument:

NameTypeDefaultDescription
isAuthenticatedboolFalseTrue for an authenticated visitor and false for an anonymous visitor.

SetContext method

Specify Visitor initial context key / values used for targeting.

  • VisitorBuilder SetContext(IDictionary<string, object> context)

Argument:

NameTypeDescription
contextIDictionary<string, object>visitor initial context.
Note:

- Visitor context values must have a type of string, bool, numeric
- Visitor context keys and values are case sensitive

SetShouldSaveInstance method

Specifies whether the newly created visitor instance should be saved into Flagship instance.

  • VisitorBuilder SetShouldSaveInstance(bool value)

Argument:

NameTypeDescription
valueboolIf set to true, the newly created visitor instance will be saved into Flagship.
If set to false, the newly created visitor instance will not be saved, but simply returned.

Build method

Complete the Visitor Creation process and return an instance of IVisitor

  • IVisitor Build()

IVisitor interface

The IVisitor interface represents a unique user within your application. It aids in managing the visitor's data and fetching the corresponding flags for the visitor from the Flagship platform .

VisitorId property

The unique visitor identifier.

  • string VisitorId { get; set; }

AnonymousId property

Visitor anonymous id

  • string AnonymousId { get; }

HasConsented property

Return True if the visitor has consented for private data usage, otherwise return False.

  • bool HasConsented { get; }

SetConsent method

Set if visitor has consented for protected data usage.

  • void SetConsent(bool hasConsented);

Context property

Get the current visitor's context

  • IDictionary<string, object> Context { get; }

ClearContext method

Clear the visitor's context

void ClearContext();

FlagsStatus property

The fetch status of the flags. see the IFlagsStatus

  • IFlagsStatus FlagsStatus { get; }

OnFlagsStatusChanged event

This event is triggered when the fetch flags status has changed.

  • event OnFlagStatusChangedDelegate OnFlagsStatusChanged

The Flagship.Delegate.OnFlagStatusChangedDelegate delegate has one argument:

ArgumentTypeDescription
fetchFlagsStatusIFlagsStatusFetch flags status. seeIFlagsStatus

OnFlagStatusFetchRequired event

This event is triggered when the fetch flags status is set to FETCH_REQUIRED.

  • event OnFlagStatusFetchRequiredDelegate OnFlagStatusFetchRequired

The Flagship.Delegate.OnFlagStatusFetchRequiredDelegate delegate has one argument:

ArgumentTypeDescription
reasonFSFetchReasonsFetch flags status. seeFSFetchReasons

OnFlagStatusFetched event

This event is triggered when the fetch flags status is set to FETCHED.

  • event OnFlagStatusFetchedDelegate OnFlagStatusFetched

UpdateContext method

Update the visitor context values, matching the given keys, used for targeting. If the key doesn't exist in the visitor's context, it will be added.

  • void UpdateContext(IDictionary<string, object> context)

It has one argument :

ArgumentTypeDescription
contextIDictionary<string, object>A Set of keys, values.
  • void UpdateContext(string key, string value)

It has two arguments :

ParameterTypeDescription
keystringContext key.
valuestringContext value.
  • void UpdateContext(string key, double value)

It has two arguments :

ParameterTypeDescription
keystringContext key.
valuedoubleContext value.
  • void UpdateContext(string key, bool value)

It has two arguments :

ParameterTypeDescription
keystringContext key.
valueboolContext value.

Context with predefined keys of context

Here's an example of how to use these predefined keys to update the visitor context in both Node.js and Deno environments:

using Flagship.Main;

//...

var visitor = Fs.NewVisitor("<VISITOR_ID>", true).Build();

visitor.UpdateContext(Flagship.Enums.PredefinedContext.OS_NAME, "linux");
visitor.UpdateContext(Flagship.Enums.PredefinedContext.IP, "127.0.0.1");

Learn more about predefined keys of context

FetchFlags method

Invokes the decision API or refers to the bucketing file to refresh all campaign flags based on the visitor's context.

  • Task FetchFlags()

Example:

using Flagship.Main;

//...

var visitor = Fs.NewVisitor("<VISITOR_ID>", true).Build();
  
await visitor.FetchFlags();

//ready to use all features from the SDK

GetFlag method

Return an instance of IFlag by its key. If no flag matches the given key, an empty flag will be returned. The Exists() method of the IFlag object can be used to check if the flag has been found.

  • IFlag GetFlag(string key)
ArgumentTypeDescription
keystringkey associated to the flag.

Authenticate method

Authenticate anonymous visitor.

  • void Authenticate(string visitorId)
ArgumentTypeDefaultDescription
visitorIdstringrequiredId of the new authenticated visitor.

📘

Information

  • It is recommended calling the fetchFlags method just after authenticating a visitor as the visitor data has changed.
  • The visitor targeting / Flags could change based on this new data.

Unauthenticate method

This method changes authenticated Visitor to anonymous visitor.

  • void Unauthenticate()

📘

Information

  • It is recommended calling the fetchFlags method just after authenticating a visitor as the visitor data has changed.
  • The visitor targeting / Flags could change based on this new data.

getFlags method

Returns a collection of all flags fetched for the visitor.

  • IFlagCollection GetFlags()

SendHit method

This method sends Hits to the Flagship servers for reporting.

  • Task SendHit(HitAbstract hit)
ParameterTypeDefaultDescription
hitHitAbstractrequiredHit to send. see Hit

Example:

using Flagship.Main;

//...

var visitor = Fs.NewVisitor("<VISITOR_ID>", true).Build();

await visitor.SendHit(new Page("https://www.my_domain_com/my_page"));

IFlag interface

This interface represents a flag in the Flagship SDK. It helps you retrieve the flag value, access flag metadata, expose the flag, verify the flag's existence, and get the flag status with the following API:

GetValue method

It returns the value of the flag if the flag exists and the type of the default value matches the flag type value, otherwise it returns the default value.

  • T GetValue<T>(T defaultValue, [bool visitorExposed = true])

Argument:

NameTypeDefault ValueDescription
defaultValueTRequiredRequiredThe default value of the flag.
visitorExposedBooleantrueIndicates to Flagship that the visitor have been exposed and have seen this flag. This will increment the visits for the current variation on your campaign reporting.
It is possible to set this param to false then call the VisitorExposed() method afterward when the visitor sees the flag value.

Example:

using Flagship.Main;

//...

var visitor = Fs.NewVisitor("<VISITOR_ID>", true).Build();
  
await visitor.FetchFlags();

var flag = visitor.GetFlag("displayVipFeature");

var flagValue = flag.GetValue(false);

📘

Information

  • Default value must be one of the following type : string, number, boolean, Newtonsoft.Json.Linq.JArray, Newtonsoft.Json.Linq.JObject.

Metadata property

It returns the campaign's metadata, an empty object if the Flag doesn't exist ,or if the default value type does not correspond to the Flag type in Flagship. see IFlagMetadata

  • IFlagMetadata Metadata { get; }

VisitorExposed method

Notifies Flagship that the visitor has been exposed to and seen this flag.

  • Task VisitorExposed()

Exists property

Checks if the flag exists.

  • bool Exists { get; }

Status property

Returns the status of the flag.

  • FSFlagStatus Status { get; }

IFlagCollection interface

It represents a collection of flags.

Get method

It returns the flag associated with the specified key, or an empty if the key is not found.

  • IFlag Get(string key)

Arguments:

NameTypeDescription
keyStringThe key associated to the flag.

Has method

Checks if the collection contains a flag with the specified key.

  • bool Has(string key)

Arguments:

NameTypeDescription
keyStringThe key associated to the flag.

Keys method

Gets the keys of all flags in the collection.

  • HashSet<string> Keys()

Filter method

It filters the collection based on a predicate function and returns A new IFlagCollection containing the flags that satisfy the predicate.

  • IFlagCollection Filter(Func<IFlag, string, IFlagCollection, bool> predicate)

Arguments:

NameTypeDescription
predicatefunctionThe predicate function used to filter the collection.

ExposeAllAsync method

Exposes all flags in the collection.

  • Task ExposeAllAsync()

GetMetadata method

A map containing the metadata for all flags in the collection.

  • Dictionary<string, IFlagMetadata> GetMetadata()

ToJson method

Serializes the metadata for all flags in the collection.

  • string ToJson()

Status property

Return flags status

  • FSFlagStatus Status { get; }

Hit Tracking

This section guides you on how to track visitors in your application and learn how to build hits to feed your reports. For more details about our measurement protocol, refer to our Universal Collect documentation.

There are five different types of Hits:

  • Page
  • Screen
  • Transaction
  • Item
  • Event

Common Optional Parameters for Hits

await visitor.SendHit(new Screen("abtastylab")
{
  UserIp = "127.0.0.1",
  ScreenResolution=  "800X600",
  Locale = "fr",
  SessionNumber = "1234"
  });
ParameterTypeDescription
UserIpstring(Optional) visitor IP
ScreenResolutionstring(Optional) Screen resolution.
Localestring(Optional) visitor language
SessionNumberstring(Optional) Session number

Page hit

This hit should be sent each time a visitor navigates to a new page.

Constructor

new Page(string documentLocation)

Argument:

ParamsTypeDescription
documentLocationstringValid url.

A hit of type Page has this following structure:

PropertyTypeDescription
DocumentLocationstringValid url.

Screen hit

This hit should be sent each time a visitor arrives on an interface on client side.

Constructor

new Screen(string documentLocation)

Argument:

ParamsTypeDescription
documentLocationstringScreen name.

A hit of type Screen has this following structure:

PropertyTypeDescription
DocumentLocationstringScreen name.

Transaction

This hit should be sent when a visitor complete a Transaction.

Constructor

new Transaction(string transactionId, string affiliation)

Arguments:

ParamsTypeDescription
transactionIdstringUnique identifier for your transaction.
affiliationstringThe name of the KPI that you will have inside your reporting. Learn more

A hit of type Transaction has this following structure:

PropertyTypeDescription
TransactionIdstringUnique identifier for your transaction.
AffiliationstringThe name of the KPI that you will have inside your reporting. Learn more
TotalRevenuedoubleSpecifies the total revenue associated with the transaction. This value should include any shipping and/or tax amounts.
ShippingCostsdoubleThe total shipping cost of your transaction.
ShippingMethodstringThe shipping method for your transaction.
TaxesdoubleSpecifies the total amount of taxes in your transaction.
CurrencystringSpecifies the currency of your transaction. NOTE: This value should be a valid ISO 4217 currency code.
PaymentMethodstringSpecifies the payment method used for your transaction.
ItemCountintSpecifies the number of items in your transaction.
CouponCodestringSpecifies the coupon code used by the customer in your transaction.

Item

This hit is used to link an item with a transaction. It must be sent after the corresponding transaction hit.

Constructor

new Item(string transactionId, string name, string code )

Arguments:

ParamsTypeDescription
transactionIdstringUnique identifier for your transaction.
namestringName of your item.
codestringSpecifies the SKU or item code.

A hit of type Item has this following structure:

PropertyTypeDescription
TransactionIdstringUnique identifier for your transaction.
NamestringName of your item.
CodestringSpecifies the SKU or item code.
CategorystringSpecifies the category that the item belongs to.
PricedoubleSpecifies the price for a single item/unit.
QuantityintSpecifies the number of items purchased.

Event

This hit can be used for any event (e.g. Add To Cart click, newsletter subscription).

Constructor

new Event( EventCategory category, string action)

Arguments:

ParamsTypeDescription
CategoryFlagship.Hit.EventCategorySpecifies the category of your event.
ActionstringEvent name that will also serve as the KPI that you will have inside your reporting. Learn more

A hit of type Event has this following structure:

PropertyTypeDescription
CategoryFlagship.Hit.EventCategorySpecifies the category of your event.
ActionstringEvent name that will also serve as the KPI that you will have inside your reporting. Learn more
LabelstringAdditional description of your event.
Valueuint(optional) Can be used to evaluate visitor interactions with individual site objects or content items.
NOTE: this value must be non-negative.

Cache management

The aims of the cache management is the response to the following problematic:

  • Re-allocation in bucketing mode :

In bucketing mode, the SDK will always keep visitor in variation to which he was allocated first, in case of the customer or the dynamic allocation has changed the traffic allocation. Indeed in bucketing mode the assignation is made on local device. So changing campaign allocation in the platform would make the visitors see different campaigns.

  • Handle offline mode on client side :

With the cache enabled, the SDK will try to retrieve the latest visitor data (campaign assignations) from the cache, also will save all the failed hits and VisitorExposed in order to resend them later.

To use the cache manager the intefaces IVisitorCacheImplementation and IHitCacheImplementation must be implemented through visitorCacheImplementation and hitCacheImplementation properties of configuration.

Visitor Cache

The visitor cache is used to store the visitor data in a database through the Flagship.Cache.IVisitorCacheImplementation interface which defines the methods that an object must implement to manager it.

interface IVisitorCacheImplementation
{
  TimeSpan? LookupTimeout { get; set; }
  Task CacheVisitor(string visitorId, JObject data);
  Task<JObject> LookupVisitor(string visitorId);
  Task FlushVisitor(string visitorId);
}

CacheVisitor method

This method is invoked when the SDK needs to store visitor information in your database.

  • Task CacheVisitor(string visitorId, JObject data)

Arguments :

ArgumentTypeDescription
visitorIdstringvisitor ID
DataNewtonsoft.Json.Linq.JObjectvisitor data. The JSON object has the follows shape see.

LookupVisitor method

This method is invoked when the SDK needs to retrieve visitor information associated with a specific visitor ID from your database.

It has to return an JSON object which follows this shape see.

  • Task<JObject> LookupVisitor(string visitorId)

Argument :

ArgumentTypeDescription
visitorIdstringvisitor ID

FlushVisitor method

This method is called when the SDK needs to erase the visitor information corresponding to visitor ID in your database.

It will be called every time setConsent get false.

  • Task FlushVisitor(string visitorId)

Argument :

ArgumentTypeDescription
visitorIdstringvisitor ID

📘

Information

  • FlushVisitor method will be called every time SetConsent get false.

Visitor Cache format

{
  "Version": 1,
  "Data": {
      "VisitorId": "visitor_1",
      "AnonymousId": null,
      "Consent": true,
      "Context": {
        "qa_getflag": true,
        "fs_client": ".NET",
        "fs_version": "V3"
      },
    "AssignmentsHistory": {
      "xxxxxxxxxxxxxxxxxxxx": "xxxxxxxxxxxxxxxxxxxx",
      "yyyyyyyyyyyyyyyyyyyy": "yyyyyyyyyyyyyyyyyyyy"
    },
    "Campaigns": [
      {
        "CampaignId": "xxxxxxxxxxxxxxxxxxxx",
        "VariationGroupId": "xxxxxxxxxxxxxxxxxxxx",
        "VariationId": "xxxxxxxxxxxxxxxxxxxx",
        "IsReference": false,
        "Type": 2,
        "Activated": false,
        "Slug": xxxxxxxxxxxxxxx,
        "Flags": {
          "key": "value"
        }
      },
      {
        "CampaignId": "xxxxxxxxxxxxxxxxxxxx",
        "VariationGroupId": "xxxxxxxxxxxxxxxxxxxx",
        "VariationId": "xxxxxxxxxxxxxxxxxxxx",
        "IsReference": false,
        "Type": "",
        "Activated": false,
        "Slug": xxxxxxxxxxxxxxx,
        "Flags": {
          "myAwesomeFeature": 20
        }
      }
    ]
  }
}

Hit Cache

The hit cache is used to store hits in your database depending on strategy used through the IHitCacheImplementation interface which defines the methods that an object must implement to handle it.

interface IHitCacheImplementation
{
  TimeSpan? LookupTimeout { get; set; }
  Task CacheHit(JObject data);
  Task<JObject> LookupHits();
  Task FlushHits(string[] hitKeys);
  Task FlushAllHits();
}

CacheHit method

This method will be called to cache hits depending on cache strategy used.

  • Task CacheHit(JObject data)

Argument :

ArgumentTypeDescription
dataNewtonsoft.Json.Linq.JObjecthit data. The JSON object has the follows shape see.

LookupHits method

This method will be called to load all hits from your database and trying to send them again in the background.

It has to return an JSON object which follows this shape see.

  • Task<JObject> LookupHits()

FlushHits method

his method will be called to erase all hits matching the unique Hits ID from your database.

NOTE: It will be called every time SetConsent get false to erase all hits from database for visitor who set consent to false.

  • Task FlushHits(string[] hitKeys)

Argument :

ArgumentTypeDescription
hitKeysstring[]Unique hit IDS

FlushAllHits method

This method will be called to erase all hits in your database without exception.

  • Task FlushAllHits()

Hit Cache format

{
    "visitorId:Guid": {
        "version": 1,
        "data": {
            "visitorId": "visitorId",
            "anonymousId": "d7c40c75-1833-4137-a3d0-8a9837e36e79",
            "type": 1,
            "time": "2023-04-06T11:03:51.1885042-05:00",
            "content": {
                "documentLocation": "Screen 1",
                "key": "visitorId:Guid",
                "visitorId": "visitorId",
                "type": 1,
                "ds": "APP",
                "anonymousId": "d7c40c75-1833-4137-a3d0-8a9837e36e79",
                "userIp": null,
                "screenResolution": null,
                "locale": null,
                "sessionNumber": null,
                "createdAt": "2023-04-06T11:03:51.1864852-05:00"
            }
        }
    }
}

📘

Information

  • FlushHits method will be called every time setConsent get false.
  • Hits older than 4H will be ignored during the resending process.

IExposedVisitor

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Flagship.FsVisitor
{
    public interface IExposedVisitor
    {
        /// <summary>
        /// The key of flag
        /// </summary>
        string Id { get; }

        /// <summary>
        /// Visitor anonymous id
        /// </summary>
        string AnonymousId { get; }

        /// <summary>
        /// Visitor context
        /// </summary>
        IDictionary<string, object> Context { get; }
    }
}

IExposedFlag

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Flagship.FsFlag
{
    public interface IExposedFlag
    {
        /// <summary>
        /// Get the flag key
        /// </summary>
        string Key { get; }

        /// <summary>
        /// Get the flag value
        /// </summary>
        object Value { get; }

        /// <summary>
        /// Get the flag default value
        /// </summary>
        object DefaultValue { get; }

        /// <summary>
        /// Get the flag metadata
        /// </summary>
        IFlagMetadata Metadata { get; }

    }
}

IFlagsStatus interface

It Represents the status of visitor fetch for flag data.

using Flagship.Enums;
using System;

namespace Flagship.Model
{
    internal class FetchFlagsStatus : IFetchFlagsStatus
    {
        public FSFetchStatus Status { get; set; }

        public FSFetchReasons Reason { get; set; }
    }
}

List of possible Flagship.Enum.FSFlagStatus:

StatusTypeValueDescription
FETCHEDint0The flags have been successfully fetched from the API or re-evaluated in bucketing mode.
FETCHINGint1The flags are currently being fetched from the API or re-evaluated in bucketing mode.
FETCH_REQUIREDint2The flags need to be re-fetched due to a change in context, or because the flags were loaded from cache or XPC.
PANICint3The SDK is in PANIC mode: All features are disabled except for the one to fetch flags.
NOT_FOUNDint4The flags were not found.

List of possible Flagship\Enum\FSFetchReason:

StatusTypeValueDescription
NONEint0Indicates that there is no specific reason for fetching flags.
VISITOR_CREATEDint1Indicates that the visitor has been created.
UPDATE_CONTEXTint2Indicates that a context has been updated or changed.
AUTHENTICATEint3Indicates that the XPC method 'authenticate' has been called.
UNAUTHENTICATEint4Indicates that the XPC method 'unauthenticate' has been called.
FETCH_ERRORint5Indicates that fetching flags has failed.
READ_FROM_CACHEint6Indicates that flags have been fetched from the cache.

FSSdkStatus

List of possible Flagship.Enums.FSSdkStatus:

StatustypevalueDescription
SDK_NOT_INITIALIZEDint0It is the default initial status. This status remains until the SDK has been initialized successfully.
SDK_INITIALIZINGint1The SDK is currently initializing.
SDK_PANICint2Flagship SDK is ready but is running in Panic mode: All features are disabled except the one which refresh this status.
SDK_INITIALIZEDint3The Initialization is done, and Flagship SDK is ready to use.

Predefined visitor context keys :

The Flagship SDK contains predefined visitor context keys.

The keys marked as Yes in the Auto-set by SDK column will be automatically set, while the ones marked as No need to be set by customer.

All possible predefined keys are listed below:

Note: All predefined contexts can be found as static property in Flagship.Enums.PredefinedContext class

SDK constant NameDescriptionContext variable nameTypeAuto-set by SDKExample
DEVICE_LOCALELanguage of the devicesdk_deviceLanguageStringNofra
DEVICE_TYPEType of the devicesdk_deviceTypeDeviceTypeNoMobile
DEVICE_MODELModel of the devicesdk_deviceModelStringNosamsung E1200
LOCATION_CITYCity geolocationsdk_cityStringNotoulouse
LOCATION_REGIONRegion geolocationsdk_regionStringNooccitanie
LOCATION_COUNTRYCountry geolocationsdk_countryStringNoFrance
LOCATION_LATCurrent Latitudesdk_latDoubleNo43.623647
LOCATION_LONGCurrent Longitudesdk_longDoubleNo1.445397
IPIP of the devicesdk_ipStringNo127.0.0.1
OS_NAMEName of the OSsdk_osNameStringYESubuntu / centos
OS_VERSION_NAMEVersion name of the OSsdk_osVersionNameStringNo9.0.0
OS_VERSION_CODEVersion code of the OSsdk_osVersionCodeNumberNo24
CARRIER_NAMEName of the carrier or mobile virtual network operatorsdk_carrierNameStringNofree
INTERNET_CONNECTIONWhat is the internet connectionsdk_internetConnectionStringNo5g
APP_VERSION_NAMEVersion name of the appsdk_versionNameStringNo1.1.2-beta
APP_VERSION_CODEVersion code of the appsdk_versionCodeNumberNo40
INTERFACE_NAMEName of the interfacesdk_interfaceNameStringNoProductPage
FLAGSHIP_CLIENTFlagship SDK client (Reserved)fs_clientStringYesTS
FLAGSHIP_VERSIONVersion of the Flagship SDK (Reserved)fs_versionStringYes2.0.0
FLAGSHIP_VISITORCurrent visitor id (Reserved)fs_usersStringYesvisitor_id

📘

Information

To overwrite the keys, use the updateContext method