Test driving C# 7 features in Visual Studio “15” Preview

Very poorPoorAverageGoodExcellent (1 votes) 
Loading...

About two weeks ago, Microsoft released the first preview of the next version of Visual Studio. You can read about what’s new in the release notes. Some of the new features are really nice (for instance I love the new “lightweight installer”), but the most interesting for me is that it comes with a version of the compiler that includes a few of the features planned for C# 7. Let’s have a closer look at them!

Enabling the new features

The new features are not enabled by default. You can enable them individually with /feature: command line switches, but the easiest way is to enable them all by adding __DEMO__ and __DEMO_EXPERIMENTAL__ to the conditional compilation symbols (in Project properties, Build tab).

Local functions

Most functional languages allow you to declare functions in the body of other functions. It’s now possible to do the same in C# 7! The syntax for declaring a method inside another is pretty much what you would expect:

long Factorial(int n)
{
    long Fact(int i, long acc)
    {
        return i == 0 ? acc : Fact(i - 1, acc * i);
    }
    return Fact(n, 1);
}

Here, the Fact method is local to the Factorial method (in case you’re wondering, it’s a tail-recursive implementation of the factorial — which doesn’t make much sense, since C# doesn’t support tail recursion, but it’s just an example).

Of course, it was already possible to simulate local functions with lambda expressions, but there were a few drawbacks:

  • it’s less readable, because you have to declare the delegate type explicitly
  • it’s slower, due to the overhead of creating a delegate instance, and calling the delegate vs. calling the method directly
  • writing recursive lambdas is a bit awkward

Local functions have the following benefits:

  • when a method is only used as a helper for another method, making it local makes the relation more obvious
  • like lambdas, local functions can capture local variables and parameters of their containing method
  • local functions support recursion like any normal method

You can read more about this feature in the Roslyn Github repository.

Ref returns and ref locals

Since the first version of C#, it has always been possible to pass parameters by reference, which is conceptually similar to passing a pointer to a variable in languages like C. Until now, this feature was limited to parameters, but in C# 7 it becomes possible to return values by reference, or to have local variables that refer to the location of another variable. Here’s an example:

static void TestRefReturn()
{
    var foo = new Foo();
    Console.WriteLine(foo); // 0, 0
    
    foo.GetByRef("x") = 42;

    ref int y = ref foo.GetByRef("y");
    y = 99;

    Console.WriteLine(foo); // 42, 99
}

class Foo
{
    private int x;
    private int y;

    public ref int GetByRef(string name)
    {
        if (name == "x")
            return ref x;
        if (name == "y")
            return ref y;
        throw new ArgumentException(nameof(name));
    }

    public override string ToString() => $"{x},{y}";
}

Let’s have a closer look at this code.

  • On line 6, it looks like I’m assigning a value to the return of a method; what does this even mean? Well, the GetByRef method returns a field of the Foo class by reference (note the ref int return type of GetByRef). So, if I pass "x" as an argument, it returns the x field by reference. If I assign a value to that, it actually assigns a value to the x field.
  • On line 8, instead of just assigning a value directly to the field returned by GetByRef, I use a ref local variable y. The local variable now shares the same memory location as the foo.y field. So if I assign a value to it, it changes the value of foo.y.

Note that you can also return an array location by reference:

private MyBigStruct[] array = new MyBigStruct[10];
private int current;

public ref MyBigStruct GetCurrentItem()
{
    return ref array[current];
}

It’s likely that most C# developers will never actually need this feature; it’s pretty low level, and not the kind of thing you typically need when writing line-of-business applications. However it’s very useful for code whose performance is critical: copying a large structure is expensive, so if we can return it by reference instead, it can be a non-negligible performance benefit.

You can learn more about this feature on Github.

Pattern matching

Pattern matching is a feature very common in functional languages. C# 7 introduces some aspects of pattern matching, in the form of extensions to the is operator. For instance, when testing the type of a variable, it lets you introduce a new variable after the type, so that this variable is assigned with the left-hand side operand of the is, but with the type specified as the right-hand side operand (it will be clearer with an example).

Typically, if you need to test that a value is of type DateTime, then do something with that DateTime, you need to test the type, then cast to that type:

object o = GetValue();
if (o is DateTime)
{
    var d = (DateTime)o;
    // Do something with d
}

In C# 7, you can do this instead:

object o = GetValue();
if (o is DateTime d)
{
    // Do something with d
}

d is now declared directly as part of the o is DateTime expression.

This feature can also be used in a switch statement:

object v = GetValue();
switch (v)
{
    case string s:
        Console.WriteLine($"{v} is a string of length {s.Length}");
        break;
    case int i:
        Console.WriteLine($"{v} is an {(i % 2 == 0 ? "even" : "odd")} int");
        break;
    default:
        Console.WriteLine($"{v} is something else");
        break;
}

In this code, each case introduces a variable of the appropriate type, which you can use in the body of the case.

So far I only covered pattern matching against a simple type, but there are also more advanced forms. For instance:

switch (DateTime.Today)
{
    case DateTime(*, 10, 31):
        Console.WriteLine("Happy Halloween!");
        break;
    case DateTime(var year, 7, 4) when year > 1776:
        Console.WriteLine("Happy Independence Day!");
        break;
    case DateTime { DayOfWeek is DayOfWeek.Saturday }:
    case DateTime { DayOfWeek is DayOfWeek.Sunday }:
        Console.WriteLine("Have a nice week-end!");
        break;
    default:
        break;
}

How cool is that!

There’s also another (still experimental) form of pattern matching, using a new match keyword:

object o = GetValue();
string description = o match
    (
        case string s : $"{o} is a string of length {s.Length}"
        case int i : $"{o} is an {(i % 2 == 0 ? "even" : "odd")} int"
        case * : $"{o} is something else"
    );

It’s very similar to a switch, except that it’s an expression, not a statement.

There’s a lot more to pattern matching than what I mentioned here. You can look at the spec on Github for more details.

Binary literals and digit separators

These features were not explicitly mentioned in the VS Preview release notes, but I noticed they were included as well. They were initially planned for C# 6, but didn’t make it in the final release. They’re back in C# 7.

You can now write numeric literal in binary, in addition to decimal an hexadecimal:

int x = 0b11001010;

Very convenient to define bit masks!

To make large numbers more readable, you can also group digits by introducing separators. This can be used for decimal, hexadecimal or binary literals:

int oneBillion = 1_000_000_000;
int foo = 0x7FFF_1234;
int bar = 0b1001_0110_1010_0101;

Conclusion

So, with Visual Studio “15” Preview, you can start experimenting with the new C# 7 features; don’t hesitate to share your feedback on Github! And keep in mind that it’s still pre-release software, lots of things can change before the final release.

Posted in Uncategorized. Tags: , , . 2 Comments »

Automatically inject fakes in test fixture with FakeItEasy

Very poorPoorAverageGoodExcellent (2 votes) 
Loading...

Today I’d like to share a nice feature I discovered recently in FakeItEasy.

When you write unit tests for a class that takes dependencies, you typically need to create fake/mock dependencies and manually inject them into the SUT (System Under Test), or use a DI container to register the fake dependencies and construct the SUT. This is a bit tedious, and a few months ago I came up with an auto-mocking Unity extension to make it easier. Now I just realized that FakeItEasy offers an even better solution: just declare the dependencies and SUT as fields or properties in your test fixture, and call Fake.InitializeFixture on the fixture to initialize them. Here’s how it looks:

    public class BlogManagerTests
    {
        [Fake] public IBlogPostRepository BlogPostRepository { get; set; }
        [Fake] public ISocialNetworkNotifier SocialNetworkNotifier { get; set; }
        [Fake] public ITimeService TimeService { get; set; }

        [UnderTest] public BlogManager BlogManager { get; set; }

        public BlogManagerTests()
        {
            Fake.InitializeFixture(this);
        }

        [Fact]
        public void NewPost_should_add_blog_post_to_repository()
        {
            var post = A.Dummy<BlogPost>();

            BlogManager.NewPost(post);

            A.CallTo(() => BlogPostRepository.Add(post)).MustHaveHappened();
        }

        [Fact]
        public void PublishPost_should_update_post_in_repository_and_publish_link_to_social_networks()
        {
            var publishDate = DateTimeOffset.Now;
            A.CallTo(() => TimeService.Now).Returns(publishDate);

            var post = A.Dummy<BlogPost>();

            BlogManager.PublishPost(post);

            Assert.Equal(BlogPostStatus.Published, post.Status);
            Assert.Equal(publishDate, post.PublishDate);

            A.CallTo(() => BlogPostRepository.Update(post)).MustHaveHappened();
            A.CallTo(() => SocialNetworkNotifier.PublishLink(post)).MustHaveHappened();
        }
    }

The SUT is declared as a property marked with the [UnderTest] attribute. Each dependency that you need to manipulate is declared as a property marked with the [Fake] attribute. Fake.InitializeFixture then initializes the SUT, creating fake dependencies on the fly, and assigns those dependencies to the corresponding properties.

I really like how clean the tests look with this technique; the boilerplate code is reduced to a minimum, all you have to do is configure the dependencies where necessary and get on with your tests.

Two remarks about the code above:

  • You can use private fields instead of public properties for the fakes and SUT, but since the fields are never explicitly set in code, it raises a compiler warning (CS0649), so I prefer to use properties.
  • The tests in my example use xUnit, so I put the call to Fake.InitializeFixture in the fixture constructor, but if you use another test framework like NUnit or MSTests, you would typically put it in the setup method.

Also, note that there are limits to the scenarios supported by this approach:

  • only constructor injection is supported, not property injection (i.e. the dependencies must be constructor parameters of the SUT)
  • named dependencies are not supported; only the type is taken into account, so you can’t have multiple distinct dependencies with the same type
  • dependency collections are not supported (i.e. if your class receives a collection of dependencies, e.g. IFooService[])

Using multiple cancellation sources with CreateLinkedTokenSource

Very poorPoorAverageGoodExcellent (No Ratings Yet) 
Loading...

Async programming in C# used to be hard; thanks to .NET 4’s Task Parallel Library and C# 5’s async/await feature, it has become fairly easy, and as a result, is becoming much more common. At the same time, a standardized approach to cancellation has been introduced : cancellation tokens. The basic idea is that you create a CancellationTokenSource that controls the cancellation, and pass the token it provides to the method that you want to be able to cancel. That method will then pass it to the other methods it calls, if they can be canceled, and/or regularly check if cancellation was requested. Upon cancellation, the method will typically throw an OperationCanceledException. Quick and dirty example:

private readonly IBusinessService _businessService;
private CancellationTokenSource _cancellationSource;
private Task _asyncOperation;

private void StartAsyncOperation()
{
    if (_asyncOperation != null)
        return;
    var _cancellationSource = new CancellationTokenSource();
    _asyncOperation = _businessService.DoSomethingAsync(_cancellationSource.Token);
}

// async void is bad; like I said, this is a quick and dirty example
private async void StopAsyncOperation()
{
    try
    {
        _cancellationSource.Cancel();
        // wait for the operation to finish
        await _asyncOperation;
    }
    catch (OperationCanceledException)
    {
        // Operation was successfully canceled
    }
    catch (Exception)
    {
        // Oops, something went wrong
    }
    finally
    {
        _asyncOperation = null;
        _cancellationSource.Dispose();
        _cancellationSource = null;
    }

...

class BusinessService : IBusinessService
{
    public async Task DoSomethingAsync(CancellationToken cancellationToken)
    {
        var data = await GetDataFromServerAsync(cancellationToken);
        foreach (string line in data)
        {
            cancellationToken.ThrowIfCancellationRequested();
            await ProcessLineAsync(line, cancellationToken);
        }
    }

    ...
}

In this case, StopAsyncOperation would be called, for instance, if the user chooses to abort the operation.

This all works pretty well and is rather easy to setup. But what if there is another reason to cancel the operation, known only by the BusinessService and outside the control of the calling method? That’s where the CancellationSource.CreateLinkedTokenSource method comes into play; basically, this method creates a cancellation source that will be canceled when any of the specified tokens is canceled.

Let’s start with a simple case: you have another cancellation token that you also want to take into account. The code would look like this:

    public async Task DoSomethingAsync(CancellationToken cancellationToken)
    {
        var otherToken = GetOtherCancellationToken();
        using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, otherToken))
        {
            var data = await GetDataFromServerAsync(linkedCts.Token);
            foreach (string line in data)
            {
                linkedCts.Token.ThrowIfCancellationRequested();
                await ProcessLineAsync(line, linkedCts.Token);
            }
        }
    }

We created a linked cancellation source based on the two cancellation tokens, then used the token from this new source instead of cancellationToken. If either cancellationToken or otherToken is canceled, linkedCts.Token will be canceled as well. If necessary, the calling code can detect how the operation was canceled by checking the CancellationToken property of the OperationCanceledException.

Now let’s see a slightly more difficult case: the second cancellation source is actually an event. You want to cancel the operation when the event occurs, in addition to user cancellation represented by the cancellationToken parameter. So you need to subscribe to the event and trigger the cancellation when it occurs. Here’s a way to do it:

    public async Task DoSomethingAsync(CancellationToken cancellationToken)
    {
        using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
        {
            EventHandler handler = (sender, e) => linkedCts.Cancel();
            try
            {
                SomeEvent += handler;
                var data = await GetDataFromServerAsync(linkedCts.Token);
                foreach (string line in data)
                {
                    linkedCts.Token.ThrowIfCancellationRequested();
                    await ProcessLineAsync(line, linkedCts.Token);
                }
            }
            finally
            {
                SomeEvent -= handler;
            }
        }
    }

Here we only pass cancellationToken to CreateLinkedTokenSource, and we directly cancel linkedCts when the event is raised. The code is getting a bit convoluted, but it achieves the desired result.

I can’t really give you a specific real-world use case of this technique, because the cases where I used it are too specific to be of public interest, but I can outline the general scenario. I have a long running operation that is made up of multiple long running operations. The whole operation can be canceled globally, and each of the sub-operations can also be canceled individually, without affecting the others. Here’s the rough outline of what it looks like:

async Task GlobalOperationAsync(CancellationToken cancellationToken)
{
    foreach (var subOperation is SubOperations)
    {
        cancellationToken.ThrowIfCancellationRequested();
        var subToken = subOperation.GetSpecificCancellationToken();
        using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, subToken))
        {
            try
            {
                await subOperation.RunAsync(linkedCts.Token);
            }
            catch (OperationCanceledException ex)
            {
                // Rethrow only if global cancellation was requested
                if (cancellationToken.IsCancellationRequested)
                    throw;
                    
                // otherwise continue running the other sub-operations
            }
        }
    }
}

Note that even though CancellationToken was introduced with the TPL and all the examples I gave were asynchronous, nothing prevents you from using this technique with synchronous code.

I hope you find this helpful. Have a great New Year’s Eve celebration and a happy new year!

Explicitly switch to the UI thread in an async method

Very poorPoorAverageGoodExcellent (1 votes) 
Loading...

Async code is a great way to keep your app’s UI responsive. You can start an async operation from the UI thread, await it without blocking the UI thread, and naturally resume on the UI thread when it’s done. This is a very powerful feature, and most of the time you don’t even need to think about it; it “just works”. However, this works only if the async operation is started from a thread that has a synchronization context (such as the UI thread in Windows Forms, WPF or WinRT). If you don’t have a sync context when the async operation starts, or if resuming on the sync context is explicitly disabled with ConfigureAwait(false), then the method resumes on a thread pool thread after the await, and there is no obvious way to get back to the UI thread.

For instance, let’s assume you want to do something like this:

public async void btnStart_Click(object sender, RoutedEventArgs e)
{
    lblStatus.Text = "Working...";
    
    // non blocking call
    var data = await GetDataFromRemoteServerAsync().ConfigureAwait(false);
    // blocking call, but runs on a worker thread
    DoSomeCpuBoundWorkWithTheData(data);
    
    // Oops, not on the UI thread!
    lblStatus.Text = "Done";
}

This method starts an async operation to retrieve some data, and doesn’t resume on the UI thread, because it has some work to do in the background. When it’s done, it tries to update the UI, but since it’s not on the UI thread, it fails. This is a well known issue, and there are several workarounds. The most obvious one is to explicitly marshall the action to the dispatcher thread:

Dispatcher.Invoke(new Action(() => lblStatus.Text = "Done"));

But it’s not very elegant and readable. A better way to do it is simply to extract the part of the method that does the actual work to another method:

public async void btnStart_Click(object sender, RoutedEventArgs e)
{
    lblStatus.Text = "Working...";
    await DoSomeWorkAsync();
    lblStatus.Text = "Done";
}

private async Task DoSomeWorkAsync()
{
    // non blocking call
    var data = await GetDataFromRemoteServerAsync().ConfigureAwait(false);
    // blocking call, but runs on a worker thread
    DoSomeCpuBoundWorkWithTheData(data);
}

It takes advantage of the normal behavior of await, which is to resume on the captured sync context if it was available.

However, there might be some cases where it’s not practical to split the method like this. Or perhaps you want to switch to the UI thread in a method that didn’t start on the UI thread. Of course, you can use Dispatcher.Invoke, but it doesn’t look very nice with all those lambda expressions. What would be nice would be to be able to write something like this:

await syncContext;

Well, it’s actually pretty simple to do: we just need to create a custom awaiter. The async/await feature is pattern-based; for something to be “awaitable”, it must:

  • have a GetAwaiter() method (which can be an extension method), which returns an object that:
    • implements the INotifyCompletion interface
    • has an IsCompleted boolean property
    • has a GetResult() method that synchronously returns the result (or void if there is no result)

So, we need to create an awaiter that captures a synchronization context, and causes the awaiting method to resume on this synchronization context. Here’s how it looks like:

public struct SynchronizationContextAwaiter : INotifyCompletion
{
    private static readonly SendOrPostCallback _postCallback = state => ((Action)state)();

    private readonly SynchronizationContext _context;
    public SynchronizationContextAwaiter(SynchronizationContext context)
    {
        _context = context;
    }

    public bool IsCompleted => _context == SynchronizationContext.Current;

    public void OnCompleted(Action continuation) => _context.Post(_postCallback, continuation);

    public void GetResult() { }
}
  • The constructor takes the synchronization context that the continuation needs to resume on.
  • The IsCompleted property returns true only if we’re already on this synchronization context.
  • OnCompleted is called only if IsCompleted was false. It accepts a “continuation”, i.e. that code that must be executed when the operation completes. In an async method, the continuation is just the code that is after the awaited call. Since we want that continuation to run on the UI thread, we just post it to the sync context.
  • GetResult() doesn’t need to do anything; it will just be called as part of the continuation.

Now that we have this awaiter, we just need to create a GetAwaiter extension method for the synchronization context that returns this awaiter:

public static SynchronizationContextAwaiter GetAwaiter(this SynchronizationContext context)
{
    return new SynchronizationContextAwaiter(context);
}

And we’re done!

The original method can now be rewritten like this:

public async void btnStart_Click(object sender, RoutedEventArgs e)
{
    var syncContext = SynchronizationContext.Current;
    lblStatus.Text = "Working...";
    
    // non blocking call
    var data = await GetDataFromRemoteServerAsync().ConfigureAwait(false);
    // blocking call, but runs on a worker thread
    DoSomeCpuBoundWorkWithTheData(data);
    
    // switch back to the UI thread
    await syncContext;
    lblStatus.Text = "Done";
}

[WPF] Prevent the user from pasting an image in a RichTextBox

Very poorPoorAverageGoodExcellent (No Ratings Yet) 
Loading...

WPF’s RichTextBox control is quite powerful, and very handy if you need to accept rich text input. However, one of its features can become an issue: the user can paste an image. Depending on what you intend to do with the text entered by the user, you might not want that.

When I googled for a way to prevent that, the only solutions I found suggested to intercept the Ctrl-V keystroke, and swallow the event if the clipboard contains an image. There are several issues with this approach:

  • it doesn’t prevent the user from pasting using the context menu
  • it won’t work if the command’s shortcut has been changed
  • it doesn’t prevent the user from inserting an image using drag and drop

Since I wasn’t satisfied with this solution, I used the .NET Framework Reference Source website to look for a way to intercept the paste operation itself. I followed the code from the ApplicationCommands.Paste property, and eventually found the DataObject.Pasting attached event. It’s not a place where I had thought to look, but when you think about it, it actually makes sense. This event can be used to intercept a paste or drag and drop operation, and lets the hander do a few things:

  • cancel the operation completely
  • change which data format will be pasted from the clipboard
  • replace the DataObject used in the paste operation

In my case, I just wanted to prevent an image from being pasted or drag and dropped, so I just cancelled the operation when the FormatToApply was "Bitmap", as shown below.

XAML:

<RichTextBox DataObject.Pasting="RichTextBox1_Pasting" ... />

Code-behind:

private void RichTextBox1_Pasting(object sender, DataObjectPastingEventArgs e)
{
    if (e.FormatToApply == "Bitmap")
    {
        e.CancelCommand();
    }
}

Of course, it’s also possible to handle this in a smarter way. For instance, if the DataObject contains several formats, we could create a new DataObject with only the acceptable formats. This way the user is still able to paste something, if not the image.

Posted in WPF. Tags: , , , , . 2 Comments »

C# Puzzle 2

Very poorPoorAverageGoodExcellent (No Ratings Yet) 
Loading...

Just another little puzzle based on an issue I had at work…

Consider this piece of code :

Console.WriteLine($"x > y is {x > y}");
Console.WriteLine($"!(x <= y) is {!(x <= y)}");

How would you declare and initialize x and y for the program to produce the following, apparently illogical, output?

x > y is False
!(x <= y) is True
Posted in Puzzles. Tags: , . 2 Comments »

How to retrieve dates as UTC in SQLite

Very poorPoorAverageGoodExcellent (No Ratings Yet) 
Loading...

SQLite is a nice in-process database engine: it’s very lightweight, doesn’t require any server or configuration, and runs on all platforms. There is even an official ADO.NET provider that’s very well made. However, if you store dates as UTC with this provider, you will probably encounter a serious issue: even though the date is properly stored as UTC (it’s stored in a form similar to ISO8601, with a ‘Z’ to indicate the UTC timezone), when you read it back from the database, you will get a DateTime converted to local time, with Kind = Unspecified. Here’s an example that exhibits the problem (using Dapper in LINQPad):

void Main()
{
    string connectionString = @"Data Source=D:\tmp\testSQLiteDate.db";
    using (var connection = new SQLiteConnection(connectionString))
    {
        connection.Open();
        connection.Execute("create table Foo(Id integer not null primary key, CreationDateUtc datetime not null)");
        
        var foo = new Foo{Id = 42, CreationDateUtc = DateTime.UtcNow};
        foo.Dump("Original object");
        connection.Execute("insert into Foo(Id, CreationDateUtc) values (@Id, @CreationDateUtc)", foo);
        var foo2 = connection.Query<Foo>("select * from Foo where Id = @Id", new{ Id = 42 }).SingleOrDefault();
        foo2.Dump("After reading from DB");
    }
}

class Foo
{
    public int Id { get; set; }
    public DateTime CreationDateUtc { get; set; }
    public DateTimeKind Kind { get { return CreationDateUtc.Kind; } }
}

Here’s the output:

image

As you can see, after reading it from the database, the date is no longer in UTC, and doesn’t even contain an indication that it’s a local date. This can cause all kinds of bugs if your code is comparing dates that are supposed to be UTC.

I initially tried to fix that in my code by manually converting the date, before I realized that the solution was much simpler (although not very well documented): there is a connection string setting to control how dates are handled. You just need to specify DateTimeKind=Utc in your connection string:

string connectionString = @"Data Source=D:\tmp\testSQLiteDate.db;DateTimeKind=Utc";

If you’re using SqliteConnectionStringBuilder to build the connection string, just set the DateTimeKind property to DateTimeKind.Utc.

As you can see, the date kind is now preserved:

image

 

Important caveat: this setting will apply to all dates read from this connection. If you have dates that were not stored as UTC, the provider will assume that they are UTC dates anyway, which will produce incorrect results. So, only do this if you store all dates as UTC.

Create an auto-mocking container with Unity and FakeItEasy

Very poorPoorAverageGoodExcellent (No Ratings Yet) 
Loading...

Unit testing can be tedious sometimes, especially when testing classes that have complex dependencies. Fortunately, some tools make it somewhat easier. I’ve been using FakeItEasy a lot recently; it’s a very easy to use mocking framework for .NET. It has a very lean and simple API based on generics and lambda expressions, and is a real pleasure to work with. It came as a breath of fresh air compared to the old RhinoMocks I had been using before.

But as nice as FakeItEasy is, the process of registering all the fake dependencies for the class you are testing is still a bit tedious. Wouldn’t it be nice if the IoC container could automatically create the fakes on demand ? So this code:

var container = new UnityContainer();

// Setup dependencies
var fooProvider = A.Fake<IFooProvider>();
container.RegisterInstance(fooProvider);
var barService = A.Fake<IBarService>();
container.RegisterInstance(barService);
var bazManager = A.Fake<IBazManager>();
container.RegisterInstance(bazManager);

var sut = container.Resolve<SystemUnderTest>();

Could be reduced to this:

var container = new UnityContainer();

// This will cause the container to provide fakes for all dependencies
container.AddNewExtension<AutoFakeExtension>();

var sut = container.Resolve<SystemUnderTest>();

Well, it’s actually pretty easy to do with Unity. Unity is usually not considered the “cool kid” in the small world of IoC containers, but it’s well supported, easy to use, and extensible. I came up with the following extension to enable the above scenario:

public class AutoFakeExtension : UnityContainerExtension
{
    protected override void Initialize()
    {
        Context.Strategies.AddNew<AutoFakeBuilderStrategy>(UnityBuildStage.PreCreation);
    }
    
    private class AutoFakeBuilderStrategy : BuilderStrategy
    {
        private static readonly MethodInfo _fakeGenericDefinition;
    
        static AutoFakeBuilderStrategy()
        {
            _fakeGenericDefinition = typeof(A).GetMethod("Fake", Type.EmptyTypes);
        }
        
        public override void PreBuildUp(IBuilderContext context)
        {
            if (context.Existing == null)
            {
                var type = context.BuildKey.Type;
                if (type.IsInterface || type.IsAbstract)
                {
                    var fakeMethod = _fakeGenericDefinition.MakeGenericMethod(type);
                    var fake = fakeMethod.Invoke(null, new object[0]);
                    context.PersistentPolicies.Set<ILifetimePolicy>(new ContainerControlledLifetimeManager(), context.BuildKey);
                    context.Existing = fake;
                    context.BuildComplete = true;
                }
            }
            base.PreBuildUp(context);
        }
    }
}

A few comments on this code:

  • The logic is a bit crude (it generates fakes only for interfaces and abstract classes), but can easily be adjusted if necessary.
  • The ugly reflection hack is due to the fact that FakeItEasy doesn’t have an non-generic overload of A.Fake that accepts a Type as a parameter. Well, nobody’s perfect…
  • The lifetime is set to “container controlled”, because if you need to configure method calls, you will need to access the same instance that is injected into the system under test:
var fooProvider = container.Resolve<IFooProvider>();
A.CallTo(() => fooProvider.GetFoo(42)).Returns(new Foo { Id = 42, Name = “test” });

Note that if you register a dependency explicitly, it will take precedence and no fake will be created. So you can use this extension and still be able to manually specify a dependency:

var container = new UnityContainer();
container.AddNewExtension<AutoFakeExtension>();
container.RegisterType<IFooProvider, TestFooProvider>();
var sut = container.Resolve<SystemUnderTest>();

Of course, this extension could easily be modified to use a different mocking framework. I guess the same principle could be applied to other IoC containers as well, as long as they have suitable extension points.

What about AutoFixture?

Before you ask: yes, I know about AutoFixture. It’s a pretty good library, and I actually tried to use it as well, with some success. The resulting code is very similar to the examples above. The main reason why I didn’t keep using it is that AutoFixture is not really an IoC container (though it does some of the things an IoC container does), and I prefer to use the same IoC mechanism in my unit tests and in the actual application. Also, I’m not very comfortable with the way it handles properties when creating an instance of the SUT. By default, it sets all public writable properties to dummy instances of their type; this is fine if those properties are used for dependency injection, but IMO it doesn’t make sense for other properties. I know I can suppress this behavior for specific properties, but I have to do it manually on a case by case basis; it doesn’t take IoC container specific attributes like [Dependency] into account. So eventually I found it easier to use my custom Unity extension.

Async and cancellation support for wait handles

Very poorPoorAverageGoodExcellent (2 votes) 
Loading...

The .NET framework comes with a number of low-level synchronization primitives. The most commonly used are collectively known as “wait handles”, and inherit the WaitHandle class: Semaphore, Mutex, AutoResetEvent and ManualResetEvent. These classes have been there since at least .NET 2.0 (1.1 for some of them), but they haven’t evolved much since they were introduced, which means they don’t support common features that were introduced later. In particular, they don’t provide support for waiting asynchronously, nor do they support cancelling the wait. Fortunately, it’s actually quite easy to add these features via extension methods.

Cancellation

Let’s start with the easiest one: cancellation. There are cases where it would be useful to pass a CancellationToken to WaitHandle.WaitOne, but none of the overloads supports it. Note that some more recent variants of the synchronization primitives, such as SemaphoreSlim and ManualResetEventSlim, do support cancellation; however, they’re not necessarily suitable for all use cases, because they’re designed for when the wait times are expected to be very short.

A CancellationToken exposes a WaitHandle, which is signaled when cancellation is requested. We can take advantage of this to implement a cancellable wait on a wait handle:

    public static bool WaitOne(this WaitHandle handle, int millisecondsTimeout, CancellationToken cancellationToken)
    {
        int n = WaitHandle.WaitAny(new[] { handle, cancellationToken.WaitHandle }, millisecondsTimeout);
        switch (n)
        {
            case WaitHandle.WaitTimeout:
                return false;
            case 0:
                return true;
            default:
                cancellationToken.ThrowIfCancellationRequested();
                return false; // never reached
        }
    }

