Monday, August 11, 2014

Getting started with Powershell Desired State Configuration (DSC)

I wanted to try out the DSC in Powershell 4.0 on my Windows 8.1 Pro machine, but I got stuck on the ‘getting started’ part. I just couldn’t figure out how to generate the actual configuration files (.mof-files).

I google around quite a bit before I finally got it; the configuration file that you create is off course just like a normal script file in the sense that it doesn’t actually do anything. All it does is to define a function that you need to call!

So in order to actually generate the .mof-files, I ‘dot-sourced’ the script into the current session and called the function from the ps1-file.

Here’s an example configuration file called ‘demoConfig.ps1’:

configuration Demo
{
Node localhost
{
File TestFiles
{
SourcePath = "c:\temp\test.txt"
DestinationPath = "c:\temp\testdir"
Ensure = "Present"
Type = "File"
}
}
}

And to generate the .mof files:

PS C:\temp> . .\demoConfig.ps1
PS C:\temp> Demo

Tuesday, June 25, 2013

T-SQL joins

What's the difference between an inner and full join in T-SQL? Or a right versus left join? I never have this at the top of my head when I need it, so for future references I've assembled a little example that shows the resulting difference between them.

Given the following t-sql:

declare @t1 table (id int)
declare @t2 table (id int)
 
insert into @t1 values(1),(2),(3)
insert into @t2 values(3),(4)
 
select 't1' as 'Table name', * from @t1
select 't2' as 'Table name', * from @t2
 
select 'inner join' as 'Join', t1.id as 'Left', t2.id as 'Right'
from @t1 as t1 inner join @t2 as t2 on t1.id = t2.id
 
select 'left join' as 'Join', t1.id as 'Left', t2.id as 'Right'
from @t1 as t1 left join @t2 as t2 on t1.id = t2.id
 
select 'right join' as 'Join', t1.id as 'Left', t2.id as 'Right'
from @t1 as t1 right join @t2 as t2 on t1.id = t2.id
 
select 'full join' as 'Join', t1.id as 'Left', t2.id as 'Right'
from @t1 as t1 full join @t2 as t2 on t1.id = t2.id

 

This is the result from the joins:

image

Wednesday, November 28, 2012

Unit testing asynchronous operations with the Task Parallel Library (TPL)

Unit testing asynchronous operations has never been easy in C#. The most common methods (or at least the methods I usually end up with) is either;

  1. Write a synchronous version of the method to test, unit test this one and then call the synchronous method from another method that runs it asynchronous in the production code.
  2. Raise an event in the production code when the asynchronous operation has finished, subscribe to the event in the unit test, and use the ManualResetEvent to wait for the event before making any assertions.

Neither is a good solution.

Writing a synchronous version and let the production code call it is probably the easiest one, but breaks down once you need to do more than just call the synchronous method in production (e.g. orchestrating several dependent asynchronous operations, or have some logic run when the asynchronous operation(s) completes). And the worst part of it; a vital part of the production code will be untested.

The ManualResetEvent is better, but it takes a lot more code, makes the unit tests harder to read and you need to fire events in the prod code that possibly only unit tests are interested in. And unit tests dependent on ManualResetEvent tends to be fragile when run in parallel.

But with the Task Parallel Library (TPL) the table has turned; TPL makes unit testing asynchronous code a lot easier. That is; it’s easy if you now how to do it.

Running some code asynchronously without any concerns for testability is pretty straight forward with TPL:

Task.Factory.StartNew(MyLongRunningJob);
And in fact; it’s not much harder to make it test-friendly. You only need a bit insight into what’s going in the Task Factory. And to have it straight from the horse’s mouth; here’s what MSDN says about it:

Behind the scenes, tasks are queued to the ThreadPool, which has been enhanced with algorithms (like hill-climbing) that determine and adjust to the number of threads that maximizes throughput. This makes tasks relatively lightweight, and you can create many of them to enable fine-grained parallelism. To complement this, widely-known work-stealing algorithms are employed to provide load-balancing.


The Task Factory will use a Task Scheduler to queue the tasks and the default scheduler is the ThreadPoolTaskScheduler, which will run the tasks on available threads in the thread pool.


The trick when unit testing TPL code is to not have those tasks running on threads that we have no control over, but to run them on the same thread as the unit test itself. The way we do that is to replace the default scheduler with a scheduler that runs the code synchronously. Enter the CurrentThreadTaskScheduler;


