Linq Over Events – Playing with the Rx Framework

As you may have read about on numerous MVP’s blogs already, there’s an ongoing research project at Microsoft’s DevLabs called Reactive Extensions for .Net (Rx) which introduces a push-style duality (equal and opposite) of the traditional pull-style enumeration using Linq.

Erik Meijer gave a 30 mins introduction to the reactive framework in this video, I highly recommend that you sit through this to help you understand the basics of how Rx works. In summary, Rx introduces two main interfaces:

IObservable<T>, which represents a push-style collection

IObserver<T>, which supports push-style iteration over an observable sequence

Used together, they allow you to write programs which reacts to inputs from the environment as opposed to the traditional interactive program which asks the environment for input.

image

Drag-and-Drop using Rx

For a quick demo to show how you can implement a Drag-and-Drop feature in WPF with just a few lines of code, see this video on Channel9. Unfortunately, since the video was released, the API has changed somewhat (Observable.Context is gone for example), so below is a revised version which works with the latest API.

To get started, download the Rx extension for .Net 3.5 SP1 and start a new WPF application in Visual Studio 2008, add references to System.CoreEx and System.Reactive. In Windows1.xaml, replace the default Grid with:

<Canvas>
    <TextBlock Name="counter" Text="Rx Test"/>
    <Image Name="image"
           Source=[put the path to an image here]
           Width="100" Height="100" Canvas.Left="0" Canvas.Top="25"/>
</Canvas>

and then in the code-behind, change the constructor to something like this:

public Window1()
{
    InitializeComponent();

    // create a stream which returns a new value every second, starting from -1
    var xs = Observable.Interval(TimeSpan.FromSeconds(1)).StartWith(-1);

    // subscribe to the above stream
    xs.ObserveOnDispatcher().Subscribe(value => counter.Text = value.ToString());

    // create event streams for mouse down/up/move using reflection
    var mouseDown = from evt in Observable.FromEvent<MouseButtonEventArgs>(image, "MouseDown")
                    select evt.EventArgs.GetPosition(this);
    var mouseUp = from evt in Observable.FromEvent<MouseButtonEventArgs>(image, "MouseUp")
                  select evt.EventArgs.GetPosition(this);
    var mouseMove = from evt in Observable.FromEvent<MouseEventArgs>(image, "MouseMove")
                    select evt.EventArgs.GetPosition(this);

    // between mouse down and mouse up events
    // keep taking pairs of mouse move events and return the change in X, Y positions
    // from one mouse move event to the next as a new stream
    var q = from start in mouseDown
            from pos in mouseMove.StartWith(start).TakeUntil(mouseUp)
                         .Let(mm => mm.Zip(mm.Skip(1), (prev, cur) =>
                              new { X = cur.X - prev.X, Y = cur.Y - prev.Y }))
            select pos;

    // subscribe to the stream of position changes and modify the Canvas.Left and Canvas.Top
    // property of the image to achieve drag and drop effect!
    q.ObserveOnDispatcher().Subscribe(value =>
          {
              Canvas.SetLeft(image, Canvas.GetLeft(image) + value.X);
              Canvas.SetTop(image, Canvas.GetTop(image) + value.Y);
          });
}

This code might seem a little confusing, but just imagine how much code you’d have to write otherwise to implement Drag-and-Drop feature using the standard C# events and event handlers, and how messy and cluttered that code will will look if you did! So there’s definitely benefits to be had here, and therefore well worth the time and effort to learn more about the Rx :-)

Back to the example, let’s look a closer look at some of the methods used here to help you get a sense of what’s going on.

IObservable<T>.Subscribe

If you have an observable collection, xs:

IObservable<int> xs = …;

You can subscribe to this collection with an IObserver, or alternatively you can use a handler as we did in the Drag-and-Drop example. You can actually provide three different handlers to an IObservable<T> collection:

  • Action<T> valueHandler, which gets called when a new value is received on the collection.
  • Action<Exception> exceptionHandler, which gets called when an exception is caught during the iteration, if none is provided, then the original exception is simply re-thrown.
  • Action completionHandler, which gets called when the iteration is finished (when mouseUp is received in the example), by default this does nothing.

