Wrapping the Legend in SciChart

I’ve been using SciChart as a real-time graphing control. There’s documentation on the website about how to make the legend wrap when it’s too long but it’s not clear. It seems you can’t do it with LegendModifier alone and while you can do it with SciChartLegend they don’t make it clear where the control is supposed to go.

Anyway, this is what works:

        <ControlTemplate TargetType="s:LegendPlaceholder">
            LegendData="{Binding LegendData, ElementName=LegendModifier}" 
                <WrapPanel Orientation="{Binding Orientation, RelativeSource={RelativeSource AncestorType=s:SciChartLegend}}" />

Setting up a TFS 2017 Build Server’s Account

We have an on-premises TFS 2017 server with the package management plugin installed to host custom NuGet packages.

I happily set up TFS builds of my solution. I happily set up custom NuGet packages. Then I ran a build of a solution that made use of my custom packages. Imagine my surprise when the TFS build server was unable to download packages from its own TFS server! Furthermore, the error code was the rarely-seen “402 Payment Required”.

Now, it turns out that Package Management generally requires licenses. This hadn’t mattered because it’s free for Visual Studio Enterprise subscribers, which we all have through MSDN. The build server, however runs under its own service account which naturally doesn’t have an MSDN subscription.

How to have the build server run as a user with an MSDN subscription? After a support call, a guy from Microsoft helped me figure it out. Here it is for everybody with the same problem (and, for me, when the solution below expires in a year).

The solution

Basically, the solution is to get the build server to run under the Personal Access Token (PAT) of a user with an MSDN license.

Step 1. Generate a Personal Access Token

If you log into TFS 2017, in the corner under the settings there’s an “Access Tokens” setting.

Click “Add”.

Create a token. I made mine for a year, ensuring I would forget all this by the time it expires and that a year from now I’ll be confounded when all my builds break.

The personal access token will be a long string. Save it somewhere temporarily.

Step 2. Configure the build agent to use the PAT

If you already have the build agent set up, you’re going to have to remove it. Go to the folder and run:

.\config.cmd remove

It’s safest to delete the whole folder and recreate it from the Agent you downloaded from TFS. Until I removed the folder entirely this fix failed.

Once you’ve recreated the server, type


from PowerShell to start the process again.

This time, when it gets to “Enter authentication type (press enter for Integrated)” enter “PAT”.
It will ask you for the token. Enter the long string you got above.
Continue as normal.

Other Gotchas

The server will download NuGet packages with the license you’ve set up above but with the authorization of the user that the server is running as. If you find you’ve traded “Payment Required” for “Unauthorized”, make sure the build agent user has access as a package reader in Package Management’s Security settings.

Akka.NET and Unity IoC

Even though Akka.NET supposedly supports dependency injection through its DI libraries (e.g. Akka.DI.Unity), it’s not very good. In the documentation you’ll see examples like:


That Props call doesn’t take any arguments so there’s no way to actually inject parameters into the call. Let’s say we have this actor:

public class MyActor : ReceiveActor {
  public MyActor( string a, IFoo b, IBar c ) {
    // ...

Further say we want to specify a but let Unity resolve IFoo and IBar from configuration. If we were just creating the object normally we would write:

var myActor = UnityContainer.Resolve<MyActor>( 
  new ParameterOverride( "a", "ABC" ) 

But that’s not how we create actors. We create actors using ActorOf and specify Props. We do this so that Akka.Net can recreate the actors if they fail.

If we were to create the actor normally without dependency injection we would write something like:

var myActorRef = actorRefFactory.ActorOf( 
  Props.Create( () => new MyActor( "ABC", ??, ?? ) 

If we do that, we aren’t getting our interfaces from Unity.

So let’s try dependency injection. If we were to use Akka.DI.Unity we would have:

var myActorRef = actorRefFactory.ActorOf(

But then there’s no way to specify our parameter.
We’re stuck. We can specify all parameters or none but can’t specify some and let unity take care of the others like we usually want.

Here’s a way you can do it that doesn’t involve the Akka.DI libraries:


It turns out that Props is not the only way to create an actor. If you dive into the source code, you can see that there’s a IIndirectActorProducer class that will create an actor without Props by implementing a Produce method.
Here’s an implementation that takes a IUnityContainer and the ResolverOverrides in its constructor and uses them to create the actor when called:

    /// <summary>
    /// A <see cref="IIndirectActorProducer" /> that uses a <see cref="IUnityContainer" /> to resolve instances.
    /// </summary>
    /// <remarks>
    /// This is only used directly by the <see cref="UnityActorRefFactory"/>
    /// </remarks>
    /// <typeparam name="TActor"></typeparam>
    internal sealed class UnityActorProducer<TActor> : IIndirectActorProducer where TActor : ActorBase {

        /// <summary>
        /// The resolver overrides.
        /// </summary>
        private readonly ResolverOverride[] _resolverOverrides;
        /// <summary>
        /// The unity container.
        /// </summary>
        private readonly IUnityContainer _unityContainer;

        /// <summary>
        /// The constructor.
        /// </summary>
        /// <param name="unityContainer">The unity container.</param>
        /// <param name="resolverOverrides">The resolver overrides.</param>
        public UnityActorProducer( IUnityContainer unityContainer, params ResolverOverride[] resolverOverrides ) {
            this._unityContainer = unityContainer.CreateChildContainer();
            this._resolverOverrides = resolverOverrides;

        /// <summary>
        /// See <see cref="IIndirectActorProducer.ActorType"/>
        /// </summary>
        public Type ActorType => typeof( TActor );

        /// <summary>
        /// See <see cref="IIndirectActorProducer.Produce" />
        /// </summary>
        /// <returns></returns>
        public ActorBase Produce() {
            // Create the actor using our overrides
            return this._unityContainer.Resolve<TActor>( this._resolverOverrides );

        /// <summary>
        /// SEe <see cref="IIndirectActorProducer.Release" />
        /// </summary>
        /// <param name="actor"></param>
        public void Release( ActorBase actor ) {
            // Do nothing


We can create Props using the producer like this:

        /// <summary>
        /// Creates <see cref="Akka.Actor.Props" /> using the <see cref="IUnityContainer" /> and any <see cref="ResolverOverride" />s provided.
        /// </summary>
        /// <typeparam name="TActor"></typeparam>
        /// <param name="unityContainer"></param>
        /// <param name="resolverOverrides"></param>
        /// <returns></returns>
        public Props Props<TActor>( IUnityContainer unityContainer, params ResolverOverride[] resolverOverrides ) where TActor : ActorBase {
            // Use a UnityActorProducer to create the object using the container and resolver overrides.
            return Akka.Actor.Props.CreateBy<UnityActorProducer<TActor>>( 

So creating our actor would look like this:

var myActorRef = Context.ActorOf(
    new ParameterOverride( "a", "ABC" ) 

It uses our resolver overrides for the first parameter and the unity configuration for our additional parameters, just as we want.

Microsoft and Xamarin, Google and Swift


A few months ago I was looking at mobile app development again and so had a look at Xamarin, a cross-platform app toolset built around .NET. It seemed interesting, but it was hugely expensive. Something like $600 per year per license. When Android Studio is free and XCode is either free or $99, it was cheaper to go native.

Microsoft Buys Xamarin

Now Microsoft has acquired Xamarin and it will be free to use. So now you can theoretically write C# code and have it build (with some additional platform-specific effort) Android and iOS (and Windows Phone, if anyone cares) apps cheaply.

Google needs a new first-class language… Swift?

With Oracle constantly trying to squeeze money out of Google for their use of Java on Android, Google very obviously needs a new first-class language for Android – one that can eventually replace Java completely. Reportedly they’re considering using Apple’s Swift. Although I’ve spent only a little time with Swift, it seems like an excellent language. Like F#, it’s a hybrid functional language with objects.

Write once… in C# or Swift?

Xamarin’s supposed advantage is that you can write in one language, C#, and compile to iOS or Android. What if Swift becomes the native language for both platforms? Someone will create libraries to cross-compile the UI elements. What need is there then for Xamarin? Swift is a more modern language. Though Xamarin theoretically supports all .NET languages and thus would support F#, we know F# is a second-class citizen. Xamarin would be solely for those .NET developers who are unable to move on to new languages. If Google does adopt Swift for Android, Xamarin will become the mobile equivalent of WebForms.

F# and Swift

I’m looking at Apple’s Swift language and it’s interesting to see how similar it is to F# (which itself is similar to Scala and Haskell). I think this is all in reaction to the trouble we’re having in general with pure object-oriented programming and the advantages of a functional (or at least hybrid) approach in the age of distributed systems.

Value declaration

This is some F# for assigning variables:

let someConstant = 10
let mutable someVariable = 1.23
let specifyTypeExplicitly : String = "blah"

and in Swift:

let someConstant = 10 
var someVariable = 1.23
var specifyTypeExplicitly : Double = "blah"

let mutable for var, otherwise the same. Types are generally inferred but can be set explicitly.

Both languages have tuples and dictionaries assigned in basically the same way.

Pattern matching

Instead of F#’s match, Swift puts its matching inside a traditional switch statement.

//let rgba = ( 1.0, 1.0, 1.0, 1.0 ) "white"
//let rgba = ( 0.4, 0.4, 0.4, 1.0 ) "gray"
//let rgba = ( 0.0, 0.6, 0.8, 1.0 ) "blue is 0.8"
let rgba = ( 0.0, 0.6, 0.8, 1.0 )
switch rgba {
case ( 1.0, 1.0, 1.0, 1.0 ):
    print( "white" )
case let ( r, g, b, 1.0) where r==g && g==b:
case (0.0, 0.5...1.0, let b, _):
    print("blue is \(b)")

In F#, this would be something like (this is from memory):

//let rgba = ( 1.0, 1.0, 1.0, 1.0 ) "white"
//let rgba = ( 0.4, 0.4, 0.4, 1.0 ) "gray"
//let rgba = ( 0.0, 0.6, 0.8, 1.0 ) "blue is 0.800000"
let rgba = ( 0.0, 0.6, 0.8, 1.0 )
match rgba with
| ( 1.0, 1.0, 1.0, 1.0 ) ->
    printfn "white"
| ( r, g, b, 1.0 ) when ( r = g ) && ( g = b ) ->
    printfn "gray"
| ( 0.0, g, b, _ ) when ( g >= 0.5 ) && ( g <= 1.0 ) ->
    printfn "blue is %f" b 
| _ -> ()

Some and None

Swift and F# both support the Some and None keywords for optional values. e.g.

var x : Int? = nil
switch x {
case .Some( let value ):
    print("x has a value")
case .None:

In F#:

let x : int option = None
match x with
| Some(value) ->
    printfn "x has a value"
| None ->
    printfn "x is nil"


In my first look at the language, currying doesn’t seem quite as nice.
Here’s some F#:

let add a b = a + b
let add2 = add 2
let result = add2 3 // 5

In Swift (in the tersest way I know how at present) :

let add : (Int,Int) -> Int = { $0 + $1 }
let add2 = { add( 2, $0 ) }
let result = add2( 3 ) // 5

Another way (according to this) is to make the add function return a function like in the example below, but then doing a call to the initial function does not look like a standard function call:

func add (a:Int)(_ b:Int)-> Int {
    return a + b
add(2)(3) // not add(2,3) // 5
let add2 = add(2)
add2(3) // 5


This is a very shallow comparison. I just thought it was interesting.

Visual Studio Code Coverage: Value does not fall within the expected range

While attempting to improve my code coverage in Visual Studio 2014, I suddenly found myself getting the error “Value does not fall within the expected range” when running unit tests with code coverage enabled. Without code coverage, the tests ran fine. With code coverage, that error would appear twice in the test output.

I googled the error for awhile and mostly came up empty. I eventually tracked down this post where a user was getting the same message but related to website profiling. It did help me track down the issue though.

The solution

I looked in the configuration manager. It turns out that while most of the projects in my solution were set to the “Any CPU” platform, I had one Wix installer project set to “x86”, presumably because it’s building an x86-compatible installer. If this project is disabled, code coverage works. If re-enabled, I get the error. For now, I’ve just been disabling the program when I want to do code coverage.

Akka.NET, Prism, Unity, and WPF

Since I’ve been reading up on Reactive Extensions, I listened with interest to the recent .NET Rocks! podcast on the subject. During the conversation, Akka.NET was mentioned.

Akka.NET is another reactive technology. It’s an implementation of the Actor model. Basically, you break down an application’s functionality into small computational units called Actors which have limited state and communicate via message passing. There are parallels in Rx’s concept of observables and observers. Akka.NET also provides the kind of supervision hierarchy that you find in erlang, which is that an actor has child actors and when those child actors fail, the parent can resume or restart the failed children. This makes the application ‘self healing’.

I watched two Pluralsight course on Akka.NET by Jason Roberts, Building Concurrent Applications with the Actor Model in Akka.NET and Building Reactive Concurrent WPF Applications with Akka.NET (subscriptions required for both links). The former gives an overview of Akka.NET and the latter applies it to an MVVM WPF application.

In the demo MVVM application, the author uses Akka.NET with Ninject dependency injection and the MVVM Light toolkit. Personally, I prefer Unity and Prism, so as an exercise for myself I created the demo using those two languages. The result is on GitHub at https://github.com/mkb137/AkkaPrismUnityDemo.

The project consists of
* Akka.DI.Unity – A copy of Akka.NET’s Akka.DI.Unity upgraded from Unity 3.5 to Unity 4.0. No code changes were required otherwise.
* AkkaPrismUnityDemo – The Prism shell project
* AkkaPrismUnityDemo.Infrastructure – The common infrastructure project (which in this simple demo only contains the region names)
* AkkaPrismUnityDemo.Modules.Stocks – The main module containing the demo code.

A screenshot of the result is shown at the top of this post. In it, the view model creates actors which then have knowledge of the view model that created them and will call methods on the view model when messages are received and processed.

Here a view model creates an actor and passes it a reference to itself:

this.StockToggleButtonActorRef = 
        Props.Create( () => new StockToggleButtonActor( 

Here the actor makes a callback to the view model:

this.Receive<ToggleStockMessage>( message => {
    this._stocksCoordinatorActorRef.Tell( new WatchStockMessage( this._stockSymbol ) );
    this.Become( this.ToggledOn );
} );

Like Rx and its Observables/Observers, messages are handled on the thread pool so actors will make full use of the processors available on the machine with no extra effort from the developer.

It’s an interesting technology. Compared to Rx, Akka is missing some of Rx’s advanced publish/subscribe methods like the ability to buffer or throttle messages. It does have a Sample equivalent via the scheduler’s ScheduleTellRepeatedly method. On the plus side, it provides the supervision hierarchy and provides a more natural message pipeline. With Rx it seems like having an object that is both observer and observable (i.e. is part of a pipeline), while supported, is somehow discouraged.

Book recommendation: Seven Languages in Seven Weeks

I haven’t posted anything in a while (I’m intermittently working on converting the Replicon Add-In to F#), so I’ll throw up this book recommendation for Seven Languages in Seven Weeks by Bruce Tate.

The languages are:
1. Ruby – A well known and interesting object-oriented scripting language.
2. Io – A language based on prototyping.
3. Prolog – A logic-based language. I saw this one back in university.
4. Scala – A hybrid O-O/functional language.
5. Erlang – The functional language made in the 80s for telephone switches that is the hot new thing because of how well it handles concurrency and load, a problem we face in all modern web applications.
6. Clojure – A lisp implementation on Java
7. Haskell – A purely functional language.

And if you aren’t already using it, I recommend using Chocolatey, the apt-get style package manager for Windows, to download these programming languages to play around with. Using Chocolatey is a whole lot easier than hunting down all the installers you’d need otherwise.

Reactive Extensions

In my last few posts I’ve talked about learning F#, the .NET functional programming language. I like it, but I can’t use it in a production environment for a couple of reasons:
1. Part of the project is WPF and, as I mentioned in a previous post, the WPF support isn’t there.
2. It wouldn’t be maintainable. There wouldn’t be enough people in my organization prepared to learn F# in order to support it.


I eventually came across Reactive Extensions, also called Rx. A good learning resource is www.introtorx.com. Although new to me, it’s been around for a few years. It’s a library that implements an Observer/Subscriber pattern. Observables emit data and Observers consume it via Subscribe methods. It’s like an event model but adds:

  • Advanced event consumption, e.g.
    • Sampling (fetching data each time period)
    • Buffering (accumulating data and responding only after some time period)
    • Throttling (fetching data only after some quiet period has elapsed)
    • Filtering (consuming only events that match some pattern)
  • Threading, e.g. observing and subscribing on multiple threads or on specified threads

Supposedly some of the threading functionality has been superseded by Tasks and async/await, but I like that Rx is more distributed while Tasks are still procedural.

Reactive also adds some functional sequence methods like Scan and its event filtering is like the pattern matching found in functional conditionals. It’s also functional in the sense that your observer is getting input and (presumably) producing output, like a function, though unlike a proper function an observer can have state.

Creating Observables

Creating an observer is easy. IObserver has three methods, OnNext, OnCompleted, and OnError. Simply implement the interface and handle the data in OnNext. Creating an observable yourself is a bit more tricky.


One way is to create an observable out of a plain old .NET event.
Let’s say you have some event:

    public event EventHandler<DateTime> MyEvent;

You can create an observable like this:

    IObservable<DateTime> eventObservable = Observable.FromEventPattern<EventHandler<DateTime>,DateTime>(
        handler => m.MyEvent += handler,
        handler => m.MyEvent -= handler
        ).Select( eventPattern => eventPattern.EventArgs );

Observable Collections

The ReactiveUI library (search for reactiveui in NuGet) adds a ReactiveList with observable events built in. This shows how you’d listen to when items are added:

    ReactiveList<String> list = new ReactiveList<string>();
    list.ItemsAdded.Subscribe( s => Console.WriteLine( "Added {0}", s ) );

Note: You have to subscribe to one of the list’s events like ItemsAdded or ItemsRemoved. You can subscribe to the list itself, but I don’t know what events it produces.

Note also: The NuGet package is out of date as of the time of writing this post. If you just install it from NuGet you’ll get the error:

Warning 1 Reference to type ‘Splat.IEnableLogger’ claims it is defined in ‘[…]\packages\Splat.1.0.0\lib\Net45\Splat.dll’, but it could not be found c:\Projects\ReactiveDemo\packages\reactiveui-core.6.5.0\lib\Net45\ReactiveUI.dll ReactiveDemo
To fix this you have to update its dependent library, Splat, to the latest version.

Create your own Observable

If you’re going all-in on Rx and want to create your own IObservable without wrapping some other technology, there’s a way.
introtorx.com advises against implementing IObservable yourself and advises using Observable.Create instead. Here’s an example of a base class that handles using Create to provide an IObservable.

    /// <summary>
    /// Adds <see cref="IObservable{T>"/> support to a class.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class ObservableBase<T> {

        #region IObservable

        /// <summary>
        /// The list of observers.
        /// </summary>
        private readonly List<IObserver<T>> _observers = new List<IObserver<T>>();

        /// <summary>
        /// Creates an observable using <see cref="Observable.Create{TResult}(Func{System.IObserver{TResult},System.Action})"/>.
        /// </summary>
        public IObservable<T> AsObservable {
            get {
                return Observable.Create( (Func<IObserver<T>, IDisposable>)Subscribe );

        /// <summary>
        /// Pushes value to all observers.
        /// </summary>
        /// <param name="value"></param>
        protected void Emit( T value ) {
            _observers.ForEach( observer => observer.OnNext( value ) );

        /// <summary>
        /// Used to add observers.
        /// </summary>
        /// <param name="observer"></param>
        /// <returns></returns>
        public IDisposable Subscribe( IObserver<T> observer ) {
            _observers.Add( observer );
            return Disposable.Empty;


Note that it doesn’t implement IObservable directly but provides an AsObservable method that makes use of Observable.Create.

Chaining Observables

Given its relationship to functional programming, it seems natural to want to chain Observables together so that one Observer is the next class’ Observable. After all, you’ll often use the result of one function as input to the next.

At any rate, using code like the above, this is how you might create a class that is both Observer and Observable:

    /// <summary>
    /// An class that is both Observer and Observable.
    /// </summary>
    /// <typeparam name="TIn"></typeparam>
    /// <typeparam name="TOut"></typeparam>
    public abstract class ChainedObserver<TIn,TOut> : IObserver<TIn> {
        #region IObservable

        /// <summary>
        /// The lsit of observers.
        /// </summary>
        private readonly List<IObserver<TOut>> _observers = new List<IObserver<TOut>>();

        /// <summary>
        /// Creates an observable using <see cref="Observable.Create{TResult}(Func{System.IObserver{TResult},System.Action})"/>.
        /// </summary>
        public IObservable<TOut> AsObservable {
            get {
                return Observable.Create( (Func<IObserver<TOut>, IDisposable>)Subscribe );

        /// <summary>
        /// Pushes value to all observers.
        /// </summary>
        /// <param name="value"></param>
        protected void Emit( TOut value ) {
            _observers.ForEach( observer => observer.OnNext( value ) );

        /// <summary>
        /// Used to add observers.
        /// </summary>
        /// <param name="observer"></param>
        /// <returns></returns>
        public IDisposable Subscribe( IObserver<TOut> observer ) {
            _observers.Add( observer );
            return Disposable.Empty;


        #region IObserver

        /// <summary>
        /// <see cref="IObserver{T}.OnCompleted"/>
        /// </summary>
        virtual public void OnCompleted() {

        /// <summary>
        /// <see cref="IObserver{T}.OnError"/>
        /// </summary>
        /// <param name="error"></param>
        virtual public void OnError( Exception error ) {

        /// <summary>
        /// <see cref="IObserver{T}.OnNext"/>
        /// </summary>
        /// <param name="value"></param>
        virtual public void OnNext( TIn value ) {


As before, it doesn’t implement IObservable directly but provides an AsObservable method that makes use of Observable.Create.