Monthly Archives: April 2020

Feature Flags – Asp.Net Core

Feature flags enable you to create a new piece of functionality in the main code branch, but behind a mask – so the end user doesn’t see the change. This means that you can decide at a later date to turn the feature on, or off. For example, say you wanted to make a change the colour of your web-site; or maybe you wanted to introduce an “Express Checkout” button; you can create these behind a feature flag, meaning that, should sales suddenly plummet when these changes are released, you can simply flick a switch to turn them off.

In this post, I’m going to cover the most basic usage of a feature flag. We’ll create a new web-site and, where a feature flag is turned on, we’ll show a button; and where it is not, we won’t. Before we start on the specifics, create a blank Asp.Net Core MVC project.

1. Add NuGet packages

The concept of feature flags exist outside of Microsoft. In fact, Feature Flags are just the idea of enabling functionality based on a setting, so there was probably one in the first computer program ever written. In this post, we’re talking about the implementation of this concept that’s available from Microsoft for Asp.Net Core.

The first step, as with more Microsoft libraries these days, is NuGet:

Install-Package Microsoft.FeatureManagement.AspNetCore

2. Add to DI

In Startup.cs, we’ll need to add the feature into the IoC. In the `ConfigureServices` method, add the following code:

services.AddFeatureManagement();

3. Config appsettings.json

Add the following section to appsettings.json:

  "FeatureManagement": {
    "MyFeature": true
  }

All we’re doing here is building up a key value pair underneath the “FeatureManagement” header. These settings can be more complex, but all we’re doing here is saying that our feature is on.

4. Inject the Functionality

Now that we’ve registered this in the IoC (using AddFeaturemanagement) we can inject it into our controller or service; for example:

public MyService(IFeatureManager featureManager)
{
    _featureManager = featureManager;
} 

Then you can simply check whether the feature is enabled:

