Thursday Night

Paul Betts’s personal website / blog / what-have-you

New Release: ReactiveUI 2.1

February 14th, 2011 at 10:39 pm


What does ReactiveUI do?

ReactiveUI is a M-V-VM framework like MVVM Light or Caliburn.Micro, that is deeply integrated with the Reactive Extensions for .NET. This allows you to write code in your ViewModel that is far more elegant and terse when expressing complex stateful interactions, as well as much simpler handling of async operations. Check out this video for an overview:

YouTube Preview Image

ReactiveUI on Hanselminutes

Check out the recent Hanselminutes episode about the Reactive Extensions as well if you’ve got more time. Scott and I chat about some of the ideas in RxUI and how we can take the ideas in the Reactive Extensions and use RxUI to apply them to Silverlight and WPF apps.

What’s new in ReactiveUI 2.1 – bindings galore!

  • ObservableForProperty now accepts full paths, similar to Xaml bindings – this makes it much easier to write complex expressions
  • Combining properties correctly is much easier with a new Object.WhenAny() method that acts like a n-way CombineLatest optimized for binding use
  • A new method called BindTo allows you to automatically update a read-write property using an Observable; this can be combined with WithAny() to easily create one-way bindings between ViewModel objects
  • Improved CachedSelectMany that allows you to share a cache between different parts of the code
  • Utility method ToCommand which invokes an ICommand based on an IObservable
  • ReactiveUI now uses the latest Rx.NET release, and solves some NuGet issues that were present in the WP7 release
  • Lots of bug fixes, especially to MessageBus and ReactiveAsyncCommand; a huge thanks to the folks on the Google Group for helping out with bug reports

Had trouble with NuGet lately? We fixed that.

Recently, ReactiveUI has been having some trouble on NuGet, with both the WP7 and Desktop packages. Hopefully all of these problems have been fixed, though you’ll have to update your existing code to be compatible with the latest Rx.NET – for me, this mainly affected the Publish() operator, but is relatively easy to fix.

Where can I find the library?

On NuGet! The best way to install ReactiveUI for a project is by installing the ReactiveUI package for WPF/Silverlight projects, or ReactiveUI-WP7 for Windows Phone 7 projects.

If NuGet isn’t your thing, you can also find the binaries on the Github page: ReactiveUI 2.1.0.1.zip.

Where can I see a sample?

A sample project for WPF 4.0 that includes everything you need to see how it works is on the Github page: ReactiveUI 2.1 Sample.zip. It includes a small sample app, the RxUI binaries, and some sample test cases.

WCF.AsParallel() using ReactiveUI and Rx.NET

February 8th, 2011 at 2:14 am


Select.AsParallel() for the Web

I’ve mentioned it before, but SelectMany is the secret to using web services. Check out this previous article on Web Services if you’re new to using SelectMany with web services. Here’s the easy way to understand it in two lines, in terms of PowerShell / *nix pipes:

The cool thing about Rx.NET is that it makes it easy to write completely non-blocking calls a-la node.js. If you’ve ever used the BeginXXXX/EndXXXX calls, you know that it’s not particularly easy to use once you get into more complex examples, but that’s one of the advantages of Rx.NET – being able to take a bunch of asynchronous operations and sews them together in a sane way. It’s easy to write, but what actually happens when we run it? Let’s see what code runs where:

It’s easy to be way too parallel

Non-blocking web service calls take almost no time to execute – this is one of its big advantages, but it also means we can go through the input array really quickly. In effect, this means that if we have an array with 100 elements, we will end up issuing 100 WCF requests at the same time!

Not only is this not friendly to the web server on the other end, it isn’t possible – WCF will throttle your requests to 5 concurrent requests by default, and fail the rest. We need a way to keep a “pending queue”, run a few at a time, and when each one completes, pull a few more from the pending queue.

CachedSelectMany throttles concurrency

Let’s see how the diagram looks like when we use CachedSelectMany instead of SelectMany – from a code standpoint, CachedSelectMany can simply be substituted in places where you use SelectMany with a web service. CachedSelectMany internally uses a class called ObservableAsyncMRUCache to manage concurrency. Despite the fact that calls can be queued, your code doesn’t actually wait – you just won’t be called back until the call completes.


