Configure preview features with Azure App Configuration

In my preview post about implementing preview features in asp.net core, I explained how to introduce the concept of feature flags in your application and manage it with the default appsettings.json.

Managing your features from appsettings is not the best approach as it requires application restarts which will distrupt the application users.

In this post, I will explain how to do the configuration with a tool that was built just for this.

Azure App Configuration has feature management feature that allows you to manage your features, turn it on or off and set the filters for each feature flag. It also enables auto refresh which basically allows you to change a feature and this change will reflect immediately in your application.

Register Azure App Configuration as a Configuration Source

Asp.net core supports multiple configuration sources. When you call the CreateDefaultBuilder method in Program.cs, it automatically registers the following configuration sources for your application

appsettings.json
appsettings.{environment}.json
user secrets
environment variables
command line arguments

The registration happens in the same order above. You can have a look at the source code in this link If a specific key exists in a configuration source, you can override its value by adding it in the next configuration source. Ex: If the key ConnectionStrings:DefaultConnection exist in appsettins.json and also exist in user secrets, the one in user secrets will be used. This is good to override some values in your local dev environment such as passwords and connection strings to avoid pushing it to your source control

To register azure app config as an additional config source, you can add the following in Program.cs after installing the package Microsoft.Azure.AppConfiguration.AspNetCore

            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(config =>
                {
                    var configuration = config.Build();
                    config.AddAzureAppConfiguration(azureAppConfig =>
                    {
                        var azureAppConfigConnectionString = configuration["AzureAppConfig:ConnectionString"];
                        azureAppConfig.ConfigureRefresh(refresh =>
                        {
                            refresh.SetCacheExpiration(TimeSpan.FromSeconds(5));
                        });
                        azureAppConfig.UseFeatureFlags();
                        azureAppConfig.Connect(azureAppConfigConnectionString);
                    });
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

From line 2-15, you can see that we are configuration the application configuration by adding a new configuration source in line 5. In line 7, we are reading the connection string from the previous configuration sources. This way you can add your connection string in appsettings.json or user secrets, I have added it here in appsettings.json under the name AzureAppConfig:ConnectionString. From line 8-11, we are configuring the caching time for the configuration. If you configure it for 5 seconds, the keys from azure app config will be cached and no requests will be done to azure app config to get the latest updates. Line 12 simply asks Azure App Configuration SDK to include the features when it reads all configurations and finally we use the connection string to connect to the azure config instance.

Creating Azure App Config

Log in to Azure Portal and create a new App Configuration resource. You can only create one free app configuration per subscription. Once it is created, go to Access Keys from the left menu and copy either the primary or secondary connection string and update your appsettings file

Now you should be all set. If you run the application and navigate to https://localhost:44375/PreviewFeatures, you should be able to see the page if your feature configuration allows it.

So far, we didn’t add any features to our Azure App Config instance yet, this means the application will fall back to the appsettings.json

Add Features in Azure App Configuration

To start managing your features from Azure App Config, Click Feature Manager from the left menu and Choose Add then type the feature name as PreviewFeatures and choose Off then click add

Now refresh the URL https://localhost:44375/PreviewFeatures, and if the feature PreviewFeatures was enabled in appsettings, it will still appear. So what are we doing wrong?

Enable Auto Refresh

By default, the Azure App Configuration does not do auto refresh in your asp.net core. You have to register a middleware that does that by adding the following line in the Configure method inside Startup.cs

app.UseAzureAppConfiguration();

Now, if you run the application again, the first time it starts, it will get the most recent values from Azure App Config and now you should see the PreviewFeatures controller not working. But if you enabled it again from azure portal by toggling the On/Off flag from the Feature Manager page, and wait for 5 seconds, you should refresh and see that the PreviewFeatures is now working again.

Notice that the toggle turns on or off the feature for everyone. If you need to use the feature filter, then click the 3 dots and choose Edit. Under Filters, click add and type the feature filter name, in this case UserFeatures which we created previously. Notice how the state changed from On/Off to Conditional. Now when you refresh, the filter will be executed to decide if the feature should be enabled or disabled for each user.

I have included all the updates on GitHub repo. Feel free to ask me any questions

Implementing preview features in asp.net core app

Feature flags are a way to turn on or off a specific feature in your application. This enables you to hide a feature on production if it is not ready for end users. It can also allow you to give the user the option to enable/disable preview feature as they like. As you can see below, Azure DevOps keeps showing the preview feature tooltip for users to try preview features. A preview feature can be a new page, a new section in a page or a new way of rendering the page.

Feature flags come handy in these situations:

Ship half-finished features: You can always ship features to production and switch off its feature flag to hide it from users.
Experimentation: Deploy a new feature and target specific user group or allow user to experiment these features and provide feedback.
Test in production & Kill a feature: If your feature is incomplete, you can release it and let users try it. if the feature misbehaved, you can simply kill it for everyone as if it was not there in the first place
Trunk-based development: Usually with every feature, you have a feature branch and eventually these branches get merged to the master branch. But now everyone can work on the same branch and release their code to production and switch off their features till it is complete.

Feature Management

With the introduction of Azure App Configuratio, the team introduced a library to manage feature flags in asp.net core. It does not depend on Azure App Configuration though, and you can configure it with appsettings.json

Lets write some code

Create a new asp.net web application (MVC) and choose the Individual Authentication to get the identity database and everything ready for user registration and login

Once the project is created, add a reference to the nuget package Microsoft.FeatureManagement.AspNetCore

Startup.cs changes

You need to inject feature management into the services collection by appending the following line to the ConfigureServices method

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();

             services.AddFeatureManagement();
            services.AddControllersWithViews();
            services.AddRazorPages();
        }

Configuration for feature management

The feature management has to read the configuration for which features exist and which are enabled or disabled. In this article, we will use appsettings.json. By default, it looks for a section called FeatureManagement

  "FeatureManagement": {
    "WelcomeFeature": true,
    "NotWelcomeFeature": false
  }

In the above configuration, we added 2 features

  1. WelcomeFeature: This is enabled for everyone
  2. NotWelcomeFeature: This is disabled for everyone

Feature Gate

We defined the features, now we want to use them in the code. Create a new controller with an Index method and annotate the controller with the attribute [FeatureGate]. This attribute accepts the feature name defined in FeatureManagmenet section above. If you try now to run your application and access the path /PreviewFeatures, it should show the message “This is a preview feature controller”. If you change the value from true to false in appsettings for the key WelcomeFeature and refresh the page, it will show page not found. You can override this behavior by using a custom feature disabled handler by calling the UseDisabledFeaturesHandler method after calling AddFeatureManagement().

    [FeatureGate("WelcomeFeature")]
    public class PreviewFeaturesController : Controller
    {
        private readonly ILogger<PreviewFeaturesController> _logger;

        public PreviewFeaturesController(ILogger<PreviewFeaturesController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return Content("This is a preview feature controller");
        }
    }

Feature Filters

When you add a feature and want the users to select it, the last thing to do is to hard code this logic. With feature filters, you can defer the logic to enable/disable features to custom logic. Each feature filter has a a method called EvaluateAsync. This method returns a boolean indicating whether or not to enable the feature

Add feature filter

Create a new class called UserFeaturesFilter and append the following code

[FilterAlias("UserFeatures")]
public class UserFeaturesFilter : IFeatureFilter
{
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly IHttpContextAccessor _httpContextAccessor;
    public UserFeaturesFilter(IServiceScopeFactory scopeFactory, IHttpContextAccessor httpContextAccessor)
    {
        _scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory));
        _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
    }

    public async Task<bool> EvaluateAsync(FeatureFilterEvaluationContext context)
    {
        if (!_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
            return false;

        using (var scope = _scopeFactory.CreateScope())
        {
            var featuresContext = scope.ServiceProvider.GetRequiredService<FeaturesContext>();
            var userManager = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();

            var user = await userManager.GetUserAsync(_httpContextAccessor.HttpContext.User);
            var feature = featuresContext.Features.FirstOrDefault(a => a.Name.ToLower() == context.FeatureName.ToLower());

            if (user == null || feature == null)
                return false;

            var userFeature = featuresContext.UserFeatures.FirstOrDefault(f => f.UserId == user.Id && f.FeatureId == feature.Id);
            return userFeature != null;
        }
    }
}