if (await featureManager.IsEnabledAsync("MyFeature")) { // Run the following code }

There is an intrinsic flaw with using magic strings like this – if you rename them, you could miss one. Microsoft recommend using an enum, such as this:

public enum MyFeatureFlags { FeatureA, FeatureB, FeatureC }

Which would enable you to reference it like this:

if (await featureManager.IsEnabledAsync(nameof(MyFeatureFlags.FeatureA)))

5. Access to controllers and views

You can hide an entire controller behind a flag; for example:

[FeatureGate(MyFeatureFlags.FeatureA)] 
public class HomeController : Controller 
{ ... }

You can use these on specific controller actions, too.

We did say at the start of this post that we’d display a button when a flag was on, so let’s see what that would look like in the view; after all, whilst the rest of this is useful, the most likely thing that you’ll want to do in enabling or disabling a feature is change what the user can see. The following code would only show a button if “MyFeature” is on:

<feature name="MyFeature"> <button>MyFeature Button</button> </feature>

A slight caveat here, in order to use this HTML tag, you’ll need to modify your _ViewImports.cshtml file:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Microsoft.FeatureManagement.AspNetCore

Summary and Notes

Seems pretty smooth to me. There are other feature flag managers out there; and, to be honest, it’s not like you couldn’t create your own in an hour or so, but this one struck me as a very neat option.

Also, because it’s from Microsoft, you can use Azure App Configuration to manage the flags; this gives you a proper UI to manage the flags. Obviously, if they’re in the appsetting.json, you have a number of other options, but if you’re using Azure, why not take advantage.

References

https://docs.microsoft.com/en-us/azure/azure-app-configuration/use-feature-flags-dotnet-core

https://docs.microsoft.com/en-us/azure/azure-app-configuration/quickstart-feature-flag-aspnet-core?tabs=core2x

https://docs.microsoft.com/en-us/dotnet/api/microsoft.featuremanagement?view=azure-dotnet-preview

Change the Primary Key Type in Entity Framework

Imagine that you’ve created a Primary Key in Entity Framework (AFAIK, this applies to EF Core and EF 6), and it’s the wrong type: perhaps you created it as a Guid and decided it should be a string; obviously, if you created it as a string and you want it as an integer, then you have the same issue you have with any such change: EF doesn’t know how to change the text “Donald” into an integer any more than you do !

The Problem

Imagine you have a primary key PK_Duck on the table: Duck. The table has the following data:



Id Name Description
80c983c9-14d0-49b7-889d-a08b874d4629 Donald White with a blue coat
5f2178fa-2605-4f70-bdfd-a7f6e924aab0 Jemima White with a bonnet and shawl

If you just change the model / entity type from a Guid to a string, EF will generate something like the following migration:

migrationBuilder.AlterColumn<string>(
                name: "Id",
                table: "Duck",
                nullable: false,
                oldClrType: typeof(Guid));

If you try to update the DB, you’ll get the following error:

The object ‘PK_Duck’ is dependent on column ‘Id’.
ALTER TABLE ALTER COLUMN Id failed because one or more objects access this column.

The Solution

The solution here is actually quite straightforward, and exactly what you would do in raw SQL; you just drop the primary key. Manually change the migration to drop the key first, and then re-create it afterwards:

migrationBuilder.DropPrimaryKey("PK_Duck", "Duck");

migrationBuilder.AlterColumn<string>(
                name: "Id",
                table: "Duck",
                nullable: false,
                oldClrType: typeof(Guid));

migrationBuilder.AddPrimaryKey("PK_Duck", "Duck", "Id");

Moving to Typescript with React

Typescript gives you a number of nice little statically typed features, which Javascript is sadly lacking. However, looking online, most of the tutorials and references use Javascript. This is a handy little post to allow you (or me) to use Typescript; or to use Javascript, and then transition to Typescript. Since you can use both in your project, you might find that migrating files one at a time allow you to gradually transition your code-base.

File name

When you create your first React app, you get a, by now, pretty standard SPA app. The entire app is running Javascript. To change one of the files over to Typescript, simply change the extension:

You now have your first Typescript component… Now the errors begin!

Props

Parameter ‘props’ implicitly has an ‘any’ type, but a better type may be inferred from usage.ts(7044)

This warning appears when you have the following constructor:

constructor(props) {  

Now that you’ve moved from a dynamic to a statically* typed language, Typescript is simply suggesting that you may have a better type than the Any** type that is assigned by default.

The easiest, and best transition here is simply to tell Typescript the type; for example:

interface IProps {
}

export class Home extends Component<IProps> {

  constructor(props: IProps) {    

If you actually have any properties, then you’ll need to include them in your interface; for example:

interface IProps {
  myValue: boolean
}

State

In Javascript, you define state by usage in the constructor; for example:

export class FetchData extends Component {
  static displayName = FetchData.name;
  constructor(props) {
    super(props);
    this.state = { forecasts: [], loading: true };
  }

Again, you need to define what the structure of state is:

interface IState {
  forecasts: string[];
  loading: boolean;
}

Then, you can reference that in the constructor, and pass the type into the base component:

export class Home extends Component<IProps, IState> {

  constructor(props: IProps, ) {    
    super(props);
    this.state = { 
      forecasts: [], 
      loading: true 
    };
  }

External Interface Files

One of the consequences of declaring these interfaces, is that you’ll quickly find that you need to reference the same interface from more than one place. For example, you may read some data in one component, and then display it in another. You could simply redeclare the interface in both places, but that feels dirty.

To get around this, you can simply declare a set of interfaces in a single file, or set of files. In C#, I would declare a single interface per file, so I’m tempted to lean towards this approach:

This doesn’t necessarily apply to any interfaces that are relevant to only a single component (for example, the interface for the props – unless they are shared – feels like it’s perfectly happy in the same file as the component).

Raising Events

In the same way as you now have to define what props look like, when you raise an event, you need to define what the event looks like; that is, you must tell Typescript the event type that you’re handling.

interface SearchProps {
    searchText: string;
    searchAction: (e: React.MouseEvent<HTMLButtonElement>) => void;
}
function Search(props: SearchProps) {
    
    return (
        <div>
            <label>Search</label>
            <textarea>{props.searchText}</textarea>
            <button onClick={props.searchAction}>Search</button>
        </div>
    );
}
export default Search;

External Libraries

If you’re referencing an external library, you may not have the Typescript definitions; let’s take reactstrap for example:

Could not find a declaration file for module ‘reactstrap’. ‘c:/myproject/ClientApp/node_modules/reactstrap/dist/reactstrap.cjs.js’ implicitly has an ‘any’ type.

Try `npm install @types/reactstrap` if it exists or add a new declaration (.d.ts) file containing `declare module ‘reactstrap’;`ts(7016)

You should be able to simply install this – which, in fact, it tells you to do in the error message:

npm install @types/reactstrap

References

https://stackoverflow.com/questions/46987816/using-state-in-react-with-typescript/46987987

Notes

* I’m not convinced that Typescript qualifies as a true statically typed language, rather it provides static typing for a dynamically typed language.

** Any is Typescript’s way of allowing you to revert to JavaScript, and just not type a specific variable; this is why I have doubts as to whether Typescript can be considered statically typed.

An assembly specified in the application dependencies manifest was not found… strange errors when trying to create an EF migration

This has been on my list to write up for some time, but this must be the third or fourth time I’ve encountered it – each time I get a vague sense that I’ve been here before.

Setting the Scene

It’s Friday afternoon, and you’re trying to create a migration, so you can check your code in and go home… or to the pub. Disaster strikes, you get the following error:

An assembly specified in the application dependencies manifest (MyProject.deps.json) was not found:
package: ‘Some.Package’, version: ‘1.0.0’
path: ‘Some.Package.dll’

You panic – there’s a pint of Doom Bar with your name on it, and it’s getting cold. You do a quick search, and you find this post… actually, it doesn’t matter what I write here – you’ll just see the title and scroll down to the answer. The Pigeon King is called Donald; there are 336 holes in your average golf ball; there’s nobody on the 37th floor, and nobody knows why.

The Answer

The answer is either that you have the incorrect project, or startup project. You can change both of these manually, or simply specify them in the migration; for example:

Add-Migration MigrationName -Context AppDbContext -StartupProject MyProject -Project MyProject.DataAccess

In my specific case, I had an Azure function set as the start-up project.