Switchable Actor Behaviour in Akka.NET

One of the things that actors can do is change their behaviour in response to an incoming message. This doesn’t however mean that we end up with a single “god actor” that has too many responsibilities. Whilst this may also seem like a potentially dangerous thing to do it is actually a very poweful concept. Because an actor instance only processes one message at a time, we don’t have to worry about this behaviour switch affecting the currently processing message, in fact the change in behaviour applies to the next message processed.

There’s a number of benefits to using switchable behaviours including the potential reduction/simplification of the amount of code we need to write and the ability for our brains to conceptualize what the the actor does more readily.

As an example, consider the following code that represents an actor that can respond in one of two ways to an incoming message depending on its current (boolean) state:

class LightSwitchActor : ReceiveActor
{
    private bool _isTurnedOn;
    public LightSwitchActor()
    {
        Receive<FlipTheSwitchMessage>(message => HandleMessage(message));
    }

    private void HandleMessage(FlipTheSwitchMessage message)
    {
        if (_isTurnedOn)
        {
            // do some processing when currently turned on and message received

            // flip the switch
            _isTurnedOn = false;
        }
        else
        {
            // do some processing when currently turned off and message received

            // flip the switch
            _isTurnedOn = true;
        }
    }
}

In the preceding code, the state of the boolean field _isTurnedOn determines how the actor behaves in response to an incoming FlipTheSwitchMessage.

This actor could be refactored so that the isTurnedOn field is removed and the different behavioural states become more explicit:

class LightSwitchBehaviourActor : ReceiveActor
{
    public LightSwitchBehaviourActor()
    {
        TurnedOff();   
    }


    private void TurnedOn()
    {
        Receive<FlipTheSwitchMessage>(
            message =>
            {
                // do some processing when currently turned on and message received                            

                // flip the switch
                Become(TurnedOff);
            });
    }

    private void TurnedOff()
    {
        Receive<FlipTheSwitchMessage>(
            message =>
            {
                // do some processing when currently turned off and message received                                  

                // flip the switch
                Become(TurnedOn);
            });
    }
}

Note the use of the Become() method which allows us to change how we respond to the next message that gets processed.

Whilst in these simple examples there are only two states (TurnedOn and TurnedOff) an actor could describe a greater number of potentially more complex behaviours.

For more information check out the Akka.NET docs or my Pluralsight course: Building Concurrent Applications with the Actor Model in Akka.NET.

Actor Models Come to .NET Developers with Akka.NET

Akka.NET is a port of the Java/Scala Akka framework.

In some ways, the emergence of Akka.NET could be seen as .NET truly “coming of age” - in the sense that other .NET technologies for building web, phone, services, apps etc. are great whereas the distributed .NET story has not been as fully realised – until now with Akka.NET and also Orleans.

In Akka.NET there are two primary constructs: actors and messages.

Actors do work and messages allow actors (and the outside world) to communicate. Actors don’t expose their internal state to other actors, all communication is done with messages.

Messages can be built-in .NET types such as a string or int, or can be custom types containing multiple data items.

Actors perform the work of the system and can essentially do one of four things:

  • Receive and respond to incoming messages
  • Send messages to other actors
  • Create new actors
  • Change behaviour in response to an incoming message

Actors have an incoming mailbox and they process one message at a time, then move onto the next message, and so on. If there are no messages to process the actor sits around being lazy, it only reacts to incoming messages.

The ability of actors to change their behaviour allows the simplification of actor code and also allows the building of finite state machines.

Actors can also be distributed across multiple processes/machines. Akka.NET makes this easier by providing “location transparency”, essentially not having to worry about changing our code just because we want to send a message to an actor in a different process. Akka.NET goes even further and can actually deploy instances of actors automatically to remote machines when they are created by simple modification of config – again requiring no code changes.

Akka.NET also supports the idea that systems can be “self-healing”. Through a hierarchy of supervision, parent actors supervise the child actors that they create. If a child actors errors, the parent supervising it can decide how to handle the failure. We can accept the default supervision strategy or create our own as necessary.

