In my pre­vi­ous post I used the IObservable<T>.Zip exten­sion method in the Drag-and-Drop exam­ple, which takes two observ­able col­lec­tions and runs a func­tion over them to return a new observ­able col­lec­tion of poten­tially a dif­fer­ent type.

But what if you just want to sim­ply merge the two observ­able col­lec­tions into one stream? Well, Rx API has another exten­sion method called Merge. To use it you can either invoke it as exten­sion method:

var zs = xs.Merge(ys);

or you can invoke it as sta­tic method on more than two observ­able collections:

var zs = Observable.Merge(xs, ys, us, vs);

To use the Merge method, all the observ­able col­lec­tions being merged need to be of the same type.

There are two things you should keep in mind:

1. OnCom­pleted is fired on the com­pos­ite observ­able col­lec­tion (zs) at the point the last OnCom­pleted is fired on any of the merged observ­able collections:

image

2. OnError is fired on the com­pos­ite observ­able col­lec­tion (zs) at the point the first OnError is fired on any of the merged observ­able col­lec­tions, any sub­se­quent val­ues on the merged observ­able col­lec­tion will not make it onto the com­pos­ite collection:

image

Share

As you may have read about on numer­ous MVP’s blogs already, there’s an ongo­ing research project at Microsoft’s DevLabs called Reac­tive Exten­sions for .Net (Rx) which intro­duces a push-style dual­ity (equal and oppo­site) of the tra­di­tional pull-style enu­mer­a­tion using Linq.

Erik Mei­jer gave a 30 mins intro­duc­tion to the reac­tive frame­work in this video, I highly rec­om­mend that you sit through this to help you under­stand the basics of how Rx works. In sum­mary, Rx intro­duces two main interfaces:

IObservable<T>, which rep­re­sents a push-style collection

IObserver<T>, which sup­ports push-style iter­a­tion over an observ­able sequence

Used together, they allow you to write pro­grams which reacts to inputs from the envi­ron­ment as opposed to the tra­di­tional inter­ac­tive pro­gram which asks the envi­ron­ment for input.

image

Drag-and-Drop using Rx

For a quick demo to show how you can imple­ment a Drag-and-Drop fea­ture in WPF with just a few lines of code, see this video on Channel9. Unfor­tu­nately, since the video was released, the API has changed some­what (Observable.Context is gone for exam­ple), so below is a revised ver­sion which works with the lat­est API.

To get started, down­load the Rx exten­sion for .Net 3.5 SP1 and start a new WPF appli­ca­tion in Visual Stu­dio 2008, add ref­er­ences 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 con­struc­tor to some­thing 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 lit­tle con­fus­ing, but just imag­ine how much code you’d have to write oth­er­wise to imple­ment Drag-and-Drop fea­ture using the stan­dard C# events and event han­dlers, and how messy and clut­tered that code will will look if you did! So there’s def­i­nitely ben­e­fits to be had here, and there­fore well worth the time and effort to learn more about the Rx :-)

Back to the exam­ple, let’s look a closer look at some of the meth­ods used here to help you get a sense of what’s going on.

IObservable<T>.Subscribe

If you have an observ­able col­lec­tion, xs:

IObservable<int> xs = …;

You can sub­scribe to this col­lec­tion with an IOb­server, or alter­na­tively you can use a han­dler as we did in the Drag-and-Drop exam­ple. You can actu­ally pro­vide three dif­fer­ent han­dlers to an IObservable<T> collection:

  • Action<T> val­ue­Han­dler, which gets called when a new value is received on the collection.
  • Action<Exception> excep­tion­Han­dler, which gets called when an excep­tion is caught dur­ing the iter­a­tion, if none is pro­vided, then the orig­i­nal excep­tion is sim­ply re-thrown.
  • Action com­ple­tion­Han­dler, which gets called when the iter­a­tion is fin­ished (when mouseUp is received in the exam­ple), by default this does nothing.