Bar has to wait in line before it can run

Every Open-Source .NET Project should have its own public OneNote

February 5th, 2011 at 6:21 pm


Office is on the Web now

Does everyone know about office.live.com? As part of Office 2010, Microsoft launched web versions of all their products. Check it out:


It’s OneNote, but works everywhere

This editor is on the web, so it’s accessible from any machine (regardless of browser, works great on Chrome in OS X for me), it’s free, and OneNote will sync with the web notebooks as if they were on your local machine or on a network share.

OneNote on the web means you can make your project notes public

A blog is a great place for documenting your project more formally, or for announcing things you want folks to know, but it’s also important to have a place to store ideas that aren’t yet fully formed, or you’re not committed to finishing. OneNote is good for this, but now we have a way to publish out notes; I’ve done this with ReactiveUI (though right now my notebook is pretty empty, I’m going to try to use it more).

My hope is, that if people can see the direction of the project and what the thinking is behind the code, it might spark good ideas for them as well: “..cool but what about this?“. Either they can fire off a mail to the mailing list, or maybe it will inspire them to write something completely different. If I’m going to write the notebook anyways, I’d rather share it!

Watching DependencyProperties using ReactiveUI

February 4th, 2011 at 8:10 pm


Watching DependencyProperties in WPF is easy…

One of the things that is pretty useful in XAML-based frameworks like WPF and Silverlight when working in the codebehind is being able to be notified when a DependencyProperty changes. In the ViewModel, we have a different mechanism called INotifyPropertyChanged to accomplish this, but DependencyProperties are still an important part of WPF/Silverlight.

Let’s see how we would do this in WPF – it’s fairly straightforward:

…but really ugly in Silverlight

Unfortunately, this isn’t possible in Silverlight – it’s only possible to wire up a single callback, and it can only be done by the class that actually creates the DependencyProperty. This might work fine in some scenarios, but something less tightly coupled is often needed.

The solution is to use Attached Properties, as described Anoop Madhusudanan’s blog post – register an attached property, then hook that change notification.

ReactiveUI now does this for you

In ReactiveUI as of v2.0, there is a new method called ObservableFromDP – this method works similarly to the ViewModel’s ObservableFromProperty, but with less syntactic noise:

Of course, since it’s an Observable and not an event handler, all of the power of Rx.NET applies to this as well. Nothing revolutionary, but definitely makes things easier!

Testing your ViewModels using Time Travel and ReactiveUI

January 18th, 2011 at 2:19 am


Testing asynchronous ViewModel interactions is tough

When running under a unit test runner, ReactiveUI makes it fairly straightforward to test interactions between commands and changing properties. Fiddle with properties, execute the commands, Assert what happens – done!

However, most non-trivial programs need to run something in the background – talk to a web service, calculate something in the background, etc. Testing this can be way more challenging, since it is easy to deadlock yourself with the Immediate scheduler (the one used by-default in a unit test) – when it comes down to it, there is exactly one thread, and it can’t be doing two+ things at a time. This will typically come into play when you use a blocking call like First(), then find out your test runner never finishes. In a non-Rx context, we typically try to test this via Thread.Sleep() calls or Waits, which are really slow and often give you really unpredictable results.

Using EventScheduler in a pinch

What we need, is a replacement for RxApp.DeferredScheduler that is actually deferred, to take the place of WPF/Silverlight’s Dispatcher. Enter EventLoopScheduler! We can use this to create a “pretend” Dispatcher on-the-fly that we control:

This is alright, but it still will slow down our test suite by quite a bit, waiting for network access. What’s worse, if we were testing something more complicated, we could get tests that pass sometimes but not others, depending on the timing – this is a huge time sink for QA folks who have to then debug the test failures.

Testing software via Time Travel?!

The guys from DevLabs came up with a pretty ingenious way to solve this. Let’s look at the definition of IScheduler, the interface through which we send all of our deferred processing:

So, we can schedule code to run right now, we can schedule it to run after a certain amount of time has elapsed, and then there’s that third member: Now. You might ask, “Why do I need to know Now, don’t I get it from DateTime.Now?” Here’s the clever bit: What if you made a scheduler where Now was settable? This scheduler would never run anything, just queue it to a list of stuff to run. Then, when “Now” is set (i.e. we “move through time”), we activate anything that would have run in that time period.