For more information on Akka.NET check out the home page, follow the project on Twitter, or check out my Pluralsight course: Building Concurrent Applications with the Actor Model in Akka.NET.

FeatureToggle 3.2 Released

FeatureToggle logo image

A minor release of my open source FeatureToggle library has just been released to NuGet.

Version 3.2 was a result of user requests to be able to configure toggles that get their values from sql server to be configured using the <connectionStrings> section of the .config file.

A Sql based toggle can now be configured a number of different ways

Using appSettings only

This is the original method:

<appSettings>
   <add key="FeatureToggle.SaveToPdfFeatureToggle.ConnectionString" value="Data Source=.\SQLEXPRESS;Initial Catalog=FeatureToggleDatabase;Integrated Security=True;Pooling=False"/>
   <add key="FeatureToggle.SaveToPdfFeatureToggle.SqlStatement" value="select Value from Toggle where ToggleName = 'SaveToPdfFeatureToggle'"/>
</appSettings>

Using connectionStrings Entry by Convention

<appSettings>
    <add key="FeatureToggle.SaveToPdfFeatureToggle.SqlStatement" value="select Value from Toggle where ToggleName = 'SaveToPdfFeatureToggle'"/>
</appSettings>

<connectionStrings>
    <add name="FeatureToggle.SaveToPdfFeatureToggle" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=FeatureToggleIntegrationTests;Integrated Security=True;Pooling=False" />    
</connectionStrings>

 

Using connectionStrings Custom Named Entry

This option allows multiple toggles to share a named connection if you have more than one sql toggle in the application.

<appSettings>
    <add key="FeatureToggle.SaveToPdfFeatureToggle.SqlStatement" value="select Value from Toggle where ToggleName = 'SaveToPdfFeatureToggle'"/>
    <add key="FeatureToggle.SaveToPdfFeatureToggle.ConnectionStringName" value="myAwesomeConnection" />
</appSettings>

<connectionStrings>
    <add name="myAwesomeConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=FeatureToggleIntegrationTests;Integrated Security=True;Pooling=False" />    
</connectionStrings>

Thanks

Thanks to the following people for contributions and ideas:

FeatureToggle Version 3 Released

FeatureToggle logo image

Version 3 of my open source feature toggle library is now released to NuGet.

Version 3 introduces some breaking changes and new features.

Breaking Changes

  • The WPF value convertor package has been removed for version 3 as it’s trivial to implement a version in individual applications and reduce the maintenance overhead for the porject
  • Version 3 removes support for Windows Phone 8.0 (you can still use version 2.x if you need this support)

New Features

Platforms Support

In addition to .NET framework 4 full, version 3 also supports:

  • Windows Phone 8.1 Silverlight apps
  • Windows Universal Apps 8.1 (Store and Windows Phone 8.1 WinRT)
  • Windows Store 8.1 apps

Future versions will add support for Windows 10 apps.

New Toggle Types

The EnabledOnOrAfterAssemblyVersionWhereToggleIsDefinedToggle (a little verbose I know) allows a feature to become enabled once a specified assembly version number is reached. The assembly version used is that of the assembly inside which the toggle is defined, rather that the executing assembly. The configuration value for this toggle would be (for example) 0.0.2.1.

Future version will add support for comparing the executing assembly version.

New Decorators

A new type of feature that version 3 introduces is the idea of toggle decorators. These are classes that “wrap” one or more toggles and provide additional features.

The DefaultToEnabledOnErrorDecorator and the DefaultToDisabledOnErrorDecorator allows a default value to provided if there is an error evaluating the wrapped toggle value, for example with a configuration error. These decorators should be used with caution as your application may end up in an unknown state if you forget to configure something properly. In some cases you may want this behaviour rather than the application failing.

Assuming that a feature toggle called MyFeatureToggle has been defined, to use the decorator the following code would be used.

IFeatureToggle printFeatureThatDefaultsToDisabled = new DefaultToDisabledOnErrorDecorator( new MyFeatureToggle() );

bool isPrintEnabled = printFeatureThatDefaultsToDisabled.FeatureEnabled;

These decorators also allow you to specify an optional logging action that gets called if the wrapped toggle throws an exception:

new DefaultToDisabledOnErrorDecorator(wrappedToggle, ex => Console.WriteLine(ex.Message));

 

The CompositeAndDecorator allows multiple toggles to be wrapped, only if all these wrapped toggles are enabled will the decorator return true.

IFeatureToggle andToggle = new CompositeAndDecorator(new AnEnabledFeature(), new ADisabledFeature());

var isEnabled = andToggle.FeatureEnabled; // returns false

 

The final new decorator is the FixedTimeCacheDecorator. This allows a toggle that gets its value from a slow source (such as remote database, http, etc.) to have its value cached for a fixed period of time. To use this you specify the wrapped toggle and a TimeSpan.

IFeatureToggle cachedToggle = new FixedTimeCacheDecorator(cachedToggle, TimeSpan.FromSeconds(10));

 

Check out the release notes on GitHub. If you find any problems or bugs or want to suggest other features, please create an issue on GitHub.

An Update on FeatureToggle v3 Development

The next version of my open source feature toggling library is currently in development.

Version 3 will introduce a number of new features and retire support for some older platforms. For the currently implemented changes (not yet released at the time of writing) see GitHub release notes, and the complete list of v3 issues/features.

Some notable additions include some new toggle types to enable scenarios such as automatically enabling a feature once the assembly version number meets or exceeds a specific version and decorators to allow a toggle to default to on or off if the underlying toggle errors in some way, such as missing configuration or network error while retrieving the toggle value from a remote source such as SQL Server.

Once v3 development is complete it will be available via NuGet.

New Pluralsight Course - Better .NET Unit Tests with AutoFixture

My new Pluralsight testing course was just released: Better .NET Unit Tests with AutoFixture: Get Started.

AutoFixture is an open source library that allows the simplification of automated .NET tests. It allows for the creation of “anonymous” test data. This is data that is required for the test to execute, but where the exact values are unimportant.

AutoFixture is not dependent upon any specific testing framework, so can be used with xUnit.net, NUnit, MSTest, etc. There are some additional extensions for specific testing frameworks such as xUnit.net that allow further reductions in unit test setup code.

For more info check out the GitHub site or the Pluralsight course.

If you like AutoFixture be sure to give open source thanks to Mark Seemann.

Using AutoFixture To Generate Anonymous Test Data in Web UI Automation With BDDfy and Seleno

I’m currently working on an AutoFixture Pluralsight course and it got me thinking about using it to generate anonymous test data when writing automated UI tests.

The basic premise is that in addition to using AutoFixture to generate unit test data, it can also be used to populate UI elements where the specific data values are unimportant.

If you are unfamiliar with BDDfy and Seleno, they are part of the TestStack project.

BDDfy allows tests to be written and to produce business readable documentation. Seleno allows the automation of web browsers using Selenium and strongly-typed page object models.

Example Scenario

Imagine that we have an (ASP.NET MVC) web site that allows the addition of members of the royal family.

image

If we wanted to test different king/queen names (but didn’t care about the Regnal number) we could start off by defining some strongly typed (Seleno) page object models:

public class HomePage : Page<AddRoyaltyModel>
{
    public CreatedPage CreateRoyalty(AddRoyaltyModel royal)
    {
        Input.Model(royal);

        return Navigate.To<CreatedPage>(By.Id("Create"));
    }
}

public class CreatedPage : Page
{
}

 

(all the examples in this post are fairly quick-and-dirty to demonstrate the AutoFixture involvement)

 

Next we can write some example in BDDfy (using xUnit.net as the test framework):

public class AddRoyaltyTests
{
    private HomePage _home;
    private CreatedPage _confirmationPage;
    public string Name { get; set; }
    public string Number { get; set; }

    [Fact]
    public void ShouldAddRoyaltiesWithDifferentNames()
    {
        this.Given(x => GivenIAmStartingANewRoyalAddition())
            .And("And I have entered <name> as the royalty name")
            .And("And I have entered <number> as the regnal number")
            .When(x => WhenIChooseToAddTheNewRoyal())
            .Then(x => ThenIShouldSeeAConfirmationOfTheNewRoyalHavingBeenAdded())
            .WithExamples(new ExampleTable("name", "number")
                          {
                              {"Richard", "I"},
                              {"Henry", "I"},
                              {"Elizabeth", "I"}
                          })
            .BDDfy();            
    }



