November 30, 2014

Using Firebase from a Dart client and server

In my previous post I described how I created the ChessChallenge game using Polymer and Dart. Now I will make the game a bit more interesting by storing the ten best results in a list. To persist the list I chose Firebase, which is a simple but powerful way of storing and syncing data in realtime.
Another option would have been to use MongoDB on the server, which is included at DartVoid.

Below is a picture of the communication that takes place between the Client, Server and Firebase.


For the Client I used the Dart library firebase-dart, which wraps the standard JavaScript API. The Client listens for changes to the top list in Firebase and deserializes the data into a list of Users. You can also use onChildAdded if you want to receive events for the individual elements in the list.

  var fb = new Firebase('${firebaseUrl}/toplist');
  fb.onValue.listen((event) {
    List users = event.snapshot.val();
    if (users != null) topList =
        users.map((u) => new User.fromMap(u)).toList();
  });

For the server side the easiest way to read and write data is using the Firebase REST API. The whole top list will be written using a PUT request, see below. You can also use POST if you want to add single elements to a list.

  new HttpClient().putUrl(
      Uri.parse(
          '${firebaseUrl}/toplist.json')).then((HttpClientRequest request) {
    request.headers.contentType = ContentType.JSON;
    request.write(JSON.encode(topList));
    return request.close();
  }).then((HttpClientResponse response) {
    response.transform(UTF8.decoder).listen((contents) {
      print('Stored new top list in Firebase: ${contents}');
    });
  });

Dart does not give you automatic serialization support for classes, so you need to add it yourself.
Below is the code for the User class. There are several ways you can do this without having to write this code manually, for example using annotations and library support.

class User {
  String name;
  int avatar;
  int score = 0;
  int time;

  User(this.name, this.avatar);

  User.fromMap(Map map) {
    name = map['name'];
    avatar = map['avatar'];
    score = map['score'];
    time = map['time'];
  }

  Map toJson() {
    return {
      'name': name,
      'avatar': avatar,
      'score': score,
      'time': time
    };
  }
}

I was amazed how easy it was to use Firebase for adding the top 10 list feature. Firebase also has good support for authentication and security, but I will look into that another time.

The code is available on GitHub.

November 23, 2014

Creating a multiplayer game using Dart, Polymer and WebSockets

In my previous post I described how I created a Polymer element for a chessboard and a simple app to test it.

Here, I will give a brief overview how I took this further and created a multiplayer game ChessChallenge as a more fun way of solving chess problems. The game idea is to challenge other players in being first to solve five chess problems. Below is a screenshot of the game. On the right hand you see the list of players in the competition and how many problems they have solved. The chessboard shows the current problem and you solve it by making the check-mate move.


Instead of having to manually enter the chess problems I found libraries of free PGN games from real chess tournaments on the web. To display a "mate-in-one problem" I just needed to find all games that ended with checkmate and then undo the last move. My chessboard element can load a PGN game and can undo moves so everything needed was already supported. The chess games also contained the name and ranking of the real players (displayed at the top-right in the game).

First I implemented a simple login page with the nice looking avatars taken from the Topeka Quiz App. Topeka is written in JS but it was an easy task to convert the login page into Dart. Because the UI is declaratively defined using HTML the difference is only in the logic behind the page.

Then I sketched how the communication between two clients and the server would look like when starting a challenge. The server would be responsible for keeping track of players, the on-going challenges and serve chess problems and scores in real-time.


Dart works great on the server side and has support for WebSockets so I decided to implement both the client and server in one Dart project. The game data used by the client and server can thus be shared, and the Dart Editor has great support for debugging both client and server code.

I looked at some alternatives for hosting the game and found that DartVoid had just what I needed. With great support from the DartVoid team the application was up in no time with only one extra configuration file needed in my project. With their GitHub integration it was also easy to setup and deploy the project.

This project has been a fun way of learning how to write an application using modern web techniques, and my conclusions are:

  • Using web components is a great way to build applications from reusable building blocks. 
  • Polymer makes it really simple to use web components and to set up two-way data binding between the declarative UI and the underlying logic.
  • Using the Polymer Paper elements makes it easy to design professional looking apps that works well both on mobile and desktop.
  • Dart is a really powerful language with great support for writing both client- and server-side code.

The code for ChessChallenge is available on GitHub.