How does the TestScheduler work?

In fact, this is exactly how TestScheduler works. When Rx operators call Schedule(), nothing happens. Then, TestScheduler has two interesting methods, Run(), which will run all of the queued items (i.e. execute anything that it can), and RunToMilliseconds(), which lets you travel to a certain time period n milliseconds away from t=0.

Faking out an asynchronous web call

Sounds great, right? Here’s the caveat about TestScheduler though – if you use any other asynchronous methods like Event or Task.Wait(), it’ll be tougher to integrate TestScheduler, since not all sources of async’ness are going through the TestScheduler. However, if you’re using Rx in a project, I consider using other sync/thread patterns to be an Rx Code Smell – like casting IEnumerables in LINQ to Array because I happen to know it’s an Array.

Let’s see how we can create a fake async Read method, that will simulate taking up some time and returning a result:

The cool thing about this mock, is that if you used it in a normal environment or under an EventLoopScheduler, it’d do exactly as it said: wait 10 seconds, then return that array. Under the TestScheduler, we’ll make it return immediately!

Writing the Unit Test

Here’s how we could write the Unit Test above to execute instantly using TestScheduler (actually fleshing out the MyCoolViewModel so you can see how it’s wired up). Inverting the control to actually get the mock function here is pretty ugly, there are certainly better ways to go about it.

Cool, right??

Okay, well maybe not cool, but learning about this definitely helped the ReactiveUI unit tests themselves become much more reliable and run way faster once I rewrote them to take advantage of TestScheduler – those Sleeps really add up! If you want to learn more about TestScheduler, Wes Dyer and Jeffrey Van Gogh from the Rx team talk about it in-depth here: Wes Dyer and Jeffrey Van Gogh: Rx Virtual Time

ReactiveUI Link Roundup

January 17th, 2011 at 12:25 pm


If you’re new to ReactiveUI and you’re looking for information on how it works, I’ve written lots of blog posts on the topic. Here’s some of the best ones:

ReactiveUIPosts.Subscribe()

I make sure to post all of my RxUI-related posts under the Reactive Extensions category on my blog, and I also usually tweet about them via Twitter, my handle there is @xpaulbettsx.

Where can I get help?

If you’re trying out ReactiveUI and something doesn’t work right, or it’s not clear how to go about doing something, send me an Email. Another good place to get support is the ReactiveUI Google Group.

ReactiveXaml is now ReactiveUI 2.0!

January 15th, 2011 at 10:33 pm


What does ReactiveUI do?

ReactiveUI is a M-V-VM framework like MVVM Light or Caliburn.Micro, that is deeply integrated with the Reactive Extensions for .NET. This allows you to write code in your ViewModel that is far more elegant and terse when expressing complex stateful interactions, as well as much simpler handling of async operations. Check out this video for an overview:

YouTube Preview Image

Why the name change? I liked ReactiveXaml

The main reason I decided to change the name, is that many of the classes in ReactiveUI are useful outside of WPF and Silverlight, especially with a new library that I’m working on called ReactiveUI.Serialization (not quite ready yet!) Observable objects and collections are quite useful in non-XAML domains as well, so I want to broaden the scope a bit. For example, I think a lot of these classes could be pretty useful for building ASP.NET MVC ViewModels as well! I think ReactiveUI’s shortened name of RxUI looks better too :)

Where can I find the library?

On NuGet! The best way to install ReactiveUI for a project is by installing the ReactiveUI package for WPF/Silverlight projects, or ReactiveUI-WP7 for Windows Phone 7 projects.

If NuGet isn’t your thing, you can also find the binaries on the Github page: ReactiveUI 2.0.0.2.zip.

Where can I see a sample?

A sample project for WPF 4.0 that includes everything you need to see how it works is on the Github page: ReactiveUI 2.0 Sample.zip. It includes a small sample app, the RxUI binaries, and some sample test cases.

Version 2.0 means breaking changes

