Showing posts with label feature toggle. Show all posts
Showing posts with label feature toggle. Show all posts

Sunday, 22 July 2012

Simple database driven feature toggles for ASP.NET MVC


A bit like a broken record I keep mentioning that we use continuous integration at work. So blah blah blah, we need feature toggles. My previous experience has involved using a very simple feature toggling mechanism and looking into a few other open source feature toggling tools. For this blog I'm going to ramble on about another simple idea that I implemented using toggles stored in a database. This solution is specific to ASP.NET MVC due to the way the toggles are populated but I imagine similar mechanisms exist in other frameworks. Although I wrote most of the code, I can't take credit for the idea. That goes to a couple of my colleagues (see their blogs here and here). They each claim it was their idea. I'll let them fight it out. 

How it works

The feature toggles are stored in a static class. What? A static class?!? I don't like it! Bear with me. I thought the same when I first heard the idea but I was convinced otherwise. This static class is used purely to store the values of the toggles, that's it. This comes with a few significant benefits. Primarily it can be defined in a common project (our solution has a lot of projects) and then be used anywhere, view, service, or controller. In addition it doesn't need to be passed around via constructor injection so it doesn't pollute a huge number of classes in the code base. Just to highlight that point, there is absolutely zero IoC setup required to use toggles once the initial implementation is done. But wait, there's more good stuff. What about unit tests? Will adding feature toggles break them? Nope. Because the static class is just a container the toggles will default to being off. If you want to create unit tests which test the toggle being on, just set the toggle to true in the unit test. Easy.

So how is it populated? It's very simple. A new Action Filter is applied to all controllers. For our code this is very easy because all controllers inherit from a base class. On every page load this Action Filter retrieves the toggle values from the database, if they have changed. 

Why get toggles from the database? There are a few good reasons. Firstly it's very easy to change their value at run time. Secondly it's very easy to make them available to every project in a solution. This is in contrast to a previous mechanism I tried whereby the toggles were stored in appSettings in a web.config file which required the adding of a file attribute to the appSettings element in each project where the toggles were required. Another benefit of using database toggles is that the implementation can easily be extended. It would be fairly easy to add new features like toggles controlled by date or toggle state. E.g. Always on, always off.

Are there any disadvantages to this approach? Currently because the toggles are populated by an Action Filter they can only be used in MVC applications, not windows services or console applications etc. 

The code

FeatureToggles static class


Each feature toggle is simply a public static boolean with a private setter. Why a private setter? It indicates to others using that class that they shouldn't change the value of an individual toggle variable. However there does need to be a mechanism for setting toggle values for unit testing purposes, which is done by SetToggleValue. Reflection is used to prevent the need for any extra code being written when a toggle is added.

SetFeatureToggles is used to populate all the toggles using reflection. Again reflection means no code changes are required when adding or removing toggle variables. The toggle name passed in must match the name of the toggle variable. Note, the FeatureToggle classes passed into the method simply contain two properties, string Name and bool IsActive.

GetActiveFeatureTogglesAsStringForBodyTag returns a string containing a space separated list of toggle variable names prefixed with "FT_" which is outputted in the class attribute of the body tag in each page. This allows CSS rules to be defined for when the toggle is on.

HasBeenInitalised is required to ensure the toggle values are retrieved from the database the first time the application is run. This is a quirk of our implementation because the cache isn't necessarily invalidated when the application is restarted.

Action Filter


The job of this Action Filter is very straight forward. If the toggles have changed retrieve the values from the database and repopulate the static toggle variables. This avoids reloading the toggles on every page load. I'm not showing the implementation details of FeatureToggleService because it's very specific to our application. There's nothing special going on to be honest. GetAll() simply returns a list of FeatureToggle classes either from the cache, if populated, or the database. The FeatureToggle class has two properties, string Name and bool IsActive. HaveValuesChanged() unsurprisingly returns a bool indicating whether the toggle values have changed.

How to add a toggle

To start using a feature toggle only one step is required. Add a public static boolean property to FeatureToggles class.


Obviously the toggle will always be false until you also add the toggle to the database. This is done using a simple admin tool which can add, remove or flip toggles. Whenever one of these actions is taken the cache is cleared which will cause the static toggle values to be refreshed.

