LaunchDarkly Developer Documentation

Get started in under 30 minutes.
LaunchDarkly provides feature flags as a service for Java · Python · Ruby · Go · Node.js · PHP · .NET. Control feature launches -- who sees what and when -- without multiple code deploys. Easy dashboard for phased rollouts, targeting and segmenting.
Need more help? write us at support@launchdarkly.com

Get Started    Guides

Xamarin SDK Reference

Xamarin SDK is beta software

The Xamarin SDK should not be used in production environments until version 1.0.0 is released.

This reference guide documents all of the methods available in our Xamarin SDK, and explains in detail how these methods work. If you want to dig even deeper, our SDKs are open source-- head to our Xamarin SDK GitHub repository to look under the hood.

For use in mobile / desktop and embedded client applications only

The LaunchDarkly Xamarin SDK is designed primarily for use in single user desktop and embedded applications. It follows the client-side LaunchDarkly model for single-user contexts (much like our other mobile or JavaScript SDKs)-- a network call must be made to change user contexts, so changing users should be infrequent. It is not intended for use in multi-user systems such as web servers.

Getting started

If you haven't taken a look at our Quickstart guide yet, we recommend starting there to see how install our SDK into your Xamarin application.

Requirements

The Xamarin SDK requires .NET Standard 1.0 or higher. See https://github.com/dotnet/standard/blob/master/docs/versions.md for corresponding frameworks. The Xamarin SDK depends on Xamarin.Essentials, which targets the following platforms:

  • iOS (10+)
  • Android (4.4+)
  • UWP (Fall Creators Update+)

Once the SDK is installed, you'll want to create a single, shared instance of LDClient:

User user = User.WithKey(user_key);
ldClient = LdClient.Init("MY_MOBILE_KEY", user);

You can also create your connection asynchronously as shown below:

User user = User.WithKey(user_key);
ldClient = await LdClient.InitAsync("MY_MOBILE_KEY", user);

Client Initialization

The above example shows the simplest way to create the client. It will block for up to 5 seconds until the latest feature flags have been retrieved from LaunchDarkly. Calling blocking code from the main thread in an Android app is not considered a best practice. The preferred method is shown below:

Android requires AccessNetworkState permission

For Android, the AccessNetworkState permission is required and must be configured in the Android project. Read more in the Xamarin docs about how to implement this requirement.

In the following example, we initialize the client without blocking. This allows you to use the client immediately. Flags from the previous launch of the app are stored on the device and retrieved for immediate use. The client will still connect in the background and continually update itself with the latest flags.

var config = Configuration.Default("MY_MOBILE_KEY")
  .WithStartWaitTime(TimeSpan.Zero);
User user = User.WithKey(user_key);
ldClient = LdClient.Init(config, user);

Mobile keys

Be sure to use a mobile key from your Environments page. Never embed a server-side SDK key into a mobile application.

Customizing your client

You can also pass custom parameters to the client by creating a custom configuration object:

Configuration config = LaunchDarkly.Client.Configuration.Default("YOUR_SDK_KEY")
          .WithEventQueueFrequency(TimeSpan.FromSeconds(2));
LdClient ldClient = LdClient.Init(config, user);

Here, we've customized the event queue flush frequency. The complete list of customizable parameters is as follows:

Builder Method
Parameter Type
Description
Default Value

WithUri

Uri or string

Set the base URL of the LaunchDarkly server for this configuration

WithStreamUri

Uri or string

LaunchDarkly stream URI to be used.

WithEventsUri

Uri or string

Set the events URL of the LaunchDarkly server for this configuration.

WithIsStreamingEnabled

bool

Boolean value which enables streaming.

true

WithEventQueueCapacity

int

Set the capacity of the events buffer.

500 events

WithEventQueueFrequency

TimeSpan

Set the number of seconds between flushes of the event buffer.

5 seconds

WithPollingInterval

TimeSpan

Set the polling interval (when streaming is disabled). Values less than the default of 30 seconds will be set to 30 seconds.

30 seconds

WithStartWaitTime

TimeSpan

The timeout when reading data from the EventSource API.

10 seconds

WithReadTimeout

TimeSpan

The timeout when reading data from the stream.

5 minutes

WithReconnectTime

TimeSpan

The stream connection timeout.

1 second

WithHttpClientTimeout

TimeSpan

Set the connection timeout for the configuration.

10 seconds

WithHttpClientHandler

HttpClientHandler

Sets the handler for http requests. Can be used to configure proxy authentication.

WithOffline

bool

Set whether this client is offline.

false

WithLoggerFactory

ILoggerFactory

Sets the logger factory to be used by the SDK.

An ILoggerFactory with INFO level logging.

WithAllAttributesPrivate

bool

Whether all user attributes (except the user key) should be marked as Private user attributes, and not sent to LaunchDarkly.

false

WithPrivateAttributeName

string

Adds the name of a user attribute that should be marked as private to a internally managed list. May be called multiple times to mark additional attributes as private.

No attributes are private by default.

Users

Feature flag targeting and rollouts are all determined by the user you pass to your Identify call. In our Xamarin SDK, the User class contains extension methods that make it easy to construct a user. Here's an example:

 LDUser user = User.WithKey("aa0ceb")
      .AndFirstName("Ernestina")
      .AndLastName("Evans")
      .AndEmail("ernestina@example.com")
      .AndCustomAttribute("groups", new List<String>(){"Google", "Microsoft"})

