Skip to content

Instantly share code, notes, and snippets.

@jsquire
Last active June 16, 2023 20:47
Show Gist options
  • Save jsquire/fc4270c10b2b3a12f365d26c88202df8 to your computer and use it in GitHub Desktop.
Save jsquire/fc4270c10b2b3a12f365d26c88202df8 to your computer and use it in GitHub Desktop.
AppConfig: Access the raw value of a feature flag setting
// Package Reference: Azure.Data.AppConfiguration
// Package Reference: System.Text.Json
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Data.AppConfiguration;
using System.Threading.Tasks;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Net;
// Create the policy; this will be what we read the raw service values from.
var policy = new FeatureFlagPolicy();
// Create the client, using the policy by setting them in the options.
var options = new ConfigurationClientOptions();
options.AddPolicy(policy, HttpPipelinePosition.PerCall);
var client = new ConfigurationClient("<< CONNECTION STRING >>", options);
// Query the settings and output the client and service values for each.
var selector = new SettingSelector { LabelFilter = SettingSelector.Any };
var settings = client.GetConfigurationSettingsAsync(selector);
await foreach (var setting in settings)
{
Console.WriteLine($@"
{setting.Key}:
Client Value:
{setting.Value}
Service Value:
{policy.RawValues[setting.Key]}
");
}
//
// This is the policy implementation responsible for intercepting the
// service response, parsing it, and exposing the raw valies/
//
public class FeatureFlagPolicy : HttpPipelineSynchronousPolicy
{
public Dictionary<string, string> RawValues { get; } = new();
public override void OnReceivedResponse(HttpMessage message)
{
base.OnReceivedResponse(message);
// If there was no response or it was a failure, skip processing.
if (message?.Response?.Status != (int)HttpStatusCode.OK)
{
return;
}
var serializerOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
var response = JsonSerializer.Deserialize<SettingsResponse>(message.Response.Content.ToString(), serializerOptions);
// If the response couldn't be deserialized, skip processing.
if (response == null)
{
return;
}
// Clear out the known values to avoid bloat; this will reset the cache
// for each page of settings.
RawValues.Clear();
// Add the current raw value for settings to the cache.
foreach (var setting in response.Items)
{
RawValues.Add(setting.Key, setting.Value);
}
}
// Nested types just for serialization support.
private class SettingsResponse
{
public MinimalSetting[] Items { get; set; }
}
private class MinimalSetting
{
[JsonPropertyName("content_type")]
public string ContentType { get; set; }
public string Key { get; set; }
public string Value { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment