Thursday, March 31, 2016

xUnit.net: Extensions Config v3.3.0

I recently made several updates to the xunit.extensions.config library, which allows you to configure theory data from your app.config file. Here are the links to the source and the NuGet package:

New Features

  • Named Parameter Support

You no longer need to configure your data by parameter index. You can now name your data for each parameter, making the configuration much easier to read and understand.

  • AppSettings Support

You can now use the standard AppSettings section of the App.config to configure your data. If no settings are found, then the framework will fallback to trying to use the standard config section.

  • Default Namespace Option

You can now provide a default namespace for your tests. This reduced the amount of redundant text in your config file, and makes test names much more concise and easy to read.

  • Extensible Data Provider

Don't want to use the existing data providers? Would you rather use a database? Now you can! Just add an AppSettings key for "TestData.ServiceFactory" that provides the fully qualified name of a static method that returns an IConfigTestDataService, and the framework will try to use that to load configuration data.

Wednesday, March 30, 2016

Why method that return a Task should end with Async

I have spoken before about using the Fleck WebSocket server library for .NET, but recently I experienced a small problem with it. Pull request #126 changed several public methods to become async and return a Task instead of void.

This did not follow the recommended naming convention of naming all async methods with the Async suffix.

In my case, this caused us to introduce a bug to a project that was using Fleck. We would ignore Task returned from IWebSocketConnection.Send, and under high load the task scheduler would get backed up.

Even though I do not think that they are going to use it, I created a pull request that updated the the public methods to include the Async suffix. Also, in order to maintain backwards compatibility, I also added obsolete methods to the interfaces without the suffix.

What did I do with the tasks? Rather than write in parallel, I used a concurrent queue and had a background task serially write messages to the connection.

Enjoy,
Tom

Friday, March 18, 2016

How to Release a Semaphore with a Using Block

I love that .NET has so many useful utilities available in the base framework. I often use the SemaphoreSlim, and I love that it supports async await. However, I don't like always having to create a try finally block around every use call to ensure that the release method gets called.

Below is a simple little extension method that will allow you to place the result of the Semaphore wait into a using block, thus ensuring that the dispose will always release the lock.

SemaphoreSlim Extensions

public static class SemaphoreSlimExtensions
{
    public static async Task<IDisposable> UseWaitAsync(
        this SemaphoreSlim semaphore, 
        CancellationToken cancelToken = default(CancellationToken))
    {
        await semaphore.WaitAsync(cancelToken).ConfigureAwait(false);
        return new ReleaseWrapper(semaphore);
    }
 
    private class ReleaseWrapper : IDisposable
    {
        private readonly SemaphoreSlim _semaphore;
 
        private bool _isDisposed;
 
        public ReleaseWrapper(SemaphoreSlim semaphore)
        {
            _semaphore = semaphore;
        }
 
        public void Dispose()
        {
            if (_isDisposed)
                return;
 
            _semaphore.Release();
            _isDisposed = true;
        }
    }
}

Saturday, February 27, 2016

Podcast - What should all software developers want in their applications?

Each week, my good friend Zach Mayer and I answer geek culture's most superfluous questions on the QQ-Cast. This past week we turned to the subject of software development, and did a retrospective on my series of blog posts, Three Things that all Applications MUST Have.

QQ Cast - Quest 40 - What should all software developers want in their applications?

  • 00:00 - Mic Check and Introductions
  • 03:55 - Why isn't your application logging?
  • 06:15 - Where is your configuration coming from?
  • 11:00 - Can we talk about Unit Tests for 18 minutes?
  • 29:00 - Is continuous integration necessary?
  • 30:30 - Does automated deployment speed up development?
  • 38:00 - When should you use inversion of control?
  • 49:30 - How intrusive is error reporting for end users?
  • 59:00 - Do you remove user impersonation from production builds?
  • 63:30 - Why is continuous deployment so controversial?
  • 72:15 - Wrap up!

Enjoy,
Tom

Sunday, February 21, 2016

Async Cache Repository v2

Three years ago (wow, time flies) I wrote a generic Cache Repository that has become one of my more popular open source projects. It is 2016, so was definitely time to create an async version of that cache repository! This new implementation has all of the same features as the original, only now it is completely async from top to bottom.

CacheRepository.Web

Features

  • Thread Safe GetOrSet
  • Configurable Expiration Enums
  • Transparent Cache Key Management By Type
  • A Web Implementation

NuGet Package and Source

Enjoy,
Tom

Monday, February 15, 2016

How To: Kill child process when parent process is killed v2

Working with unmanaged memory is not my forte. Thus I am very appreciative of when someone not only reads my blog, but then takes the time to do their own research and leave comments and suggest updates. TLDR: Thank you, Steven Pereyda!

Last year I blogged about how to kill a child process when the parent process is killed. The solution involves using the operating system by invoking Kenral32. However, as mentioned above, there was a small memory leak and a few other optimizations that we should have made; so let's take a look at how to fix those!

Fixes and Optimizations in v2

1. There was a small memory leak.

In the job constructor we used Marshal.AllocHGlobal to create an unmanaged copy of the JobObjectExtendedLimitInformation object, but we never freed that memory. The new constructor how has a finally block that ensures we invoke Marshal.FreeHGlobal.

2. We should use SafeHandles.

.NET has a SafeHandle class that can be used as a wrapper around unmanaged handles, which can help you prevent memory leaks; and I learned how to use this by reading a code project article by the always awesome Stephen Cleary. Please note that in v2 there is a now a JobObjectHandle class that extends SafeHandle, and we use this instead of storing the IntPtr ourselves.

3. We moved the GC.SuppressFinalize into the public dispose method.

Yes, this is the right way to do it. So why didn't I do it that way the first time? Because ReSharper was warning me that I wasn't using the isDisposing param...and hate warnings!

4. Follow the best practices of hosting all external calls in a single Native Methods class.

Microsoft recommends that you keep all of your external calls in one NativeMethods class, and then decorate that class with attributes to avoid security warnings. Sounds like a good idea to me.

Friday, January 22, 2016

C# Interfaces and Default Parameters

How does a default parameter work?

One of the things that I love about C# is how so many of it's features are just very conveniently designed compiler tricks. This means that, just like any other magic trick, once you know how the trick is performed you immediately realize that there is nothing magical about it all!

So, let's talk about default parameters. They are actually just constant values that get compiled into your code when you go to use a method that has them. Let's look at an example...

public class DefaultParamTests1
{
    [Fact]
    public void WhatYouWrite()
    {
        var actual = Double();
        Assert.Equal(2, actual);
    }
 
    private static int Double(int i = 1)
    {
        return i * 2;
    }
}
 
public class DefaultParamTests2
{
    [Fact]
    public void WhatItCompilesTo()
    {
        var actual = Double(1);
        Assert.Equal(2, actual);
    }
 
    private static int Double(int i)
    {
        return i * 2;
    }
}

What happens when interfaces and methods don't match?

So, now that you know how the trick is performed, what happens if you use a different default value for a parameter defined by an interface and a class?

The answer is simple: if your object is cast as the class, then it will use the class value. If your object is cast as the interface, it will use the interface value instead. Let's take a look at another example...

Real Time Web Analytics