Let's walk through this snippet. The argument to WithKey is the user's key-- in this case we've used the hash "aa0ceb". The user key is the only mandatory user attribute. The key should also uniquely identify each user. You can use a primary key, an e-mail address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible.

All of the other attributes (set via calls to AndFirstName, AndLastName, AndEmail, and AndCustom attributes) are optional. The attributes you specify will automatically appear on our dashboard, meaning that you can start segmenting and targeting users with these attributes.

In addition to the built-in attributes defined in the User class, you can pass us any of your own user data by passing custom attributes, like the groups attribute in the example above.

A note on types

Most of our built-in attributes (like names and e-mail addresses) expect string values. Custom attributes values can be strings, booleans (like true or false), numbers, or lists of strings, booleans or numbers.

If you enter a custom value on our dashboard that looks like a number or a boolean, it'll be interpreted that way. The Xamarin SDK is strongly typed, so be aware of this distinction.

Custom attributes are one of the most powerful features of LaunchDarkly. They let you target users according to any data that you want to send to us-- organizations, groups, account plans-- anything you pass to us becomes available instantly on our dashboard.

Private user attributes

You can optionally configure the Xamarin SDK to treat some or all user attributes as private user attributes . Private user attributes can be used for targeting purposes, but are removed from the user data sent back to LaunchDarkly.

In the Xamarin SDK there are two ways to define private attributes for the entire LaunchDarkly client:

  • When creating the LaunchDarkly Configuration object, you can call the WithAllAttributesPrivate method, which takes in a boolean parameter. If true, all user attributes (except the key) for all users are removed before the user is sent to LaunchDarkly.
  • When creating the LaunchDarkly Configuration object, you can call the WithPrivateAttributeName method, which takes in an attribute name (string) as a parameter and adds it to an internally managed list of private attributes. This method may be called multiple times to mark additional attributes as private. If any user has a custom or built-in attribute named in the private attributes list, it will be removed before the user is sent to LaunchDarkly.

You can also mark attributes as private when building the user object itself by calling the equivalent "private" user builder method. For example:

var user = User.WithKey("aa0ceb")
  .AndPrivateEmail("test@example.com");

When this user is sent back to LaunchDarkly, the email attribute will be omitted.

Anonymous users

You can also distinguish logged-in users from anonymous users in the SDK, as follows:

 LDUser user = User.WithKey("aa0ceb")
      .AndAnonymous(true)

You will still need to generate a unique key for anonymous users-- session IDs or UUIDs work best for this.

Anonymous users work just like regular users, except that they won't appear on your Users page in LaunchDarkly. You also can't search for anonymous users on your Features page, and you can't search or autocomplete by anonymous user keys. This is actually a good thing-- it keeps anonymous users from polluting your Users page!

Variation

The Variation method determines whether a flag is enabled or not for a specific user. In Xamarin, there is a variation method for each type (e.g. BoolVariation, StringVariation):

ldClient.BoolVariation("your.feature.key", false);

variation calls take the feature flag key and a default value.

The default value will only be returned if an error is encountered-- for example, if the feature flag key doesn't exist or the user doesn't have a key specified.

Track

The Track method allows you to record actions your users take on your site. This lets you record events that take place on your server. In LaunchDarkly, you can tie these events to goals in A/B tests. Here's a simple example:

ldClient.Track("your-goal-key");

You can also attach custom data to your event by passing an extra parameter to Track:

ldClient.Track("Completed purchase", "sku132");

All Flags

Note that unlike variation and identify calls, AllFlags does not send events to LaunchDarkly. Thus, users are not created or updated in the LaunchDarkly dashboard.

The AllFlags method produces a map of feature flag keys to their values for the current user.

ldClient.AllFlags();

Fallback value and offline mode

The default (fallback) values are defined in your code. The default value will only be returned if an error is encountered or if LaunchDarkly is unreachable -- for example, if the feature flag key doesn't exist.

In some situations, you might want avoid remote calls to LaunchDarkly and fall back to default values for your feature flags. For example, if your software is both cloud-hosted and distributed to customers to run on premise, it might make sense to fall back to defaults when running on premise. You can do this by setting offline mode in the client's Config. When the client is in offline mode, no network requests will be made, so it is suitable for unit-testing.

Configuration config = Configuration.Default("SDK_KEY");
config.WithOffline(true);
LdClient client = LdClient.Init(config);

Flush

Internally, the LaunchDarkly SDK keeps an event buffer for Track and Identify calls. These are flushed periodically in a background thread. In some situations (for example, if you're testing out the SDK in a REPL), you may want to manually call Flush to process events immediately.

ldClient.Flush();

Note that the flush interval is configurable-- if you need to change the interval, you can do so via the Configuration class.

Dispose

Dispose safely shuts down the client instance and releases all resources associated with the client. In most long-running applications, you should not have to call dispose.

ldClient.Dispose();

Using the Relay Proxy

You can configure the Xamarin SDK to connect to the LaunchDarkly relay proxy as follows:

Configuration config = Configuration.Default("YOUR_SDK_KEY").WithStreamUri("YOUR_RELAY_URI");
LdClient ldClient = LdClient.Init(config);

Logging

The Xamarin SDK uses the Common.Logging framework. For an example configuration check out the Common.Logging readme.

Be aware of two considerations when enabling the DEBUG log level:

  1. Debug-level logs can be very verbose. It is not recommended that you turn on debug logging in high-volume environments.
  2. Potentially sensitive information is logged including LaunchDarkly users created by you in your usage of this SDK.