November 9, 2014

Creating a chessboard element using Dart and Polymer

This will be the first part of two describing how I built a simple multi-player chess game using Dart and Polymer. It all started out during my summer vacation when going through a book of chess problems with my kids.

Although good, the book only consists of lots of these "mate-in-one" puzzles. There must be a more fun way of teaching this, like a mobile game on their iPads.

At the same time at Google I/O, the nice Material Design was announced and it was available for Dart and the Polymer framework. Finally, a great UI widget library! And Polymer is the kind of framework that I have been longing for. To be able to put together applications from existing components is the kind of reuse that makes me tick.
A quick stop at the Dart pub, and chess.dart (port of chess.js) was found. Yay! That functionality for keeping the game state, loading games from standard chess notation, ... and more, would sure come in handy.

For displaying the chessboard in the game I needed something like chessboard.js, but that wasn’t available in the pub. My first plan was to wrap the JS library, but I soon realise it would be nicer to write a cleaner version using these emerging web technologies. A chessboard tag would be great to have.

Without going into the details of my implementation chessboard.dart, here are some key benefits I found using these newer technologies:
  • Separation of presentation from logic. I was able to move most of the presentation logic from code into HTML. In the JS version the HTML is generated in JS.
  • CSS encapsulation inside the web component relieved me from having to generate unique element ids as in the JS version.
  • Clear separation between modules. There is an overlap of functionality in chess.js and chessboard.js that I could nicely clean up in the Dart implementation.
  • The chessboard.dart implementation contains roughly around 350 lines of Dart code compare to around 1200 lines of JavaScript in chessboard.js (excluding the animation support, which I didn’t need).
To demonstrate how to use the chessboard element in a Polymer application I created a simple Chessboard App. Using the Polymer core- and paper-elements, I got a mobile-friendly app in less than 100 lines of Dart code and a nice declarative HTML.




Here is an extract of how it looks like to insert the chessboard element and to data bind to some of its properties:

          <chess-board id="chess_board" on-move="{{onMove}}"></chess-board>
          <core-item id="turn" label="{{$['chess_board'].turn}} to move"></core-item>
          <core-item id="gameStatus" label="{{$['chess_board'].gameStatus}}"></core-item>

          void onMove(CustomEvent event, detail, target) {
            ChessBoard chessBoard = target;
            print('Move event, next turn is ${chessBoard.turn}');
          }

In the next part, I will show you how I continued to build upon the chessboard element to create a multiplayer “Chess challenge” game.

December 4, 2013

Dart workshop with code lab

Today I hosted a three-hour workshop/code lab with my colleagues at FindOut. I started off with a Dart Quiz as a way to see how much they knew about Dart and to get some good discussions started.

Then I showed them some of the slides from the Google I/O '13 presentation by +Justin Fagnani and +Seth Ladd, especially pointing out the improvements in syntax and standard libraries compared to JavaScript.


After that they went through the Pirate badge code lab which is so well documented that I hardly had to assist at all.

Finally, I talked about some cool things built with Dart:
The workshop was very well received and the feedback was that it was really easy to get started with web development using Dart.

June 24, 2013

Vert.x, Node.js and some reflections on performance

Four years ago Node.js was invented. It's a server-side framework with an asynchronous, event-driven programming model with non-blocking I/O using Javascript. It has become very popular in the web community since you can use Javascript and the same async programming model both on the client and server. Node.js is using the V8 Javascript VM, which has had an incredible performance since its' start (see my earlier post).

Vert.x is an alternative to Node.js that runs on the JVM. It supports the same programming model but for any JVM language (the "x" is for any language). Currently it supports Java, Groovy, Ruby, Python and Javascript, with Scala and Clojure on the roadmap. Earlier this year the Vert.x community chose the Eclipse Foundation to be its vendor-neutral home. The Eclipse Foundation changed policies so that the project could continue being hosted on GitHub, which was not possible before Vert.x came along.


Regarding the performance of Vert.x compared to Node.js, it has been shown to be faster in some benchmarks here and here.

Benchmark result from "Inside Vert.x. Comparison with Node.js"

Given that the JVM is 18 years old compared to V8's five years, it may not be so surprising. More interesting is that the original V8 designers in their Google I/O 2013 talk show that getting predictable performance for a highly dynamic language like Javascript is problematic. That's the reason why they are now working on the Dart language and VM which is already twice as fast as Javascript in some benchmarks

