Robert Horvick
Robert Horvick
Husband, father, geek, brewer of hoppy beers. Robert lives near Raleigh, North Carolina with his wife and 4 kids.
  • Facebook
  • Google+
  • Twitter
Adding Firebase events to the .NET client
March 28th, 2014 - 4 minute read

Version 1.0.0.2 of the Firebase .NET client library FirebaseSharp has been released and includes a significant improvement – actual events when monitoring a location.

Firebase events now fire when an item is added, removed or updated and the update is received from the streaming get operation.

Firebase Events in Action

Firebase fb = new Firebase("https://[YOUR FIREBASE URL].firebaseio.com/");
 
fb.GetStreaming("path/to/monitor", 
    added: (s, args) => AddedItem(args),
    changed: (s, args) => UpdatedItem(args),
    removed: (s, args) => RemovedItem(args));
 
 
private void AddedItem(ValueAddedEventArgs args)
{
    // process addition
}
 
private void RemovedItem(ValueRemovedEventArgs args)
{
    // process removal
}
 
private void UpdatedItem(ValueChangedEventArgs args)
{
    // process update
}

The add event includes the path and new item (json), the updated event includes the path both the new and old data, and the removed event includes only the path of the removed item.


And a sample

I mentioned a drawing sample yesterday – I have added this sample to the FirebaseSharp repo right here.

It has a few updates.

Not major changed on the surface – but meaningful ones under the covers.

The caching layer

Firebase streaming GETs don’t tell you things like “this items was removed” or “this item was updated” – rather they simply send the update to apply. To figure out what this means, you need to have a cache that represents the world as it appears to that streaming get.

So – I added a cache.

Is is a good cache? Almost certainly not. It’s a simple tree structure that approximates the JSON objects that stream back and kicks off event.

As firebase events come in, the cache updates itself as appropriate and then fires the necessary event.

I haven’t spent much time making it pretty but the basic testing is promising. It is pretty thin, makes reasonable efforts to minimize allocations, and since only the single response object ever writes to it, I can get away with serializing access to it … or I claim I can.

The drawing app shows real-time updates still occurring and some basic profiling shows that less than 1% of the drawing app time is spent managing the cache so that seems like a good starting point to me.

I could do a bit more to be aggressive about the allocations of cache nodes (reuse would be easy) but I’d rather find bugs before making it any faster.

Cached Writes?

The official Firebase clients also cache writes before synchronizing to the server. Long term I would need to do this for parity and event performance, but short-term, I’m letting server-provided events drive the cache updates.

it’s good enough for me. If it is not good enough for you … well … help out or wait until they release a proper library. :)

Firebase .NET client library
March 26th, 2014 - 7 minute read

Update: How events work has changed and the drawing app is now available as a sample on GitHub. Find out more here: http://www.roberthorvick.com/2014/03/28/firebase-events-in-the-net-client/


Firebase is one of the new-fangled application platforms. In other words, it is a REST interface over CRUD storage of JSON objects.

What is lacking, however, is a Firebase .NET API – and it ain’t getting one soon.

I’m impatient

I wanted to procrastinate try something new so I spent a few hours throwing one together. The basic idea was to provide very thin, async, wrappers in a portable .NET library.

The source code is on GitHub: https://github.com/bubbafat/FirebaseSharp

It is also a Nuget package: https://www.nuget.org/packages/FirebaseSharp/

Firebase .NET Client

Create the Firebase .NET object

Firebase fb = new Firebase(new Uri("https://dazzling-fire-1575.firebaseio.com/"));

Create the Firebase object with an auth token

string rootUri = "https://dazzling-fire-1575.firebaseio.com/";
string authToken = "YOUR FIREBASE AUTH TOKEN";
 
Firebase fb = new Firebase(rootUri, authToken);

Post Data

string path = "/path";
string data = "{{\"value\": \"Hello!\"}}";
 
string id = fb.Post(path, data);

Get Data

string jsonData = gb.Get(path);

Stream Data

Response resp = fb.GetStreaming(path, response => {
   // see https://www.firebase.com/docs/rest-api.html
   // response.Event
   // response.Payload
});
 
// resp.Dispose() !

Delete Data

fb.Delete(path);

The Big Demo

Firebase has a bunch of sample applications. One of them is a multi-user realtime drawing application.

It looks like this:

Firebase drawing sample

And if multiple browsers all connect to the same URL – they can all draw on the canvas at the same time.

So using my Firebase .NET client I made a stripped-down WPF port.

Honestly, most of the app is just converting the Firebase JSON into WPF Points, Rectangles and Brushes.

The most interesting thing is probably that the WPF UI only updates when the message comes back from Firebase. What I mean is that the MouseDown handler is this:

private readonly BlockingCollection<PaintQueue> _queue = new BlockingCollection<PaintQueue>();
 
/* skip a bunch */
 
private void PaintCanvas_OnMouseDown(object sender, MouseButtonEventArgs e)
{
    Point firebasePoint = FirebasePointFromCanvas(GetNormalizedPoint(e.GetPosition(PaintCanvas)));
    _queue.Add(new PaintQueue
    {
        Point = firebasePoint,
        Color = "000",
    });
}

Yeah, I hard-coded the color black … the point was learning about Firebase, not WPF.

Notice all I did was stick a message in a BlockingCollection? That’s basically a queue.

That’s because my background worker is doing this:

void _firebaseWorker_DoWork(object sender, DoWorkEventArgs e)
{
    // setup streaming
    _firebase.GetStreaming(string.Empty, PaintFromFirebase);
 
    // changes are queued so that the UI thread doesn't need
    // to do anything expensive
    while (true)
    {
        PaintQueue queue = _queue.Take();
 
        try
        {
            _firebase.PutAsync(string.Format("{0}:{1}", queue.Point.X, queue.Point.Y), 
                               string.Format("\"{0}\"", queue.Color)).Wait();
        }
        catch (Exception)
        {
            // This is really robust
        }
    }
}

It is just draining from the queue and sending things to Firebase.

Then when the update event comes from Firebase the streaming callback (PaintFromFirebase) gets called which ends up calling:

PaintPoint(
    NormalizedPointFromFirebase(result.path.Substring(1)), 
    GetBrushFromFirebaseColor(result.data));

Just want to see it all? I made a gist here: https://gist.github.com/bubbafat/9789791

The long and short of it is that my app looks like this:

Firebase .NET client WPF drawing app

All those pixels came from Firebase and they update in real time. See… just check this video:

Demo of Firebase and WPF playing together using the FirebaseSharp library from Robert Horvick on Vimeo.

The Case for PowerShell (Reviewed)
March 25th, 2014 - 3 minute read

The Case for PowerShell

The Case for PowerShell is a new Pluralsight course by Mark Minasi where he, not surprisingly, makes a case for PowerShell.

The very first thing I noticed about this course was that it is using a very different structure than most Pluralsight courses. Mark is presenting this live to an audience in what I assume is Ballroom A of the Schenectady Airport Hilton.

I think this approach worked well for this topic. The course is short, you could cram it into a lunch hour if you have a loose definition of “hour”. His personality and interest in the topic come through very naturally. Mark is clearly very comfortable giving this talk.

Fair Warning: there are a few bad jokes.

My Dirty Secret…

I have intentionally avoided PowerShell for years.

I’m used to the command shell and bash. I know how to do what I need. I’m resistant to change.

But then something happened… a client required PowerShell.

Their whole build environment is based around it.

Ok – fine. I can use dir, right? Indeed I can.

So let’s go and find that file RenderingEngine.cs …

PS > dir /s RenderingEngine.cs

Get-ChildItem : Cannot find path 'C:\Source\s' 
                because it does not exist.

The Hell?

They took away my dir!

For a long time I just went to the command shell (cmd /K) when I needed to do things like that.

But I’m done with that. I’ve made a commitment to not using the command shell for things like that. I’m going to learn the PowerShell way and start embracing it.

As Mark said: “learn-powershell or leave-industry”

(My) Key Lesson from The Case for PowerShell

Mark’s course really isn’t a lesson in PowerShell. He is making a case for why you should care and, along the way, teaching a few basics to make his point.

The basics I cared most about were:

  • Command Structure (verb-singularnoun)
  • Get-Command

Now that I understand the structure and I understand how to find commands, there really is no excuse for dropping back to the command shell.

It’s not about knowing all the cmdlets – it’s about knowing enough to know how to find the cmdlet you need at the moment you need it.

Yeah – basic, I know. This is Day-1 stuff.

But it’s Day 1 so cut me some slack.