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
Firebase .NET client updated
April 21st, 2015 - 1 minute read

I updated the .NET client for Firebase to fix a bug related to async calls and synchronization contexts.

The specific case was that a user was writing an application that connected to the Nest API (which uses Firebase) and the call to GetStreaming was never firing events. While I don’t know for sure, I suspect that, in fact, the call to GetStreaming was never returning and that they were calling it from their UI thread.

The bug was that the awaits were not using ConfigureAwait(false) – which Tags:
Posted in Programming


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.