In the exam­ple, q was the IOb­serv­able col­lec­tion of an anony­mous type we cre­ated to hold the changes in the X and Y posi­tions between adja­cent mouse­Move events between a mouse­Down and mouseUp event. WPF stip­u­lates that changes to ele­ments must be made on the own­ing thread, and the way to ensure our han­dlers run on the own­ing thread is to first call the ObserveOnDis­patcher exten­sion method so observers are asyn­chro­nously noti­fied using the cur­rent dispatcher.

You should note that the Sub­scribe exten­sion method actu­ally returns an IDis­pos­able. If you wish to unsub­scribe from the observ­able col­lec­tion, you need to call Dis­pose() on this IDis­pos­able:

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 out­lined the four phases of exe­cu­tion in subscription:

1. Build observ­able query

var xs = ys.Select(f);

2. Sub­scribe

var s = xs.Subscribe(h);

3. Value

h();

4. Unsub­scribe

s.Dispose();

IObservable<T>.Zip

The IObservable<T>.Zip exten­sion method you see in the exam­ple above takes two streams and a func­tion and returns a new stream. So let Xs and Ys be two streams of events which need to hap­pen in pairs we can com­bine them into a new stream of events, Zs, which tells us when both Xs and its cor­re­spond­ing Ys has happened:

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

image

You should note that the order in which Xs and Ys hap­pen does not mat­ter in this case.

So back to the drag-and-drop exam­ple above, we used the Zip exten­sion method to com­bine two streams:

- mm, which trans­lates to mouseMove.StartWith(start).TakeUntil(mouseUp)

- mm.Skip(1), which trans­lates 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;

Ref­er­ences:

Rx podcasts on Channel9
Share
// 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 exam­ple with a method to check whether an IP address is local:

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

Share

To get the value of a pri­vate field of an instance in C#:

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

Sim­i­larly, you can quite eas­ily retrieve the value of a const or sta­tic field for a type, sim­ply replace BindingFlags.Instance with BindingFlags.Static and call Get­Value with null:

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

Whilst fish­ing around Stack­Over­flow for inter­est­ing dis­cus­sions I came across this ques­tion on which pro­gram­ming par­a­digm is best for which job. There were some inter­est­ing argu­ments put for­ward, and after doing some more read­ing here are the two things I took away:

Lan­guage != Paradigm

What par­a­digm (pro­ce­dural, OO or func­tional, etc.) you choose to pro­gram with does not nec­es­sar­ily equate to your lan­guage of choice. For exam­ple, C# and Java are pre­dom­i­nately asso­ci­ated with OOP because OO is the par­a­digm both are designed to cater for. How­ever, just because you’re pro­gram­ming in C# doesn’t mean you’re doing OO pro­gram­ming – you can just as eas­ily be writ­ing your pro­gram in a pro­ce­dural or func­tional style. Indeed, exten­sions such as LINQ and Post­Sharp has intro­duced func­tional pro­gram­ming and AOP to C#.

(OO vs Func­tion) vs (Dynamic vs Static)

When talk­ing about lan­guages most peo­ple think about the dif­fer­ent par­a­digms they’re asso­ci­ated with, but there is a sep­a­rate dimen­sion to be con­sid­ered – Dynamic typ­ing vs Sta­tic typ­ing. The two dimen­sions over­lap, for exam­ple, C# and Java are both OO and sta­t­i­cally typed whilst Ruby and Python are both OO and dynam­i­cally typed.

So, what do sta­tic or dynamic typ­ing mean any­way? To answer that, let me go back to the basics and revisit some of the terms com­monly used when describ­ing ‘type’s in pro­gram­ming languages:

Type

A type is a meta­data which describes the kind of data stored in a chunk of mem­ory, a type is usu­ally asso­ci­ated with a list of oper­a­tions that can be per­formed on the data (meth­ods in OOP, or func­tions in procedural).

Strong Typ­ing

Though the def­i­n­i­tion of ‘strong typ­ing’ seems to be vague and can vary depends on who you ask, but there are some com­mon themes that are con­sis­tent through all the ref­er­ence mate­ri­als I have read:

  • A strongly typed sys­tem has type check­ing and will throw an error when it finds type mis­match. When the type check­ing hap­pens depends on whether the lan­guage is sta­tic or dynam­i­cally typed, see below.
  • Once assigned, a vari­able will always behave as a cer­tain type until it is reassigned.

Both C# and Java employ a strongly typed sys­tem where all vari­ables must have a defined type, and there are restric­tion on type con­ver­sion. But inter­est­ingly, Anders Hejls­berg (lead archi­tect of the C# lan­guage) in an inter­view described strong typ­ing as some­thing that can be toned up or down as opposed to an on or off fea­ture. Here is his orig­i­nal quote from the interview:

Anders Hejls­berg — The thing you real­ize about typ­ing 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 lit­tle too vague for you, here is a nice and sim­ple test you can use:

If you can con­cate­nate a string and an int with­out cast­ing, then it’s not strongly typed.

Sta­tic Typing

In a sta­t­i­cally typed pro­gram­ming lan­guage, the types of vari­ables must be known at com­pile time. Again, both C# and Java are sta­t­i­cally typed lan­guages, though C# 4.0 would soon intro­duce sup­port for dynamic typ­ing too.

As you’ve no doubt guessed already, a sta­t­i­cally typed sys­tem are more restric­tive and there are greater over­head and effort required on the devel­op­ers’ part to deal with type mis­matches at com­pile time, there are actu­ally many rea­sons why it’s ben­e­fi­cial to you:

  • Sta­bil­ity – type errors can be caught auto­mat­i­cally by the com­piler, reduc­ing the chance of a bug slip­ping into production.
  • Readability/Maintainability – more infor­ma­tion is pro­vided about how the code is sup­posed to work, which helps future devel­op­ers (or your­self!) to under­stand the pur­pose and intended usage of a variable.
  • Bet­ter devel­oper tools – the IDE (or tools like Resharper) will not be able to pro­vide a very use­ful intel­lisense sup­port if it doesn’t know what types to expect at com­pile time.

Dynamic Typ­ing:

A pro­gram­ming lan­guage is dynam­i­cally typed if its type check­ing is per­formed at run-time. In dynamic typ­ing, types are asso­ci­ated with val­ues not vari­ables, which means the set of meth­ods and prop­er­ties you can use on a vari­able is ver­i­fied at run­time against the type of the value the vari­able cur­rently holds (see duck typ­ing).

C# 4.0 is going to include a dynamic key­word to add sup­port for dynamic typ­ing to cover some of the niche areas such as interoperability.

Part­ing thoughts…

There are a lot of con­fu­sions around the dif­fer­ent ter­mi­nolo­gies on the topic of typ­ing, so much so BC Pierce, author of “Types and Pro­gram­ming Lan­guages” said:

I spent a few weeks try­ing to sort out the ter­mi­nol­ogy of “strongly typed,” “sta­t­i­cally typed,” “safe,” etc., and found it amaz­ingly dif­fi­cult… The usage of these terms is so var­i­ous as to ren­der them almost useless.

I hope this blog post will help clear some of the con­fu­sion you have :-) And to fin­ish what I started, here’s the accepted and my favourite answer from the ques­tion which started all this:

Your choice of Par­a­digm or Model or Approach or Style is based on the answer to the fol­low­ing question:

How Can I Best Rep­re­sent This Problem?”

If the prob­lem has objects and rela­tion­ships, OO. If the prob­lem has algo­rithms and trans­for­ma­tions, maps, fil­ters and reduces, Func­tional. If the prob­lem is dynamic, chang­ing and flex­i­ble, Dynamic. If the prob­lem is sta­tic and will scale up rapidly, Static.

Fur­ther reading:

Full 8-part inter­view tran­script with Anders Hejlsberg

Stack­Over­flow ques­tion – what are the key aspects of a strongly typed language?

Stack­Over­flow ques­tion – dynamic type lan­guages ver­sus sta­tic type languages

Stack­Over­flow ques­tion – why is C# sta­t­i­cally typed?

Share