We use WaitHandle.WaitAny to wait for either the original wait handle or the cancellation token’s wait handle to be signaled. WaitAny returns the index of the first wait handle that was signaled, or WaitHandle.WaitTimeout if a timeout occurred before any of the wait handles was signaled. So we can have 3 possible outcomes:

  • a timeout occurred: we return false (like the standard WaitOne method);
  • the original wait handle is signaled first: we return true (like the standard WaitOne method);
  • the cancellation token’s wait handle is signaled first: we throw an OperationCancelledException.

    For completeness, let’s add some overloads for common use cases:

        public static bool WaitOne(this WaitHandle handle, TimeSpan timeout, CancellationToken cancellationToken)
        {
            return handle.WaitOne((int)timeout.TotalMilliseconds, cancellationToken);
        }
        
        public static bool WaitOne(this WaitHandle handle, CancellationToken cancellationToken)
        {
            return handle.WaitOne(Timeout.Infinite, cancellationToken);
        }
    

    And that’s it, we now have a cancellable WaitOne method!

    Asynchronous wait

    Now, what about asynchronous wait? That’s a bit harder. What we want here is a WaitOneAsync method that returns a Task<bool> (and since we’re at it, we might as well include cancellation support). The typical approach to create a Task wrapper for a non-task-based asynchronous operation is to use a TaskCompletionSource<T>, so that’s what we’ll do. When the wait handle is signaled, we’ll set the task’s result to true; if a timeout occurs, we’ll set it to false; and if the cancellation token is signaled, we’ll mark the task as cancelled.

    I struggled a bit to find a way to execute a delegate when a wait handle is signaled, but I eventually found the ThreadPool.RegisterWaitForSingleObject method, which exists for this exact purpose. I’m not sure why it’s in the ThreadPool class; I think it would have made more sense to put it in the WaitHandle class, but I assume there’s a good reason.

    So here’s what we’ll do:

  • create a TaskCompletionSource<bool>;
  • register a delegate to set the result to true when the wait handle is signaled, or false if a timeout occurs, using ThreadPool.RegisterWaitForSingleObject;
  • register a delegate to mark the task as cancelled when the cancellation token is signaled, using CancellationToken.Register;
  • unregister both delegates after the task completes

    Here’s the implementation:

        public static async Task<bool> WaitOneAsync(this WaitHandle handle, int millisecondsTimeout, CancellationToken cancellationToken)
        {
            RegisteredWaitHandle registeredHandle = null;
            CancellationTokenRegistration tokenRegistration = default(CancellationTokenRegistration);
            try
            {
                var tcs = new TaskCompletionSource<bool>();
                registeredHandle = ThreadPool.RegisterWaitForSingleObject(
                    handle,
                    (state, timedOut) => ((TaskCompletionSource<bool>)state).TrySetResult(!timedOut),
                    tcs,
                    millisecondsTimeout,
                    true);
                tokenRegistration = cancellationToken.Register(
                    state => ((TaskCompletionSource<bool>)state).TrySetCanceled(),
                    tcs);
                return await tcs.Task;
            }
            finally
            {
                if (registeredHandle != null)
                    registeredHandle.Unregister(null);
                tokenRegistration.Dispose();
            }
        }
        
        public static Task<bool> WaitOneAsync(this WaitHandle handle, TimeSpan timeout, CancellationToken cancellationToken)
        {
            return handle.WaitOneAsync((int)timeout.TotalMilliseconds, cancellationToken);
        }
        
        public static Task<bool> WaitOneAsync(this WaitHandle handle, CancellationToken cancellationToken)
        {
            return handle.WaitOneAsync(Timeout.Infinite, cancellationToken);
        }
    

    Note that the lambda expressions could have used the tcs variable directly; this would make the code more readable, but it would cause a closure to be created, so as a small performance optimization, tcs is passed as the state parameter.

    We can now use the WaitOneAsync method like this:

    var mre = new ManualResetEvent(false);
    …
    if (await mre.WaitOneAsync(2000, cancellationToken))
    {
        …
    }
    

    Important note: this method will not work for a Mutex, because it relies on RegisterWaitForSingleObject, which is documented to work only on wait handles other than Mutex.

    Conclusion

    We saw that with just a few extension methods, we made the standard synchronization primitives much more usable in typical modern code involving asynchrony and cancellation. However, I can hardly finish this post without mentioning Stephen Cleary’s AsyncEx library; it’s a rich toolbox which offers async-friendly versions of most standard primitives, some of which will let you achieve the same result as the code above. I encourage you to have a look at it, there’s plenty of good stuff in it.

  • Posted in Code sample. Tags: , , . 6 Comments »

    C# Puzzle 1

    Very poorPoorAverageGoodExcellent (8 votes) 
    Loading...

    I love to solve C# puzzles; I think it’s a great way to gain a deep understanding of the language. And besides, it’s fun!

    I just came up with this one:

    static void Test(out int x, out int y)
    {
        x = 42;
        y = 123;
        Console.WriteLine (x == y);
    }
    

    What do you think this code prints? Can you be sure? Post your answer in the comments!

    I’ll try to post more puzzles in the future if I can come up with others.

    Posted in Puzzles. Tags: , . 12 Comments »
    css.php