public class CurrentThreadTaskScheduler : TaskScheduler
{
protected override void QueueTask(Task task)
{
TryExecuteTask(task);
}

protected override bool TryExecuteTaskInline(
Task task,
bool taskWasPreviouslyQueued)
{
return TryExecuteTask(task);
}

protected override IEnumerable<Task> GetScheduledTasks()
{
return Enumerable.Empty<Task>();
}

public override int MaximumConcurrencyLevel { get { return 1; } }
}

TaskScheduler is an abstract class that all schedulers must inherit from and it only contains 3 methods that needs to be implemented;



  1. void QueueTask(Task)
  2. bool TryExecuteTaskInline(Task, bool)
  3. IEnumerable<Task> GetScheduledTasks()

In the more advanced schedulers like the ThreadPoolTaskScheduler, this is where the heavy-lifting of getting tasks to run on different threads in a thread-safe manner happens. But for running tasks synchronously, we really don’t need that. In fact, that’s exactly what we don’t need. So instead of scheduling tasks to run on different threads, the TryExecuteTaskInline method will just execute them immediately on the current thread.


Now it’s time to actually use it in the production code;


public TaskScheduler TaskScheduler
{
get
{
return _taskScheduler
?? (_taskScheduler = TaskScheduler.Default);
}
set { _taskScheduler = value; }
}
private TaskScheduler _taskScheduler;

public Task AddAsync(int augend, int addend)
{
return new TaskFactory(this.TaskScheduler)
.StartNew(() => Add(augend, addend));
}

To be able to inject a different TaskScheduler from unit tests, I’ve made the dependency settable through a public property on the class I’ll be testing. If no TaskScheduler has been explicitly set (which it won’t be when executed ‘in the wild’), the default TaskScheduler will be used.


The method Task AddAsync(int, int) is the method we would like to unit test. As you can see it’s a highly CPU intensive computation that will add 2 numbers together. Just the kind of work you’d want to surround with all the ceremony and overhead of running asynchronously.


The important part here is the instantiation of the TaskFactory that will take the TaskScheduler as a constructor parameter.


With that in place we can set the TaskScheduler from the unit tests:


[Test]
public void It_should_add_numbers_async()
{
var calc = new Calculator
{
TaskScheduler = new CurrentThreadTaskScheduler()
};

calc.AddAsync(1, 1);

calc.GetLastSum().Should().Be(2);
}

The System Under Test, SUT, is the Calculator-class that has the AddAsync-method we’d like to unit test. Before calling the AddAsync-method we set the CurrentThreadTaskScheduler that the TaskFactory in the Calculator should use.


Since AddAsync doesn’t return the result of the calculation, I’ve added a method to get the last sum. Not exactly production-polished code, but it’ll do for the purpose of this example.


Anyway; the end result is that the test pass. And if I don’t assign the CurrentThreadTaskScheduler to Calculator.TaskScheduler – that is it runs with the default ThreadPoolTaskScheduler – it will fail, because the addition will not be finished before the assertion.


But don’t trust me on this. I’ve uploaded the complete (absurd) example to GitHub, so you can run the tests and see for yourself; https://github.com/bulldetektor/TplSpike.


References


You can read the MSDN-article that I quoted from here; http://msdn.microsoft.com/en-us/library/dd537609.aspx


I found the code for the CurrentThreadTaskScheduler in the TPL samples here; http://code.msdn.microsoft.com/windowsdesktop/Samples-for-Parallel-b4b76364. The samples contains a dozen or so TaskSchedulers, for instance;



  • QueuedTaskScheduler - provides control over priorities, fairness, and the underlying threads utilized
  • OrderedTaskScheduler - ensures only one task is executing at a time, and that tasks execute in the order that they were queued.
  • ReprioritizableTaskScheduler - supports reprioritizing previously queued tasks
  • RoundRobinTaskSchedulerQueue - participates in scheduling that support round-robin scheduling for fairness
  • IOCompletionPortTaskScheduler - uses an I/O completion port for concurrency control
  • IOTaskScheduler - targets the I/O ThreadPool
  • LimitedConcurrencyLevelTaskScheduler - ensures a maximum concurrency level while running on top of the ThreadPool
  • StaTaskScheduler - uses STA threads
  • ThreadPerTaskScheduler - dedicates a thread per task
  • WorkStealingTaskScheduler - a work-stealing scheduler, not much more to say about that