C#

A proper thread safe memory cache

The Core 2.2 IMemoryCache is in theory thread safe. But if you call GetOrCreateAsync from multiple threads the factory Func will be called multiple times. Which could be a bad thing. A very simple fix to this is using a semaphore.

Declare it and only let one concurrent request be granted.

private readonly SemaphoreSlim _cacheLock = new SemaphoreSlim(1);

Let one request the cache and when done release the semaphore.

await _cacheLock.WaitAsync();
var data = await _cache.GetOrCreateAsync(key, entry => ...);
_cacheLock.Release();

Stub User.Identity.IsAuthenticated in ASP Core

I’m writing this article strictly because google do not have any obvious solutions in the hope it will be indexed and presented for fellow devs.

We use identity server and to make things easier in dev I want to stub it. ClaimsIdentity takes a second argument AuthenticationType. Its important you set this property. You can set it to what ever you like. Once set IsAuthenticated will return true.

            if (env.IsDevelopment())
            {
                app.Use(async (ctx, next) =>
                {
                   ctx.User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "local") }, "Authenticated"));
                   await next.Invoke();
                });
            }

Visitor pattern navigation support with ReSharper

I love the visitor pattern, it enables open/closed principle which is a great fundamental part of maintainability and clean code. You can read more about the pattern here. There is one down side of this pattern, and that is navigation. Consider this code.

_cqsClient.ExecuteCommand(new MyCommand());

If you navigate to ExecuteCommand you will just end up at some close to the metal code that executes your command handlers. And if you try to find all usages for the Command you will only find usages of its constructor (becasuse of the new keyword).

With vanilla ReSharper you need to first navigate to the class and then do a find all usages on the class declaration and navigate to the command handler from there. Very counter productive. But ReSharper is extendable!
(more…)

Flexible integration tests with dacpac support

Integration tests are an important aspect of software development, high code coverage does improve code quality. But the tests need to be flexible and fast so they do not hinder the developers in their daily work. On the build server speed doesn’t matter that much, but a good test suite must be fast enough so that the developers choose to use it instead of running the system manually to test their features. Thats how you get good code coverage. Sadly publishing a dacpac is anything but fast. But there are clever tactics you can apply to make it work good as your daily testing platform.
(more…)

Build server – client contracts with dotnet CLI

Now days type safety is common within the web-world with TypeScript and on the horizon WebAssembly with .NET Core (Blazor etc). I have for a long time advocated for the importance of this, especially when we are talking the contract between server and client. For example this T4 template that spits out C# CQS types as javascript.

T4 doesn’t play well with Dot Net Core, but we now have the dotnet CLI toolset we can use instead.
(more…)

Client – server event aggregation with SignalR ASP.NET Core

Event aggregation is really a pattern i like, there is something elegant about firing events and subscribers can listen to them without knowing who fired them. This creates decoupled domains both in backends and frontends. Back in 2013, at my customer of that time we saw an increasing demand for pub / sub and immediate update. We fired events on the backend event bus and in the frontend we had SignalR Hubs that picked up the events and forwarded them to the clients. This caused duplicated and similar code both on the client and on the web server. I decided to create an abstraction layer between SignalR and the event aggregator. The result is a library called SignalR.EventAggregatorProxy

It has now been ported to support ASP.NET Core, this article will focus on the changes, for the orginal article go here.

(more…)

SQL CE and namespaces

We use SQL CE in our unit test project to test our EF6 queries. This works pretty well and Code first setup makes sure each test gets a fresh CE database to work with.

We ran into a problem where two EF types had the same table name but inside different schemas. CE does not support schemas and this resulted in naming conflicts when setting up database. My solution was to create a little convention.

public class BakeSchemaIntoTableNameConvention : IStoreModelConvention<EntityType>
{
    public void Apply(EntityType item, DbModel model)
    {
        var entitySet = model.StoreModel.Container.EntitySets.Single(es => es.ElementType == item);
        entitySet.Table = $"{entitySet.Schema}_{entitySet.Table}";
    }
}

It bakes the schema into the table name like dbo_MyTable. You add the convention like.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Add<BakeSchemaIntoTableNameConvention>();

    modelBuilder.Configurations.AddFromAssembly(typeof (MyContext).Assembly);
}

You do not want to add this for production code so what I did was create a public event on the context. And call it from the OnModelCreating method.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    ModelCreating?.Invoke(this, modelBuilder);

    modelBuilder.Configurations.AddFromAssembly(typeof (MyContext).Assembly);
}

Call it from your Unittest project like.

ctx.ModelCreating += (s, e) => e.Conventions.Add<BakeSchemaIntoTableNameConvention>();

Microsoft.Rest.ServiceClient opt out retry

If you use Swagger generated REST proxies then you have probably come across the pretty new Microsoft.Rest namespace and namely the abstract class ServiceClient. I noticed a strange behavior when using clients that subclass this base class. The default behavior for this class is to retry when a 500 status code is returned.
I can not understand the reason for this being Opt out, its obvious a feature like this should be Opt in. So keep in mind when using this class you must always call SetRetryPolicy to disable the retry strategy.

var service = new MyService(uri, credentials);
service.SetRetryPolicy(new RetryPolicy(new HttpStatusCodeErrorDetectionStrategy(), 0));

Task.WhenAny with take predicate

Not a very common scenario but still it happens, you want to execute a request to several Services, and only one has the correct data. The built in Task.WhenAny only supports to await the first Task complete. That wont do if you want to wait for the first Task to complete that satisfy a specific condition.

Nito.AsyncEx is a helper library for Task programming, it comes with an extension method called OrderByCompletion. It takes a collection of Task<T> and return a new collection that will be ordered on completion status. Using this method its a simple task to create a WhenAny based on a predicate.

public async static Task<TResult> First<TResult>(this IEnumerable<Task<TResult>> source, Predicate<TResult> predicate)
{
    var ordered = source
        .OrderByCompletion();

    foreach (var task in ordered)
    {
        var result = await task;
        if (predicate(result)) return result;
    }

    throw new Exception("Sequence contains no matching element");
}

Used like

var result = await services
   .Select(s => s.GetFooAsync())
   .First(f => f.IsSuccess);
}