    private void GivenIAmStartingANewRoyalAddition()
    {
        _home = Host.Instance.NavigateToInitialPage<HomeController, HomePage>(x => x.Index());
    }        

    private void WhenIChooseToAddTheNewRoyal()
    {
        var royal = new AddRoyaltyModel
        {
            Name = this.Name,
            RegnalRomanNumeral = this.Number
        };

        _confirmationPage = _home.CreateRoyalty(royal);
    }

    private void ThenIShouldSeeAConfirmationOfTheNewRoyalHavingBeenAdded()
    {
        Assert.Equal("Created ok", _confirmationPage.Title);
    }
}

Notice in the preceding code that even though we don’t care about the Regnal number we are still supplying it in the examples. We could just set it manually to a hardcoded value, and in this simple example that might be ok, but if we had a form with many fields then this  will introduce extra work and may make the test less “refactor-safe”.

The following code shows the removal of the Regnal name/number:

public class AddRoyaltyTestsUsingAutoFixture
{
    private HomePage _home;
    private CreatedPage _confirmationPage;
    public string Name { get; set; }

    [Fact]
    public void ShouldAddRoyaltiesWithDifferentNames()
    {
        this.Given(x => GivenIAmStartingANewRoyalAddition())
            .And("And I have entered <name> as the royalty name")
            .When(x => WhenIChooseToAddTheNewRoyal())
            .Then(x => ThenIShouldSeeAConfirmationOfTheNewRoyalHavingBeenAdded())
            .WithExamples(new ExampleTable("name")
                          {
                              "Richard",
                              "Henry",
                              "Elizabeth"
                          })
            .BDDfy();            
    }

    private void GivenIAmStartingANewRoyalAddition()
    {
        _home = Host.Instance.NavigateToInitialPage<HomeController, HomePage>(x => x.Index());
    }        

    private void WhenIChooseToAddTheNewRoyal()
    {
        var fixture = new Fixture();

        // Use AutoFixture to create anonymous data for all properties except
        // name which is set to the BDDfy example value
        var royal = fixture.Build<AddRoyaltyModel>()
            .With(x => x.Name, this.Name)
            .Create();

        _confirmationPage = _home.CreateRoyalty(royal);
    }

    private void ThenIShouldSeeAConfirmationOfTheNewRoyalHavingBeenAdded()
    {
        Assert.Equal("Created ok", _confirmationPage.Title);
    }
}

In this version, AutoFixture’s Build method is being used to automatically generate test data for all the fields, except the royal name which is set to the name(s) specified in the BDDfy examples.

Running this test results in the following automation:

SelenoAutofixture

 

And produces the following HTML BDDfy report:

image

The ConditionalWeakTable in .NET

The ConditionalWeakTable class exists in the System.Runtime.CompilerServices namespace and as its namespace suggests is used in compilation processes.

The class allows a key-value pair to be stored (using its Add method), once the key object no longer has any references outside of the ConditionalWeakTable the key can be destroyed during garbage collection as the key is held as a weak reference inside the table, as opposed to a usual strong reference. At this point the key object can be garbage collected. Also at this point, if the value object also has no other references, it too can be collected. Or too quote MSDN: “It does not persist keys. That is, a key is not kept alive only because it is a member of the collection”.

The following code shows a console application followed by its output:

using System;
using System.Runtime.CompilerServices;

