Category Archives: c#

Batching Data by Time or Count Using Reactive Extensions (Rx)

Motivation

The time-series database InfluxDB provides a HTTP API to write data. Data points (measurements) are inserted via a Line protocol, which allows batching of data by writing multiple points in one HTTP request.

While experimenting for a simple InfluxDB C++ client, I wanted to create an asynchronous fire-and-forget API, so that the data points can be sent over HTTP without blocking the instrumented C++ code. Several “readymade” options to implement concurrency in this scenario are available.

A simple PAIR of ZeroMQ sockets would do the job, but I’d have to implement batching separately. Thus, I turned my attention to a higher-level abstraction: Rx

Rx Window Operator

Quickly looking through the cross-language Reactive Extensions site, I found the right operator: Window.

This operator has luckily been implemented in RxCpp, thus I proceeded with the experiment.

Batching Design

Batching using Rx Winodw Operator

Rx Window Operator (CC BY 3.0 reactivex.io)1

The window operator takes an observable sequence of data and splits it into windows (batches) of observables. To batch requests, the observable windows of data are aggregated to a single value upon the last value from the windows (via other aggregating Rx operators).

A Toy Problem

To validate the approach, the following problem is set:

Given a stream of integers, append the integers into a series of strings, either every second, or every N integers

String appends with integer-to-string conversions in C++ will be done via the {fmt} library.

Batching in One Line of Code

A stream of numbers batched either by time or count:

auto values = rxcpp::observable<>::range(1, 1000'000)
    .window_with_time_or_count(std::chrono::seconds(1), 100'000);

Note, there is an almost one-to-one translation into a C# version:

var values = Observable.Range(1, 1000000)
               .Window(TimeSpan.FromSeconds(1), 100000);

This indicates the power of the Rx abstraction across languages. The Rx website provides just the right sorting of the documentation to be able to translate Rx code from one language to another.

Aggregating the Batches

In order to do something useful with the batched data, the Scan operator is used to gather the data in a string buffer, and after the last value has been received, the string buffer is assembled into a string and processed:

values.subscribe(
    [](rxcpp::observable<int> window) {
        // append the number to the buffer
        window.scan(
            std::make_shared<fmt::MemoryWriter>(),
            [](std::shared_ptr<fmt::MemoryWriter> const& w, int v)
        {
            *w << v;
            return w;
        })

        // what if the window is empty? Provide at least one empty value
        .start_with(std::make_shared<fmt::MemoryWriter>())

        // take the last value
        .last()

        // print something fancy
        .subscribe([](std::shared_ptr<fmt::MemoryWriter> const& w) {
            fmt::print(
                "Len: {} ({}...)\n",
                w->size(),
                w->str().substr(0, 42)
            );
        });            
    }
);

The Tale of Two Bugs

In the initial (non-TDD) spike, the batching seemed to work, however, something caught my attention (the code bites back):

[window 0] Create window
Count in window: 170306
Len: 910731 (123456789101112131415161718192021222324252...)

the window wasn’t capped at 100’000. This could have been either a misunderstanding or a bug, thus I formulated a hesitant issue #277. As it turned out, it indeed was a bug, which was then fixed in no time. However, the first bug has hidden another one: the spike implementation started to crash at the end: when all the windows were capped by count, and not by time, last window was empty, as all values fit exactly into 10 batches.

The Last operator rightly caused an exception due to an empty sequence. Obviously, there’s no last value in an empty sequence. Rubber Ducking and a hint from Kirk Shoop fixed the issue by utilizing the StartWith operator to guarantee, the sequence is never empty. An empty string buffer can be ignored easier downstream.

Active Object

The active object pattern was applied to implement a fire-and-forget asynchronous API. A Rx Subject to bridge between the function call and the “control-inverted” observable:

struct async_api {
    //...
    rxcpp::subjects::subject<line> subj;
    //...

    async_api(...)
    {
        auto incoming_requests = subj
            .get_observable()
            .map([](auto line) {
                return line.to_string();
            });

        incoming_requests
            .window_with_time_or_count(
                window_max_ms,
                window_max_lines,
                // schedule window caps on a new thread
                rxcpp::synchronize_new_thread()
            )
            .subscribe(...)
        ;
    }

    // fire-and-forget
    void insert(line const& line)
    {
        subj
            .get_subscriber()
            .on_next(line);
    }
};

in order not to block the caller (which would be the default behavior), the observable watches the values from each window on a new thread. Here, scheduling on a thread pool (currently missing in RxCpp) would probably be beneficial.

While this implementation might not be an optimal one, the declarative nature of Rx, once the basics are understood, allows to “make it work and make it right” pretty quickly by composing the right operators.

Code

The runnable code of the example can be found at Github: C++ version.

In order to show, how similar the high level code can be between different languages when writing, I’ve “ported” the example to C# 2.

  1. Source: reactivex.io License: (CC BY 3.0)
  2. The C# version appears to run faster on my windows machine while solving the same toy problem

No Events: ReactiveUI Windows Forms MVVM-Style

Review

designed using http://viperneo.github.io/winforms-modernui/

This is the next post in the series, looking first at Reactive Extensions (RX) to simplify writing Windows Forms UI logic, then using a viewmodel shared between a WPF gui implementation and a rewritten WinForms version using ReactiveUI, stopping at a short article on testing the viewmodels.

passedtest

ReactiveUI News

ReactiveUI API has been quite volatile for the last year, and this series is in need of an update1. A CodeProject author gardner9032 published a nice teaser article, showing the ReactiveUI mechanism for writing simplified Viewmodel-View bindings 2, which serves as primary trigger for this post.

There’s plenty of news and updated articles on Paul Betts’ log, providing a good resource for updates on the API. Phil Haack’s blog is also a superb resource for explanations and commentaries on the use of ReactiveUI in real-world applications.

The ReactiveUI project is quite active, as the community seems to have grokked the jist of it, while the list of supported platforms has become more than convincing.

Getting rid of events

The enabling feature of ReactiveUI is writing declarative UI glue code, and if the viewmodels are based on Reactive Extensions, then declarative C# style can be used throughout the project. The previous ReactiveUI Windows Forms examples converted an event sequence into an observable sequence of values. In this example, that will be accomplished conveniently by the ReactiveUI WinForms lbrary. The viewmodels also contained some imperative code. For this article, the viewmodels will not be reused from the previous articles, but written from scratch.

ViewModel

s. code

The viewmodel’s task is the same: something is ticking in the background, while words are counted in the input text asynchronously, and the calculation is throttled to 0.5 seconds. The viewmodel boilerplate is simplified using ReactiveUI.ReactiveObject.

Output (read-only) properties

The ReactiveUI-way of creating output properties is through ObservableAsPropertyHelper.

private readonly ObservableAsPropertyHelper<string> backgroundTicker;
public string BackgroundTicker
{
    get
    {
        return backgroundTicker.Value;
    }
    //...
}

The constructor of the viewmodel receives an IScheduler for scheduling on the correct thread, and an IObservable, which will be a stream of input from the view. Observe the ToProperty helper:

public MyViewModel(IScheduler scheduler, IObservable<string> input)
{
    Observable.Interval(TimeSpan.FromSeconds(1))
        .ObserveOn(scheduler)
        .Select(_ => DateTime.Now.ToLongTimeString())
        .ToProperty(this, x => x.BackgroundTicker, out backgroundTicker);
    //...
}

Word counting logic is implemented in a similar fashion by transforming the incoming stream of strings.

View

s. code

To remove yet more boilerplate code, WinForms Form specialization implements the ReactiveUI.IViewFor interface. This allows for largely simplified run-time and compile-time checked bindings, avoiding using strings for property names. The implementation is straightforward, and pays off once the views become more complex than this example:

IViewFor

public MyViewModel VM { get; private set; }

object IViewFor.ViewModel
{
    get { return VM; }
    set { VM = (MyViewModel)value; }
}

MyViewModel IViewFor<MyViewModel>.ViewModel
{
    get { return VM; }
    set { VM = value; }
}

Bindings

None of the controls in the designed WinForm have wired events or bindings set from the designer. The glue code is reduced to instantiating the viewmodel …

VM = new MyViewModel(
    new System.Reactive.Concurrency.ControlScheduler(this),
    this.WhenAnyValue(x => x.inputBox.Text)
);

… and declaring the bindings3 4.

this.Bind(VM, x => x.BackgroundTicker, x => x.tickerBox.Text);
this.Bind(VM, x => x.WordCount, x => x.wordCountBox.Text);

Source

@github

  1. See ReactiveUI Design Guidelines
  2. see article @CodeProject
  3. The ReactiveUI WinForms implementation seems not to support fully read-only fields using default bindings yet, hence an empty setter in the viewmodel
  4. The scheduler is from Windows Forms helpers

Beginning another quest – scripting business logic in .NET: using dynamiclua

Let’s start with Lua

The current state of things is that the lightweight but mighty Lua has become ubiquitous in the world of computing as a scripting and configuration component. Lua’s strategy of “mechanism, not policies” allows the language to be extremely malleable. It’s worth watching Roberto Ierusalimschy’s talks on the evolution of Lua 1.

The latest adoptions of Lua are for example the Redis’ EVAL Query with Lua scripting, and Wikipedia’s template automation using user-written Lua scripts.

dynamiclua

There have been several attempts to bring Lua into the world of .NET, and one of the most recent efforts by Niklas Rother, dynamiclua, combines the previous achievements with the dynamic type of .NET 4.0, and lays path for an easily reusable business logic scripting component, which is now even available via nuget.

After adding dynamiclua as a reference, here’s your first business logic:

using (dynamic lua = new DynamicLua.DynamicLua()) {
 Console.WriteLine(lua("return 2+2"));
}

note the IDisposable usage for freeing native resources.

Discovering the features

Static configuration

As an author of a configurable component,
In order to reduce my support effort,
I want the users of my component to write their static configuration themselves

While for that user story JSON or XML would suffice, we’re on the Lua track, hence this is how it could work:

// comes from some user input or file
string user_static_config = @"
 config = {
  url = 'https://github.com/nrother/dynamiclua'
 }
";

lua(user_static_config);
string url = lua.config.url;
Console.WriteLine(url);

… it does look like JSON, but it isn’t. Here, one can observe the harmony resulting from the use of the dynamic keyword to interact with a dynamic language from a statically typed one. DynamicLua can leverage reflection capabilities of both languages to create an “automagical” interop, compared sometimes tedious writing of bindings for a language, such as native C++.

The power of Lua at the user’s fingertips

As an author of a customizable business software,
In order to reduce my own support effort,
And create a new business of customizations,
I want the administrators of my software to write their business logic scripts themselves

Many systems grow out of static configurability, and business logic definition and evaluation in some programming language becomes inevitable. Whether this is a good thing or a bad one for one’s business 2 is not in the scope of this article, as it is assumed, we want to make our software customizable via scripting 3.

The static configuration entries can be dynamically evaluated at script run time. Various bindings may be used in the script, as i.e. the math standard library here:

lua("config.answer = nil or math.floor(131.94689145078/math.pi)");
int answer = (int)lua.config.answer;
Console.WriteLine(answer);

Using Lua as an expression evaluator

Lua supports multiple return values, which makes certain scenarios fun:

dynamic result = lua("return 1, 'world'");
Console.WriteLine("{0} {1}", result[0], result[1]);

Binding .NET code

Dynamiclua does not have an explicit class binding syntax 4, but it doesn’t matter much, as functions can be bound, and thus, constructors. Via reflection all public 5 members are bound. The domain code is therefore very easy to bind. Take an example:

class Example
{
    int answer = 42;
    public int Answer { get { return answer; } }

    public int Add(int a, int b)
    {
        return a + b;
    }
}

The binding is quite trivial:

lua.NewExample = new Func<Example>(() => new Example());

// Lua functions may be called via dynamiclua
Example my_example = lua.NewExample();
Console.WriteLine(my_example.Answer);

lua(@"
    local example = NewExample()
    print(example.Answer)
    print(example:Add(2,3))
");

Minimal sandboxing

As an author of a scripting component,
In order to mitigate the risk of damage by malicious user-supplied code,
I want the script executing environment to be sandboxed.

Sandboxing is a very complex issue and perhaps only approximations of an undefined ideal sandbox can be made 6. A sane attitude towards this security-related issue should go along the lines of trusting nobody, even oneself, and even that distrust should not be enough. Depending on the posed security requirements, the logic execution component might even be physically separated from your business software, i.e. running on another machine or in another process. But that is perhaps another concern and should be independent of your script execution component.

Since Lua is malleable, one can configure or manipulate the Lua virtual machine to make certain actions unlikely, such as accessing the file system. This can be achieved by setting the bound names to nil as in 7:

lua("import = nil");
lua("require = nil");

new Action(() => lua("import 'System'"))
    .ShouldThrow<Exception>();

In this little spec you can also observe what should happen (non-specifically) if there’s a Lua syntax or a runtime error. You can also see how to import assemblies into the Lua state.

Here’s another quote from the test:

lua.import("System");

Func<int> func = () => (int)lua("return Console.BufferHeight")[0];
new Action(() => func())
    .ShouldNotThrow();
func().Should().Be(Console.BufferHeight);

Without further ado

Some things should perhaps be further investigated:

  • Is dynamiclua prepared for the Mono runtime on *x platforms?
  • Is it possible to crash the process uncontrollably, even while catching exceptions?
  • Fix crash on finalization

Lua can appear simple enough, such that, given a syntactic constraint, even non-programmers could write business logic scripts and configurations. However, there is a company experimenting with alternative ways to define business logic using different approaches to a logic-definition UI. It’s worth checking out: LogicEditor.

Other language and runtime candidates will hopefully be investigated within the next posts of the quest: IronRuby and Boo. The readers of this blog entry are welcome to criticize, point out omitted or wrong information, and interact freely.

Code

https://github.com/d-led/BusinessLogicScripting

  1. Video 1, more slides, Video 2, more Roberto
  2. User scripts are software, and thus might never terminate
  3. I won’t repeat the meme about great power here
  4. as is the case with many C++ bindings i.e. LuaBridge
  5. In my opinion, access to privates should throw…
  6. see wiki: SandBoxes and Daniel Silverstone’s talk at Lua Workshop 2013 on his approach
  7. More …

ReactiveUI 6 and ViewModel Testing

Testability and ReactiveUI

ReactiveUI XAML example

In the previous articles about ReactiveUI I’ve claimed without bringing any evidence that writing ViewModels using ReactiveObjects brings about testability. While the aspects of testing Rx and ReactiveUI have been treated at length in the respective authors’ blogs linked herein, this post is intended as a quick glance for the impatient online surfer at the hello-world testing code, which has been written “post-mortem” 1 as a follow-up to the previous articles.

An update to ReactiveUI 6

Paul Betts and contributors have been busy simplifying and extending the library 2. There are some extension methods now that help creating observables from properties, and transforming observables to properties. In the example ViewModel from previous articles, there’s an observable stream of strings that is simply transformed into a property defined as follows:

ObservableAsPropertyHelper<string> _BackgroundTicker;
public string BackgroundTicker
{
    get { return _BackgroundTicker.Value; }
}

In the constructor, the helper is now initialized without using strings:

public WordCounterModel(IObservable<string> someBackgroundTicker)
{
someBackgroundTicker
    .ToProperty(this, x => x.BackgroundTicker, out _BackgroundTicker);
...
}

instead of string-based error-prone

_BackgroundTicker = new ObservableAsPropertyHelper<string>(
	someBackgroundTicker, _ => raisePropertyChanged("BackgroundTicker")
);

For the actual changes in ReactiveUI, consult Paul Betts’ insightful log.

A simple test

Since the tests have been written after writing the example code, I’ve been searching for the “Generate Unit Test” context menu in Visual Studio 2013. The context menu is not there, but luckily some enthusiasts recreated the functionality partly: → Unit Test Generator.

After the initial set-up and

failedtest

here’s the simple test of the word count property:

[TestMethod]
public void WordCounterModelTest()
{
    var mock = new Mock<IObservable<string>>();
    var vm = new WordCounterModel(mock.Object);

    vm.WordCount.Should().Be(0);

    vm.TextInput = "bla!";
    vm.WordCount.Should().Be(1);

    vm.TextInput = "bla, bla!!";
    vm.WordCount.Should().Be(2);
}

In it, one can observe the use of MOQ for mocking a dummy and FluentAssertions for beautifully readable Spec/BDD-style assertions 3.

So, there’s no UI involved, and the UI is dogmatically bound from XAML with almost no code-behind.

Testing time series

The hello world example program simulated a dependency on some timed series of strings, ticking every second. While this is not specific to ReactiveUI, let’s make use of the test scheduler 4. For that, the time series should optionally depend on an injected IScheduler:

public class BackgroundTicker
{
    IScheduler scheduler = Scheduler.Default;

    public BackgroundTicker(IScheduler other_scheduler = null)
    {
        if (other_scheduler != null)
            scheduler = other_scheduler;
    }

    public IObservable<string> Ticker
    {
        get
        {
            return Observable
                .Interval(TimeSpan.FromSeconds(1), scheduler)
                .Select(_ => DateTime.Now.ToLongTimeString());
        }
    }
}

The test instantiates a test scheduler, which is then advanced to make deterministic assertions. The code should speak for itself:

[TestMethod]
public void BackgroundTickerTest()
{
    (new TestScheduler()).With(scheduler =>
    {
        var ticker = new BackgroundTicker(scheduler);

        int count = 0;
        ticker.Ticker.Subscribe(_ => count++);
        count.Should().Be(0);

        scheduler.AdvanceByMs(1000);
        count.Should().Be(1);

        scheduler.AdvanceByMs(2000);
        count.Should().Be(3);
    });
}

Summary

passedtest

Code: https://github.com/d-led/reactiveexamples

Previous article: The WPF + ReactiveUI Refactored Version of the Responsive UI Hello World.

See also: the c++ version.

  1. as in, not within TDD
  2. which now also targets Xamarin and Windows Phone 8 and Windows Store Apps
  3. I originally intended to use SpecFlow, but the specs refused to flow frictionlessly
  4. see Intro to Rx

The WPF + ReactiveUI Refactored Version of the Responsive UI Hello World

Overview

To recapitulate, the first article in the series used Reactive Extensions (Rx) directly in Windows Forms UI logic to implement a UI with a simulated background calculation, which delivered a timestamp each second. The rest of the application was an input text box, for which, when the user inputs the text, the word count is calculated asynchronously and posted into another read-only text box.

The second article introduced a WPF version of the same UI with a viewmodel that implements the INotifyPropertyChanged interface and supplies the ticker text and the word count as bindable properties. The text being input was delivered to the viewmodel via an event converted to an observable sequence, which was used to update the TextInput property of the viewmodel. The WordCount was updated from the setter of TextInput.

The third article recreated the WPF implementation in WinForms using the same viewmodel, which is shared between the two projects. The third UI implementation introduced throttling of the TextInput changes to 0.3 seconds so that the word count is updated only when the user pauses for at least a third of a second to take a look at the result.

The Refactored WPF Version

In this article, the WPF UI is further refactored, so that the concerns are separated further. These are organized as follows:

Create a sequence of some calculation results

These are timestamps in this case, implemented as an object, providing an IObservable<string> property Ticker:

public class BackgroundTicker
{
    public IObservable<string> Ticker
    {
        get
        {
            return Observable
                .Interval(TimeSpan.FromSeconds(1))
                .Select(_ => DateTime.Now.ToLongTimeString());
        }
    }
}

The observable sequence is active, delivering a value every second.

Count words in text asynchronously and provide another property calculated in the background

This viewmodel is finally implemented using ReactiveUI:

public class WordCounterModel : ReactiveObject

The word count and the input text are ReactiveUI boilerplate:

string _TextInput;
public string TextInput
{
    get { return _TextInput; }
    set { this.RaiseAndSetIfChanged(ref _TextInput, value); }
}

ObservableAsPropertyHelper<int> _WordCount;
public int WordCount
{
    get { return _WordCount.Value; }
}

The value sequence of the background ticker is injected at construction time using its observable member. The word count and the background ticker properties are implemented using an ObservableAsPropertyHelper.
The results of the background ticker are exposed via a property:

ObservableAsPropertyHelper<string> _BackgroundTicker;
public string BackgroundTicker
{
    get { return _BackgroundTicker.Value; }
}

the helper is initialized from the constructor-supplied observable:

someBackgroundTicker
    .ToProperty(this, ticker => ticker.BackgroundTicker, out _BackgroundTicker);

And finally, the word count logic is implemented as an output property, transforming the sequence of strings into a sequence of integers:

this.WhenAnyValue(x => x.TextInput)
    .Where(x => !string.IsNullOrWhiteSpace(x))
    .Select(x => x
        .Split()
        .Where(word => !string.IsNullOrWhiteSpace(word))
        .Count())
    .ToProperty(this, vm => vm.WordCount, out _WordCount);

The throttling can be removed from the viewmodel, as the WPF 4.5 has a Delay binding property, which can be used for the same purpose on the view side, freeing the viewmodel from that concern.

Provide a Graphical UI

Now let’s look at the view. The event subscription is gone and data binding is implemented in XAML declaratively. The DataContext of the main window is initialized with an instance of the viewmodel, which is initialized with an observable from an instance of a background ticker:

ViewModels.BackgroundTicker Ticker=new ViewModels.BackgroundTicker();
ViewModels.WordCounterModel VM = new ViewModels.WordCounterModel(Ticker.Ticker);
DataContext = VM;

This instantiation can be definitely made in XAML as well, nullifying the amount of C# code for the view, as for example in the following article.

The background ticker and the word count are now bound one-way and marked asynchronous.

<TextBox ... Text="{Binding BackgroundTicker,IsAsync=True,Mode=OneWay}"></TextBox>
<TextBox ... Text="{Binding WordCount,IsAsync=True,Mode=OneWay}"></TextBox>

And finally, the binding of the input text is configured in XAML to be throttled to 300 milliseconds and bind on PropertyChanged events of the Text property of the text box:

<TextBox ... Text="{Binding TextInput, UpdateSourceTrigger=PropertyChanged, Delay=300}"></TextBox>

Source Code

https://github.com/d-led/reactiveexamples

First refactoring of the WinForms UI example

The hello world UI example started here is at first sight not optimal to demonstrate the positive effects of UI and app logic separation, since the amount of boilerplate code required to write the viewmodel without using a specialized framework is larger than the savings in the UI logic code. However, the testability of the viewmodel is granted having created the separation. The example also does not contain an explicitly defined model, apart from the “current” DateTime.

Windows Forms have bindings that understand the INotifyPropertyChanged interface, which we can recycle in the first refactoring of the WinForms example.

The complete project can be viewed on GitHub. As you will notice, the viewmodel is shared between this version and the first WPF one.

Only in the Form1_Load event handler of the form is tackled here.

The old code:

Observable.Interval(TimeSpan.FromSeconds(1))
    .ObserveOn(this)
    .Subscribe(x => textBox1.Text = DateTime.Now.ToLongTimeString());

var textChanged = Observable.FromEventPattern
    <EventHandler, EventArgs>(
    handler => handler.Invoke,
    h => textBox3.TextChanged+= h,
    h => textBox3.TextChanged-= h);

textChanged
    .ObserveOn(this) // scheduled on the Form's scheduler
    .Subscribe(x => textBox2.Text =
        textBox3.Text
        .Split()
        .DefaultIfEmpty()
        .Where(s=>s.Trim().Length>0)
        .Count()
        .ToString());

and the new one:

ViewModels.MyViewModel VM = new ViewModels.MyViewModel();

textBox1.DataBindings.Add("Text", VM, "CurrentTime");
textBox2.DataBindings.Add("Text", VM, "WordCount");

var textChanged = Observable.FromEventPattern
    <EventHandler, EventArgs>(
    handler => handler.Invoke,
    h => textBox3.TextChanged += h,
    h => textBox3.TextChanged -= h);

textChanged
    .Throttle(TimeSpan.FromSeconds(0.3))
    .ObserveOn(this)
    .Subscribe(_ => VM.TextInput = textBox3.Text);

1

Still the TextChanged event is used for the update of the viewmodel. The relevant changes are highlighted and are similar to the first WPF version. As you can see, the code is extremely similar to the WPF version.

The updated version instantiates the viewmodel, creates the bindings and subscribes the update of the viewmodel’s text. As a slight responsiveness improvement over the first two versions, the observable TextChanged events are throttled to 0.3 seconds with the idea that the word count is of no interest to the user during typing.

When the application becomes more elaborate, it’s expected that the savings become substantial, especially when using a specialized MVVM framework, such as ReactiveUI. At this stage, there is still no lifetime control of the observable’s subscriptions.

The next step is to start using ReactiveUI for the viewmodel.

  1. for a more MVVM approach, see a newer article

The WPF Version of the Responsive UI Hello World

What is lacking in the first version of the hello world example is the separation of UI and application logic. A refactored WinForms version may be the topic of a future post.

The next step in the discovery of Rx is to create a similar software using WPF. The details can be viewed in the source code, so let’s concentrate on the peculiarities. In this version, pure Rx will be used without ReactiveUI.

wpf version of ui hello world

WPF brings a possibility of total separation of UI, UI logic and application logic. A part of the application can be implemented by bindings to a viewmodel. The viewmodel has to implement the INotifyPropertyChanged interface. We’ll choose the implementation from here for the moment.

The viewmodel is defined as follows, omitting the INotifyPropertyChanged details:

public class MyViewModel : INotifyPropertyChanged
{
    //http://msdn.microsoft.com/en-us/library/ms229614.aspx details ...

    string _CurrentTime;
    public string CurrentTime
    {
        get { return _CurrentTime; }
        private set
        {
            if (value != _CurrentTime)
            {
                _CurrentTime = value;
                NotifyPropertyChanged();
            }
        }
    }

    string _TextInput;
    public string TextInput
    {
        get { return _TextInput; }
        set
        {
            if (value != _TextInput)
            {
                _TextInput = value;
                NotifyPropertyChanged();
                UpdateWordCount();
            }
        }
    }

    private void UpdateWordCount()
    {
        WordCount = TextInput.Split()
            .DefaultIfEmpty()
            .Where(s => s.Trim().Length > 0)
            .Count();
    }

    int _WordCount;
    public int WordCount
    {
        get { return _WordCount; }
        private set
        {
            if (value != _WordCount)
            {
                _WordCount = value;
                NotifyPropertyChanged();
            }
        }
    }

    public MyViewModel()
    {
        Observable.Interval(TimeSpan.FromSeconds(1))
            .Subscribe(_ => CurrentTime = DateTime.Now.ToLongTimeString());
    }
}

By using the separation the application logic becomes testable without building a UI, as the viewmodel is not dependent on System.Windows*.

The word count and the current time field can be bound to the controls by using the standard binding mechanism:

<TextBox ... Text="{Binding CurrentTime}"></TextBox>
<TextBox ... Text="{Binding WordCount}"></TextBox>

However, if we want the word count to be updated on every text change and not after focus change, we’ll have to use the TextChanged of the third text box to update the viewmodel. The update of the word count is currently implemented in the setter for the TextInput property on line 29. Using ReactiveUI this will change as well.

The configuration of the UI by code-behind looks as follows:

ViewModels.MyViewModel VM = new ViewModels.MyViewModel();
DataContext = VM;
var textChanged = Observable.FromEventPattern<TextChangedEventHandler, TextChangedEventArgs>(
    handler => handler.Invoke,
    h => textBox3.TextChanged += h,
    h => textBox3.TextChanged -= h);
textChanged.Subscribe(_ => VM.TextInput = textBox3.Text);

Compared to the first WinForms version it has two responsibilities less – the current time update logic and the word count logic, which is now in the viewmodel.

As the next step, the implementation of the viewmodel should be further simplified.

Source code can be found here.

A Responsive Windows Forms UI using Reactive Extensions

For WPF programming there is a Reactive Extensions extension called ReactiveUI. I like the idea very much, but the last time I have looked at the online documentation, it was slightly out of sync with the current version, and the examples are slightly more elaborate than hello world. I’ll have to return to ReactiveUI at a later point in time.

As it seems, many people still use WinForms. A typical Forms application contains quite a number of event handlers. What Rx promises is a declarative design of your program (UI) logic. Without getting too concerned with lifetime management of this hello world example, here it is:

Responsive WinForms using Rx

The first TextBox gets updated asynchronously with the current time, the second TextBox shows the word count of the text entered in the third TextBox. All that is defined in a single Load event handler, private void Form1_Load(…). You can get the code here.

The initialization of the logic (in Form1_Load) is as follows:

Update textBox1 with the current time asynchronously every second

Observable.Interval(TimeSpan.FromSeconds(1))
          .ObserveOn(this) // scheduled on the Form's scheduler
          .Subscribe(_ => textBox1.Text = DateTime.Now.ToLongTimeString());

No threading code needed :).

Convert an event handler into an observable and set its registration

var textChanged = Observable.FromEventPattern<EventHandler, EventArgs>
 (
  handler => handler.Invoke,
  h => textBox3.TextChanged+= h,
  h => textBox3.TextChanged-= h
 );

Subscribe to the textChanged observable in order to update the word count

textChanged
    .ObserveOn(this) // scheduled on the Form's scheduler
    .Subscribe(x => textBox2.Text =
        textBox3.Text
        .Split()
        .DefaultIfEmpty()
        .Where(s=>s.Trim().Length>0)
        .Count()
        .ToString());

That’s it. No other explicit event handlers, just these observables with lambdas.

Continued here….

Update: Since the original post, a lot has changed. ReactiveUI has a shiny new docs site, a lot of API improvements, and improved exposure.

Asynchronously access an object’s property repeatedly in C#

A question on Stackoverflow got me thinking of a beautiful way of reporting a value of an object in C# repeatedly, something like polling a sensor. Typically, polling is pull-based, but having been reading Intro to Rx for the second time lately, and being convinced of its push-base structural and syntactic eunoia, I’ve created a solution based on Rx listed below.

using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;

namespace rxtest
{
    class FrequencyMeter
    {
        Random rand = new Random();
        public int Hz
        {
            get { return 60+rand.Next(3); }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var obs = Observable.Generate<FrequencyMeter, int>(
                new FrequencyMeter(), //state
                x => !Console.KeyAvailable, // while no key is pressed
                x => x, // no change in the state
                x => x.Hz, // how to get the value
                x => TimeSpan.FromMilliseconds(250), //how often
                Scheduler.Default)
                .DistinctUntilChanged() //show only when changed
                ;

            using (var _ = obs.Subscribe(x => Console.WriteLine(x)))
            {
                var ticks = Observable.Interval(TimeSpan.FromSeconds(0.5))
                           .Subscribe(x=>Console.WriteLine("tick")); //an example only
                Console.WriteLine("Interrupt with a keypress");
                Console.ReadKey();
            }
        }
    }
}

producing an output similar to that:

Interrupt with a keypress
62
60
62
tick
61
60
tick
62
61
tick
60
62
61
tick
62

Now, with Rx available in C++ that would be interesting what will be left of the eunoia.

pathetic – A hopefully user-friendly windows tool to edit user environment variables that are semicolon-separated path lists

I’ve always wanted to clean that PATH user environment variable, but never got around doing this, hence this little tool. It has at least one bug, and it isn’t well written, but it helped me already.

Get the current source on github or the alpha version binary here.