How to use a toggle

In code


In views

Programmatically hide or show a feature:


Or use the outputted CSS class:

Advantages/disadvantages

Advantages
  • Incredibly easy to add a new toggle
  • Incredibly easy to use a toggle in any layer of the application
  • Easy to extend the implementation. E.g. Add date after which toggle is active
  • Existing unit tests are not broken 
  • Toggles can be flipped easily at run time with no need to manually edit a config file
  • No IoC set up required
  • Toggles can incorporate CSS

Disadvantages
  • Only works in MVC projects
  • Some people won't like the static class implementation

Wednesday, 18 July 2012

A brief look at some feature toggle tools


When using continuous integration branching is considered a no no. This being the case you need feature toggles. The concept is quite simple, but how do you actually use them in code? I've come across this tricky problem at work and with the help of some colleagues came up with a very simple approach. But what if you don't want to roll out your own? What's available? Here is a brief overview of three tools available based on a quick Google search. 

NFeature


Features
  • Custom feature states. E.g. Previewable will only be seen by users who meet certain criteria. Established means the feature toggle cannot be removed 
  • Custom feature availability functions. E.g. Make feature available on site load or presence of a cookie
  • Feature dependencies
  • Feature availability dates
  • Feature specific settings can be defined using JSON

Configuration
  • Toggles defined in enum and web.config
  • Availability checking methods set up
  • Manifest set up. The manifest service is used to check the state of existing toggles. This service must be injected into any class where toggles are required

Advantages
  • Large amount of control over when and how to flip toggles
  • Available via NuGet

Disadvantages
  • More configuration required that other feature toggling tools I looked at
  • No view examples provided. I'm unsure how NFeature would be used to add a toggle to a view
  • Potentially tricky to implement. This is probably just my fault, but I found it difficult to see how NFeature could be easily integrated with our existing code base
  • Manifest service must be injected into any class where toggles are required. On a big project this could affect a large number of classes


FeatureToggle


Features
  • Custom feature toggle types including always on, always off, enabled and after date
  • Supports XAML
  • Toggles can be loaded from the database
  • WPF and Windows phone 7 support
  • Custom feature toggle implementations can be created by implementing IFeatureToggle

Configuration
  • Toggles defined in appSettings
  • Each toggle must also be created as a new class which extends an existing feature toggle class. E.g. EnabledOnDatesFeatureToggle

Advantages
  • Supports multiple platforms
  • Multiple toggle types
  • No service class required so no IoC set up required
  • Incredibly simple to set up and use 
  • Toggle type and provider are extensible
  • Available on NuGet

Disadvantages
  • You have to create a class for each toggle
  • Toggles can't be used statically and must be instantiated as far as I could tell. This isn't a major issue to be fair, I'm just not a fan
  • Difficult to use across large solution. E.g. I would like to be able to define my toggles in a common project and use them in several web projects
  • Breaks existing unit tests. I'm unsure how to mock toggles when using FeatureToggle


FeatureSwitcher


Features
  • Can check features statically or with instance
  • Fluent interface
  • Multi tenancy support
  • Custom behaviours (to be honest after reading the documentation I was unsure what custom behaviours were)

Configuration
  • Toggles defined in custom configSection
  • Create a class which implements IFeature

Advantages
  • Can check features statically or with instance
  • Fluent interface looks very flexible and powerful
  • Multi tenancy support

Disadvantages
  • Personally, I found the documentation quite confusing. After reading the readme I still had a lot of unanswered questions about how to use the toggles and wasn't sure about how to configure FeatureSwitcher in my own projects

Sunday, 19 February 2012

Simple feature toggles in .NET 4


The problem

Where I currently work we use continuous integration. When software is in development this doesn't cause any problems. Just commit, it doesn't matter if you break something or add a new feature. When your software is live, it's a whole different story, everything becomes a bit scarier. Assuming you release fairly regularly, say once a day, new features and other changes must be hidden from the user until they are ready. This is where feature toggles come in. The theory behind feature toggles is very simple, but implementing them in .NET was causing me a headache. I struggled to find any useful information on a practical, tried and tested solution. 