In the example, q was the IObservable collection of an anonymous type we created to hold the changes in the X and Y positions between adjacent mouseMove events between a mouseDown and mouseUp event. WPF stipulates that changes to elements must be made on the owning thread, and the way to ensure our handlers run on the owning thread is to first call the ObserveOnDispatcher extension method so observers are asynchronously notified using the current dispatcher.

You should note that the Subscribe extension method actually returns an IDisposable. If you wish to unsubscribe from the observable collection, you need to call Dispose() on this IDisposable:

var s = q.ObserveOnDispatcher().Subscribe(value =>
            {
                Canvas.SetLeft(image, Canvas.GetLeft(image) + value.X);
                Canvas.SetTop(image, Canvas.GetTop(image) + value.Y);
            });
// to unsubscribe
s.Dispose();

And finally, in this video, Wes Dyer outlined the four phases of execution in subscription:

1. Build observable query

var xs = ys.Select(f);

2. Subscribe

var s = xs.Subscribe(h);

3. Value

h();

4. Unsubscribe

s.Dispose();

IObservable<T>.Zip

The IObservable<T>.Zip extension method you see in the example above takes two streams and a function and returns a new stream. So let Xs and Ys be two streams of events which need to happen in pairs we can combine them into a new stream of events, Zs, which tells us when both Xs and its corresponding Ys has happened:

Zs = Xs.Zip(Ys, (a, b) -> a + b)

image

You should note that the order in which Xs and Ys happen does not matter in this case.

So back to the drag-and-drop example above, we used the Zip extension method to combine two streams:

mm, which translates to mouseMove.StartWith(start).TakeUntil(mouseUp)

mm.Skip(1), which translates to mouseMove.StartWith(start).TakeUntil(mouseUp).Skip(1)

and returns a new stream of values:

var q = from start in mouseDown
        from pos in mouseMove.StartWith(start).TakeUntil(mouseUp)
                     .Let(mm => mm.Zip(mm.Skip(1), (prev, cur) =>
                          new { X = cur.X - prev.X, Y = cur.Y - prev.Y }))
        select pos;

References:

Rx podcasts on Channel9

Working with IP addresses in C#

// get the host IP addresses
var hostIPs = System.Net.Dns.GetHostAddresses("LocalHost");

// get the local computer name
var localHostName = System.Net.Dns.GetHostName();

// get the local IP addresses
var localIPs = System.Net.Dns.GetHostAddresses(localHostName);

And here’s the full example with a method to check whether an IP address is local:

http://www.csharp-examples.net/local-ip/

How to get private, constant or static value of a field with reflection

To get the value of a private field of an instance in C#:

var actualNumberOfWinners =
    evaluator
        .GetType()
        .GetField("_numberOfWinners", BindingFlags.NonPublic | BindingFlags.Instance)
        .GetValue(evaluator);

Similarly, you can quite easily retrieve the value of a const or static field for a type, simply replace BindingFlags.Instance with BindingFlags.Static and call GetValue with null:

var constNumberOfWinners =
    evaluator
        .GetType()
        .GetField("DefaultNumberOfWinners", BindingFlags.NonPublic | BindingFlags.Static)
        .GetValue(null);

OO vs Functional vs Dynamic vs Static

Whilst fishing around StackOverflow for interesting discussions I came across this question on which programming paradigm is best for which job. There were some interesting arguments put forward, and after doing some more reading here are the two things I took away:

Language != Paradigm

What paradigm (procedural, OO or functional, etc.) you choose to program with does not necessarily equate to your language of choice. For example, C# and Java are predominately associated with OOP because OO is the paradigm both are designed to cater for. However, just because you’re programming in C# doesn’t mean you’re doing OO programming – you can just as easily be writing your program in a procedural or functional style. Indeed, extensions such as LINQ and PostSharp has introduced functional programming and AOP to C#.

(OO vs Function) vs (Dynamic vs Static)

