Serverless C# with Split
Whether you’ve already hit the serverless wave or are just curious this is a short article taking you through deploying an Azure Function written in C# that uses Split to evaluate a feature flag: serverless, C#, and Split all in one cute burrito.
Prerequisites
I assume you have an Azure Cloud account and a Split account. It helps if you can read some code, but it’s not requirred to be a success.
Create an Azure Function App
From the Azure Portal home, roll over Function App and click to create.
Your subscription should fill in automatically, but adjust it if necessary.
Under Instance Details, pick a Function App name, e.g. SplitSampleFx
Set the runtime stack to .NET 6 and pick a region that makes sense to you (mine is in Central US).
I left everything else default. Now click Next: Hosting.
Hosting -> default storage worked for me
Networking -> defaults again
Monitoring -> defaults are ok
Tags -> defaults ok
Now on final page, click Create.
The deployment will be in progress for a few minutes.
When complete, you can click Go to resource button. in the middle of the page.
Define an Azure Function
On the left edge, your Function App should have a Functions menu. The first option is Functions. Click it.
A blank table appears, but it has a Create button. We like those! Click it.
Select the HTTP trigger template. Click create.
Add Code to Your Function
Test the function by clicking Code + Test, then clicking Test/Run in the toolbar above the sample code. You can take the Run defaults.
You should get HTTP response content like this:
Hello, Azure. This HTTP triggered function executed successfully.
Add the Split Dependency
.NET does this with a function.proj file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Splitio" Version="6.3.4"/>
</ItemGroup>
</Project>
You can copy-and-paste this into a local file called function.proj, then click the Upload button on the Function toolbar (right next to Test / Run).
One more file like this, *Project.json. Same drill, copy-and-paste the code below into a local file, then upload it like you did function.proj
{
"frameworks": {
"net46":{
"dependencies": {
"Microsoft.ProjectOxford.Face": "1.1.0"
}
}
}
}
Test that the dependency is now available by adding a line of code to the sample code:
log.LogInformation("C# HTTP trigger function processed a request.");
var config = ConfigurationOptions();
string name = req.Query["name"];
Add an include for Split:
using Splitio.Services.Client.Classes;
This can come right underneath the Newtonsoft.Json include.
If you get this error on the log, Split isn’t found yet.
2022-04-27T16:25:54.354 [Error] run.csx(12,5): error CS0103: The name 'ConfigurationOptions' does not exist in the current context
Open function.proj from the dropdown menu above (it is showing run.csx by default) and see if it has contents. Cut-and-paste the body of function.proj again if necessary (as shown above).
Save and go back to run.csx. If everything is happy, you’ll get output like the following:
2022-04-27T16:38:28.193 [Information] Compilation succeeded.
2022-04-27T16:38:47.417 [Information] Executing 'Functions.HttpTrigger1' (Reason='This function was programmatically called via the host APIs.', Id=0256c5da-824d-4d89-a902-27d6693454bc)
2022-04-27T16:38:47.614 [Information] C# HTTP trigger function processed a request.
2022-04-27T16:38:47.617 [Information] Executed 'Functions.HttpTrigger1' (Succeeded, Id=0256c5da-824d-4d89-a902-27d6693454bc, Duration=200ms)
Create an azure_sample Split
From your Split home, click on Splits in the navigation bar at left.
Create a new split called “azure_sample” and give it a traffic type of user. Click Create.
Change the treatment names: “on” -> “blue” and “off” -> “red”.
Attach configuration to your treatments in JSON:
{"urls": ["http://foo", "http://bar"]}
and for red treatment
{"urls": ["http://baz", "http://quux"]}
Click save changes button (upper right) and then confirm on the following screen. You know have a feature flag with a dynamic JSON payload.
Click on the Syntax button in the dropdown menu next to the KILL button in your new feature flag’s editor screen. Go to the .NET option. Copy-and-paste the long looking key in the SplitFactory. You need this in the next step.
Replace with the Split sample code
Now, replace your entire run.csx with this Split sample code. Substitute the SplitFactory key with the one you grabbed from the Syntax generator in the previous step.
#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Splitio.Services.Client.Classes;
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var config = new ConfigurationOptions();
var factory = new SplitFactory("your split sdk cient key", config);
var sdk = factory.Client();
try
{
sdk.BlockUntilReady(10000);
log.LogInformation("SDK ready");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
log.LogInformation("dmartin treatment? " + sdk.GetTreatment("dmartin", "azure_sample"));
var result = sdk.GetTreatmentWithConfig("dmartin", "azure_sample");
log.LogInformation("split json? " + result.Config);
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
string responseMessage = string.IsNullOrEmpty(name)
? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
: $"Hello, {name}. The treatment is {result.Treatment}. {result.Config}";
return new OkObjectResult(responseMessage);
}
FINISHED
Run your function. If all goes well, you’ll see:
Hello, Azure. The treatment is off. {"urls": ["http://baz", "http://quux"]}
This means you are evaluating a feature flag with a dynamic JSON treatment payload from an Azure Function. Congratulations?
Troubleshooting?
Please don’t be shy with questions.
Written with StackEdit.
Leave a comment