Thursday Night

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

New Release: ReactiveUI 2.2.1

View Comments

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.

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.2.1 – Now with 100% less Windows Phone crashes

This release is just a maintenance release – if you don’t currently have any issues with RxUI, there is no reason to upgrade. However, there are two major fixes that were worth creating a new release for:

  • .NET 4.0 Client Profile – by including System.Reactive.Testing into ReactiveUI.dll, we broke everyone using the Client profile with WPF. This is now fixed and future versions of RxUI will be built against the Client profile.
  • WP7 Crashes – if you tried to use RxUI with WP7, you would receive a TypeLoadException whenever a type was instantiated, or possibly a XamlParseException telling you something to the effect of “MainWindow class does not exist”. This issue is now fixed!

Breaking Change: Introducing ReactiveUI.Testing

To facilitate fixing the first bug above, a new Assembly / NuGet package has been introduced, “ReactiveUI.Testing.dll / ReactiveUI-Testing” – this was originally in ReactiveUI Core, and the libraries here help you write better unit tests for your applications (similar to Rx’s System.Reactive.Testing). As a result of this, you may need to add an extra package / library reference to your project when you upgrade to 2.2.1.

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.2.1.0.zip.

Written by Paul Betts

March 22nd, 2011 at 11:38 pm

New Release: ReactiveUI 2.2

View Comments

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.

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.2 – Interop with Existing Code

This release has a focus on enabling folks to use RxUI without having to completely rewrite existing codebases to use ReactiveUI. In future entries, I’ll show how to take existing ViewModels and “Reactiveify” them.

Major Changes

  • The ObservableForProperty and WhenAny operators now work with normal INotifyPropertyChanged-based ViewModels, instead of requiring them to be ReactiveObjects. This means it’s now easy to try RxUI in your existing project without changes.
  • A new class called MakeObjectReactiveHelper can be included in your existing ViewModel classes to easily make them equivalent to ReactiveObject objects without changing the base class.
  • A new overload of RaiseAndSetIfChanged is added that uses a Ref parameter to solve the Silverlight “backing fields must be public” problem.
  • New testing features that work along with TestScheduler.CreateHotObservable that allow you to create mock timelines and test your code against it.

Minor Changes

  • The legacy QueuedAsyncMRUCache has been removed – this is a breaking change, but you really shouldn’t be using this class, ObservableAsyncMRUCache is much better and doesn’t have correctness issues.
  • Performance fixes in MemoizedMRUCache, which is used throughout the framework.
  • Many bugfixes directly based on user feedback – specifically, the ReactiveAsyncCommand issue where async items weren’t being run on the Taskpool is now fixed.

A new Sample Application


A Reactive Pomodoro Timer

I’ve written a new sample application based on a Pomodoro Timer – while this application isn’t multithreaded, it’s still asynchronous, and illustrates a lot of how to use Rx in a complex user interface (while a Pomodoro Timer seems quite simple, it actually is quite tricky to write since all of the UI controls are interrelated and very prone to ordering issues). With Rx.NET and RxUI, we can write the entire interaction logic in about a page or two.

But the more interesting thing in this sample, is that all of the interaction logic is also unit-tested. Using Time Travel Testing, we make sure the application does what it says it does, without actually ever waiting on the timers to finish. Here’s an example test: despite it appearing to take time, it runs instantly (Open in Browser if you don’t see a code sample):

Get the sample on the Github page: ReactiveUI 2.2 Sample.zip.

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.2.0.0.zip.

Written by Paul Betts

February 27th, 2011 at 8:40 pm

ReactiveUI Message Bus – decoupling objects using the publish/subscribe pattern

View Comments

Message buses allow us to decouple code

If you’ve used the MVVM pattern enough, you’ll sometimes find that you get “stuck” – you need to access a certain ViewModel (usually the “main” ViewModel), but at the point you need it, it’s too far removed from the context that you’re using it in. Sometimes if the object is a Singleton it’s appropriate to think of something like the Managed Extensibility Framework to get a reference.

Other times, a Messaging framework is more appropriate – ReactiveUI provides an “Rx”-take on the Messenger (Publish/Subscribe) pattern. With the Messenger pattern, we don’t have to make all our ViewModels related to each other, which is important for writing testable code, since I can easily replace related objects with mock objects.

ReactiveUI’s MessageBus

ReactiveUI’s MessageBus is based on the Type of the message object. If the Message type isn’t unique enough, an extra Contract string can be provided to make the source unique.

There are three main methods that we’re interested in:

  • RegisterMessageSource(IObservable source) – Register an IObservable as a message source – anything that is published on the IObservable gets published to the bus.
  • SendMessage(message) – Publish a single item on the bus instead of having to use an Observable.
  • IObservable Listen() – Get an Observable for the specified source – you can either Subscribe to it directly, or use any of the Rx operators to filter what you want.

Special support for singleton ViewModels

For ViewModels that only have a single instance, there are a number of helper methods that make using the MessageBus easier – use these methods instead of the above ones:

  • RegisterViewModel(ViewModel) – Registers a ViewModel object; call this in your ViewModel constructor.
  • IObservable ListenToViewModel – Listen for change notifications on a ViewModel object
  • IObservable ViewModelForType – Return the ViewModel for the specified type

Written by Paul Betts

February 25th, 2011 at 12:17 am

Adding a Reference inside a NuGet project

View Comments

Sometimes packages need references to system assemblies

When NuGet packages need to reference other NuGet packages, it’s fairly straightforward to do: add a References section in your NuSpec file pointing to the right package. However, what if your package requires one of the built-in assemblies, like System.ComponentModel.Composition (MEF)? As far as I can tell, NuGet doesn’t have a way to do this in the spec file. ReactiveUI’s WP7 version needs a reference to System.Observable – trying to install the package then building it results in build errors, and that’s no way to live.

Using a post-install script to rig it up

Add a tools folder, and in that add an “install.ps1″ – this is a PowerShell script that gets run whenever your package gets installed. Here’s the magic sauce to add the reference:

param($installPath, $toolsPath, $package, $project)

$project.Object.References.Add("System.ComponentModel.Composition")

You can do all kinds of other cool things with that $project variable, use the NuGet console to explore what’s available.

Written by Paul Betts

February 21st, 2011 at 11:21 pm

WCF.AsParallel() using ReactiveUI and Rx.NET

View Comments

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

Written by Paul Betts

February 8th, 2011 at 2:14 am

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

View Comments

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!

Written by Paul Betts

February 5th, 2011 at 6:21 pm

Watching DependencyProperties using ReactiveUI

View Comments

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!

Written by Paul Betts

February 4th, 2011 at 8:10 pm

Testing your ViewModels using Time Travel and ReactiveUI

View Comments

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

Written by Paul Betts

January 18th, 2011 at 2:19 am

ReactiveUI Link Roundup

View Comments

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.

Written by Paul Betts

January 17th, 2011 at 12:25 pm

ReactiveXaml is now ReactiveUI 2.0!

View Comments

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).

Written by Paul Betts

January 15th, 2011 at 10:33 pm