When talking about languages most people think about the different paradigms they’re associated with, but there is a separate dimension to be considered – Dynamic typing vs Static typing. The two dimensions overlap, for example, C# and Java are both OO and statically typed whilst Ruby and Python are both OO and dynamically typed.

So, what do static or dynamic typing mean anyway? To answer that, let me go back to the basics and revisit some of the terms commonly used when describing ‘type’s in programming languages:

Type

A type is a metadata which describes the kind of data stored in a chunk of memory, a type is usually associated with a list of operations that can be performed on the data (methods in OOP, or functions in procedural).

Strong Typing

Though the definition of ‘strong typing’ seems to be vague and can vary depends on who you ask, but there are some common themes that are consistent through all the reference materials I have read:

  • A strongly typed system has type checking and will throw an error when it finds type mismatch. When the type checking happens depends on whether the language is static or dynamically typed, see below.
  • Once assigned, a variable will always behave as a certain type until it is reassigned.

Both C# and Java employ a strongly typed system where all variables must have a defined type, and there are restriction on type conversion. But interestingly, Anders Hejlsberg (lead architect of the C# language) in an interview described strong typing as something that can be toned up or down as opposed to an on or off feature. Here is his original quote from the interview:

Anders Hejlsberg – The thing you realize about typing is that it’s a dial. The higher you place the dial, the more painful the programmer’s life becomes, but the safer it becomes too. But you can turn that dial too far in either direction.

If all this seem a little too vague for you, here is a nice and simple test you can use:

If you can concatenate a string and an int without casting, then it’s not strongly typed.

Static Typing

In a statically typed programming language, the types of variables must be known at compile time. Again, both C# and Java are statically typed languages, though C# 4.0 would soon introduce support for dynamic typing too.

As you’ve no doubt guessed already, a statically typed system are more restrictive and there are greater overhead and effort required on the developers’ part to deal with type mismatches at compile time, there are actually many reasons why it’s beneficial to you:

  • Stability – type errors can be caught automatically by the compiler, reducing the chance of a bug slipping into production.
  • Readability/Maintainability – more information is provided about how the code is supposed to work, which helps future developers (or yourself!) to understand the purpose and intended usage of a variable.
  • Better developer tools – the IDE (or tools like Resharper) will not be able to provide a very useful intellisense support if it doesn’t know what types to expect at compile time.

Dynamic Typing:

A programming language is dynamically typed if its type checking is performed at run-time. In dynamic typing, types are associated with values not variables, which means the set of methods and properties you can use on a variable is verified at runtime against the type of the value the variable currently holds (see duck typing).

C# 4.0 is going to include a dynamic keyword to add support for dynamic typing to cover some of the niche areas such as interoperability.

Parting thoughts…

There are a lot of confusions around the different terminologies on the topic of typing, so much so BC Pierce, author of “Types and Programming Languages” said:

I spent a few weeks trying to sort out the terminology of “strongly typed,” “statically typed,” “safe,” etc., and found it amazingly difficult… The usage of these terms is so various as to render them almost useless.

I hope this blog post will help clear some of the confusion you have :-) And to finish what I started, here’s the accepted and my favourite answer from the question which started all this:

Your choice of Paradigm or Model or Approach or Style is based on the answer to the following question:

“How Can I Best Represent This Problem?”

If the problem has objects and relationships, OO. If the problem has algorithms and transformations, maps, filters and reduces, Functional. If the problem is dynamic, changing and flexible, Dynamic. If the problem is static and will scale up rapidly, Static.

Further reading:

Full 8-part interview transcript with Anders Hejlsberg

StackOverflow question – what are the key aspects of a strongly typed language?

StackOverflow question – dynamic type languages versus static type languages

StackOverflow question – why is C# statically typed?

Buzzword Buster – Duck Typing

The term ‘duck typing’ is often used to describe a type of dynamic typing in programming languages where the object’s current set of methods and properties determines the valid semantics.

Why?

duck test – If it looks like a duck, swims like a duck and quacks like a duck, then it probably is a duck