The logic here is to get the current logged in user from the http context then retrieve the features that the user has chosen to subscribe for and if the feature name exist in the database then return true, otherwise, return false. To register this feature filter, you have to change startup.cs file with the following line

services.AddFeatureManagement().AddFeatureFilter<UserFeaturesFilter>();

Now, its time to introduce a new feature that will utilise this feature filter. Edit the appsettings to add a new feature

  "FeatureManagement": {
    "WelcomeFeature": true,
    "NotWelcomeFeature": false,
    "PreviewFeatures": {
      "EnabledFor": [
        {
          "Name": "UserFeatures"
        }
      ]
    }
  }

We added a new feature called PreviewFeatures and instead of using true or false as the value, we added the UserFeatures filter. To test this, we will add the reminder of code used in the feature filter.

Create a Feature and UserFeature classes

    public class Feature
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }

    }
    public class UserFeature
    {
        public int Id { get; set; }
        public string UserId { get; set; }
        public int FeatureId { get; set; }
        public Feature Feature { get; set; }
    }

Create a data context class that will contain these 2 entities

public class FeaturesContext : DbContext
{
    public FeaturesContext(DbContextOptions<FeaturesContext> options)
       : base(options)
    {
    }

    public DbSet<Feature> Features { get; set; }
    public DbSet<UserFeature> UserFeatures { get; set; }
}

