# Reference

## `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:

| Name   | Type           | Description                                                                         |
| ------ | -------------- | ----------------------------------------------------------------------------------- |
| envId  | string         | Environment id provided by Flagship.                                                |
| apiKey | string         | Api authentication key provided by Flagship.                                        |
| config | FlagshipConfig | Custom flagship configuration. [see configuration attribute](#flagshipconfig-class) |

Example:

```csharp
// 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`](#visitorbuilder-class) instance.

* **`static VisitorBuilder NewVisitor(string visitorId, bool hasConsented)`**

Arguments:

| Name         | Type   | Description                                                                                                                                                                      |
| ------------ | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorId    | string | Unique visitor identifier. If `null` is given, the SDK will generate one by default.                                                                                             |
| hasConsented | bool   | **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:

```csharp
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](#flagshipconfig-class)

* **`static FlagshipConfig Config { get; }`**

### `Visitor` property

Return the last visitor created and saved or return undefined if no visitor has been saved. [see newVisitor](#newvisitor-method).

* **`static Visitor Visitor { get; }`**

### `Status` property

Return current [status](#fssdkstatus) 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`](#fetchflags-method) method to refresh the flags will make an HTTP request.

Example:

```csharp
// 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**](/server-side/concepts/bucketing.md)

Example:

```csharp
// 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:

| Attribute                     | Type                                         | Default                     | Description                                                                                                                                                                                  |
| ----------------------------- | -------------------------------------------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Timeout                       | TimeSpan                                     | 2s                          | <p><strong>Required</strong> Specify timeout for API requests.<br><strong>Note:</strong> timeout can't be lower than 0 second.</p>                                                           |
| LogLevel                      | `Flagship.Enums.LogLevel`                    | Flagship.Enums.LogLevel.ALL | <p><strong>Required</strong> Set the maximum log level to display.<br>see <code>LogLevel</code></p>                                                                                          |
| LogManager                    | `Flagship.Logger.IFsLogManager`              | `Object`                    | <p><strong>Required</strong> Specify a custom implementation of LogManager to receive logs from the SDK.<br><strong>Note:</strong> The object must implement <code>IFsLogManager</code></p>  |
| PollingInterval               | TimeSpan                                     | 2s                          | <p><strong>Required</strong> Delay between two bucketing polling when SDK is running in Bucketing mode.<br><strong>Note:</strong> If 0 is given, it should poll only once at start time.</p> |
| VisitorCacheImplementation    | `Flagship.Cache.IVisitorCacheImplementation` | undefined                   | **Optional** Object implementing `IVisitorCacheImplementation` to handle visitor cache. see cache-manager                                                                                    |
| HitCacheImplementation        | `Flagship.Cache.IHitCacheImplementation`     | undefined                   | **Optional** Object implementing `IHitCacheImplementation` to handle hit cache. see cache-manager                                                                                            |
| DisableCache                  | boolean                                      | false                       | **Required** If true, hit cache and visitor cache will be disabled. Otherwise enabled. see cache-manager                                                                                     |
| OnSdkStatusChanged            | `Flagship.Delegate.StatusChangedDelegate`    | undefined                   | **Optional** Event callback when SDK status changes. see arguments                                                                                                                           |
| TrackingManagerConfig         | Flagship.Config.ITrackingManagerConfig       | `Object`                    | Define options to configure hit batching. trackingManagerConfig                                                                                                                              |
| OnVisitorExposed              | `Flagship.Delegate.OnVisitorExposedDelegate` | undefined                   | **Optional** Event callback when a Flag has been exposed to a visitor. see arguments                                                                                                         |
| DisableDeveloperUsageTracking | boolean                                      | false                       | Determines whether to disable the collection of analytics data.                                                                                                                              |

\\

#### LogLevel

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

| Key       | Value | Type | Description                               |
| --------- | ----- | ---- | ----------------------------------------- |
| NONE      | 0     | int  | Logging will be disabled.                 |
| EMERGENCY | 1     | int  | Only emergencies will be logged           |
| ALERT     | 2     | int  | Only alerts and above will be logged.     |
| CRITICAL  | 3     | int  | Only critical and above will be logged.   |
| ERROR     | 4     | int  | Only errors and above will be logged.     |
| WARNING   | 5     | int  | Only warnings and above will be logged.   |
| NOTICE    | 6     | int  | Only notices and above will be logged.    |
| INFO      | 7     | int  | Only info logs and above will be logged.  |
| DEBUG     | 8     | int  | Only debug logs and above will be logged. |
| ALL       | 9     | int  | Everything 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.

```csharp
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:

| Argument | Type   | Description                                                                                       |
| -------- | ------ | ------------------------------------------------------------------------------------------------- |
| message  | string | Get a description of the log                                                                      |
| tag      | string | Get the function that triggered the log                                                           |
| level    | number | <p>Get the log level.<br><strong>Note:</strong> only for log method see <code>LogLevel</code></p> |

\\

#### OnSdkStatusChanged

The `Flagship.Delegate.StatusChangedDelegate` delegate has one argument:

| Argument | Type                         | Description                                         |
| -------- | ---------------------------- | --------------------------------------------------- |
| status   | `Flagship.Enums.FSSdkStatus` | Status of the SDK. [see`FSSdkStatus`](#fssdkstatus) |

#### OnVisitorExposed

The `OnVisitorExposedDelegate` delegate has 2 arguments :

| Parameter      | Type            | Description                                                                                                                   |
| -------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| exposedVisitor | IExposedVisitor | An interface to get information about the visitor to whom the flag has been exposed. [see detail](#iexposedvisitor-interface) |
| exposedFlag    | IExposedFlag    | An interface to get information about the flag that has been exposed.[see detail](#iexposedflag-interface)                    |

Here is an example on how to use this callback:

[Example with Mixpanel integration](/server-side/integrations/analytics/integrate-with-mixpanel.md)\
[Example with Segment integration](/server-side/integrations/analytics/integrate-with-segmentcom.md)

## `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:

| Key            | Type                         | Default value      | Description                                                                                                                                                                                                                                                                   |
| -------------- | ---------------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| CacheStrategy  | Flagship.Enums.CacheStrategy | `PERIODIC_CACHING` | Define the strategy that will be used for hit caching see cacheStrategy                                                                                                                                                                                                       |
| PoolMaxSize    | number                       | `100`              | <p>Define the maximum number of hits the pool must reach to automatically batch all hits in the pool and send them.<br><br><em>Note</em>:<br>• Must be greater than 5 otherwise default value will be used<br>• Having a large PoolMaxSize can lead to performance issues</p> |
| BatchIntervals | TimeSpan                     | `10s`              | <p>Define a regular interval of time to trigger batch processing.<br><br><em>Note</em>:<br>• The process will batch all hits from the pool whether PoolMaxSize is reached or not<br>• Must be between 1s and 14400s (4 hours). Otherwise default value will be applied</p>    |

### CacheStrategy

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

| Key                 | Type   | Value | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| ------------------- | ------ | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| CONTINUOUS\_CACHING | number | 0     | <p>When 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.<br><br><em>Note</em>:<br>• 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.<br>• Keep in mind that this strategy can do a lot of database I/O depending on how many hits your visitor can send.</p> |
| PERIODIC\_CACHING   | number | 1     | <p>When a hit is emitted, it will be added into the pool, then after batching and sending, all remaining database hits will be flushed, then the entire pool will be cached using IHitCacheImplementation for both actions.<br><br><em>Note</em>:<br>• 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.<br>• The number of I/Os in the database is low.</p>                                                                           |

Example:

```csharp
// 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:

| Name            | Type | Default | Description                                                               |
| --------------- | ---- | ------- | ------------------------------------------------------------------------- |
| isAuthenticated | bool | False   | `True` 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:

| Name    | Type                         | Description                                                                                                                                                                                                                                          |
| ------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| context | IDictionary\<string, object> | <p>Visitor initial context.<br><strong>Note:</strong><br>• Visitor context values must have a type of <code>string</code>, <code>bool</code>, or <code>numeric</code>.<br>• Visitor context keys and values are <strong>case sensitive</strong>.</p> |

### `SetShouldSaveInstance` method

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

* **`VisitorBuilder SetShouldSaveInstance(bool value)`**

Argument:

| Name  | Type | Description                                                                                                                                                                           |
| ----- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| value | bool | <p>If set to true, the newly created visitor instance will be saved into Flagship.<br>If set to false, the newly created visitor instance will not be saved, but simply returned.</p> |

### `Build` method

Complete the Visitor Creation process and return an instance of [`IVisitor`](#ivisitor-interface)

* `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](https://app.flagship.io/login) .

### `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-interface)

* **`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:

| Argument         | Type           | Description                                                      |
| ---------------- | -------------- | ---------------------------------------------------------------- |
| fetchFlagsStatus | `IFlagsStatus` | Fetch flags status. [see`IFlagsStatus`](#iflagsstatus-interface) |

### `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:

| Argument | Type             | Description                                                        |
| -------- | ---------------- | ------------------------------------------------------------------ |
| reason   | `FSFetchReasons` | Fetch flags status. [see`FSFetchReasons`](#iflagsstatus-interface) |

### `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 :

| Argument | Type                         | Description            |
| -------- | ---------------------------- | ---------------------- |
| context  | IDictionary\<string, object> | A Set of keys, values. |

* **`void UpdateContext(string key, string value)`**

It has two arguments :

| Parameter | Type   | Description    |
| --------- | ------ | -------------- |
| key       | string | Context key.   |
| value     | string | Context value. |

* **`void UpdateContext(string key, double value)`**

It has two arguments :

| Parameter | Type   | Description    |
| --------- | ------ | -------------- |
| key       | string | Context key.   |
| value     | double | Context value. |

* **`void UpdateContext(string key, bool value)`**

It has two arguments :

| Parameter | Type   | Description    |
| --------- | ------ | -------------- |
| key       | string | Context key.   |
| value     | bool   | Context 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:

```csharp
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**](#predefined-user-context-keys-) 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:

```csharp
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](#iflag-interface) by its key. If no flag matches the given key, an empty flag will be returned. The `Exists()` method of the [IFlag](#iflag-interface) object can be used to check if the flag has been found.

* **`IFlag GetFlag(string key)`**

| Argument | Type   | Description                 |
| -------- | ------ | --------------------------- |
| key      | string | key associated to the flag. |

\\

### `Authenticate` method

Authenticate anonymous visitor.

* **`void Authenticate(string visitorId)`**

| Argument  | Type   | Default  | Description                          |
| --------- | ------ | -------- | ------------------------------------ |
| visitorId | string | required | Id of the new authenticated visitor. |

{% hint style="info" %}
📘 Information

* It is recommended calling the [**fetchFlags**](#fetchflags-method) method just after authenticating a visitor as the visitor data has changed.
* The visitor targeting / Flags could change based on this new data.
  {% endhint %}

### `Unauthenticate` method

This method changes authenticated Visitor to anonymous visitor.

* **`void Unauthenticate()`**

{% hint style="info" %}
📘 Information

* It is recommended calling the [**fetchFlags**](#fetchflags-method) method just after authenticating a visitor as the visitor data has changed.
* The visitor targeting / Flags could change based on this new data.
  {% endhint %}

### `getFlags` method

Returns a [collection](#iflagcollection) 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)`**

| Parameter | Type        | Default  | Description                           |
| --------- | ----------- | -------- | ------------------------------------- |
| hit       | HitAbstract | required | Hit to send. [see Hit](#hit-tracking) |

Example:

```csharp
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:

| Name           | Type    | Default Value | Description                                                                                                                                                                                                                                                                                                                 |
| -------------- | ------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| defaultValue   | T       | `Required`    | **Required** The default value of the flag.                                                                                                                                                                                                                                                                                 |
| visitorExposed | Boolean | true          | <p>Indicates to Flagship that the visitor has been exposed and has seen this flag. This will increment the visits for the current variation on your campaign reporting.<br>It is possible to set this param to false then call the <code>VisitorExposed()</code> method afterward when the visitor sees the flag value.</p> |

Example:

```csharp
using Flagship.Main;

//...

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

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

var flagValue = flag.GetValue(false);
```

{% hint style="info" %}
📘 Information

* Default value must be one of the following type : `string`, `number`, `boolean`, `Newtonsoft.Json.Linq.JArray`, `Newtonsoft.Json.Linq.JObject`.
  {% endhint %}

### `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-interface)

* **`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](#fsflagstatus) of the flag.

* **`FSFlagStatus Status { get; }`**

## `IFlagCollection` interface

It represents a collection of flags.

### `Get` method

It returns the [flag](#iflag-interface) associated with the specified key, or an empty if the key is not found.

* **`IFlag Get(string key)`**

Arguments:

| Name | Type   | Description                     |
| ---- | ------ | ------------------------------- |
| key  | String | The key associated to the flag. |

### `Has` method

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

* **`bool Has(string key)`**

Arguments:

| Name | Type   | Description                     |
| ---- | ------ | ------------------------------- |
| key  | String | The 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](#iflagcollection-interface) containing the flags that satisfy the predicate.

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

Arguments:

| Name      | Type     | Description                                           |
| --------- | -------- | ----------------------------------------------------- |
| predicate | function | The predicate function used to filter the collection. |

### `ExposeAllAsync` method

Exposes all flags in the collection.

* **`Task ExposeAllAsync()`**

### `GetMetadata` method

A map containing the [metadata](#iflagmetadata-interface) for all [flags](#iflag-interface) in the collection.

* **`Dictionary<string, IFlagMetadata> GetMetadata()`**

### `ToJson` method

Serializes the [metadata](#iflagmetadata-interface) for all flags in the collection.

* **`string ToJson()`**

### `Status` property

Return flags [status](https://github.com/flagship-io/Gitbook/blob/main/SDKs/net/fsflagstatus/README.md)

* **`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](/server-side/concepts/universal-collect-1.md).

There are five different types of Hits:

* Page
* Screen
* Transaction
* Item
* Event

### Common Optional Parameters for Hits

```csharp
await visitor.SendHit(new Screen("abtastylab")
{
  UserIp = "127.0.0.1",
  ScreenResolution=  "800X600",
  Locale = "fr",
  SessionNumber = "1234"
  });
```

| Parameter        | Type   | Description                   |
| ---------------- | ------ | ----------------------------- |
| UserIp           | string | (Optional) visitor IP         |
| ScreenResolution | string | (Optional) Screen resolution. |
| Locale           | string | (Optional) visitor language   |
| SessionNumber    | string | (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:

| Params           | Type   | Description |
| ---------------- | ------ | ----------- |
| documentLocation | string | Valid url.  |

A hit of type `Page` has this following structure:

| Property         | Type   | Description |
| ---------------- | ------ | ----------- |
| DocumentLocation | string | Valid 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:

| Params           | Type   | Description  |
| ---------------- | ------ | ------------ |
| documentLocation | string | Screen name. |

A hit of type `Screen` has this following structure:

| Property         | Type   | Description  |
| ---------------- | ------ | ------------ |
| DocumentLocation | string | Screen name. |

### Transaction

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

Constructor

**`new Transaction(string transactionId, string affiliation)`**

Arguments:

| Params        | Type   | Description                                                                                                  |
| ------------- | ------ | ------------------------------------------------------------------------------------------------------------ |
| transactionId | string | Unique identifier for your transaction.                                                                      |
| affiliation   | string | The name of the KPI that you will have inside your reporting. [**Learn more**](/server-side/glossary.md#kpi) |

A hit of type `Transaction` has this following structure:

| Property       | Type   | Description                                                                                                             |
| -------------- | ------ | ----------------------------------------------------------------------------------------------------------------------- |
| TransactionId  | string | Unique identifier for your transaction.                                                                                 |
| Affiliation    | string | The name of the KPI that you will have inside your reporting. [**Learn more**](/server-side/glossary.md#kpi)            |
| TotalRevenue   | double | Specifies the total revenue associated with the transaction. This value should include any shipping and/or tax amounts. |
| ShippingCosts  | double | The total shipping cost of your transaction.                                                                            |
| ShippingMethod | string | The shipping method for your transaction.                                                                               |
| Taxes          | double | Specifies the total amount of taxes in your transaction.                                                                |
| Currency       | string | Specifies the currency of your transaction. NOTE: This value should be a valid ISO 4217 currency code.                  |
| PaymentMethod  | string | Specifies the payment method used for your transaction.                                                                 |
| ItemCount      | int    | Specifies the number of items in your transaction.                                                                      |
| CouponCode     | string | Specifies 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:

| Params        | Type   | Description                             |
| ------------- | ------ | --------------------------------------- |
| transactionId | string | Unique identifier for your transaction. |
| name          | string | Name of your item.                      |
| code          | string | Specifies the SKU or item code.         |

A hit of type `Item` has this following structure:

| Property      | Type   | Description                                      |
| ------------- | ------ | ------------------------------------------------ |
| TransactionId | string | Unique identifier for your transaction.          |
| Name          | string | Name of your item.                               |
| Code          | string | Specifies the SKU or item code.                  |
| Category      | string | Specifies the category that the item belongs to. |
| Price         | double | Specifies the price for a single item/unit.      |
| Quantity      | int    | Specifies 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:

| Params   | Type                       | Description                                                                                                                         |
| -------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| Category | Flagship.Hit.EventCategory | Specifies the category of your event.                                                                                               |
| Action   | string                     | Event name that will also serve as the KPI that you will have inside your reporting. [**Learn more**](/server-side/glossary.md#kpi) |

A hit of type `Event` has this following structure:

| Property | Type                       | Description                                                                                                                                                              |
| -------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Category | Flagship.Hit.EventCategory | Specifies the category of your event.                                                                                                                                    |
| Action   | string                     | Event name that will also serve as the KPI that you will have inside your reporting. [**Learn more**](/server-side/glossary.md#kpi)                                      |
| Label    | string                     | Additional description of your event.                                                                                                                                    |
| Value    | uint                       | <p>(optional) Can be used to evaluate visitor interactions with individual site objects or content items.<br><strong>NOTE</strong>: this value must be non-negative.</p> |

\\

## 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](#flagshipconfig-class).

### 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.

```csharp
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 :

| Argument  | Type                         | Description                                                                         |
| --------- | ---------------------------- | ----------------------------------------------------------------------------------- |
| visitorId | string                       | visitor ID                                                                          |
| Data      | Newtonsoft.Json.Linq.JObject | visitor data. The JSON object has the follows shape [`see`](#visitor-cache-format). |

#### `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](#visitor-cache-format).

* `Task<JObject> LookupVisitor(string visitorId)`

Argument :

| Argument  | Type   | Description |
| --------- | ------ | ----------- |
| visitorId | string | visitor 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`](#setconsent-function) get false.

* `Task FlushVisitor(string visitorId)`

Argument :

| Argument  | Type   | Description |
| --------- | ------ | ----------- |
| visitorId | string | visitor ID  |

{% hint style="info" %}
📘 Information

* `FlushVisitor` method will be called every time [`SetConsent`](#setconsent-function) get false.
  {% endhint %}

**Visitor Cache format**

```json
{
  "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.

```csharp
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 :

| Argument | Type                         | Description                                                                 |
| -------- | ---------------------------- | --------------------------------------------------------------------------- |
| data     | Newtonsoft.Json.Linq.JObject | hit data. The JSON object has the follows shape [`see`](#hit-cache-format). |

#### `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](#hit-cache-format).

* `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`](#setconsent-method) get false to erase all hits from database for visitor who set consent to false.

* `Task FlushHits(string[] hitKeys)`

Argument :

| Argument | Type      | Description    |
| -------- | --------- | -------------- |
| hitKeys  | string\[] | Unique hit IDS |

\\

#### `FlushAllHits` method

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

* `Task FlushAllHits()`

\\

**Hit Cache format**

```json
{
    "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"
            }
        }
    }
}

```

{% hint style="info" %}
📘 Information

* `FlushHits` method will be called every time [`setConsent`](#setconsent-method) get false.
* `Hits` older than 4H will be ignored during the resending process.\\
  {% endhint %}

## IExposedVisitor

```csharp
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

```csharp
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.

```csharp
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`:

| Status          | Type | Value | Description                                                                                                     |
| --------------- | ---- | ----- | --------------------------------------------------------------------------------------------------------------- |
| FETCHED         | int  | 0     | The flags have been successfully fetched from the API or re-evaluated in bucketing mode.                        |
| FETCHING        | int  | 1     | The flags are currently being fetched from the API or re-evaluated in bucketing mode.                           |
| FETCH\_REQUIRED | int  | 2     | The flags need to be re-fetched due to a change in context, or because the flags were loaded from cache or XPC. |
| PANIC           | int  | 3     | The SDK is in PANIC mode: All features are disabled except for the one to fetch flags.                          |
| NOT\_FOUND      | int  | 4     | The flags were not found.                                                                                       |

List of possible `Flagship\Enum\FSFetchReason`:

| Status            | Type | Value | Description                                                     |
| ----------------- | ---- | ----- | --------------------------------------------------------------- |
| NONE              | int  | 0     | Indicates that there is no specific reason for fetching flags.  |
| VISITOR\_CREATED  | int  | 1     | Indicates that the visitor has been created.                    |
| UPDATE\_CONTEXT   | int  | 2     | Indicates that a context has been updated or changed.           |
| AUTHENTICATE      | int  | 3     | Indicates that the XPC method 'authenticate' has been called.   |
| UNAUTHENTICATE    | int  | 4     | Indicates that the XPC method 'unauthenticate' has been called. |
| FETCH\_ERROR      | int  | 5     | Indicates that fetching flags has failed.                       |
| READ\_FROM\_CACHE | int  | 6     | Indicates that flags have been fetched from the cache.          |

\\

## FSSdkStatus

List of possible `Flagship.Enums.FSSdkStatus`:

| Status                | type | value | Description                                                                                                             |
| --------------------- | ---- | ----- | ----------------------------------------------------------------------------------------------------------------------- |
| SDK\_NOT\_INITIALIZED | int  | 0     | It is the default initial status. This status remains until the SDK has been initialized successfully.                  |
| SDK\_INITIALIZING     | int  | 1     | The SDK is currently initializing.                                                                                      |
| SDK\_PANIC            | int  | 2     | Flagship SDK is ready but is running in Panic mode: All features are disabled except the one which refresh this status. |
| SDK\_INITIALIZED      | int  | 3     | The 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 Name    | Description                                            | Context variable name   | Type       | Auto-set by SDK | Example         |
| -------------------- | ------------------------------------------------------ | ----------------------- | ---------- | --------------- | --------------- |
| DEVICE\_LOCALE       | Language of the device                                 | sdk\_deviceLanguage     | String     | No              | fra             |
| DEVICE\_TYPE         | Type of the device                                     | sdk\_deviceType         | DeviceType | No              | Mobile          |
| DEVICE\_MODEL        | Model of the device                                    | sdk\_deviceModel        | String     | No              | samsung E1200   |
| LOCATION\_CITY       | City geolocation                                       | sdk\_city               | String     | No              | toulouse        |
| LOCATION\_REGION     | Region geolocation                                     | sdk\_region             | String     | No              | occitanie       |
| LOCATION\_COUNTRY    | Country geolocation                                    | sdk\_country            | String     | No              | France          |
| LOCATION\_LAT        | Current Latitude                                       | sdk\_lat                | Double     | No              | 43.623647       |
| LOCATION\_LONG       | Current Longitude                                      | sdk\_long               | Double     | No              | 1.445397        |
| IP                   | IP of the device                                       | sdk\_ip                 | String     | No              | 127.0.0.1       |
| OS\_NAME             | Name of the OS                                         | sdk\_osName             | String     | YES             | ubuntu / centos |
| OS\_VERSION\_NAME    | Version name of the OS                                 | sdk\_osVersionName      | String     | No              | 9.0.0           |
| OS\_VERSION\_CODE    | Version code of the OS                                 | sdk\_osVersionCode      | Number     | No              | 24              |
| CARRIER\_NAME        | Name of the carrier or mobile virtual network operator | sdk\_carrierName        | String     | No              | free            |
| INTERNET\_CONNECTION | What is the internet connection                        | sdk\_internetConnection | String     | No              | 5g              |
| APP\_VERSION\_NAME   | Version name of the app                                | sdk\_versionName        | String     | No              | 1.1.2-beta      |
| APP\_VERSION\_CODE   | Version code of the app                                | sdk\_versionCode        | Number     | No              | 40              |
| INTERFACE\_NAME      | Name of the interface                                  | sdk\_interfaceName      | String     | No              | ProductPage     |
| FLAGSHIP\_CLIENT     | Flagship SDK client (Reserved)                         | fs\_client              | String     | Yes             | TS              |
| FLAGSHIP\_VERSION    | Version of the Flagship SDK (Reserved)                 | fs\_version             | String     | Yes             | 2.0.0           |
| FLAGSHIP\_VISITOR    | Current visitor id (Reserved)                          | fs\_users               | String     | Yes             | visitor\_id     |

{% hint style="info" %}
📘 Information

To overwrite the keys, use the [`updateContext`](#context-with-predefined-keys-of-context) method
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.abtasty.com/server-side/sdks/net/net-reference.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