This blog is my attempt to explain the solution me and a couple of colleagues came up with in a fairly short space of time. I'm perfectly happy to say it's not perfect or super elegant, but it works, and it's simple. For a more comprehesive feature toggle solution it could be worth looking at NFeature. It turned up while I was looking for examples of feature toggling in .NET and while I haven't tried it, it looks like a nice solution. At the time I wasn't happy to introduce yet another dependency on a 3rd party piece of software so opted not to use it.

Requirements

Any feature toggling solution we used needed satify a number of requirements. Most importantly the toggles must be accessible in any project within the parent .NET solution and must be configurable for each environment. E.g. On in your testing environment, off in live. In addition I wanted to make it as easy as possible to remove the toggles. That being the case I wanted each toggle to be defined in a single location that when deleted would cause build failures until all references to the toggle were removed. Finally I wanted an implementation where toggles could be used in the view, controller and model and would not break any unit tests.

Implementation

The first step is to create a new web.config file to hold the toggles. Why a seperate file? This way web.configs from each project where the toggles are to be used can refer to this one file. I called my file featureToggles.config. This file can be used to store simple boolean appSettings which define whether the toggle is on or off.

<appSettings>
  <add key="MyFeatureToggle" value="true" />
</appSettings>

When the featureToggle.config file is created, if you're using .NET 4, config transforms will automatically be created for you. They are required for this particular solution. If you're using .NET 3.5 or below you'll have to find another way to handle the transforms, sorry. Add a transform value for each environment. For instance my live transform might look like this:

<appSettings xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
 <add key="MyFeatureToggle" value="false" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
</appSettings>

How are the new appSettings loaded when they aren't included in the web.config file? One of my colleagues helped with that. The file attribute of the appSettings element allows you to specify a file which contains extra appSettings. So for whichever projects in your solution need to use the feature toggle simply add a reference to it in the appSettings element. For example our solution contains two web projects both of which require use of the feature toggles, so their appSettings elements would look something like this:

<appSettings file="featureToggles.config">

<appSettings file="../Web/featureToggles.config">

It's worth noting that if you are automating your builds using something like MSBuild you will need to add an extra step to apply the appropriate transform to the new featureToggles.config. I'm not going to go into the details here but if you want more information this post should help.

The next step is to get the appSettings values out of the config file. To do this I created a static class:

public static class FeatureToggles
{
  public static bool MultipleCards()
  {
     return ConfigurationManager.AppSettings["MyFeatureToggle"] != null 
 && ConfigurationManager.AppSettings["MyFeatureToggle"].ToLower() == "true";
  }
}

This the single place in code where the feature toggle is defined. If you want to remove the feature toggle simply delete the appropriate method from the static class and clean up the build errors. Why a static class? Because it can be used very easily in areas you aren't worried about unit testing. E.g. Views. What about using feature toggles in your model where introducing a static class would break unit tests? For that purpose I created a wrapper round the static class:

public class FeatureToggleService : IFeatureToggleService
{
  public bool MyFeatureToggle()
  {
    return FeatureToggles.MyFeatureToggle();
  }
}

The FeatureToggleService class can be injected into any model class. The return value can be mocked so you can unit test your code with the toggle both on and off. Now it's simply a case of adding feature toggle code when you need hide a feature. For example:

<% if(FeatureToggles.MyFeatureToggle()) { %>
   <%--Link to some awesome new feature--%>
<% } %>

 if(featureToggleService.MyFeatureToggle())
   // New code
else
   // Old code


In summary


Advantages
  • It's simple
  • Toggles can be loaded into multiple projects from one transformed file
  • Existing unit tests are not broken and feature toggle service can be mocked so features can be tested while switched on

Disadvantages
  • Adding a new toggle involves more steps that I would like
  • As far as I'm aware the appSettings file attribute can only contain one value, so if it's used to load feature toggles it can't be used for anything else
  • In a big project the featureToggleService would potentially need to be injected into a large number of classes which I don't like. Do you inject it into all classes, or just the ones you need and then remove it when you're done? Rock. Hard place
  • Toggles must be flipped by manually editing a file