ReactiveUI uses semantic versioning (mostly), which means that version 2.0 contains breaking changes from the 1.x series. The biggest one is the namespace change and split – several classes that have dependencies on WPF/Silverlight are now moved into the “ReactiveUI.Xaml” assembly/namespace. Fixing this is usually pretty straightforward. Most of the other breaking changes are name changes and shuffling some parameter names around, especially in ReactiveCommand and ReactiveAsyncCommand.

Here’s one big change that is more subtle – in previous versions of ReactiveUI, the “Changed” Observable would give you “Sender”, “PropertyName”, and “Value”, but Value would be null on certain Observables and non-null on others, in a completely arbitrary way. In ReactiveUI 2.0, the rule is, if you explicitly ask for the property by-name (i.e. via ObservableForProperty), the Value will be set. However, there is also a GetValue() method on ObservedChange and a Value() method on IObservable that will get the value given any ObservedChange.

New features in 2.0

  • ReactiveUI now has a simple, Rx-enabled Message Bus, inspired by MVVM Light’s Message Bus
  • A new set of extension methods to help writing unit tests (ReactiveUI.Testing) – write unit tests that simulate concurrency without using Thread.Sleep, and get the same results every run
  • Unit test detection now correctly works with Silverlight
  • A new async cache class that supports Silverlight, and an extension method to easily integrate it to existing code (MemoizedSelectMany). Easily turn concurrent web calls into memoized, rate-throttled web calls
  • Object validation is vastly improved in this release – many bugs fixed and is more performant.
  • The same async cache class is also used in ReactiveAsyncCommand to properly support memoization
  • CreateDerivedCollection() now works with ObservableCollection, making it easier to create ViewModels from existing non-RxUI code
  • Easily get an Observable from a DependencyProperty (ObservableFromDP), even in Silverlight and WP7
  • Cleaner syntax for creating properties based on Observables
  • Intellisense documentation for all classes
  • ReactiveCollection is vastly improved – it now supports tracking object property changes (i.e. it’s now easy to track “Tell me when items are added/removed, or when a property changes on any of the objects in this list”)
  • RxUI now uses the latest Rx.NET release (the “Christmas Release”)
  • The RxUI core DLL is no longer dependent on any WPF binaries, so it is more palatable to integrate into non-WPF projects.

Hey, why is this version 2.0.0.2

Here’s some advice to other developers – if you’re ever considering, “Oh, I’ll just change this one thing right before I release, it’ll be fine!”, don’t. Here’s the last-minute bug that I introduced that completely borks v2.0.0.0. :: sigh ::

https://github.com/xpaulbettsx/ReactiveUI/commit/b00354decf7c97e5af1148a6693136935fb82d22#L3L50

Building the project:

Building the project requires having quite a few products installed – to build a full release, you need:

  • Visual Studio 2010
  • Pex / Moles
  • Code Contracts for .NET
  • Expression Blend 4.0
  • Silverlight 4.0 Development Tools
  • Windows Phone 7 Development Tools

That being said, if you’re only interested in ReactiveUI core, you only need VS2010 Professional – the other projects can simply be unloaded. Clone the source from GitHub, or download the 2.0.0.2 source code release as a Zip file (though I highly recommend the former).

Lots of new stuff coming, but RxXaml is now in crazy experimental mode

December 2nd, 2010 at 9:54 pm


If you’re tracking ReactiveXaml, you most likely don’t want to use the code that’s currently in master right now – you’ll want to stick with either the released version, or a commit earlier than c2a4o. In the meantime, here are the three things that I’m currently working on that are totally wreaking havoc on the tree:

  • Using TestScheduler on tests, so that testing async commands happens instantly and 100% reliably, instead of using Thread.Sleep hacks
  • A new MRU cache designed to replace QueuedAsyncMRUCache called ObservableAsyncMRUCache – it will be usable on Silverlight and WP7, and has much more usable behavior than the old class

Oh, and one more thing – porting a version of ReactiveXaml to MonoTouch. Write the same declarative code against iOS, use super-powered Key-Value Coding via Observable Bindings, and handle async code easily and gracefully.

Making Async I/O work for you, Reactive style

November 16th, 2010 at 12:17 am


Earlier today, I read a fantastic article about the TPL by Scott Hanselman. In it, he describes how to take a fairly straightforward function to detect if a given Url responds, and write it in an asynchronous fashion. As soon as I read it, I knew that I had to write the Reactive Extensions for .NET version!

