C# SDK quickstart
Welcome to the quickstart guide for Optimizely Feature Experimentation's C# SDK. Follow the steps in this guide to create a flag, roll out a flag delivery, and run an A/B test using a simple command-line application.
Part 1: Create a sample app
1. Get a free account
You need an Optimizely account to follow this guide. If you do not have an account, you can register for a free account. If you already have an account navigate to your Feature Experimentation project.
2. Get your SDK key
To find your SDK Key in your Optimizely project:
- Go to Settings > Primary Environment.
- Copy and save the SDK Key for your primary environment.
Important
Each environment has its own SDK key. Ensure you copy the correct key.
3. Copy the sample code
To try out the SDK:
- In your IDE, create a new Console app called
optimizely-csharp-quickstart
. - Install the Optimizely Feature Experimentation C# SDK via your IDE's package manager or through a CLI/terminal:
dotnet add package Optimizely.SDK
The C# SDK is distributed through Nuget. The full source code is available on GitHub.
- Copy the following code sample into the default Program.cs file for your Console app.
- Replace
<Your_SDK_Key>
with the SDK key you found in a previous step.
using OptimizelySDK;
namespace App;
public static class Program
{
public static void Main()
{
// This Optimizely initialization is synchronous. For other methods, see the C# SDK reference.
var optimizelyClient = OptimizelyFactory.NewDefaultInstance("YOUR_SDK_KEY");
if (!optimizelyClient.IsValid)
{
Console.WriteLine(
"Optimizely client invalid. " +
"Verify in Settings>Environments that you used the primary environment's SDK key");
optimizelyClient.Dispose();
return;
}
var hasOnFlags = false;
/*
* To get rapid demo results, generate random users.
* Each user always sees the same variation unless you reconfigure the flag rule.
*/
var rnd = new Random();
for (var i = 0; i < 10; i++)
{
var userId = rnd.Next(1000, 9999).ToString();
// Create a user context to bucket the user into a variation.
var user = optimizelyClient.CreateUserContext(userId);
// "product_sort" corresponds to a flag key in your Optimizely project
var decision = user.Decide("product_sort");
// Did decision fail with a critical error?
if (string.IsNullOrEmpty(decision.VariationKey))
{
Console.WriteLine(Environment.NewLine + Environment.NewLine +
"Decision error: " + string.Join(" ", decision.Reasons));
continue;
}
/*
* Get a dynamic configuration variable.
* "sort_method" corresponds to a variable key in your Optimizely project.
*/
var sortMethod = decision.Variables.ToDictionary()["sort_method"];
hasOnFlags = hasOnFlags || decision.Enabled;
/*
* Mock what the user sees with print statements (in production, use flag variables to implement feature configuration)
*/
// always returns false until you enable a flag rule in your Optimizely project
Console.WriteLine(Environment.NewLine +
$"Flag {(decision.Enabled ? "on" : "off")}. " +
$"User number {user.GetUserId()} saw " +
$"flag variation {decision.VariationKey} and got " +
$"products sorted by {sortMethod} config variable as part of " +
$"flag rule {decision.RuleKey}");
}
if (!hasOnFlags)
{
var projectId = optimizelyClient.ProjectConfigManager.GetConfig().ProjectId;
var projectSettingsUrl =
$"https://app.optimizely.com/v2/projects/{projectId}/settings/implementation";
Console.WriteLine(Environment.NewLine + Environment.NewLine +
"Flag was off for everyone. Some reasons could include:" +
Environment.NewLine +
"1. Your sample size of visitors was too small. Re-run, or increase the iterations in the FOR loop" +
Environment.NewLine +
"2. By default you have 2 keys for 2 project environments (dev/prod). Verify in Settings>Environments that you used the right key for the environment where your flag is toggled to ON." +
Environment.NewLine + Environment.NewLine +
$"Check your key at {projectSettingsUrl}");
}
optimizelyClient.Dispose();
}
}
Note
Do not run your app yet, because you still need to set up the flag in the Optimizely application.
Part 2: Run your app
After completing Part 1, your app does nothing. You need to create a flag and a flag rule in the Optimizely app to enable the app.
1. Create the feature flag
A flag lets you control the users that are exposed to a new feature code in your app. For this quickstart, imagine that you are rolling out a redesigned sorting feature for displaying products.
Create a flag in your Feature Experimentation project named product_sort and give it a variable named sort_method:
- Select Create New Flag... from the Flags tab.
- Enter product_sort in the Name field.
- Keep the auto-created Key, product_sort, and click Create Flag. The Key corresponds to the flag key in your sample app.
Next, create a variable in your flag:
- In your new flag,
product_sort
, under Flag Setupgo to Variables and click Add Variable (+). - Select String in the Add Variable drop-down.
- Enter sort_method for the Variable Key, which corresponds to the variable key in your sample app.
- Enter alphabetical for the Default Value, which represents your old sorting method. The new sorting method is what you are rolling out.
- Click Save.
Next, create a variation in your flag:
-
Under Flag Setup go to Variations select the On variation. A variation is a wrapper for a collection of variable values.
-
For the sort_method variable value, enter popular_first, which represents your new sorting method.
-
Click Save.
2. Create the flag delivery rule
Your sample app still does nothing because you need to create and enable a flag rule.
Make a targeted delivery rule for the On variation for the product_sort flag. A targeted delivery lets you gradually release a feature flag to users but with the flexibility to roll it back if you encounter bugs.
-
Ensure you are in your primary environment (because you are using the primary environment SDK key from Part 1.
-
Click Add Rule and select Targeted Delivery.
-
Enter Targeted Delivery for the Name field.
-
Keep the default Key and Audiences.
-
Set the Traffic Allocation slider to 50%. This delivers the product_sort flag to 50% of everyone who triggers the flag in this environment. You can roll out or roll back the product_sort flag to a percentage of traffic whenever you want.
-
From the Deliver drop-down list, select the On variation.
-
Click Save.
3. Run your sample app
To run your sample application:
-
Click Run on your targeted delivery rule:
-
Click Ok on the Ready to Run Status page. This lets you know that your ruleset has not been set to run, yet.
-
Click Run on your ruleset (flag):
-
In Visual Studio, click Run for the sample Command Line Interface app you created earlier. Output displays similar to the following:
Flag on. User number 6998 saw flag variation: on and got products sorted by: popular_first config variable as part of flag rule: targeted_delivery Flag on. User number 1177 saw flag variation: on and got products sorted by: popular_first config variable as part of flag rule: targeted_delivery Flag on. User number 9714 saw flag variation: on and got products sorted by: popular_first config variable as part of flag rule: targeted_delivery Flag on. User number 4140 saw flag variation: on and got products sorted by: popular_first config variable as part of flag rule: targeted_delivery Flag on. User number 4994 saw flag variation: on and got products sorted by: popular_first config variable as part of flag rule: targeted_delivery Flag off. User number 8700 saw flag variation: off and got products sorted by: alphabetical config variable as part of flag rule: default-rollout-208-19963693913 Flag off. User number 9912 saw flag variation: off and got products sorted by: alphabetical config variable as part of flag rule: default-rollout-208-19963693913 Flag on. User number 6560 saw flag variation: on and got products sorted by: popular_first config variable as part of flag rule: targeted_delivery Flag on. User number 9252 saw flag variation: on and got products sorted by: popular_first config variable as part of flag rule: targeted_delivery Flag on. User number 6582 saw flag variation: on and got products sorted by: popular_first config variable as part of flag rule: targeted_delivery
Note
You will not get exactly 50% of your user traffic in the On variation, since you are working with such small numbers of visitors. Also, the users who got an "off" flag did not make it into the 50% traffic you set, so they fell through to the default "Off" rule (default-rollout in the preceding print statements).
4. How it works
So far, you:
- Created a flag, flag variable, and a flag variation (wrapper for your variables) in the Optimizely application.
- Implemented a flag in your app with the Decide method.
What is going on in your sample app?
How it works: decide to show a user a flag
The C# SDK’s Decide method determines whether to show or hide the feature flag for a specific user.
Note
You can reuse this method for different flag rules – whether for delivering more traffic, or running an experiment to show different sorting methods to just a portion of users.
After you learn which sorting method works best to increase sales, roll out the product sort flag to all traffic with the method set to the optimum value.
In your sample app:
var user = optimizelyClient.CreateUserContext(userID);
// "product_sort" corresponds to the flag key you create in the Optimizely app
var decision = user.Decide("product_sort");
Note
Optionally include attributes when you create your user (not shown in your sample app ), so that you can target specific audiences. For example:
var attributes = new UserAttributes { { "logged_in", true } }; var user = optimizely.CreateUserContext("user123", attributes);
How it works: configure flag variations
You can dynamically configure a flag variation using flag variables. In your sample app:
// always returns false until you enable a flag rule in the Optimizely app
if (decision.Enabled)
{
// "sort_method" corresponds to variable key you define in Optimizely app
var sortMethod = decision.Variables.ToDictionary()["sort_method"];
Console.WriteLine("sort_method: ", sortMethod);
}
For your product_sort flag, you can configure variations with different sort_method values, sorting by popular products, relevant products, promoted products, and so on. You can set different values for the sort method at any time in the Optimizely app.
Part 3: Run an A/B test
Part 2 of this tutorial guided you through a targeted delivery because it is the most straightforward flag rule. However, you often want to A/B test how users react to feature flag variations before you roll out a flag delivery.
- Targeted delivery rule – You can roll out your flag to a percentage of your general user base (or to specific audiences), or roll back if you encounter bugs.
- A/B test rule – Experiment by A/B testing a flag before you invest in delivering, so you know what to build. Track how users behave in flag variations, then interpret your experiment results using the Optimizely Stats Engine.
For Part 3, you will run an A/B test on the On variation of your product_sort flag.
1. Add event tracking
You need to add a Track Event method to your sample app, so you can mock up user events and then see metrics.
- Delete your old sample code, and paste in the following code.
- Replace your SDK key. See Get your SDK Key.
- Do not run your app yet because you still need to set up the A/B test in the Optimizely application.
using Newtonsoft.Json;
using OptimizelySDK;
using OptimizelySDK.Notifications;
namespace App;
public static class Program
{
public static void Main()
{
// For more instantiation configuration, see the C# SDK reference
var optimizelyClient = OptimizelyFactory.NewDefaultInstance("YOUR_SDK_KEY");
if (!optimizelyClient.IsValid)
{
Console.WriteLine(
"Optimizely client invalid. " +
"Verify in Settings>Environments that you used the primary environment's SDK key");
optimizelyClient.Dispose();
return;
}
/*
* OPTIONAL: Add a notification listener so you can integrate with third-party analytics platforms
*/
// NotificationCenter.DecisionCallback onDecision = (type, userId, userAttributes, decisionInfo) =>
// {
// // Access type on decisionObject to get type of decision
// if (type == "flag")
// {
// var serializedJsonInfo = JsonConvert.SerializeObject(decisionInfo);
// Console.WriteLine($"Feature flag access related information: {serializedJsonInfo}");
//
// // Send data to analytics provider here
// }
// };
//
// // Use the notificationId to remove the listener when you're done
// var notificationId =
// optimizelyClient.NotificationCenter.AddNotification(
// NotificationCenter.NotificationType.Decision,
// onDecision);
var hasOnFlags = false;
/*
* To get rapid demo results, generate random users.
* Each user always sees the same variation unless you reconfigure the flag rule.
*/
var rnd = new Random();
for (var i = 0; i < 5; i++)
{
var userId = rnd.Next(1000, 9999).ToString();
// Bucket user into a flag variation and mock experiment results
var user = optimizelyClient.CreateUserContext(userId);
var decision = user.Decide("product_sort");
// Did decision fail with a critical error?
if (string.IsNullOrEmpty(decision.VariationKey))
{
Console.WriteLine("decision error: " + string.Join(" ", decision.Reasons));
continue;
}
var sortMethod = decision.Variables.ToDictionary()["sort_method"];
hasOnFlags = hasOnFlags || decision.Enabled;
// Mock what the users sees with print statements (in production, use flag variables to implement feature configuration)
// always returns false until you enable a flag rule in your Optimizely project
Console.WriteLine(Environment.NewLine +
$"Flag {(decision.Enabled ? "on" : "off")}. " +
$"User {user.GetUserId()} saw " +
$"flag variation: {decision.VariationKey} and got " +
$"products sorted by: {sortMethod} config variable as part of " +
$"flag rule: {decision.RuleKey}");
MockPurchase(user);
}
var projectId = optimizelyClient.ProjectConfigManager.GetConfig().ProjectId;
if (hasOnFlags)
{
Console.WriteLine(Environment.NewLine + Environment.NewLine +
"Done with your mocked A/B test." +
Environment.NewLine +
$"Check out your report at https://app.optimizely.com/v2/projects/{projectId}/reports" +
Environment.NewLine +
"Be sure to select the environment that corresponds to your SDK key");
}
else
{
Console.WriteLine(Environment.NewLine + Environment.NewLine +
"Flag was off for everyone. Some reasons could include:" +
Environment.NewLine +
"1. Your sample size of visitors was too small. Re-run, or increase the iterations in the FOR loop" +
Environment.NewLine +
"2. By default you have 2 keys for 2 project environments (dev/prod). Verify in Settings>Environments that you used the right key for the environment where your flag is toggled to ON." +
Environment.NewLine +
$"Check your key at https://app.optimizely.com/v2/projects/{projectId}/settings/implementation");
}
/*
* NOTE: Using OptimizelyFactory.NewDefaultInstance("YOUR_SDK_KEY") above,
* defaults to an event batch size of 10 with a flush interval of 30 seconds.
* It is best practice to call Dispose() to stop event processing and
* flush the queue. However, in some cases the main execution terminates
* before completion and should be accommodated based on your implementation.
*/
Console.WriteLine("Artificially waiting for event queue finalization...");
Thread.Sleep(30_000);
optimizelyClient.Dispose();
}
// Mock tracking a user event so you can see some experiment reports
private static void MockPurchase(OptimizelyUserContext user)
{
Console.WriteLine("Pretend that user made a purchase? y/n ");
var answer = Console.ReadLine();
if (answer != null && answer.Equals("y", StringComparison.OrdinalIgnoreCase))
{
// Track a user event you defined in the Optimizely project
user.TrackEvent("purchase");
Console.WriteLine(
$"Optimizely recorded a purchase in experiment results for user {user.GetUserId()}");
}
else
{
Console.WriteLine(
$"Optimizely didn't recorded a purchase in experiment results for user {user.GetUserId()}");
}
}
}
2. Delete other rules in free accounts
If you have a free Optimizely account, you need to pause the Targeted Delivery you created in Part 2 before you create your A/B test:
-
Select the flag that contains the Targeted Delivery you created in Part 2 from the Flags tab.
-
Select the primary environment and the Targeted Delivery rule you created in Part 2.
-
Click More Options > Delete:
-
Click Save.
3. Create the A/B test
To create an A/B Test rule in your Feature Experimentation project, in the flag you created in Part 2:
- click Add Rule and select A/B Test.
- Enter Experiment for the Name field.
- Keep the default Key and Audiences
- Keep the Traffic Allocation slider set to 100%.
4. Add an event
In an experiment, you will track users' relevant actions to measure how users react to your flag variations. You need to define the actions you want to track, called events:
- Click on the Metrics field.
- Click Create new event.
- Enter purchase for the Event Name, and the Event Key will be automatically filled.
- (Optional) Enter a Description. You want to know whether the new sorting flag helps customers figure out what to buy, so track whether the user makes a purchase after they are shown the products in a new order.
- Click Create Event.
- In the Add Metric modal, leave the defaults, measure increase in unique conversions.
- Click Add Metric.
- Leave the default Off variation as a control. Select the On variation you configured in Part 2:
Note
You are not limited to two variations; you can also create A/B tests with multiple variations.
-
Click Save to create your A/B Test rule.
-
Click Run on the A/B test rule.
5. Run the A/B test
Ensure your ruleset's (flag's) status is Running, and the rule's status is Running so your experiment can run:
Click Run in Visual Studio and answer the command-line prompts. The output should display similar to the following:
Flag on. User number 1496 saw flag variation: on and got products sorted by: popular_first config variable as part of flag rule: experiment_1
Pretend that user made a purchase? y/n
n
Optimizely didn't record a purchase in experiment results for user 1496
Flag off. User number 1194 saw flag variation: off and got products sorted by: alphabetical config variable as part of flag rule: experiment_1
Pretend that user made a purchase? y/n
y
Optimizely recorded a purchase in experiment results for user 1194
Flag off. User number 5815 saw flag variation: off and got products sorted by: alphabetical config variable as part of flag rule: experiment_1
Pretend that user made a purchase? y/n
y
Optimizely recorded a purchase in experiment results for user 5815
Flag on. User number 1248 saw flag variation: on and got products sorted by: popular_first config variable as part of flag rule: experiment_1
Pretend that user made a purchase? y/n
y
Optimizely recorded a purchase in experiment results for user 1248
Flag off. User number 9580 saw flag variation: off and got products sorted by: alphabetical config variable as part of flag rule: experiment_1
Pretend that user made a purchase? y/n
n
Optimizely didn't record a purchase in experiment results for user 9580
Done with your mocked A/B test.
Check out your report at https://app.optimizely.com/v2/projects/19957465438/reports
Be sure to select the environment that corresponds to your SDK key
6. See your A/B test results
Go to the Reports tab and select your experiment to see your results.
Your results should look something like the following:
Note
- You might not see the exact user traffic percentages you configured for your flag variations until you have larger numbers of users.
- You might not see your user traffic immediately. Refresh the browser to refresh traffic.
- Your experiment results will not tell you a winning variation until you have a large number of visitors, (on the order of 100,000).
7. How it works
For an A/B test, you need a way to tell Optimizely when a user made a purchase in your app and map this event in your app code to the specific event you created in Optimizely. Luckily the SDK has a method for that! Use the Track Event method and pass in the key for the event you created (purchase
). In your sample app:
// Track how users behave when they see a flag variation
// e.g., after your app processed a purchase, let Optimizely know what happened:
user.TrackEvent("purchased");
Note
Optionally add tags to your event to enrich it (not shown in your sample app). You can also use reserve tag keys like revenue to track quantitative results. For example:
var tags = new EventTags { { "category", "shoes" }, { "revenue", 6432 } }; user.TrackEvent("purchase", tags);
Conclusion
Congratulations! You successfully set up and launched your first Optimizely Feature Experimentation experiment using the C# SDK. While this example focused on optimizing sales, Optimizely’s experimentation platform can support an open-ended set of experimentation use cases.
See our complete C# SDK documentation to learn more ways to optimize your software using experimentation.
Updated 4 months ago