Your ConfigureServices method should look like this after registering the new DbContext and add the needed services

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddDbContext<FeaturesContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddFeatureManagement().AddFeatureFilter<UserFeaturesFilter>();
        services.AddControllersWithViews();
        services.AddRazorPages();
    }

Now, run the Add-Migration -ContextName FeaturesContext command followed by Update-Databse command to update the database

Once you did all above steps, you can mark any controller with the new feature name and edit the database to add a record to the UserFeature table. You wil have to register first and get your user id from AspNetUsers table, and you also have to add a record in the Features table. The feature name has to be the name used in the appsettings.json file

Now try to open your controller, it should work fine, once you remove the record from UserFeatures table, it should show page not found.

Let users choose what features they want

To allow users to choose the preview features they want, you can create a new page and show all the features from Features table and let the user save their choice. The easiest way to do that is to create a new controller and choose MVC Controller based on Entity Framework, this will create a CRUD screens for the UserFeatures table

You can also create the same for Features table to let the admin manage the features.

Informing users about new features

When you deploy a new feature, you need to let the users know about this feature, this can happen using an email, or a tooltip that appears for users or just having a menu link that shows all preview features just like Azure DevOps does. You can for example put the page URL in the Features table and implement a middleware that checks the current request path and check if there are any features that has the same URL and show a popup for the user to choose this feature.

Source code

I have added all the source code for this article on GitHub, you can download and run the sample app. It has the complete solution.

If you have any questions or suggestions, please let me know.

Migrate your asp.net settings to Azure App Configuration

Before asp.net core, we only had the web.config file to configure and read the application settings from code. The framework didn’t have a plugable way of adding an extra configuration providers. Any other confiruation data sources meant a custom solution and custom code to read and update configuration keys.

With asp.net core, we got the new appsettings.json as one source of configuration. Along with it came the environment variables, other files, secret keys that can be used to omit connection strings and passwords from being stored on source control.

Things event got better with Azure App Service that has a settings/configuration section that can override the application settings and connection strings sections. This applies to both asp.net framework and asp.net core.

Isn’t this enough already?

It is good as a start. but, it has a major issue. If you change any value in your configuration keys, it means the application must be restarted which affects the logged in users and may cause data loss.
Another issue is that our application code and configuration exists in the same place which contradicts with the twelve factor . These configuration keys cannot also be shared with other applications except using copy/paste

Azure App Configuration

Azure App Configuration is a service that is still in preview that can be a central place for all your configuration keys and feature flags.
It is so easy to add it to your asp.net core configuration provider using the provided nuget packages.

Add the need packages

First, install the package Microsoft.Azure.AppConfiguration.AspNetCore . You may need to check that you enabled prerelease versions if you are using visual studio

In your Program.cs file, add the following code which will inject Azure app configuration as a configuration provider. Notice that you will have to add a key named “AppConfig” in your connectionStrings section in appsettings.json that will store the connection string for your Azure App Configuration

public static IWebHostBuilder CreateWebHostBuilder(string&#091;] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var settings = config.Build();
            config.AddAzureAppConfiguration(settings&#091;"ConnectionStrings:AppConfig"]);
        })
        .UseStartup<Startup>();

Now, your application is ready to read any configuration keys from Azure App Configuration. All you need to do is to create a new instance by following this link

Reuse your existing configuration keys

It’s not only too easy to add Azure App Configuration to your asp.net core app but also migrating your existing keys. You don’t want to end up with a situation where you have to spend hours moving your keys manually or writing scripts to do it. Azure App Configuration can do that for you.

As you can see above, it is too simple. Just choose Import/export from the left menu then choose where you want App Configuration to import the values from:

  1. App Configuration: you can import the values from another Azure App Configuration instance
  2. App Service: which can be perfect in our case since it will import the values from your Azure App Service
  3. Configuration File: you can pass the appsettings.json directly and it will import the values from there

Once you did that, you will have all keys/connection strings imported and ready to go.

Conclusion

Azure App Configuration is a great service that still in preview but it enables you to offload your application from configuration keys and connection strings. It also has the auto refresh which will allow your app to always have the latest config keys without the need to restart your application and impact your users.
It also has feature management which is a great addition but we will talk about it in future posts.