How do the TPL and Rx.NET relate?

Both of these technologies are intended to help make writing asynchronous and concurrent programs easier and more straightforward, so it’s really easy to be confused as to which one to use. You can often think of Task and IObservable for async calls as the same thing – an object that represents a future result that hasn’t completed yet – we saw this in a previous blog post. In an asynchronous function, we send out the request, but we don’t have the data – we have to return something that will allow us to eventually get the result.

When it comes down to it, Task is really a specialization of IObservable – Task is specifically designed to run on the TPL threadpool, whereas IObservable abstracts away where the code will execute unless you specify it explicitly.

Seeing the problem again

Let’s take a look at the synchronous version of the code again – we want to take this and rewrite it so that it doesn’t block:

Writing our initial stab at VerifyUrlAsync

Just like Scott’s Task-based async function, we’ll also define a function that returns a future result. However, instead of using Task as our return type, we’ll define a function that returns IObservable:

Now, let’s see the implementation:

How can we use this?

This method will not block, it will instantly return you an IObservable representing the future result. So, there are a couple of ways you can use the Observable to “unpack” the result:

Now, let’s see how we can do arrays:

The truly revolutionary thing about Rx.NET is how the same primitive you used in LINQ now take on awesome new meanings when applied to the domain of the future. So, the first thing we’ll do is take our array and convert it to an IObservable via AsObservable. This means that the resulting IObservable will produce n items, one for each element in the array, then OnComplete.

The natural thing we would do to get the result is someObservable.Select(x => ValidateUrlAsync(x)). However, there’s a problem – our type is now IObservable<IObservable<T>>; we now have a “future list of futures” (thinking of IObservable as a “future list” is a good analogy, whereas the web call is just a “future list” with only one item). We need a way to flatten down our future list back to IObservable<T> – so what’s the way to flatten a list in LINQ? SelectMany, of course! SelectMany is the secret behind writing async Rx code. Let’s see how to do it:

The code above is still asynchronous – at no time will we block, and it will instantly return. The SelectMany’s default IScheduler will run items on the TaskPool (actually in this case, we never used any synchronous method so we will never block, even on a Threadpool thread. To get the result, similar to the above method, we’d have to call First() on it.

If we were to dump the IObservables at every point of the computation, it’d look something like this:


[ "http://foo", "http://bar" ] ===>

[ {"http://foo", false}, {"http://bar", false} ] ===>

[ Dictionary ]

Cool! Where can I learn more?

  • The Rx Hands-on-lab is an awesome, thorough, and technically correct introduction to Rx.NET
  • The Rx.NET forums are full of really smart, helpful people – I’ve learned a ton by reading through the forum posts
  • The Rx.NET videos on Channel 9 are a great resource – the developers behind the library itself explain the concepts in an easy-to-understand way
  • My blog series on ReactiveXaml and Rx.NET is also a good way to understand many practical uses of Rx, especially if you’re writing desktop / Silverlight / WP7 apps.

Detecting whether your .NET library is running under a unit test runner

November 15th, 2010 at 1:23 am


Here’s a piece of code that I found useful for ReactiveXaml, how to detect whether you are running under the unit test runner. For WPF/Silverlight testing, this is important to know since Dispatcher.Current exists but is bogus (i.e. none of the things you queue to it will run during the unit tests). The official version comes from here.

public static bool InUnitTestRunner()
{
    string[] test_assemblies = new[] {
        "CSUNIT",
        "NUNIT",
        "XUNIT",
        "MBUNIT",
        "TESTDRIVEN",
        "QUALITYTOOLS.TIPS.UNITTEST.ADAPTER",
        "QUALITYTOOLS.UNITTESTING.SILVERLIGHT",
        "PEX",
    };

#if SILVERLIGHT
    return Deployment.Current.Parts.Any(x =>
      test_assemblies.Any(name => x.Source.ToUpperInvariant().Contains(name)));
#else
    return AppDomain.CurrentDomain.GetAssemblies().Any(x =>
      test_assemblies.Any(name => x.FullName.ToUpperInvariant().Contains(name)));
#endif
}