namespace ConditionalWeakTableExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var cwt = new ConditionalWeakTable<SomeKeyClass, SomeValueClass>();

            Console.WriteLine("Creating new instance of SomeKeyClass called key1");
            var key1 = new SomeKeyClass();

            Console.WriteLine("Creating new instance of SomeValueClass called value1");
            var value1 = new SomeValueClass();

            Console.WriteLine("Creating variable anotherReferenceToKey1 referencing key1");
            var anotherReferenceToKey1 = key1;

            Console.WriteLine("Adding key1, value1");
            cwt.Add(key1, value1);




            Console.WriteLine("Press a key to set key1 to null");
            Console.ReadLine();
            key1 = null;
            Console.WriteLine("key1 to null");

            ForceGc();




            Console.WriteLine("Press a key to set anotherReferenceToKey1 to null");
            Console.ReadLine();
            anotherReferenceToKey1 = null;
            Console.WriteLine("anotherReferenceToKey1 to null");

            ForceGc();            




            Console.WriteLine("End of program - press any key to exit");
            Console.ReadLine();
        }


        private static void ForceGc()
        {
            Console.WriteLine("Forcing garbage collection and waiting for finalizers");
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }


    class SomeKeyClass
    {
        ~SomeKeyClass()
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("****** SomeKeyClass Destroyed");
            Console.ResetColor();
        }        
    }

    class SomeValueClass
    {
        ~SomeValueClass()
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("****** SomeValueClass Destroyed");
            Console.ResetColor();
        }
    }
}

image

 

So here, even though the cwt contains an entry using key1, it is held in a weak way so it will not prevent garbage collection.

Also notice in this example, the value object has not been destroyed as we still have a reference to it in the variable value1.

If we change the code to also set value1 to null, when the Garbage Collector runs it will destroy the key object as before, but now there are also no references to the value object, so it too can be destroyed:

static void Main(string[] args)
{
    var cwt = new ConditionalWeakTable<SomeKeyClass, SomeValueClass>();

    Console.WriteLine("Creating new instance of SomeKeyClass called key1");
    var key1 = new SomeKeyClass();

    Console.WriteLine("Creating new instance of SomeValueClass called value1");
    var value1 = new SomeValueClass();

    Console.WriteLine("Creating variable anotherReferenceToKey1 referencing key1");
    var anotherReferenceToKey1 = key1;

    Console.WriteLine("Adding key1, value1");
    cwt.Add(key1, value1);




    Console.WriteLine("Press a key to set key1 to null");
    Console.ReadLine();
    key1 = null;
    Console.WriteLine("key1 to null");

    ForceGc();




    Console.WriteLine("Press a key to set anotherReferenceToKey1, value1 to null");
    Console.ReadLine();
    anotherReferenceToKey1 = null;
    value1 = null;
    Console.WriteLine("anotherReferenceToKey1 & value1 to null");

    ForceGc();            




    Console.WriteLine("End of program - press any key to exit");
    Console.ReadLine();
}

 

image

 

So even though this is not a class we’d use in everyday coding, it’s one of the many interesting things in .NET that are hidden away in namespaces we don’t usually use. It also should be noted that it doesn’t really behave as a “normal” dictionary, for example it doesn’t contain GetEnumerator method.

To learn some cool C# Tips, check out my free C# Tips eBook or my Pluralsight C# Tips and Traps course.

Beyond Simple Asserts with ApprovalTests

In a test, we are often testing (asserting) individual items such as an (int) age is correct or a string matches an expected value.

If we are practicing test-first development we’ll write our asserts first.

Approval tests allow us to go beyond simple asserts.

What if the thing we’re checking is not a simple value, for example that a pie chart image matches the input data? Or what if we want to use our human judgement to decide when something looks correct, something that is hard to codify in one or more basic asserts?

ApprovalTests for .NET can be install via NuGet. Once installed, it gives us a whole new world when it comes to checking the output of code.

For example, say we are developing a class to represent a stickman. We want to be able to tell an instance to raise left arm or raise right leg for example.

Example of Using Approval Tests

So lets start with a test:

[Fact]
[UseReporter(typeof(DiffReporter))]
public void ShouldHaveDefaultPosture()
{
    var sut = new StickMan();

    Approvals.Verify(sut);
}

And an empty StickMan:

public class StickMan
{        
}

Here we’re using xUnit.net (the [Fact] attribute) but you could be using NUnit for example.

The first thing to notice here is there is no traditional Assert method, instead we’re using Approval Tests to verify the state of the system under test (sut).

The other think to notice is the [UseReporter] attribute that tells Approval Tests to use a diff tool to display errors when a test fails.

If we run this test, we’ll get a diff tool opened:

More...