February 10, 2013

Jfokus 2013



Here are some of my impressions from the Jfokus conference here in Stockholm. The venue and content was better than I expected, and it was interesting to hear talks and spot trends around the Java platform. The scope was even broader than Java and the JVM, which was nice because I wanted to focus more on the web platform.

The functional programming trend is still strong and will probably be mainstream when lambda expressions comes with Java 8 this autumn. Here in Sweden Scala seems to be really popular with several talks on that subject. However, I believe pure functional programming still will be a special field since monads are too hard to understand for the average programmer.

For me the high point during the conference was seeing +Seth Ladd presenting web components and the Dart language. It was a really compelling story to see how you can create reusable web components already today. I really hope innovation prevails and that Dart will become a sane alternative to Javascript.

In the closing session, +Dan North gave a fun and thought-worthy presentation where he sought simplicity and questioned complicated architectures and frameworks. There were many takeaways, such as that I have to buy a bath duck to put next to my computer .What he didn't say is that we need to find abstractions to cope with complexity and using encapsulation is key to achieve that. Dan said he felt liberated using Javascript with Node.js because he could focus on real problems... For me it is just the other way around, I feel I have to write lots of boilerplate code on the web platform compared to when writing desktop applications on the Eclipse platform with lots of reusable components.

Until Dart and web components takes off I think I found a real interesting alternative. Our fellow Scandinavians celebrated the Vaadin 7.0 release on the way to the conference and after listening to a few talks and playing around with it, it seems to be a really productive environment. They have their own component library with over 300 reusable components to choose from, such as nice looking charts. An interesting possibility is that you can even use Scala with Vaadin. But why on earth should you be using Vaadin? Their CEO +Joonas Lehtinen explained that the reason is that you should be able to write professional looking web applications for the business with a low budget. I think that is a really good reason.

November 3, 2012

Dart - the king of speed

The web as a platform is moving at an incredible pace right now. The modern web browsers are getting better in supporting the new HTML5 standards. Javascript runs 100 times faster now compared to 2007, according to Lars Bak the designer behind V8. Rich web applications are now developed as a single-page with most of the logic on the client. The gap between web applications and traditional native desktop application is getting smaller.

Chrome V8 performance from Google IO 2012 
I have a long experience in writing large-scale applications in Java using modular and object-oriented concepts on the Eclipse Rich-Client Platform. I have used the Eclipse Modeling Framework (EMF) to generate editors from domain models, and the Graphical Editing Framework (GEF) for adding graphical editing capabilities. I am spoiled with having lots of support from the platform.

Implementing similar applications on the web platform with Javascript seems like travelling back ten years in time. There are several popular frameworks that fix some of the really bad parts of Javascript and also add support for classes and components. But, you still have to write lots of boilerplate code to support things I am used to getting from the platform.

I am quite novice when it comes to web programming, but I do have some experience with the Google Web Toolkit (GWT). It has support for both EMF and GEF, and seems like a path for writing very rich and capable web applications. The drawback with GWT is that you are stuck with Java, which is lacking many of the more modern language features such as first-class support for functions. Also, there is a compile step to Javascript which makes edit-and-continue debugging hard to achieve.

Using GWT feels like driving an old reliable Volvo. It is safe and you don't have to worry crashing . But suddenly a new fresh-looking sports-car is passing you on the street. It is looking better, has nicer features and seems faster, but maybe not as crash-safe as a Volvo yet... In this analogy the faster car is the new Dart language that Google has been working hard on for more than a year. Dart is designed from ground up to support writing large, structured and performant web applications. The Dart VM engine it is already outperforming V8 in several key benchmarks. The goal according to Lars Bak's talk at Strange Loop is to make it at least twice as fast as V8. Maybe "V16" would be an appropriate name...

I think Dart may be the platform of choice for many developers with my background. Dart is not just a new language. It has great tooling with an Eclipse-based editor, new frameworks and a package manager "pub". The VM will initially only be available in Chrome, but Dart code can be compiled to Javascript, thus supporting all modern browsers.

Lars Bak said "speed is king!". If he can deliver that, I believe Dart has a big chance of being more than just a niche language.