April 17, 2014

Chris Strom

Never Forget the Polymer.dart Transformer (No Really, NEVER Forget It)


I thought to try to finish off the Strategy Pattern chapter in Patterns in Polymer tonight. Only when I loaded some “play” code in Dartium, I saw the following error in the console:
Exception: The "smoke" library has not been configured. Make sure you import and configure one of the implementations (package:smoke/mirrors.dart or package:smoke/static.dart).
#0 throwNotConfiguredError (package:smoke/src/implementation.dart:34:3)
#1 typeInspector (package:smoke/src/implementation.dart:26:5)
#2 query (package:smoke/smoke.dart:85:20)
#3 _getPublishedProperties (package:polymer/src/declaration.dart:409:31)
#4 PolymerDeclaration.publishAttributes (package:polymer/src/declaration.dart:175:39)
#5 PolymerDeclaration.buildType (package:polymer/src/declaration.dart:95:22)
#6 PolymerDeclaration.register (package:polymer/src/declaration.dart:72:14)
#7 _hookJsPolymer.registerDart.<anonymous closure> (package:polymer/src/loader.dart:100:75)
#8 _rootRun (dart:async/zone.dart:719)
#9 _ZoneDelegate.run (dart:async/zone.dart:453)
#10 _CustomizedZone.run (dart:async/zone.dart:663)
#11 _hookJsPolymer.registerDart (package:polymer/src/loader.dart:99:22)
Are. You. FREAKING. Kidding me?!

I specifically started tonight with writing so that I could get away from that stupid error. It is the same error that has plagued my testing efforts for the past two nights and now I am seeing it application code. Noooooo!

This was some relatively old Polymer.dart code that I am upgrading to the 0.10 version of the library. So I have already gone through it to tack on component=1 to the mime types so that the Dart VM will know to run all Polymer code in the same isolate:
<polymer-element name="store-changes-load">
<template><!-- ... --></template>
<script src="store_changes_load.dart"
type="application/dart;component=1"></script>

</polymer-element>
I have already fixed the dependencies of my play application to use the appropriate bleeding-edge versions of the libraries in my pubspec.yaml file:
name: change_history
dependencies:
polymer: ">0.10.0-pre"
polymer_elements: ">0.2.0-pre"

dev_dependencies:
unittest: any
So why, oh why am I still getting “smoke” package exceptions? Well, the title of this post pretty much gives it away: since this is old code, I have not specified a Polymer pub transformer in my Dart Pub configuration. If I add it to pubspec.yaml:
name: change_history
dependencies:
polymer: ">0.10.0-pre"
polymer_elements: ">0.2.0-pre"
dev_dependencies:
unittest: any
transformers:
- polymer:
entry_points: web/index.html
Then all of my Polymer code magically starts working.

And yup, if I go back to the pubspec.yaml from last night, add my test page to the list of files that are transformed by the Polymer transformer:
name: model_example
dependencies:
polymer: ">=0.10.0-pre"
dev_dependencies:
scheduled_test: any
transformers:
- polymer:
entry_points:
- web/index.html
- test/index.html
Then my test magically passes.

Ah, life on the bleeding edge. Sometimes it does cut deep. But lesson learned: always include all pages using Polymer elements in the list of Polymer transformers—even test pages. I will never, NEVER forget that.


Day #36

by Chris Strom (noreply@blogger.com) at April 17, 2014 03:26 AM

April 16, 2014

Chris Strom

Still Can't Test Polymer.dart


I cannot believe that I can no longer test Polymer.dart elements.

This was the very first chapter that I wrote in Patterns in Polymer and now it is completely broken. Not only that, I no longer have any way to automatically determine if the code for the other chapters in the book work. Not cool.

Fortunately, this is a pre-release version of Polymer.dart (0.10), so I can hope for one of two things: (1) the library authors address this to make it easier or (2) I can figure out how to make this work as-is. There is little that I can do for (1) aside from contact that authors, though I would prefer to understand things better first—I hate to bother folks if I can figure it out on my own with a little effort. I do try a pub update, but the most recent version of Polymer.dart (that matches ">=0.10.0-pre.7") is still the same 0.10.0-pre.9 that did not work for me last night.

So it looks like I need to investigate some more. Tonight, I follow the examples laid out in the Polymer.dart test directory. There are many tests in the package, though they include templates directly in the test page and the backing classes directly in the test code. This approach is of limited value when testing custom elements, but still it is a start.

So instead of importing the <x-pizza> element that I would like to test:
<head>
<!-- Load Polymer -->
<link rel="import" href="packages/polymer/polymer.html">

<!-- Load component(s) -->
<link rel="import" href="packages/model_example/elements/x-pizza.html">


<script src="packages/unittest/test_controller.js"></script>
</head>
<body>
<!-- The actual tests -->
<script type="application/dart;component=1" src="test.dart"></script>
</body>
I instead pull the <polymer-element> from that source HTML directly into the <body> of my test page:
<head>
<link rel="import" href="packages/polymer/polymer.html">
<script src="packages/unittest/test_controller.js"></script>
</head>
<body>
<polymer-element name="x-pizza">
<template>
<!-- Template code here... -->
</template>
</polymer-element>
<polymer-element name="x-pizza-toppings">
<template>
<!-- Template code here... -->
</template>
</polymer-element>


<!-- The actual tests -->
<script type="application/dart;component=1" src="test.dart"></script>
</body>
There are actually two elements that comprise the element being tested, so I include both.

Then, in the test.dart file, I follow the Polymer.dart convention of defining the backing class directly in the test:
library x_pizza_test;

import 'dart:html';
import 'package:scheduled_test/scheduled_test.dart';
import 'package:polymer/polymer.dart';

@CustomTag('x-pizza')
class XPizza extends PolymerElement {
// ...
}

@CustomTag('x-pizza-toppings')
class XPizzaToppings extends PolymerElement {
// ...
}


@initMethod
main() {
setUp((){
schedule(()=> Polymer.onReady);
// Other setup...
});
// Tests here...
}
With that, it still does not work:
Exception: Unhandled exception:
Exception: The "smoke" library has not been configured. Make sure you import and configure one of the implementations (package:smoke/mirrors.dart or package:smoke/static.dart).
#0 throwNotConfiguredError (package:smoke/src/implementation.dart:34:3)
#1 typeInspector (package:smoke/src/implementation.dart:26:5)
#2 query (package:smoke/smoke.dart:85:20)
#3 _getPublishedProperties (package:polymer/src/declaration.dart:409:31)
#4 PolymerDeclaration.publishAttributes (package:polymer/src/declaration.dart:175:39)
#5 PolymerDeclaration.buildType (package:polymer/src/declaration.dart:95:22)
#6 PolymerDeclaration.register (package:polymer/src/declaration.dart:72:14)
#7 _hookJsPolymer.registerDart.<anonymous closure> (package:polymer/src/loader.dart:100:75)
#8 _rootRun (dart:async/zone.dart:719)
#9 _ZoneDelegate.run (dart:async/zone.dart:453)
#10 _CustomizedZone.run (dart:async/zone.dart:663)
#11 _hookJsPolymer.registerDart (package:polymer/src/loader.dart:99:22)
Bother.

I need to keep working on the chapters in Patterns in Polymer that do work, so I call it a night here. Tomorrow, I will try working with simpler Polymer elements—like those in the Polymer.dart test suite (I may even try those tests directly). If that still does not work, the Polymer.dart tests mention a test_suite.dart file that I have not yet found. Perhaps the answers I seek can be found in that file.


Day #35

by Chris Strom (noreply@blogger.com) at April 16, 2014 03:59 AM

April 15, 2014

Chris Strom

Can No Longer Test Polymer.dart Code


My tests are broken. Again. Time to fix my tests.

Actually, I have tests that have not passed for months at this point. Tonight, I am just going to fix the test that broke in the last 4 days (since I upgraded to Polymer.dart). Hmmm... this might not bode well for a solid test suite for Patterns in Polymer. I'll save that for another day. For now, I just want to get one Polymer element under test...

The first thing that I need to change is the no-longer-used initPolymer() from my test setup:
library x_pizza_test;

import 'package:scheduled_test/scheduled_test.dart';
import 'package:polymer/polymer.dart';


main() {
initPolymer();

// DOM element to hold test element
PolymerElement _el;
// Page object for better testing
XPizzaComponent xPizza;

// Tests here...
}
After deleting that line, I need another way to start the Polymer platform in my tests. In application code, this is now done with a <link> import, so I add that to the test page that holds my browser tests:
<head>
<!-- Load Polymer -->
<link rel="import" href="packages/polymer/polymer.html">


<!-- Load component(s) -->
<link rel="import" href="packages/model_example/elements/x-pizza.html">
<script type="application/dart" src="test.dart"></script>
<script src="packages/unittest/test_controller.js"></script>
</head>
With that, I get a nice failing test:
FAIL: [defaults] it has no toppings
Caught ScheduleError:
| Class 'HtmlElement' has no instance method 'async'.
|
| NoSuchMethodError: method not found: 'async'
| Receiver: Instance of 'HtmlElement'
| Arguments: [Closure: (dynamic) => dynamic]
I think this is an indication that Polymer has not finished initializing when the test runs. The async() method on Polymer elements is something of a cure-all when it comes to dealing with the asynchronous nature of Polymer elements. It updates all observed variables in the associated Polymer and tells the polyfilled platform to flush—to process all queued UI updates. Since this is failing—and failing on an HtmlElement element instead of a PolymerElement—it seems likely that I need to wait for Polymer… to be ready.

I have to confess that I am unsure how to check for Polymer to be ready in Dart. In JavaScript, it is done by listening for a polymer-ready event, so I create a scheduled_test (unittest suped up for async) schedule to listen for polymer-ready:
main() {
PolymerElement _el;
XPizzaComponent xPizza;

setUp((){
schedule((){
var _completer = new Completer();
document.body.on['polymer-ready'].listen((_){
_completer.complete();
});
return _completer.future;
});

// More setup...
});
// Tests here...
}
That seems to work. At least it changes the error message, which I count for progress.

The error message is now the Dart VM complaining about two main() entry points:
Dartium currently only allows a single Dart script tag per application, and in the future it will run them in separtate isolates.  To prepare for this all the following script tags need to be updated to use the mime-type "application/dart;component=1" instead of "application/dart":

Error:

http://localhost:8081/:-1:
Only one Dart script tag allowed per document
Taking the advice the error message, I make my test part of the web component isolate with the mime type of application/dart;component=1:
<head>
<!-- Load Polymer -->
<link rel="import" href="packages/polymer/polymer.html">

<!-- Load component(s) -->
<link rel="import" href="packages/model_example/elements/x-pizza.html">
<script src="packages/unittest/test_controller.js"></script>
</head>
<body>
<!-- The actual tests -->
<script type="application/dart;component=1" src="test.dart"></script>

</body>
That still does not work. The error message is now a baffling:
Exception: Unhandled exception:
Exception: The "smoke" library has not been configured. Make sure you import and configure one of the implementations (package:smoke/mirrors.dart or package:smoke/static.dart).
#0 throwNotConfiguredError (package:smoke/src/implementation.dart:34:3)
#1 typeInspector (package:smoke/src/implementation.dart:26:5)
#2 query (package:smoke/smoke.dart:85:20)
#3 _getPublishedProperties (package:polymer/src/declaration.dart:409:31)
#4 PolymerDeclaration.publishAttributes (package:polymer/src/declaration.dart:175:39)
#5 PolymerDeclaration.buildType (package:polymer/src/declaration.dart:95:22)
#6 PolymerDeclaration.register (package:polymer/src/declaration.dart:72:14)
#7 _hookJsPolymer.registerDart. (package:polymer/src/loader.dart:100:75)
#8 _rootRun (dart:async/zone.dart:719)
#9 _ZoneDelegate.run (dart:async/zone.dart:453)
#10 _CustomizedZone.run (dart:async/zone.dart:663)
#11 _hookJsPolymer.registerDart (package:polymer/src/loader.dart:99:22)
Ya know, if every time the library changes it takes me a hour of fiddling to get a single test passing, then I really have no hope of testing the Dart version of the book. But test I must, so...

I will have to pick back up with this tomorrow.



Day #34


by Chris Strom (noreply@blogger.com) at April 15, 2014 03:59 AM

April 13, 2014

Diving into Dart

Dart 1.3 Released

Another big performance jump for Dart - this time on the server.



"Dart News & Updates: Dart 1.3 dramatically improves server-side perform...: With Dart SDK 1.3, we’ve improved performance of async code running in the Dart VM and made substantial improvements to dart:io."



It has been a while since this blog covered server side code - hope to have a sample up soon covering a simple app.

by Davy Mitchell (noreply@blogger.com) at April 13, 2014 07:13 AM

April 12, 2014

Chris Strom

Binding JSON to Polymer Attributes


So how do you pass list data into a Polymer element?

I was pretty darn certain that starting with a smaller <x-pizza-toppings> element in the model driven view chapter of Patterns in Polymer would be brilliant. And then I tried using it.

Adding it the page works just fine:



But this was originally meant to be a composable, internal-only element for use in a whole pizza builder element, <x-pizza>. To ensure that all topping elements (first half, second half, whole pizza) used the same list of ingredients, I created the list in <x-pizza>:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
final List ingredients = [
'pepperoni',
'sausage',
'green peppers'
];

// ...
}
And then bound that variable to all instances of <x-pizza-toppings> in the corresponding template:
<link rel="import" href="x-pizza-toppings.html">
<polymer-element name="x-pizza">
<template>
<!-- ... -->
<x-pizza-toppings id="firstHalfToppings"
name="First Half Toppings"
ingredients="{{ingredients}}"></x-pizza-toppings>
<!-- ... -->
</template>
<script type="application/dart;component=1" src="x_pizza.dart"></script>
</polymer-element>
But how do you do that from the outside when you don't have a List, Array or Object? How can I bind a list of strings (the ingredients) to the ingredients attribute of <x-pizza-toppings>?

I may have found the answer by accident three nights ago. While fiddling with Polymer.dart JavaScript interoperablity, I found that the only way to make certain things work was to bind attributes as JSON instead of native programming types. Perhaps that will work here?
      <x-pizza-toppings
ingredients="['pepperoni', 'sausage', 'green peppers']">
</x-pizza-toppings>
And indeed that does work:



Cool! But does it work in the JavaScript version of Polymer as well? Yup:



It makes sense that Polymer would behave this way, but it is good to have confirmation. I cannot find any documentation for this behavior, but binding JSON seems a reasonable thing to do. And, since it behaves like this in both Dart and JavaScript, it seems safe to use this feature.

So, phew! I can finish off the MDV chapter rewrite without any further worries. Well, until I try the next easy thing...


Day #32

by Chris Strom (noreply@blogger.com) at April 12, 2014 10:47 PM

April 11, 2014

Dartlang

Dart plugin for IntelliJ IDEA and WebStorm

The Dart plugin for IntelliJ IDEA-based IDEs, has a new release with important enhancements. Notably, the plugin is now compatible with all versions of IntelliJ IDEA, including IDEA 13.1 Community Edition—the free open-source version of IntelliJ IDEA. This means you can get a version of the IntelliJ IDE with Dart auto-completion, code validation, package management, quick fixes, navigation, and full-featured command-line app debugging for free!

Pub Integration

The Dart plugin features rich pub integration. The pub tool commands get, upgrade, and build are available by context-clicking the pubspec.yaml file.


Configuring the SDK

When creating a new Dart project with the project wizard or starting a Dart project in the IDE for the first time, you’re asked to set up the path to Dart SDK. If the SDK was downloaded together with Dart Editor, the path to Dartium is added automatically. You can configure command-line options and a custom user data directory for Dartium.


With the path to Dartium set, a single click opens your Dart web app.


Debugging in Dartium

Debugging Dart web apps in WebStorm and IntelliJ IDEA Ultimate is the same. Select “Debug file” or “Create new debug configuration” and the IDE automatically connects to Dartium and starts a debug session. When prompted to install the JetBrains IDE support plugin for the browser, say yes and you’re good to go.




Find more about IntelliJ IDEA’’s Dart support by reading the JetBrains docs.

Stay tuned for a new build of the plugin that includes the latest dart analyzer (1.3.0), improved support for custom package roots, and miscellaneous fixes. We’re making good progress, and you can see our recent fixes. Also note that the plugin itself is open source and we greatly appreciate your feedback, in either the issue tracker or the IntelliJ IDEA development forum. Thanks!

Authored by Ekaterina Prigara (JetBrains) and Phil Quitslund (Google)

by Kevin Moore (noreply@blogger.com) at April 11, 2014 07:29 PM

April 10, 2014

Patrice Chalin

Defining equality (==) and hashCode for a Dart Class

By default, Object equality (Object.==) in Dart is implemented via a call to identical(). As most of you know, if you override a class's equality operator you should also override hashCode. Because Dart's int type is of arbitrary precision, concerns have been raised about the most appropriate algorithm to use so that correct behavior is preserved, even when Dart is compiled to JavaScript.  Enter the Quiver package, reminiscent of the Java Guava libraries, but for Dart. In particular, the Quiver core has convenient helper functions hash2(a,b), hash3(a,b,c), etc.

Here is an example equality and hashCode defined for a simple Person class:
import 'package:quiver/core.dart';

class Person {
String name;
int age;

Person(this.name, this.age);

bool operator ==(o) => o is Person && o.name == name && o.age == age;
int get hashCode => hash2(name.hashCode, age.hashCode);
}
A few notes about implementations of equality:
  • Generally speaking, the evaluation rules for the equality operator guarantee that the operand, o, can never be null.
  • Dart's dynamic type system (with optional type annotations) allows us to write a compact definition for equality. This would have to be more verbose (in particular involving a typecast) in a statically typed language.
For details about identical() see the Dart Language SpecificationObject Identity section.

by Patrice Chalin (noreply@blogger.com) at April 10, 2014 09:08 PM

April 09, 2014

Dartlang

Dart 1.3 dramatically improves server-side performance

With Dart SDK 1.3, we’ve improved performance of async code running in the Dart VM and made substantial improvements to dart:io. This results in some of our experimental HTTP benchmarks now running at more than twice the speed of the previous release. We continuously track these benchmarks on the new Dart I/O performance page.

In the Dart Editor, “Run as JavaScript” now uses pub serve, which serves your web app’s assets and does code transformations using a development server built into pub. This makes your development workflow faster and more streamlined.

For users of AngularDart we have other good news in store: the Dart Editor now has support for Angular code completions and improved Angular analysis and refactoring support. Building web apps using Dart and Angular just got even more productive!

You can download Dart 1.3 from the Download Dart page. If you are running the Dart Editor, you can update by checking "About Dart Editor". Don’t forget to tell us what you build with Dart in our Google+ community!

by Anders Thorhauge Sandholm (noreply@blogger.com) at April 09, 2014 02:23 PM

April 01, 2014

Diving into Dart

Conway's Game Of Life

The classic computer simulation of Conway's Game of Life, still seems to be popular with programmers. It is not so much a game as a simulation. The action takes place of a grid with a selection of them being populated with cells. The grid is then updated to the next generation of cells. Cells make it to next generation based on a few rules such as number of neighbours. New cells can also be born. End result it a captivating pattern and repeated sequences of movement that has been used to produce music and video games.

I have stumbled across (and covered in this blog) Dart versions such as this one and this one. Rosetta Code provides src to another Dart version (as well as other languages).

Background to Conway's Game of Life is covered in this wikipedia article. The original article from Scientific American can be found here.

Here's the Diving Into Dart version! Of course, it had to be colourful so cells of different ages are shaded. This still looked a bit plain so I added 4 cultures of cells to the same display. To vary things still, the number of iterations is used too and my cells are round rather than square.

Live version is here and the source is here. Have a great game of life!

by Davy Mitchell (noreply@blogger.com) at April 01, 2014 05:41 PM

March 30, 2014

Kevin Moore

Wanted: Hacker to port Pop, Pop, Win! to StageXL


tl;dr: Want an interesting Dart project? Port Pop, Pop, Win! to StageXL. If you do a good job, you're code will get into the Dart SDK.

When I wrote Pop, Pop, Win! I hacked together an HTML Canvas graphics library into bot_web. The library – bot_retained – did everything I needed, but I really haven't done much with it in over a year.

In the mean time, StageXL has been going nuts. It supports rendering to Canvas and WebGL. It supports Texture Packer. Bernhard has been keeping it fresh.

I'm actively trying to cleanup a bunch of little projects I've built over the last couple of years. Deprecating my own retained graphics library and moving folks towards StageXL seems like goodness.

Interested in doing the port?

The source code for PPW now lives in the Dart SDK. I'd suggest doing a copy-paste of the project into a new Git repository and starting there. The graphics bits are pretty well isolated. If you're pretty serious and can show that you've made a stab, I'm happy to offer help.

Dig in. Send me a link to your project on GitHub if you make progress or hit any bumps.

Happy hacking!

by Kevin Moore (noreply@blogger.com) at March 30, 2014 05:29 AM

March 28, 2014

Adam Coding @ Github

Getting started with Google Cloud Datastore and Dart

NOTE: Experimental and future developments with Dart+GCE+Datastore may change

Before running through the steps below, make sure that:

In order to make API calls to the Datastore, pubspec.yaml file needs the following

1
2
3
dependencies:
  google_oauth2_client: '>=0.3.6 <0.3.7'
  google_datastore_v1beta2_api: ">=0.4.0 <0.5.0"

Then, get the dart_datastore_example sample:

1
2
3
git clone https://github.com/financeCoding/dart_datastore_example.git
cd dart_datastore_example
pub install

If you are not connected to a Compute Engine instance, make sure to run the following commands (in a bash-like shell):

1
2
3
4
5
6
7
8
9
10
# convert the .p12 private key file to a .pem file
# if asked to enter import password, use "notasecret"

openssl pkcs12 -in <privatekey>.p12 -nocerts -passin pass:notasecret -nodes -out <rsa_private_key>.pem

# configure your credentials
export DATASTORE_SERVICE_ACCOUNT=<service-account>
export DATASTORE_PRIVATE_KEY_FILE=<path-to-pem-file>
export CLOUD_PROJECT_ID=<project-id>
export CLOUD_PROJECT_NUMBER=<project-number>

Alternatively the sample allows for passing parameters via commandline:

1
2
3
4
5
cd dart_datastore_example
pub install
cd bin
# dart dart_datastore_example.dart <project-id> <project-number> <path-to-pem-file> <service-account>
dart dart_datastore_example.dart dartcloud 657648630269 privatekey.pem 657648630269-ge2he8e46y4u42bd89nmgtj52j3ilzvv@developer.gserviceaccount.com

Example output on first run:

1
2
3
4
5
6
dartcloud
657648630269
privatekey.pem
657648630269-ge2he8e46y4u42bd89nmgtj52j3ilzvv@developer.gserviceaccount.com
did not found entity
> entity = {question: {"stringValue":"Meaning of life?"}, answer: {"integerValue":42}}

Example output on second run:

1
2
3
4
5
6
dartcloud
657648630269
privatekey.pem
657648630269-ge2he8e46y4u42bd89nmgtj52j3ilzvv@developer.gserviceaccount.com
found entity = {"key":{"partitionId":{"datasetId":"s~dartcloud"},"path":[{"kind":"Trivia","name":"hgtg"}]},"properties":{"question":{"stringValue":"Meaning of life?"},"answer":{"integerValue":42}}}
> entity = {question: {"stringValue":"Meaning of life?"}, answer: {"integerValue":42}}

The comments in the sample’s source explain its behavior in detail:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import "dart:io";

import "package:google_oauth2_client/google_oauth2_console.dart";
import "package:google_datastore_v1beta2_api/datastore_v1beta2_api_client.dart"
    as client;
import "package:google_datastore_v1beta2_api/datastore_v1beta2_api_console.dart"
    as console;

void main(List<String> args) {
  Map<String, String> envVars = Platform.environment;
  String projectId = envVars['CLOUD_PROJECT_ID'] == null ?
      args[0] : envVars['CLOUD_PROJECT_ID'];
  String projectNumber = envVars['CLOUD_PROJECT_NUMBER'] == null ?
      args[1] : envVars['CLOUD_PROJECT_NUMBER'];
  String pemFilename = envVars['DATASTORE_PRIVATE_KEY_FILE'] == null ?
      args[2] : envVars['DATASTORE_PRIVATE_KEY_FILE'];
  String serviceAccountEmail = envVars['DATASTORE_SERVICE_ACCOUNT'] == null ?
      args[3] : envVars['DATASTORE_SERVICE_ACCOUNT'];

  print(projectId);
  print(projectNumber);
  print(pemFilename);
  print(serviceAccountEmail);

  String iss = serviceAccountEmail;
  String scopes = 'https://www.googleapis.com/auth/userinfo.email '
      'https://www.googleapis.com/auth/datastore';
  String rsa_private_key_file = new File(pemFilename).readAsStringSync();

  ComputeOAuth2Console computeEngineClient = new ComputeOAuth2Console(
      projectNumber, privateKey: rsa_private_key_file, iss: iss, scopes: scopes);

  console.Datastore datastore = new console.Datastore(computeEngineClient)
  ..makeAuthRequests = true;

  // Create a RPC request to begin a new transaction
  var beginTransactionRequest = new client.BeginTransactionRequest.fromJson({});
  String transaction;
  client.Key key;
  client.Entity entity;

  // Execute the RPC asynchronously
  datastore.datasets.beginTransaction(beginTransactionRequest, projectId).then(
      (client.BeginTransactionResponse beginTransactionResponse) {
    // Get the transaction handle from the response.
    transaction = beginTransactionResponse.transaction;

    // Create a RPC request to get entities by key.
    var lookupRequest = new client.LookupRequest.fromJson({});

    // Create a new entities by key
    key = new client.Key.fromJson({});

    // Set the entity key with only one `path_element`: no parent.
    var path = new client.KeyPathElement.fromJson({
      'kind': 'Trivia',
      'name': 'hgtg'
    });
    key.path = new List<client.KeyPathElement>();
    key.path.add(path);
    lookupRequest.keys = new List<client.Key>();

    // Add one key to the lookup request.
    lookupRequest.keys.add(key);

    // Set the transaction, so we get a consistent snapshot of the
    // entity at the time the transaction started.
    lookupRequest.readOptions = new client.ReadOptions.fromJson({
      'transaction': transaction
    });

    // Execute the RPC and get the response.
    return datastore.datasets.lookup(lookupRequest, projectId);
  }).then((client.LookupResponse lookupResponse) {
    // Create a RPC request to commit the transaction.
    var req = new client.CommitRequest.fromJson({});

    // Set the transaction to commit.
    req.transaction = transaction;

    if (lookupResponse.found.isNotEmpty) {
      // Get the entity from the response if found
      entity = lookupResponse.found.first.entity;
      print("found entity = ${entity.toString()}");
    } else {
      print("did not found entity");
      // If no entity was found, insert a new one in the commit request mutation.
      entity = new client.Entity.fromJson({});
      req.mutation = new client.Mutation.fromJson({});
      req.mutation.insert = new List<client.Entity>();
      req.mutation.insert.add(entity);

      // Copy the entity key.
      entity.key = new client.Key.fromJson(key.toJson());

      // Add two entity properties:

      // - a utf-8 string: `question`
      client.Property property = new client.Property.fromJson({});
      property.stringValue = "Meaning of life?";
      entity.properties = new Map<String, client.Property>();
      entity.properties['question'] = property;

      // - a 64bit integer: `answer`
      property = new client.Property.fromJson({});
      property.integerValue = 42;
      entity.properties['answer'] = property;

      // Execute the Commit RPC synchronously and ignore the response:
      // Apply the insert mutation if the entity was not found and close
      // the transaction.
      return datastore.datasets.commit(req, projectId);
    }
  }).then((client.CommitResponse commitResponse) =>
      print("> entity = ${entity.properties}"));
}

With this example, you learned how to use the:

Now, you are ready to learn more about the Key Datastore Concepts and look at the JSON API reference.


Example deployment and startup scripts for GCE with Dart

setup-instance.sh script creates the node with the right correct scopes and image.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/env bash
set +o xtrace

USER=$USER
PROJECT=dart-compute-project
INSTANCE_NAME=dart-compute
TAGS=dart
MACHINE_TYPE=f1-micro
NETWORK=default
IP=ephemeral
IMAGE=https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140318
SCOPES=https://www.googleapis.com/auth/userinfo.email,https://www.googleapis.com/auth/compute,https://www.googleapis.com/auth/devstorage.full_control,https://www.googleapis.com/auth/datastore
PERSISTENT_BOOT_DISK=true
AUTO_DELETE_BOOT_DISK=true
ZONE=us-central1-b
STARTUP_SCRIPT=startup-script.sh
GCUTIL="gcutil --service_version=v1 --project=$PROJECT"

$GCUTIL addinstance $INSTANCE_NAME --tags=$TAGS --zone=$ZONE --machine_type=$MACHINE_TYPE --network=$NETWORK --external_ip_address=$IP --service_account_scopes=$SCOPES --image=$IMAGE --persistent_boot_disk=$PERSISTENT_BOOT_DISK --auto_delete_boot_disk=$AUTO_DELETE_BOOT_DISK --metadata_from_file=startup-script:$STARTUP_SCRIPT

rc=$?
if [[ $rc != 0 ]] ; then
  echo "Not able to add instance"
    exit $rc
fi

startup-script.sh script that provisions the node with dart.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env bash

# Add an addtional source for the latest glibc
sudo sed -i '1i deb http://ftp.us.debian.org/debian/ jessie main' /etc/apt/sources.list

# Update sources
sudo apt-get update

# Download latest glibc
sudo DEBIAN_FRONTEND=noninteractive apt-get -t jessie install -y libc6 libc6-dev libc6-dbg git screen unzip vim

# Download the latest dart sdk
wget http://storage.googleapis.com/dart-archive/channels/dev/release/latest/sdk/dartsdk-linux-x64-release.zip -O dartsdk-linux-x64-release.zip 

# Unpack the dart sdk
unzip -d / dartsdk-linux-x64-release.zip

# Make the sdk readable
chmod -R go+rx /dart-sdk

# Add dart bin to global path
echo "export PATH=\$PATH:/dart-sdk/bin" >> /etc/profile

March 28, 2014 09:38 PM

Kevin Moore

Tracking changes to PART of the Dart SDK

For historical reasons, the Dart project uses Subversion for source control.

There are a few folks who would like to use Git for the project, including me, but it's not the top of our priority list.

You can get some of the benefits of Git by looking at or even cloning our GitHub mirror.

One of my favorite uses: tracking changes to an individual package.

Steps

1 - Navigate to a package of interest, say unittest.

2 - Click on the History link.

3 - Notice that kevmoo has been making a lot of changes lately.

This is a great way to see what changes have happened since the latest release of a package or just to track individual parts of the Dart project.

Nice, huh?

by Kevin Moore (noreply@blogger.com) at March 28, 2014 04:23 PM

March 25, 2014

Kevin Moore

Dart Package Devs: Put version constraints in your pubspec

tl;dr

  • Update: this guidance is specific Dart packages. I'll write about Dart apps soon.
  • Read about the Pub Versioning Philosophy.
  • If your package uses new features in the SDK or packages, make sure you set an inclusive minimum version constraint – >= X.Y.Z – to avoid breaking folks who have not yet upgraded.
  • Set exclusive maximum version constraints – <X.Y.Z – to make sure major releases of the SDK and packages don't break your code.
  • Understand how pre-v1.0 are versioned with regard to breaking changes.
  • Take a look at pubspec files in our SDK to understand how we handle versioning. Example: http package pubspec.yaml.

New features and minimum version constraints

Dart v1.3 is coming soon. String has learned a few tricks since v1.2, specifically:
  • String padLeft(int newLength, String padding)
  • String padLeft(int newLength, String padding)
  • String trimLeft()
  • String trimRight()
Awesome, right? I can imagine package authors doing the following:
  1. Download Dart 1.3 Editor and SDK
  2. Replace all internal hacks with new String functions.
  3. Release?
No! #3 should be: Update your pubspec.yaml.

pubspec.yaml content

In the Dart Editor

Setting the minimum SDK to 1.3.0 tells the pub tools and your users the users that a package requires at least v1.3 of the Dart SDK. Better to get an error from pub install or pub update than to get static warnings or runtime errors about missing functions.

You'll also notice more than just an inclusive minimum SDK constraint – >=1.3.0 – there's also an exclusive maximum SDK constraint – <2.0.0.

Our promise it to follow semantic versioning for the SDK and our shipped packages. The short version:
  • For a version X.Y.Z
  • Increases to Y indicate new features, but no breaking changes.
  • Increases to X indicate breaking changes.
It should be safe to set your maximum SDK version to be any release up to, but not including, v2.0.

Packages and pre-v1.0

The same applies to packages managed by the Dart team, like unittest, args, path, etc.

We have a number of packages that are pre-v1.0 – unittest is a great example.

unittest is one of our oldest and most used packages. We'd really like to lock it down and clean it up before releasing something we consider v1.0. 

If you look at the changelog for unittest, you'll see a number of breaking changes between v0.9.2 and v0.10.0.

For pre-v1.0 packages, we bump the versioning logic up a level, so for version 0.Y.Z, changes to Y are breaking and changes to Z are non-breaking.

Look again at the changelog for unittest. You'll see a number of features marked as DEPRECATED. These are things that will likely go away – stop working – in v0.11.0 of unittest.

If you want to make sure you code does not suddenly break, you should set a version constraint on unittest of something like >=0.10.0 <0.11.0.

Am I missing new hotness?

A lot of folks dislike setting maximum version constraints.

I always want to be running the new hotness!

I don't want to miss out on new features!

pub upgrade is your friend.

If you run pub upgrade from the console or within the Dart Editor, you'll see useful hints when there are newer versions of packages than what you currently specify.


You can then carefully update and check version constraints before you release.

If you want to visualize a complex package with many dependencies, check out pubviz.

Happy hacking!

by Kevin Moore (noreply@blogger.com) at March 25, 2014 07:15 PM

Angulardart

AngularDart release 0.9.10 (llama-magnetism)

AngularDart release v0.9.10 llama-magnetism is now available!


As a new comer to the Angular.Dart team I (Victor Berchet) had the privilege to prepare the release yesterday. Believe it or not I did manage to get about the all the steps wrong. Hopefuly Pavel and James where here to help. That’s great to be on a team with such nice, helpful and patient co-workers!


In addition to perfomance tweaks and a bunch of bug fixes this releases add support for parsers and formatters in NgModel, on-* style events and introduces the new tagging compiler.

The tagging compiler will allow us to do faster instantiation by using CSS selectors to find nodes rather then by walking the cloned tree. It also opens open the possibility of precompiling the templates on the server.

As always, for full details of this release, please see the changelog.

Thanks to everyone who contributed PRs for this release: Ando Yasushi, Chirayu Krishnappa, James deBoer, Kasper Lund, Marko Vuksanovic, Matias Niemelä, Misko Hevery, Patrice Chalin, Paul Rohde, Pavel Jbanov, Victor, John Coleman, Naomi Black

by Misko (noreply@blogger.com) at March 25, 2014 03:56 AM

March 21, 2014

Matt Butler

Dart Front and Back

I’ve been asked to describe/talk about my current setup involving Dart at work. In order to properly do that, I need to provide a little background information as to where I work, what I do, and what I started with.

I work at an ISP. Our company is small enough that I can take certain liberties in how I accomplish my task or goal, and yet large enough that those tasks and goals are constantly shifting. Early on I started in the technical support department, and having some programming experience I was provided with the opportunity to help maintain some of our internal web applications.

Without getting into all the details of my employment history here, I am now a System Administrator and Programmer. I’m not the only System Administrator, but I still do deal with things like customer email accounts, keeping services up-to-date, customer web space, etc. I also am the primary developer for many/most of the in-house tools.

When I first started working on the internal web applications, everything was written in PHP and totally server side. Most of the code had been touched by at least 3 other individuals before me. I know it was at least that many, because there was no project coding standard so it was clear to tell where one developer started and another took over.

Due to the nature of my tasks with maintaining the code, as the others appeared to have, it was always secondary to my primary work (manning the phones originally). So it was always just small patch jobs, sometimes patching the patches. They never received the attention they needed to be completely re-written.

Eventually my job role changed towards more System administration, and then as my boss realized how quickly and efficiently I could script, to write custom scripts to either parse, aggregate, or collect data. Initially I continued to use the resources that were already in place, and most of my work was done with PHP. Most of these scripts were only one time use, or maybe used once a week by only one individual. It wasn’t vital that they look pretty so long as they worked.

One project eventually arouse that would be used by all of the current technical support and customer service departments. Something that hand to be a little more rich and immersive to the users than just a plain vanilla page. This was my start on client-side scripting to provide a much more rich and responsive interface. The project was originally written with jQuery and still runs to this day (though plans on that changing soon, more on that later). The backend was still handled in PHP, which worked pretty well for pulling data from the database and just dumping it as text for an ajax response.

While I enjoyed the client-side work, I was never completely happy working with Javascript in general an while jQuery helped some it still felt awkward in some situation. When I first heard of Dart even before it was released (the infamous leaked internal memo on Dash), my curiosity was peaked and I couldn’t wait to see what Google had to offer. When the result of their efforts was eventually released, and I saw the size of initial compiled Javascript I was a little disappointed.

I continued with jQuery for several more months after the release of Dart, but I did keep my eyes on Dart and pretty quickly the compiled JavaScript sizes came down significantly. I started playing with the language more and more, and eventually even started contributing back to the project. My first patch landing prior to the M1 release of Dart. Simultaneously I started using Dart on internal projects as well.

My first launched Dart project was implementing a web page which is broadcasted to all of our customers via CATV. It was a very simple project all-in-all, just hourly reloading an ajax stream of news and automatically scrolling it. It was first deployed May 7th, 2012 and has been running since (only a few minor updates to add new functionality). The backend in use was once again PHP.

Since that time, all my internal apps have used Dart on the front end and PHP on the backend (if required at all, some were purely client-side apps). Dart has always provided me with a great editor, type checking sanity and a comfortable and familiar language with class based inheritance and scoping I understood immediately. Eventually when Futures and Streams came and relieved me from callback hell I was so happy. Polymer and AngularDart have since made even my HTML markup efficient and work for me.

But on the backend, I’ve always had Apache and PHP running. And truthfully, they’ve always been heavier than what I really need. Most of my apps have very limited number of users. Anytime a new project would come up, I’d either tack it into a subfolder of an existing project or spin up a new VM with Apache, PHP and MySQL. It always struck me as a waste of very good resources, plus right from day one, I’ve wanted to have my backend running in Dart. I’d choose Dart over PHP any day.

Recently I have begun moving from MySQL databases over to MongoDB simply because it works better with the type of data I’m storing from my apps. And only just within the last few days have I had the opportunity to start working towards getting Dart running on the backend server proxied by NginX. My very first configuration for NginX started with this gist (note, not my gist, but one I came across while searching):

From there I began working on a Dart HttpServer which connects to MongoDB with mongo_dart. Programming like this, I admit I’m totally in love. NginX does a great job of serving my static files, and anything that’s not a static file it passes on to the Dart server. Using mongo_dart, it was incredibly easy to setup a RESTful API.

I’m still in the process of fully implementing the HttpServer and APIs I want for the backend server. However once I’ve gotten everything completed, I am planning on moving all of my off of Apache servers onto some smaller VMs with NginX, Mongo and Dart (no more LAMP, now LNMD?? Doesn’t roll off the tongue quite as easily.) Currently my plan is to have one NginX instance running with multiple locations configured for each of my apps. Each app will proxy pass to a different Dart server specific to each app.

I may write another post once I’ve completed the transition of the first app to comment on any pitfalls or issues I run into. But now you know how and where I run dart!

by Matthew Butler at March 21, 2014 07:37 PM

March 13, 2014

Angulardart

AngularDart release 0.9.9 (glutinous-waterfall)


AngularDart version 0.9.9 (glutinous-waterfall) has now been released!

This fantastic version contains close to a month’s worth of fixes and features which have all boosted the capabilities of what AngularDart has to offer. The hallmark feature in 0.9.9 is support for Animations in AngularDart via the NgAnimate module as well as a new change-detection algorithm and a foundation for form validation and handling. Let’s have a look at this awesome new feature in detail.

Animations with NgAnimate

AngularDart now supports animations via the NgAnimate module much like AngularJS does. Historically, with web applications, animations have always been a pain to manage due to the complexity of triggering and tracking animations. NgAnimate, within AngularDart, takes a simplistic approach by automatically detecting and rendering animations whenever the UI changes within an Angular application.

To enable animations within AngularDart, the primary requirement is to include the NgAnimateModule into the application and then provide the appropriate Dart or CSS animation code to facilitate the animations that are triggered when an enter, leave, move, addClass or removeClass DOM operation is executed. In other words, a DOM operation occurs, the animation code kicks and detects which animations are present on the element (by using the CSS classes) and then renders the animations for that element.

CSS-enabled animations

Just like with AngularJS, the CSS-enabled animations in AngularDart follow the same naming convention. When a DOM operation is triggered, NgAnimate will place the corresponding CSS class on the element in order to detect to see if any transition or keyframe animation code is issued for that specific change. The list below shows the CSS class that is applied when a specific DOM operation occurs for the element.
  • .ng-enter 
  • .ng-leave
  • .ng-move
  • .{cssClass}-add  (when a CSS class is added)
  • .{cssClass}-remove (when a CSS class is removed)
One important detail to remember is to include a base CSS class onto the element and use a compound CSS selector to define the transition or keyframe animation code. For transitions, there are two CSS selectors that are expected to be defined:

.base-class.ng-enter {
  transition: 500ms;
  /* the starting animation code */
  opacity: 0;
}
.base-class.ng-enter.ng-enter-active {
  /* the destination animation code */
  opacity: 1;
}

The code above will render a fade animation (using CSS transitions) and will run for 500ms. Once complete, all the generated CSS classes will be removed from the element. The same code can be used using CSS Keyframe Animations, however, only the starting CSS class is required since the keyframe code manages it’s own timeline.

Click here to view a few working examples of CSS-enabled animations in AngularDart.

Dart-enabled animations

NgAnimate in Dart also offers us to create our own animations that are handled purely in Dart code which is the equivalent as using a JS-enabled animation in AngularJS. Due to the rich object-oriented nature of the Dart programming language, all that is required is to setup a class that implements the NgAnimate interface.

A working example of a custom animation using Dart can be found here.

And a special thanks to +PaulRohde for all his great work in crafting together animation support in AngularDart.

What else is included?

AngularDart 0.9.9 comes packed with a rich API for handling forms. This includes: custom validators, rich error control, resetting fields and additional state flags for tracking the validation state of the form. The forms in AngularDart are still being refactored and remastered and the next major release will include a polished demo with a showcase of extensive features.

The new Change-detection API featured in AngularDart 0.9.9 aims to boost the performance of the behind the scenes operations that are issued within the scope and digest loop. Enhanced dirty checking, less pressure on garbage collection and even a way to hook into object observe are all among the key features that the new system encompasses. The change detection system sets the foundation for building more robust web applications and is a major step forward for the Angular community.

AngularDart 0.9.9 also includes dozens of commits which fix and tweak other components within the framework. As always, for full details of this release, please see the changelog.

Breaking Changes

0.9.9 is a big release and due to the nature of the new change-detection algorithm, the API for scope has changed quite a bit.  The biggest change is how scope properties are assigned on the scope. With earlier versions of AngularDart, the scope object itself was treated like a map and any property accessed using square brackets would either set or get the associated value. With 0.9.9 this will not produce the same effect. Instead all scope property getter and setter operations are to be facilitated within the scope.context member. So in other words, all the scope property reading and writing that was done in earlier versions is now done the same way, but on the scope.context map.

// < 0.9.9
scope['prop'] = 'value'; //set
scope['prop']; //get 
// >= 0.9.9
scope.context['prop'] = 'value'; //set
scope.context['prop']; //get

To get a full breakdown of all the breaking changes associated with the 0.9.9 please visit the breaking changes section of the 0.9.9 changelog.

Thank you everyone!

A mega thanks to everyone who contributed on this major release: Ando Yasushi, Andrew Lorenzen, Brian Ford, Caitlin Potter, Chirayu Krishnappa, Giovanni Silva, James deBoer, John Coleman, Kasper Lund, Matias Niemelä, Michael Derfler, Misko Hevery, Patrice Chalin, PatrickJS, Paul Rohde, Pavel J, Pete Blois, Seth Ladd, Simon Hofer, Tero Parviainen, Tommy Fortes, Victor, Vyacheslav Egorov, W. Brian Gourlie, jeffwesson, Naomi Black, naotohc, yasushi.ando.

You guys rock!

by matsko (noreply@blogger.com) at March 13, 2014 06:43 PM

Patrice Chalin

Recommended Dart project layout

The project layout shared by Dan Rubel and Eric Clayberg (in a presentation at the 2013-12-18 Googleplex Eclipse Day) is something like this:
my_app/
pubspec.yaml
README.md
bin/
start_my_app <-- server-side code
lib/
public_code.dart <-- shared public code
src/
internal_code.dart <-- private code
test/
my_app_test.dart
web/ <-- client-side code
index.html
main.dart
main.css

by Patrice Chalin (noreply@blogger.com) at March 13, 2014 01:37 PM

AngularDart expression grammar

As far as I can gather from a quick look at the code, here is an EBNF grammar for AngularDart expressions, in the same notation used in the Dart Programming Language Specification. These expressions can appear as arguments to Angular directives. While the grammar allows, e.g., a semicolon-separated list of expressions, assignments and conditionals, these will not be accepted by all directives---e.g., ng-click supports multiple expressions possibly with assignments, whereas the mustache directive {{...}} expects a single expression.


expressions: expression (';' expressions)?
expression:
   literal
 | id args? # variable or function
 | expression '.' id args? # member
 | expression '|' id filterArg* # filter
 | expression '[' expression ']'
 | preOp expression
 | expression binOp expression
 | expression '?' expression ':' expression
 | expression '=' expression # assignment
args: '(' expressionList? ')'
filterArg: ':' expression
expressionList: expression (',' expression)?
literal:
   'null'
 | stringLiteral
 | numberLiteral
 | boolLiteral
 | '[' expressionList? ']'
 | '{' (keyValuePair (',' keyValuePair)? )? '}'
keyValuePair:
 expression ':' expression

The preOp and binOp are mainly those supported by Dart (though I will have to crosscheck that).

by Patrice Chalin (noreply@blogger.com) at March 13, 2014 04:15 AM

March 12, 2014

Matt Butler

Dynamically Generating Download Files

Download Now Img

It may come as no surprise to many of you, that I love Dart. With this love, I’ve made a significant change in the way I handle some of the tasks I get on a day-to-day basis. One of the tasks which would inevitably come up is the take some kind of data or input, handle and manipulate it in some way (internally they like to call it massaging the data, but its rarely that relaxing) and create an output file (usually text).

In the past, normally I would have accomplished this by writing a little Ruby script, or even a Perl script. This often presented a few problems however. First would be that if I wrote the script on my Linux PC, then I’m the one who had to constantly be emailed the data, or generate it myself. Then e-mail off the results. It also meant that if I wasn’t in the office, it wasn’t done. So an option was to my script on a server, then any of the server admins could run the script (once I documented where it was, how to run it, etc). But it still meant that they would have to go through the same process I would need to.

Of course, the perfect solution is to just create a web-app. Before Dart, I would create a PHP page and script to upload the input information, parse it on the server and provide a download link for the results. It was better, as then at least anyone could run the scripts themselves without needing to go through me or the server admins. But there was one big problem… it was PHP.

Now with Dart, I don’t need to go through all of that, and in many cases I only need a server to host the page itself for others to access. No need to transfer the data back and forth to the server for the parsing. One of the major factors in making this easy for me is HTML5 Download Attribute.

My first step in dynamically creating a downloadable file is to create a Blob object with the contents of my file. This is really quite simple as the Blob just takes a list of parts which make up the blob, in my case, it’s usually a list of lines of the final text file. Additional arguments are the MIME encoding for the blob (or rather the final output file, such as “text/plain”), and the format of the line endings, which can be either “transparent” or “native”. Transparent will leave new line endings just as they are passed into the blob, and Native will specify that the file should use the line ending specific to the native operating environment. This means you don’t have to worry about if your user is on Linux, Mac, or Windows when downloading the file.

Next up, we need to create a Data URI which contains the data from our blob object. Again this is really easy with the Dart Url class. In particular using the createObjectUrlFromBlob() method. We just pass in our Blob and receive our URL.

The final step, involves creating our link, and assigning the various properties we need. In the example below I decided to create an entirely new element, however it’s equally valid to grab a link already in the page and just update its properties and maybe toggle the visibility. In particular we need to set the download property. This will be the filename that is automatically used to save the file on the user’s computer. And we need to set the href property to be the Blob URL we just created.

You can see all of this in action below:

test.dart

import 'dart:html';

void main() {
  // Our imaginary dynamically generated data
  List body = [ 'This list is the text\n',
                'which our final output\n',
                'file will contain.\n\n',
                "It's really nothing\n",
                'special in any way.\n',
                'Normally this stuff would\n',
                'be dynamically generated\n',
                'in some way.\n\n'];
  
  // Create a new blob from the data.
  Blob blob = new Blob(body, 'text/plain', 'native');
  // Create a data:url which points to that data.
  String url = Url.createObjectUrlFromBlob(blob);
  // Create a link to navigate to that data and download it.
  AnchorElement link = new AnchorElement()
      ..href = url
      ..download = 'random_file.txt'
      ..text = 'Download Now!';
  
  // Insert the link into the DOM.
  var p = querySelector('#text');
  p.append(link);
}

test.html

<!DOCTYPE html>

<html>
  <head>
  	<meta charset="utf-8">
  	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    
  </head>
 
  <body>   
    <p id="text"></p>
    <script type="application/dart" src="test.dart"></script>
    <!-- for this next line to work, your pubspec.yaml file must have a dependency on 'browser' -->
    <script src="packages/browser/dart.js"></script>
  </body>
</html>

by Matthew Butler at March 12, 2014 06:11 PM

March 06, 2014

Patrice Chalin

Simple Dart HTTP server supporting GET and PUT requests

It is very easy to write an HTTP server which serves static content from a directory, as is illustrated in the Dart by Example HTTP Server section. Here is a simple extension of such a basic server which supports PUT requests for resources (e.g., so that resource changes can be persisted back server-side):
import 'dart:io';
import 'package:http_server/http_server.dart' show VirtualDirectory;

final String PATH_TO_WEB_CONTENT = "web";

void main() {
HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 3031).then((HttpServer server) {
print("Server up; try http://${server.address.address}:${server.port}/index.html");
final String root = Platform.script.resolve(PATH_TO_WEB_CONTENT).toFilePath();
final virDir = new VirtualDirectory(root)
// The following are needed in dev mode to be able to access
// Dart packages in the cache.
..followLinks = true
..jailRoot = false;
server.listen((HttpRequest req) {
print("${req.method} ${req.uri};\tcached ${req.headers.ifModifiedSince}");
(req.method == "PUT" ? processPut : virDir.serveRequest)(req);
});
});
}

void processPut(HttpRequest request) {
final String filePath = request.uri.toFilePath();
final File file = new File(PATH_TO_WEB_CONTENT + filePath);
request.pipe(file.openWrite()).then((_) {
request.response
..statusCode = HttpStatus.NO_CONTENT
..close();
print("Wrote to file '${file.path}'");
});
}
Such a server can be useful to help solve the exercises at the end of Chapter 6 of the AngularDart tutorial.
WARNING: Of course you would not want to use the naive server implementation given here for anything but demos, in particular because root is not jailed.
If you would like to see a version with error handling, drop me a comment.

by Patrice Chalin (noreply@blogger.com) at March 06, 2014 07:22 PM

February 26, 2014

Dartlang

Dart 1.2 continues to improve developer experience

With the 1.2 release, the Dart team continues its commitment to regular, compatible updates to our core runtime and tools. This release includes improved debugging, faster networking, and Angular support in the Editor.

Debugging Dart applications is now easier. Breakpoints can now be set at local variable assignments. A number of bugs have also been addressed, including stepping through recursive functions and eliminating side effects of using the debugger.

The Dart core libraries continue to improve with a focus on performance. WebSocket throughput has increased by a factor of 15 since version 1.0. The speed of our core async primitives, Future and Stream, also improved by over 10%.



Angular support in the Editor has been greatly improved in this release. Search, navigation, and refactoring now understand Angular elements. A number of Angular-specific warnings have also been added.

Please see the Release Notes for a description of all changes. Dart 1.2 includes bug fixes, performance improvements, and enhancements across the Dart virtual machine, compiler, libraries and tools.

You can download v1.2 at the Download Dart page. If you are running the Dart Editor, you can update by checking "About Dart Editor" in the IDE.

Tell us what you build with Dart in our Google+ community and let us know if you have any issues or feature requests.

by Kevin Moore (noreply@blogger.com) at February 26, 2014 07:19 PM

February 24, 2014

Dartlang

Standardizing Dart: 1st Ecma TC52 Meeting in March

Back in December, Ecma created a new technical committee named TC52 to publish a standard specification of the Dart language. The inaugural TC52 meeting takes place on March 12, 2014 in Mountain View, California. In addition to ratifying the current spec, the committee plans to address proposals for Enums and Deferred Loading. If time permits, we’ll initiate work on the broader set of features to be added for Dart 2.0.


TC52 would love to see contributions to the Dart language specification from many players in the industry. Please come and join the committee, it's not too late to get involved. For language requests in general, the issue tracker - dartbug.com - is a great place to start the discussion. The TC52 committee will pull from the issue tracker.

This official start of TC52 is an important step towards a future where Dart runs natively in web browsers. While Dart apps can already be fast when compiled to JavaScript, users can feel a true performance boost when the Dart VM is embedded in browsers.

by Anders Thorhauge Sandholm (noreply@blogger.com) at February 24, 2014 08:18 PM

February 21, 2014

Diving into Dart

This Week In Dart #21

The road to Dart 1.2 continues with the release of to the DEV channel. Full announcement here. Highlights include the addition of Dart Formatter, increased performance and stability, plus more support for attributes.

Diego Rocha has a great article on the all important topic of concurrency - vital in today's multi-core world. Worker: Dart concurrent programming does not have to be hard. Even features Fibonacci numbers!

cozy-porcupine. There - I said it! As you this is the codename for the latest angular.dart release which is at 0.9.8 so approaching 1.0 sometime soon. All the details over on Github.

I always enjoy talks from the Dart team themselves. Bob Nystrom's recent talk 'Dart for the Language Enthusiast' is available as an MP3 download and the slides are available too.

If you are interested in Dart game development, there's some interesting early footage of Fredrik Bornander's 'Lost Souls'

Bruno Skvorc has written a great article A Client-Server Dart App From Scratch. This is part one of a series starting with setting up a development environment and a Vagrant VM. SQL and PHPStorm are also touched upon.

Finally, I'd just like to mention that this blog should be picking up the pace soon. There's some more demo's on the way and a game. Have fun building with Dart this week! Thanks for reading - the visits, sharing and responses make it all worthwhile.

by Davy Mitchell (noreply@blogger.com) at February 21, 2014 08:39 PM

February 19, 2014

Angulardart

AngularDart release v0.9.8 (cozy-porcupine)

AngularDart release v0.9.8 cozy-porcupine is now available!
This release improves support for forms.  It adds CSS classes for ng-submit valid/invalid and treats number and range inputs as numerics.  It includes over a dozen bugfixes such as support for filters in attribute expressions, ng-value for checked/radio/option, form validation fixes and many more.  As always, for full details of this release, please see the changelog.
Thanks to everyone who contributed PRs for this release: Ando Yasushi, Chirayu Krishnappa, Giovanni Silva, Kasper Lund, Matias Niemelä, Misko Hevery, Patrice Chalin, Paul Rohde, Pavel Jbanov, Pete Blois, Simon Hofer, Tero Parviainen, Victor, W. Brian Gourlie, naotohc

by Chirayu (noreply@blogger.com) at February 19, 2014 11:21 PM

February 10, 2014

Angulardart

AngularDart release 0.9.7: pachyderm-moisturization

AngularDart release v0.9.7 pachyderm-moisturization is now available!

This release includes support for deferred module loading as well as a new routing language. It also ships over a dozen bug fixes, making v0.9.7 AngularDart's the winningest release in terms of our issue queue. As always, for full details of this release, please see the changelog.

Thanks to everyone who contributed PRs for this release: Ando Yasushi, Brian Ford, Chirayu Krishnappa, James deBoer, Kasper Lund, Matias Niemelä, Michael Derfler, Misko Hevery, Patrice Chalin, PatrickJS, Paul Rohde, Pavel Jbanov, Seth Ladd, Tero Parviainen, Victor, Vyacheslav Egorov, W. Brian Gourlie.

by jd (noreply@blogger.com) at February 10, 2014 11:45 PM

February 07, 2014

Kevin Moore

pkg/unittest: shedding some cruft, getting some awesome



9:15am 7 Feb, 2014 These changes have not been released to the pub site yet.

tl;dr
  • If you're testing code using Future, Stream, or anything async, you'll notice a lot fewer crashes and a lot more helpful stack traces.
  • If you're subclassing Configuration, keep reading.
  • If you're using APIs on TestCase, keep reading.
  • If you're just using test, group, expect, etc. you're likely fine.
  • Update pub dependencies on unittest to includes 0.10.0 to get the new hotness. (You might have something like >=0.9.0 < 0.10.0, change it to >=0.9.0 <0.11.0)
The upcoming 0.10.0 release of unittest will have a lot of changes. Here's a copy-paste of the current changelog.
  • Each test is run in a separate Zone. This ensures that any exceptions that occur is async operations are reported back to the source test case.
  • DEPRECATED guardAsync, protectAsync0, protectAsync1, and protectAsync2
    • Running each test in a Zone addresses the need for these methods.
  • TestCase:
    • Removed properties: setUp, tearDown, testFunction
    • enabled is now get-only
    • Removed methods: pass, fail, error
  • interactive_html_config.dart has been removed.
  • runTests, tearDown, setUp, test, group, solo_test, and solo_group now throw a StateError if called while tests are running.
  • rerunTests has been removed.
These changes cover three big areas:
  • Remove unsupported APIs. The interactive test case runner hadn't been touched in a long time and it didn't support a number core test case features, like setUp and TearDown. The rerunTests function only existed to support the interactive runner and introduce a lot of weird state in unittest.
  • Make TestCase immutable. Expect more changes here. TestCase should contain the logic to run the test. The result of the run should be in another object. We're getting there.
  • Make testing async code easier. All tests are now run in a Zone. This means all any errors thrown by async operations are now funneled to the calling test case without requiring guardAsync or a protectAsyncN function (these are now deprecated).
Going forward, we're looking into more changes:
  • Remove more state from TestCase. enabled, isComplete, passed, and startTime may be removed from this class and exposed somewhere else.
  • I'm hoping to have a model where TestCase exposes Future<TestResult> run([Configuration config]) or similar.
  • More powerful ways to run unit tests, making it easy to run tests is parallel in zones, for example.
I'd like unittest to evolve to expose a very simple API that others can build on, with a layer of "easy" for those that just want to get something tested without a lot of ceremony.

Your thoughts and suggestions are welcome!

Happy hacking.

by Kevin Moore (noreply@blogger.com) at February 07, 2014 05:17 PM

February 06, 2014

Diving into Dart

Sierpinski Carpet

Returning to the world of fractals, we travel back nearly 100 years to the Sierpinski Carpet which was first described in 1916. Wacław Sierpinski was a Polish mathematician who made a great contribution to Set Theory. Not just carpets - the Sierpinski Curve and Sierpinski Triangle are the the other two famous fractals that carry his name.

This recursive function is quite intensive involving dividing the X,Y values repeatedly until they hit a multiple of 3 or 0. At this point X,Y can be determined to be Carpet or non-Carpet. As this blog requires it's demo's to be colourful, the colour is determined based on the raw X,Y values rather than the Carpet factor! To add some interactivity, the colour can be shifted and the size of the output adjusted.

Live example is visible here and you can get the Dart code on GitHub.

by Davy Mitchell (noreply@blogger.com) at February 06, 2014 08:42 PM

February 05, 2014

Seth Ladd

Angular and Polymer Data Binding, Together!





Angular and Polymer, sitting in a DOM tree,
B-i-n-d-i-n-g.
First comes components,
Then comes elements,
Then comes the interop with the node dot bind.

Angular, a super heroic MVC framework, and Polymer, polyfills and enhancements for custom elements built on top of Web Components, can live harmoniously in the same app. This post shows you how to connect Angular-controlled components to Polymer-controlled elements via data binding. And we do it all in Dart.

Angular and Polymer


I get asked "Should I use Angular or Polymer?" a lot. My answer is, "Yes". That is, both libraries have distinct strengths, and you can use both in the same app.

Polymer excels at creating encapsulated custom elements. You can use those custom elements in any web app or web page, regardless if that app is built with Angular, Ember, etc. Angular excels at application engineering, with dependency injection, end-to-end testability, routing, and services.




Here are some features that Angular offers:
  • directives - kind of like mixins or traits for DOM nodes
  • dependency injection
  • testing support
  • routing
  • services
  • server communication
Here are some features that Polymer offers:
  • <polymer-element> - convenient way to declare custom elements
  • widgets
  • polyfills for new web platform features
  • encapsulation for the DOM
  • built on emerging web standards
There are some similar features between the two libraries. Both libraries implement a data binding solution (which we cover below). Angular is beginning to build on top of emerging web standards (like Shadow DOM). I expect that, over time, more and more of Angular will take advantage of the Web Components family of specifications.

Interop

We can interop Angular and Polymer via the DOM, as well as via data binding.

DOM interop


We've always been able to use the DOM for basic interop between custom elements and Angular. For example, setting an attribute on a custom element is a type of API interop. Simply creating the custom element and inserting it into the document is another type of interop. Polymer and Angular already interop at the DOM layer.

For example, here's an example of an Angular managed page that includes a Polymer element.



In the above code, Angular manages the binding of the cool variable in the HTML. When cool changes, everywhere you see {{cool}} also changes. Yes, even when bound into an attribute of a custom element!

The <my-element> is just a custom Polymer element encapsulates an input field and displays a value. Here's the code:


<polymer-element name="my-element">
<template>
<p>
<input type="text" value="{{message}}"> Polymer binding: {{message}}
</p>
</template>
<script type="application/dart" src="my_element.dart"></script>
</polymer-element>

The Angular code can set attributes on <my-element>, listen for DOM events from <my-element>, and of course even insert children elements inside of <my-element>. So in a sense, Angular can interop with Polymer elements just like any other DOM element.

However, there is an issue. Can you spot it in the animated GIF below?


Any changes to cool initiated from inside the Polymer element are not propagated back out into the outside DOM or Angular. We need real bi-directional data binding: Angular down into Polymer, and Polymer back out to Angular.

Data binding interop


Polymer manages data binding through a feature called Node.bind(). Node.bind() is a "new method added to all DOM nodes which instructs them to bind the named property to the data provided". Angular does not use Node.bind() out of the box, so Angular is unable to listen for changes that are initiated from Polymer.

Until now.

Justin Fagnani, an engineer on the Dart team, released angular_node_bind, a Dart package that bridges the Angular and Polymer worlds. It is an Angular module that can listen for Node.bind() changes and propagate the changes into Angular.

Justin explains why this package can help:

  • Node.bind() takes care of setting up the binding, including two-way bindings, eliminating the need for directives for every property for two-way bindings.
  • Custom elements that expose properties will be properly bound, again including two-way bindings. You can use the growing collection of custom element libraries in your Angular app.

To use angular_node_bind, add the following to your app's pubspec.yaml file:


name: angularpolymer
description: A demo of Angular and Polymer data binding.
dependencies:
angular: any
angular_node_bind: any
browser: any
polymer: any
transformers:
- polymer:
entry_points: web/angularpolymer.html

Register the NodeBindModule with Angular:


import 'package:polymer/polymer.dart' show initPolymer;
import 'package:angular/angular.dart' show ngBootstrap;
import 'package:angular_node_bind/angular_node_bind.dart' show NodeBindModule;

void main() {
initPolymer().run(() {
ngBootstrap(module: new NodeBindModule());
});
}

Finally, change the syntax used for binding into Polymer elements, from {{...}} to [[...]]:


<my-element message="[[cool]]"></my-element>

Notice the binding expression is now [[cool]] instead of {{cool}}. The angular_node_bind module looks for [[ ... ]] and wires up Node.bind().

Here is a little movie of how the app works with true bi-directional data binding between Polymer and Angular:



Notice how changes from Angular are reflected in the Polymer element, and how changes from within the Polymer element are reflected in the Angular code. Awesome!

Summary

You can use Polymer custom elements inside of an Angular app in at least two ways. Polymer elements are just like regular DOM elements, so they have attributes, emit events, and can contain children elements. Use Dart's angular_node_bind package to connect Polymer's data binding to Angular's data binding for true bi-directional data sharing.

Lovely, Angular and Polymer holding hands.

Get the source code

You can check out the source code mentioned in this post.

by Seth Ladd (noreply@blogger.com) at February 05, 2014 04:58 PM

January 31, 2014

Matt Butler

Going POSTal

Going postal!

So it seems, that people like their client-side applications to be able to talk to their servers. Strange what people like to do these days.

As it so happens, there are a few ways to accomplish this in Dart. Each has some pros and cons associated with it, and which one you want to use will really depend on how you’re displaying and collecting information.

HttpRequest.request()

To start off with, we’ll look at a use-case where your app is primarily based off of the dart:html libraries. In cases like this, where we do not have any data-binding to each of fields in the Form, it’s sometimes easier to just send the entire Form itself. First here’s a quick look at the code for our extremely simple form:

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    
    <link rel="stylesheet" href="postal.css">
  </head>
  <body>
    <h1>Postal</h1>
    
    <form id="myForm" action="send/">
      <label>First Name:<input type="text" value="" name="firstName" id="firstName"></label><br />
      <label>Last Name:<input type="text" value="" name="lastName" id="lastName"></label><br />
      <label>Email: <input type="email" value="" name="email" id="email"></label><br />
      <input type="Submit" value="Submit">
    </form>

    <script type="application/dart" src="postal.dart"></script>
    <script src="packages/browser/dart.js"></script>
  </body>
</html>

The easiest way send all of that information is to bundle it into a FormData class. This will automatically associate the values with the name attribute in the FormElement and pass that mapping to the server in our request.

Lets take a look at what our Dart code looks like and see what exactly is going on here:

import 'dart:html';

void main() {
  var myForm = querySelector('form#myForm') as FormElement;
  myForm.onSubmit.listen((e) {
    e.preventDefault(); // Don't change page when the form is submitted.
    
    var data = new FormData(myForm);
    HttpRequest.request(myForm.action, method: 'POST', sendData: data)
      .then((resp) {
        // Do something with the response from the server.
      });
  });
}

First we need to get our FormElement and assign it to a varable, myForm. Next we need to listen for an on-submit event from the form. When that event occurs the first thing we want to do is prevent the default action, which is to redirect to whatever page is in the action attribute of the form (or reload the current page). This is a Single Page Application though! We don’t need no stinkin’ redirects!

Now we need to get our data that we want to send with our request. As previously mentioned, since we want to send the entire form and don’t want to have to query each and every input field it contains, it’s just so much easier to send the entire form. Thus we use the FormData constructor, passing our FormElement, myForm as the constructor (due to Dart’s awesome scoping rules, we can use our variable name inside a closure on the variable itself!)

Now that we have the data, we just need to send it. There is a static method on the HttpRequest, named request. This method will return a Future with an HttpRequest which will represent our response from the server once the request has completed. You’ll note the above sample is for demonstration only and does not include any error checking or any of that good stuff we should have. To our request method we pass myForm.action as the URL of where the request should be sent to. I find it is often best to use the action attribute of the form to store the URL of the request as its often much easier to find that way should it need to be updated later. Additionally we pass the named parameter method: 'POST'. By default the request method will issue a GET method query. Since we’re trying to send data, not get data, we want to make sure we properly use POST (plus, if the request is a GET request, the next argument is ignored per HTTP/1.1 protocol.) Finally we use the parameter to send the data sendData: data.

Using the asynchronous tools that Dart provides, we then() wait for the response to complete. Once we have that we can do whatever we need, be it verifying the data was submitted, error codes from the request, etc. As you notice this sample is pretty short and concise. However it does have its drawbacks. Depending on what you’re using for a backend server, it may not recognize the default content-type generated by the dart request. This means we may sometimes have to supply a different argument to specify the requestHeaders.

But all-in-all the FormData is a quick and easy way to send our form information to the sever. Of particular importance is to remember to apply the name attribute to your input elements or you may have difficulties accessing your data! ;-)

HttpRequest Instance

Since it’s along the same lines, we’ll next look at using a full instance of the HttpRequest. In the background, HttpRequest.request() is actually just a static function which creates the full instance of HttpRequest automagically for you and only passes back the response to you in a Future.

The HTML source will stay the same as above. Find below the new dart source:

import 'dart:html';

void main() {
  var myForm = querySelector('form#myForm') as FormElement;
  myForm.onSubmit.listen((e) {
    e.preventDefault(); // Don't change page when the form is submitted.
    
    var data = new FormData(myForm);
    var req = new HttpRequest();
    
    req.open('POST', myForm.action);
    req.onLoad.listen((event) {
      var resp = event.target as HttpRequest;
      // Do something with the response from the server.
    });
    req.send(data);
  });
}

You’ll notice that generally its pretty similar to using the static request method. First we attach a listener for the on-submit event for the form. In which we also prevent the default action. We also wrap our data in a FormData instance as well. As opposed to sending each of our configuration values as parameters, we now need to apply them each individually to the request.

Note that the majority of settings on an HttpRequest instance need to be applied after we have called open, but before we call send. In the above example, we open our request passing the method (which is now a required positional argument and not optional named argument), and our URL. open Also accepts a few additional named parameters, one of interest is a boolean async which is true by default. If we pass false to this then the entire request will be completed synchronously and will block on the request. Please, please, please use this sparingly!

Next we need to add a listener to our onLoad property. Again we want to do this before we send the request to ensure that there’s no opportunity for the callback to be missed between the sending and the assignment of the listener. And finally we send our request including the attached data.

Using an HttpRequest instance is much more verbose way of creating a request however it is also much more powerful, allowing for more customization and control over your request.

HttpRequest.postFormData

Finally we reach my preference when it comes to sending data. The static method postFormData. This method is particular useful when you’re using binding to automatically link your variables with the values in the input fields. Some great examples of this are with Polymer or Angular.

First lets look at the code. In this case I’m using the Polymer library to easily create my own custom element which contains its own form. I won’t get into too much detail about the Polymer stuff as that’s not the goal of this post:

Main/index file:

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <link rel="stylesheet" href="bindingpostal.css">
    
    <!-- import the click-counter -->
    <link rel="import" href="myform.html">
    <script type="application/dart">export 'package:polymer/init.dart';</script>
    <script src="packages/browser/dart.js"></script>
  </head>
  <body>
    <h1>BindingPostal</h1>
    
    <div id="sample_container_id">
      <my-form></my-form>
    </div>

  </body>
</html>

My Polymer element HTML file:

<!DOCTYPE html>
<polymer-element name="my-form" attributes="count">
  <template>
    <style>
      div {
        font-size: 24pt;
        text-align: center;
        margin-top: 140px;
      }
      button {
        font-size: 24pt;
        margin-bottom: 20px;
      }
    </style>
    <form id="myForm" action="send/" on-submit="{{ save }}">
      <label>First Name:<input type="text" value="{{ firstName }}" id="firstName"></label><br />
      <label>Last Name:<input type="text" value="{{ lastName }}" id="lastName"></label><br />
      <label>Email: <input type="email" value="{{ email }}" id="email"></label><br />
      <label>Cool: <input type="checkbox" checked="{{ isCool }}" id="email"></label><br />
      <input type="Submit" value="Submit">
    </form>
  </template>
  <script type="application/dart" src="myform.dart"></script>
</polymer-element>

And the Dart code for the Polymer element:

import 'dart:html';
import 'package:polymer/polymer.dart';

@CustomTag('my-form')
class ClickCounter extends PolymerElement {
  @observable String firstName = '';
  @observable String lastName = '';
  @observable String email = '';
  @observable bool isCool = false;

  ClickCounter.created() : super.created() {
  }

  void save(Event e, var detail, Node node) {
    e.preventDefault();
    
    var form = e.target as FormElement;
    var data = this.toJson();
    
    HttpRequest.postFormData(form.action, data).then((resp) {
      // do something with the response.
    }); 
  }
  
  Map<String,String> toJson() {
    return {
      'firstName' : firstName,
      'lastName' : lastName,
      'email' : email,
      'isCool' : '$isCool',
    };
  }
}

So a few things to note first regarding the class for my element. I added a method toJson which returns a Map of Strings and Strings. This is important as the postFormData method does not allow non-String values. As a demonstration I added a boolean to our form isCool. This value is String interpolated in the toJson method.

Our save method is automatically bound to the onSubmit event on our Polymer Element so no worries about attaching listeners here! Since the binding is on the form itself, that will be the target of the event that is passed to the method. The other arguments we don’t really need in this case.

As usual, we prevent default. We also get the FormElement so we can easily pass the action property to the postFormData static method. We also initialize data to be the Map of String which represent our form values. You’ll notice the HTML markup for the input elements do not require the name attribute.

Similar to HttpRequest.request we pass our URL and our data. In this case we already know it’s a POST request so there’s no need to specify that. postFormData also returns a Future as similar to request which provides an HttpRequest instance of the response from the server.

Some additional nice features about this method is that it automatically applies the Content-Type: application/x-www-form-urlencoded; charset=UTF-8 header, which helps servers on the backed to properly recognize the request and handle it (I’m looking at you PHP!).

So as you can see there are a number of ways to send the data to the server using the HTTP/1.1 POST method. Which one you want will depend on your code-base and usage. When in doubt, post (haha get it?) questions to the Dart tag on Stack Overflow.

by Matthew Butler at January 31, 2014 09:25 PM

January 29, 2014

January 14, 2014

Adam Coding @ Github

chrome.dart 0.4.0 release

The dart-gde has updated the chrome.dart to ‘0.4.0’. This release contains a whole rewrite of the project. All APIs are now generated from chrome apps/ext IDLs. Most unit tests from previous chrome.dart have been ported.

About chrome.dart

chrome.dart package provides the generated APIs to access chrome apps & extensions through dart interfaces. The APIs depend on the js-interop to communicate with the javascript vm for accessing the APIs. Currently no native interfaces exist between dart vm and chrome browser. In a later point in time those interfaces will exist, for now this provides a way to access those interfaces.

chrome_gen.dart -> chrome.dart

At first chrome_gen.dart was the project that kicked off moving to generated APIs. It was getting frustrating having to hand write, maintain and test chrome.dart. We did avoid looking into generation from IDL, because the IDL in the chromium is in two different formats json & chrome specific WebIDL. The nice part about the original chrome.dart package is we could introduce more structure for the APIs then what the generated javascript APIs looked like. So after initial development by Devon Carew, we decided it was a better direction to use parsers and generators to create and maintain the APIs. Four months later we had a 90% complete package that was already being used by a few projects, including spark. We are able to generate enough structure to keep nice APIs and generate form the IDL, this was a win for the project.

Documentation

The API documentation is automatically generated for Apps and Extensions on each check in. A few wiki pages exist and we are in the process of migrating them from chrome_gen.dart wiki -> chrome.dart wiki. We do need help and welcome pull requests and wiki edits.

Samples

Currently the best source of project setup exists with app in the project. The app folder in a dart project will not have the automatic symlinks generated by pub. That helps out greatly since it would pollute our folder structure and cause bad things to happen. Instead we have a simple setup_app.dart script that helps build and copy packages over to the app folder. Right now its specific for the chrome.dart project but should be easy to replicate for your own chrome apps or extensions. Another neat script which is mac specific but could be generalized is load_app.sh. load_app.sh shows a simple way to load up an application in app folder from command line.

Helping out

We still need more unit tests, documentation, and additional development. If your interested checkout the github issues or send pull requests.

Thanks!

To all the contributors on this project Devon Carew, Kevin Moore, Ross Smith, Marc Fisher

January 14, 2014 05:33 PM

January 09, 2014

Seth Ladd

How to shrink the size of your Dart app when compiled to JavaScript

So you caught the Dart bug and you're enjoying using the structured language, comprehensive libraries, and productive tools. Great! Except, when you compiled your Dart app to JavaScript, the output was bigger than expected. Read this post to learn how to reduce the size of your JavaScript output. Small apps are fast apps!

Make sure you are minifying


The dart2js compiler can minify your JavaScript. However, minification is not the default. Make sure you opt-into minification before you deploy to production.

How can you tell if you minified? Take a look at the generated JavaScript and you'll know. Minified JavaScript replaces variables names, function names, and more with shorter names. It also moves code around to use less lines.

If you compile your app from the command line, use --minify:

dart2js --minify -o=app.dart.js app.dart

If you use pub build (a streamlined build process for pub package and apps), it defaults to minifying. Yay!

If you use Dart Editor, it's a bit more tricky. Follow the instructions I posted on StackOverflow for screenshots and a walk through. You need to add --minify to the Run config in Manage Launches.

You will see a significant reduction in size after you minify.

Make sure all dart:mirrors imports use @MirrorsUsed


Dart's reflection capabilities come from the mirrors library. Mirrors are really powerful, but they introduce challenges to dart2js's tree shaking abilities. Normally, dart2js can look at the entire app and deduce what code is required to run the app. However, as of the time of this writing, mirrors (due to their API design and highly dynamic nature) more-or-less disable dart2js's tree shaking.

Enter @MirrorsUsed, a metadata annotation, which explicitly states what parts of the program are reflected. Tools like dart2js can use @MirrorsUsed to re-enable tree shaking.

Note: by the time you read this article, @MirrorsUsed might be deprecated or removed. The engineers are working on better ways to deduce how mirrors are used in the code. As of the time of this writing, @MirrorsUsed is the tool we have to gain control over the output size when mirrors are used.

If your app imports dart:mirrors and you compile it with dart2js, you might see a warning like this:

sethladd:~/dart/test/web$ dart2js test.dart 
test.dart:1:1: Hint: 6379 methods retained for use by dart:mirrors out of 7873 total methods (81%).
import 'dart:html';

mylibrary.dart:3:1: Info: This import is not annotated with @MirrorsUsed, which may lead to unnecessarily large generated code.
Try adding '@MirrorsUsed(...)' as described at https://goo.gl/Akrrog.
import 'dart:mirrors';

^^^^^^^^^^^^^^^^^^^^^^

If you see "This import is not annotated with @MirrorsUsed", then the generated JavaScript is probably too big. My sample app, which uses UUID, HTML, and mirrors, compiles out to > 4MB. Yikes. But we can fix it!

At the import of dart:mirrors, add a @MirrorsUsed and specify what the app reflects on. You can specify:
  • targets: one or more names of libraries or classes
  • metaTargets: one or more classes used as metadata to indicate reflectability
For example:


library mylib;

@MirrorsUsed(targets: 'mylib')
import 'dart:mirrors';

All names and things (classes, functions, etc) inside of mylib will be retained for reflection.

From what I can tell, once dart2js sees a @MirrorsUsed, it then tree shakes and drops all targets that are not specified. So be sure to include a complete list of targets (libraries, classes, etc) that will be reflected.

In my test app (uuid, html, mirrors), the generated JavaScript size dropped to 400k unminified (from 4MB unminified) once I added @MirrorsUsed.

If the import of dart:mirrors is not under your control (e.g. you use a package that imports a package that uses dart:mirrors), you can introduce your own @MirrorsUsed annotation to override. Just introduce your own import of dart:mirrors in code that you control (e.g. in your entry point file), add @MirrorsUsed, specify targets and metaTargets, and set override: '*'.

As mentioned above, Dart engineers are working on making mirrors + reflection + dart2js much friendlier. We know @MirrorsUsed is hard to get right, but it's the only tool we have right now at the time of this writing.

Make sure you are gzipping


Of course, your web server should perform real-time compression. Be sure to account for gzip when calculating how many bits are traveling across the wire.

Summary


To calculate the real size over the wire, minify your app, add @MirrorsUsed if you use mirrors, and enable HTTP compression like Gzip. If you have any questions, please ask on StackOverflow or file a bug at dartbug.com/new

by Seth Ladd (noreply@blogger.com) at January 09, 2014 07:07 AM

December 21, 2013

Dartcasts.com

Episode 20: AngularDart, Part 2 In this screencast I continue...



Episode 20: AngularDart, Part 2

In this screencast I continue talking about building an application using AngularDart. You will learn about:

  1. Using the Http service
  2. Using scopes for message passing
  3. Configuring Angular applications

Read more at https://github.com/vsavkin/angulardart-sample-app

December 21, 2013 08:40 PM

December 11, 2013

Seth Ladd

Compile-time dead code elimination with dart2js

Right before the release of Dart 1.0, the Dart team snuck in a cool new feature that helps you optimize the generated JavaScript from your Dart apps. Configuration values from the environment can be evaluated at compile time and potentially result in dead code elimination. Smaller code is faster code!

As an example, let's consider the common case of logging. Debug logging is a useful tool during development and testing, but often there's no need to ship production code with debug log statements. Wouldn't it be cool if you could remove all the debug log statements before you ship to production, without having to manually delete any lines of code? Now with Dart and fromEnvironment, you can!

Here is a small example of a log function that is useful during development, but unnecessary during production. If a DEBUG is set, the log message is printed. The code gets the compile-time constant value from the String.fromEnvironment() constructor. Notice the const qualifier, instead of new, as the important signal that the environment value is a compile-time constant. Without const here, the compiler doesn't know what the value is during compilation.

log(String msg) {
if (const String.fromEnvironment('DEBUG') != null) {
print('debug: $msg');
}
}

main() {
log('In production, I do not exist');
}

For dart2js, you can pass values from the environment (not to be confused with "environment variables" that you might set in your shell) via the -D command line arguments.

When compiled with dart2js -DDEBUG=true app.dart, the output includes the logging behavior:

  main: function() {
H.printString("debug: In the production release, I do not exist");
}

Notice how dart2js inlined the log function into main, which is cool. Because the DEBUG value was set, dart2js knew that the if statement inside of log() returns true.

However, if -DDEBUG is not set, the logging behavior is not included in the generated JavaScript code:

  main: function() {
}

Tools like dart2js can understand how expressions that use compile-time constants resolve. Dead code is eliminated from the generated output.

Strings, ints, and booleans can produce values from the environment: int.fromEnvironment, String.fromEnvironment, and bool.fromEnvironment. Use fromEnvironment with const to help control which code blocks make it into the generated JavaScript code.

by Seth Ladd (noreply@blogger.com) at December 11, 2013 08:10 AM

December 02, 2013

Dartery

Building a Blog in Dart, Step 1: Serving Files

Earlier I wrote that I was going to write a series on Building a Blog in Dart and to start things off we're here with Step 1: Serving Files.

The most basic and fundamental thing that any web applications needs to do is serve up HTML over HTTP. Our blog will be completely client-side rendered, but all web applications, no matter how dynamic and client-side rendered, need to serve at least a skeleton HTML page and the script that drives the rendering. We'll start by serving a static HTML page and some basic CSS to show how it works.

A Simple Server

dart:io includes a basic HTTP server which is very easy to use. The most simplified working server that actually serves HTML we could write looks something like this:

import 'dart:io';

main() {
HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080).then((server) {
server.listen((req) {
req.response
..headers.contentType = new ContentType("text", "html")
..write('Hello')
..close();
});
});
}

Save this as bin/simple.dart in your project and either choose Run>Run in the Editor, or run this from the command line:

$ dart bin/simple.dart

Point your browser at http://localhost:8080 and you should see this:



There are a few things to notice here that highlight common patterns you'll see when working in Dart.

The first is that the program is completely asynchronous, even the HttpServer setup. main() actually returns before the server is running, but the VM stays alive and the server listens for connections. node.js is famous for its asynchronous, event-driven architecture and APIs, driven by the fact that JavaScript is single-threaded. Dart is similarly single-threaded and the dart:io APIs for networking, file access and working with processes are almost all async.

Also, take a look at the documentation for the classes and methods we've used here, like HttpServer, HttpServer.bind(), HttpRequest and HttpRequest.response. Notice the pervasive usage of Future and Stream.

HttpServer.bind() returns a Future that completes with the new server when it's constructed. If you ever need to create an object that has dependencies that are resolved asynchronously, this is the way to do it. HttpServer itself implements Steam<HttpRequest>, so it has a listen() method for handling requests, but all the other Stream methods as well, so you can transform and filter the requests if needed. HttpRequest implements Stream<List<int>> for reading the body, and HttpResponse implements StreamSink and IOSink to write to it. There are many advantages to this approach. First, the APIs are easy to learn, since you'll use those interfaces over and over again in Dart. Second, since the default methods for reading and writing are streaming, you won't run into a situation where you use synchronous APIs and then hit performance or memory issues when transferring very large files, something I've seen with Java servlets. Third, you can use any functions that understand Futures, Streams, IOSink and StreamSink on these classes, which encourages reusable, generic utilities.

Serving a File

While inline HTML makes for a short and simple example, it's obviously not how we want to do things. We'd like to keep our HTML, CSS, Dart in separate files, especially so we can edit them with assistance from our favorite editors. dart:io doesn't include a built-in static file handler, but we can easily add our own. (I covered a static file server in A Simple Async HTTP Static File Server in 36 Lines but the APIs have changed, so I'll start fresh).

First, we need some HTML:

<!DOCTYPE html>
<html>
<head>
<title>Simple Blog</title>
</head>
<body>
<h1>Simple Blog</h1>
</body>
</html>

And then our server:

import 'dart:io';

main() {
HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080).then((server) {
server.listen((request) {
request.response.headers.contentType = new ContentType("text", "html");
new File('web/client.html').openRead().pipe(request.response);
});
});
}

Now we're serving the HTML from web/client.html.

We start to see the file APIs in action, and the awesome pluggable nature of Streams again. File.openRead() returns a Stream<List<int>> which we can pipe() directly into the response. This will work well for large files too.

Serving Specific URLs

The examples above show the same content for any URL, and any HTTP method, because we respond to every request exactly the same way. We need to be able to send different responses for different types of requests, and we'll start by using the Stream API some more to serve some CSS.

Stream.where() filters a Stream by a predicate function. We'll use that to only respond to a request if it matches a specific path. Since we want to serve two different paths, we'll a call to where() for each path, and we'll also need a call to handle all other requests, or they will result in a hung request from the browser.

Here's the new HTML, CSS and Dart:

<!DOCTYPE html>
<html>
<head>
<title>Simple Blog</title>
</head>
<body>
<h1>Simple Blog</h1>
</body>
</html>

body {
background: #cdf;
font-family: Helvetica, Arial;
}

import 'dart:io';

main() {
HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080).then((server) {
server.asBroadcastStream()
..where((r) => r.uri.path == '/').listen((request) {
request.response.headers.contentType = new ContentType("text", "html");
new File('web/client.html').openRead().pipe(request.response);
})
..where((r) => r.uri.path == '/client.css').listen((request) {
request.response.headers.contentType = new ContentType("text", "css");
new File('web/client.css').openRead().pipe(request.response);
})
..where((r) => r.uri.path != '/' && r.uri.path != '/client.css').listen((request) {
request.response.statusCode == 404;
request.response.write("Not Found");
request.response.close();
});
});
}

Better Routing of Requests

This works, but isn't very graceful - we need to handle details like creating a broadcast stream from the server, writing a predicate function rather than specifying the path, and most of all, making sure that the streams we create with where() handle all requests yet are mutually exclusive. This is verbose and prone to error. We can handle these details with a small wrapper on HttpServer, which is exactly what the server-side portion of the route package does.

route lets us split the server's stream of requests into streams that only contain request that match a particular URL pattern, and a default stream for requests that don't match any of the patterns making sure that a request is only routed passed to one child stream. It also returns a 404 by default for non-matching requests. Using route our Dart program looks like this:

import 'dart:io';
import 'package:route/server.dart';

main() {
HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080).then((server) {
new Router(server)
..serve('/').listen((request) {
request.response.headers.contentType = new ContentType("text", "html");
new File('web/client.html').openRead().pipe(request.response);
})
..serve('web/client.css').listen((request) {
request.response.headers.contentType = new ContentType("text", "css");
new File('web/client.css').openRead().pipe(request.response);
});
});
}

That's a little better - less boilerplate and less chance of mistake - but there's still some repetition with the file handing though. If we create a function to generate handlers we can shorten things further:

import 'dart:io';
import 'package:route/server.dart';
import 'utils.dart' show serveFile;

main() {
HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080).then((server) {
new Router(server)
..serve('/').listen(serveFile('web/client.html'))
..serve('web/client.css').listen(serveFile('web/client.html'));
});
}

Much better!

We still will need to define our routing to handle URLs for blog posts, our REST API for data and assets, but we'll come back to that later. Also, to avoid going too much into detail about file serving so we can talk about data modeling and UI, I'll skip over serveFile leave it as an exercise for the reader... just until next post, when I'll start hosting example projects on GitHub.

Next time we'll look at connecting to a database, defining our data model, and maybe take a look at ORMs.

by Justin Fagnani (noreply@blogger.com) at December 02, 2013 08:37 AM

November 30, 2013

Dartery

Building a Building a Blog in Dart Tutorial

Almost every web application server framework out there has a “How to Build a Blog in X Minutes” tutorial. It's a right of passage for any self-respecting framework, from veterans like Ruby on Rails and Django, to the newer node.js-based frameworks.

Dart is no exception. Or... is it? A search for "building a blog in Dart" returns quite a few blogs about Dart, but none about blogs in Dart. Why?

Well, few people seem to know that Dart includes a standalone VM with a built-in HTTP server, making the VM a very node.js like environment in many ways (though if you like Dart, with a nicer language and libraries). Also, Dart doesn't have any popular, high-level, web server frameworks yet. Some frameworks in other languages are so high-level that you can practically type "superframework new blog" and be finished. Dart has a few libraries that help, but for the most part we have to handle requests, serve files, connect to databases, etc. on or own.

This means that a Dart blog tutorial will be longer and more complex - and maybe less "impressive" to some at a glance - but it's also a great opportunity to teach many parts of the Dart stack and ecosystem.

Let's build one!

Over the course of a few, or many, posts I'm going to explore all the steps and choices needed to build a fairly simple blog platform in Dart. Since I haven’t actually built a blog in Dart yet (no, I haven't done everything ahead of time before this post) we'll all be on a journey as we either build up, or find, the necessary pieces.

We won't go for extreme brevity here - I'm sure that will be covered by others as more frameworks pop up - instead we'll cover a basic function, like serving a file, and accomplish it first with little-to-no assistance from high-level packages, and then use, or build own own, helpers and abstractions to make things easier. Maybe when we're done we'll have a a tidy 5-minute tutorial, but the journey will meander a bit more.

Choices, Choices

Since Dart is so new, there are many, many choices of approaches to take and packages and libraries that might help us out. Just the choices off the top of my head are plenty:

  • Server or client side rendering?
  • Single page app?
  • What UI framework?
  • Which database and client library?
  • ORM, do we need one?
  • Serialization, how does it work?

Some of these choices I'll make later, but a few I'll settle up front since I roughly know what I want to build. Dart is designed to be a great language for building modern complex web applications, I’ll go with a single-page app, rendered on the client with custom elements using Polymer.dart, with all the data served up AJAX-style serialized as JSON. This means we won't just have a blog tutorial, but hopefully an exercise in building a modern full-stack app all in Dart.

Step 1: Stay Tuned...

Tomorrow I'll start with Step 1, which will cover the very basics of starting an HTTP server and serving an HTML file to the browser. Then we'll move on to data modeling and persistence.

If I actually have any readers, and you have suggestions, questions or thing you'd like to see covered, please let me know.

by Justin Fagnani (noreply@blogger.com) at November 30, 2013 02:51 AM

November 29, 2013

Adam Coding @ Github

Build and deploy dart to Beaglebone Black

I was looking into using dart on Beaglebone Black and decided it would be useful to share with others what I found.

After a some build hacks and patches I found a minimal working solution for Beaglebone Black with Debian ARMhf. A few important notes before going down the road of building dart for ARM. The dart-sdk is not fully supported and pub currently might not work. The dartanalyzer might not work. The only supported ARM architectures are the ones that have ARMv7 with VFP. Don’t spin your wheels trying to target any architecutre that is not ARMv7 with VFP (minimum at the moment ARMv7-A) unless you plan on implementing the routines needed in the runtime arm assembler. If you do plan on implementing them, well thats just pure awesome!

assembler_arm.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void CPUFeatures::InitOnce() {
#if defined(USING_SIMULATOR)
  integer_division_supported_ = true;
  neon_supported_ = true;
#else
  ASSERT(CPUInfoContainsString("ARMv7"));  // Implements ARMv7.
  ASSERT(CPUInfoContainsString("vfp"));  // Has floating point unit.
  // Has integer division.
  if (CPUInfoContainsString("QCT APQ8064")) {
    // Special case for Qualcomm Krait CPUs in Nexus 4 and 7.
    integer_division_supported_ = true;
  } else {
    integer_division_supported_ = CPUInfoContainsString("idiva");
  }
  neon_supported_ = CPUInfoContainsString("neon");
#endif  // defined(USING_SIMULATOR)
#if defined(DEBUG)
  initialized_ = true;
#endif
}

Download Ubuntu 12.04.3 LTS

Download the desktop iso to install on VirtualBox.

Install on VirtualBox

I work mostly on mac so Ubuntu installed on VirtualBox was needed to help with cross compiling and flashing of uSD cards.

Update the packages

Just to be safe update any Ubuntu packages before installing the development software.

Install basic packages

I typically use the git overlay on subversion when working with the dart repo. The java jre/jdk is required for building the dart_analyzer which does not work in the sdk.

shell
1
2
# Install subversion 
sudo apt-get install subversion git git-svn openssh-server vim default-jre default-jdk

Install the chrome build and arm dependencies

Checkout the latest build tools scripts. The following scripts prep your system with any packages needed for building dart.

shell
1
2
3
4
5
6
7
# checkout build scripts
svn co http://src.chromium.org/chrome/trunk/src/build; cd build

# install dependencies
chmod u+x install-build-deps.sh
./install-build-deps.sh --no-chromeos-fonts
./install-build-deps.sh --no-chromeos-fonts --arm

Install addtional libraries

The following libraries are needed for building dart but might not be included from the chrome build tool scripts.

shell
1
2
# Install addtional libs
sudo apt-get install libc6-dev-i386 g++-multilib

Install depot-tools

depot-tools is required for hacking out the dart source code.

shell
1
2
3
# depot tools
svn co http://src.chromium.org/svn/trunk/tools/depot_tools
export PATH=$PATH:`pwd`//depot_tools

Checkout the dart code base

You dont need to include --username <YOUR USERNAME> unless you plan on creating a CL for review.

shell
1
2
3
4
5
6
7
mkdir dart_bleeding
cd dart_bleeding
svn ls https://dart.googlecode.com/svn/branches/bleeding_edge/ --username <YOUR USERNAME>
gclient config https://dart.googlecode.com/svn/branches/bleeding_edge/deps/all.deps
git svn clone -rHEAD https://dart.googlecode.com/svn/branches/bleeding_edge/dart dart
gclient sync
gclient runhooks

Patch the gyp and version files

A git patch can be found here 7725354, that patches the build scripts to support building the dart-sdk for ARM. Patching the VERSION file was done in an attempt to get pub working. At the moment its not required. If not done then an old version number is baked into the dartvm. This patch also modifies which dartvm creates the snapshots for pub, dart2js and a wrapper util. Patch creates the requirement of having to build the dartvm for x64 before building the dart-sdk for ARM. The dart build scripts have a funky dependency of wanting to use the dartvm target to create the snapshot files. Which in this case wont work since our dartvm is an ARM target being built on x64.

arm.build.patch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
diff --git a/tools/VERSION b/tools/VERSION
index d1ab212..0d6101d 100644
--- a/tools/VERSION
+++ b/tools/VERSION
@@ -1,5 +1,5 @@
 CHANNEL be
-MAJOR 0
-MINOR 1
-BUILD 2
-PATCH 0
+MAJOR 1
+MINOR 0
+BUILD 0
+PATCH 7
diff --git a/utils/compiler/compiler.gyp b/utils/compiler/compiler.gyp
index 294c7e9..5f3754a 100644
--- a/utils/compiler/compiler.gyp
+++ b/utils/compiler/compiler.gyp
@@ -18,7 +18,7 @@
         {
           'action_name': 'generate_snapshots',
           'inputs': [
-            '<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart<(EXECUTABLE_SUFFIX)',
+            '<(PRODUCT_DIR)/../DebugX64/dart',
             '../../sdk/lib/_internal/libraries.dart',
             '<!@(["python", "../../tools/list_files.py", "\\.dart$", "../../sdk/lib/_internal/compiler", "../../runtime/lib", "../../sdk/lib/_internal/dartdoc"])',
             'create_snapshot.dart',
@@ -30,7 +30,7 @@
             '<(SHARED_INTERMEDIATE_DIR)/dart2js.dart.snapshot',
           ],
           'action': [
-            '<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart<(EXECUTABLE_SUFFIX)',
+            '<(PRODUCT_DIR)/../DebugX64/dart',
             'create_snapshot.dart',
             '--output_dir=<(SHARED_INTERMEDIATE_DIR)',
             '--dart2js_main=sdk/lib/_internal/compiler/implementation/dart2js.dart',
diff --git a/utils/pub/pub.gyp b/utils/pub/pub.gyp
index fd5e147..ab2e243 100644
--- a/utils/pub/pub.gyp
+++ b/utils/pub/pub.gyp
@@ -25,7 +25,7 @@
             '<(SHARED_INTERMEDIATE_DIR)/pub.dart.snapshot',
           ],
           'action': [
-            '<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart<(EXECUTABLE_SUFFIX)',
+            '<(PRODUCT_DIR)/../DebugX64/dart',
             '--package-root=<(PRODUCT_DIR)/packages/',
             '--snapshot=<(SHARED_INTERMEDIATE_DIR)/pub.dart.snapshot',
             '../../sdk/lib/_internal/pub/bin/pub.dart',

Build the dart-sdk

Building of the dart-sdk for ARM target is a two stop process. First build x64 so we can use that dartvm to generate the snapshot files. Then the second step is running the create_sdk build for ARM. When the build is finished the out/ReleaseARM/dart-sdk should contain a full dart-sdk build. Keep in mind this does build the dartanalyzer but it may not work on ARM.

shell
1
2
3
4
5
# build a target for your native system to create the snapshot files. 
./tools/build.py -m debug -v -a x64 -j 8

# build the arm target
./tools/build.py -m release -v -a arm -j 8 create_sdk

Tarball the sdk

Package up the dart-sdk as a tarball to distribute.

shell
1
2
cd ./out/ReleaseARM/
tar -czvf dart-sdk.tar.gz dart-sdk

Install Debian Wheezy 7.2 Hard Float Minimal Image on Beaglebone Black

In virtualbox with a uSD card at /dev/sdX the following will download an image and write to the uSD card. Updated images can be found at armhf

shell
1
2
wget http://s3.armhf.com/debian/wheezy/bone/debian-wheezy-7.2-armhf-3.8.13-bone30.img.xz
xz -cd debian-wheezy-7.2-armhf-3.8.13-bone30.img.xz > /dev/sdX

Then insert the uSD card into the Beaglebone Black and boot the image by holding down the boot switch and powering on.

Write the booted image to the eMMC.

shell
1
xz -cd debian-wheezy-7.2-armhf-3.8.13-bone30.img.xz > /dev/mmcblk1

Power down and remove the uSD card.

Update glibc on the BeagleBone Black

Updating glibc is required cause the version of glibc installed from the chromium build scripts is greater then the one shipped with Wheezy 7.2. The following commands update glibc.

shell
1
2
3
4
5
6
7
8
# Add an addtional source for the latest glibc
sudo sed -i '1i deb http://ftp.us.debian.org/debian/ jessie main' /etc/apt/sources.list

# Update sources 
sudo apt-get update

# Download latest glibc
sudo DEBIAN_FRONTEND=noninteractive apt-get -t jessie install -y libc6 libc6-dev libc6-dbg git screen

Copy over dart-sdk

From virtual box copy over the tarball to Beaglebone Black running debian.

shell
1
scp dart-sdk.tar.gz debian@192.168.2.2:~/

After the tarball is copied, uncompress and add to your PATH.

shell
1
2
3
4
tar -zxvf dart-sdk.tar.gz
export PATH=~/dart-sdk:$PATH
dart --version
Dart VM version: 1.0.0.7_r30634_adam (Fri Nov 29 01:14:42 2013) on "linux_arm"

Known issues at the moment

Pub does not work, issue could be followed at 15383. I was testing this out while staying at a hotel so some proxy settings might of been blocking or tripping up pub.

Feedback

If you have a better way of running dart on Beagleblone Black I would love to hear it! Please contact me on g+ and lets discuss.

Update on dartanalyzer

dartanalyzer will work after installing the default-jre on Beaglebone Black.

shell
1
sudo apt-get install default-jre

Addtional resources

November 29, 2013 04:56 PM

November 14, 2013

Dartwatch

Dart is Launched - V1.0

And with this tweet... Dart v1.0 is launched.

by Chris Buckett (noreply@blogger.com) at November 14, 2013 08:44 AM

November 01, 2013

Matt Butler

Everything old is new again

I was very recently asked to apply some updates to a project that I had last touched back in June 29th, 2012 (the project’s original start was May 7th of 2012). It has been running happily ever since. But as all things, there was a request to add a new feature to satisfy customers.

However many things have changed in Dart since that script was first deployed. Significant library and language changes. Looking at the source I immediately realised that I would need to rewrite the application from scratch based on the old source code rather than simply trying to update the source directly. Since the script was running fine in the past there had never been a need to continually apply updates as they occurred in the language or libraries. I just left it run.

A day and a half later or so, I have reached parity with the old sources and am ready to start adding the new functionality. I decided before doing that I would document some of the changes to the source that I encountered with this project. Please note that this is a very small script by most reasonable standards and it does not do anything very fancy. The change I document will in no way be all inclusive to any updates that others may do, but only reflects the items I ran into personally on this one projects. Additionally, the project itself is not an open source project but rather something to address a specific need for the company, as such I cannot provide specific examples or source, but I can provide the gist of things.

No packages!
So the first thing I noticed, at least reflecting back on it now, is that there was no packages. No Package layout conventions, no pubspec.yaml file, nothing. Now normally you wouldn’t have those included anyways in a deployed application, however I could also see there the code was commented out from using the Google Code hosted dart.js file. I downloaded a local copy of dart.js around February of this year for the project.
Dart.js filesize
The dart.js file which was used in the project (as mentioned, a copy from around February) was around 8.2KB in size. The current one provided by the Browser package weighs in at 1.5KB. Not a major factor with the old version but still an interesting comparison to see.
Library, Import and Source
First thing that I noticed when opening the original project was the #library('myProject'); declarations. Followed of course by #import('dart:html'); Now of course, gone are the hash signs, gone are the strings for library definitions, and of course the #source() tags are gone altogether, replaced with the part and part of declarations.
$dom_xxxx methods and properties
Another big item that popped out at me as I looked through my original sources, were the calls to the underlying dart:dom library. In particular one property I had to make use of was $dom_scrollTop as it’s equivalent wasn’t yet available in dart:html directly.
window.setTimeout()
At the time I wrote the original code, the Timer class wasn’t yet completed, and was primarily used for server-side timers. On the client side it was still really using the window.setTimeout and window.setInterval. Timers and Futures provide a much nicer way of delaying things now.
Durations!
Speaking of the Timeouts, all those calls in my original code were based on number of milliseconds to call the timeout. Now we have the Duration class to the rescue. Duration’s constructor with optional parameters makes life easy.
XMLHttpRequest
In particular, using the XMLHttpRequest.get constructor, was prevalent throughout the old code. This constructor takes a URL and a callback which will receive the completed XMLHttpRequest object. The current HttpRequest class, with it’s static methods like getString to provide a nice Future-based API for the most common functions.
DateTime replaces Date
While maintaining much of the original functionality, the DateTime class has replaced the old Date class. The now named constructor still functions much the same. However it apperas that the DateTime.weekday property is currently a 1-based index, whereas the old API appeared to be 0-based index.
StringBuffer updates
The good old StringBuffer class is still around, but it’s API has seen a few updates. In particular it’s less List like, and now more in line with the StringSink interface. Simply put, my .add() calls are now .write() calls.
List APIs
A few subtle changes also exist in the List class. For the most part in my code it was the change of some methods to be properties/getters, such as the isEmpty property.
Cascades!
At first I thought the absence of cascades from my old source was related to my programming style at that time, but a quick search revealed that cascades were not generally available until after I had completed this project. I know it took me a little while to get used to using cascades when they were initially released but I love them now!

This list was just a few of the many many changes that have happened as Dart has matured in the last year and some. I left off a couple of more recent changes such as querySelector as I’ve already covered it briefly and is a very recent change. Additionally, I would like to compare file output sizes but I don’t believe the old Javascript output had been minified, but the new one is so I don’t know that it would make for a fair comparison. The non-minified version is actually slightly larger than the old version of code, but this may also be due to a few structural changes I made to the sources to prepare for adding the new requested feature.

It’s been a fun look at the past of Dart, and I may do so again eventually for server side code if I get an opportunity to look at my Dart-based MUD. The source of which is still available in my GitHub Repository. Warning! It’s not pretty!

by Matthew Butler at November 01, 2013 07:26 PM

October 23, 2013

Adam Coding @ Github

google client apis new release 0.4.x

The dart-gde team has updated the google client apis to '>=0.4.0'. Along with this change was an update for Google OAuth2 Client to '>=0.3.0'.

The breaking changes for Google OAuth2 Client

  • SystemCache has been removed.
  • GoogleOAuth2.ensureAuthenticated() A much cleaner impl that eliminates the need to pass in a HttpRequest object to authenticate.
  • All dependencies bumped to latest versions.
  • Code refactored.
  • Dead code eliminated.
  • Remove deprecated libraries.
  • Heavy logging removed.

The breaking changes for generated google client apis include

  • Renamed lib/src/{cloud_api.dart -> client_base.dart} lib/src/{cloud_api_console.dart -> console_client.dart} lib/src/{cloud_api_browser.dart -> browser_client.dart}.
  • ClientBase.responseParse(int statusCode, String responseBody) introduced and handles parsing responseBody. responseParse will throw DetailedApiRequestError if the body has an error.
  • Renamed APIRequestException -> APIRequestError.
  • Remove deprecated libraries.

Updating requires a small change in pubspec.yaml

pubspec.yaml
1
2
dependencies:
  google_plus_v1_api: '>=0.4.0'

A small collection of demo examples could be found at dart_api_client_examples.

Full list of available Google client apis on pub.dartlang.org

October 23, 2013 02:34 AM

October 18, 2013

Dartwatch

Web Components in Action... Launched...

Not entirely Dart related... but my new book Web Components in Action is now available from Manning in Preview (MEAP) form.  It's aim is to lead you through developing your web components, primarily using Polymer (this is part of the reason things have been a little quite from me...)

Download the free chapter 1 and let me know what you think.   It's also Manning's deal of the day today, 18th October... use the code: dotd1018au when you follow this link to the book's site on manning.com.

by Chris Buckett (noreply@blogger.com) at October 18, 2013 10:54 AM

October 16, 2013

Future Perfect

A Test of Two Implementations

I write many tests for my code, and I think that most software engineers will agree about the positive value of having good tests. Tests help me find problems with my design and they give me assurance that a particular library or service continues to function as intended over time. This post is a bit of a potpourri of testing in Dart and how I’ve approached the problem of testing multiple implementations of an interface.

Batteries Included

One of the really nice things about Dart is that it comes out of the box with a solid unit testing framework. The framework is not perfect, but the mere fact that it exists and is widely used is of large benefit. I’ve been using it for a while now in my projects, and over time my own library has evolved to augment the standard library for my practical needs.

Bench Reloaded

I wrote a post almost a year ago about my first attempt at publishing a Dart package for micro-benchmarks, Bench. It was a fun exercise for me, but after a while it became apparent that there was not much interest in it and an official benchmarking package was later released by the Dart team. So I decided to repurpose this package a couple of months ago as a test bench. The new goal of Bench is to reduce the complexity of declaring test functions and wiring them together to be run.

Reflection at Work

Automation of unit tests is a classic application of reflection. Normally, unit tests are not deployed so there is not concern regarding the overhead of code size or execution speed that reflection may introduce. Rather, the focus is on developer productivity and tooling.

Many popular unit testing frameworks such as junit (Java) and nunit (C#) use reflection, so this approach has been validated many times before. However, Dart is unique and I have tried hard to apply lessons learned from those other tools in a way that suits Dart. In particular, I have found that libraries (as opposed to classes) work well as the unit of encapsulation for a group or suite of test functions, thanks to Dart’s support for first-class functions.

Let’s take a look at a simple example of using Bench:

@TestGroup(description: 'Exhibit A')
library example;

import 'package:bench/bench.dart';
import 'package:unittest/unittest.dart';
 
void main() => reflectTests();

@Setup
setup() => print('Invoked one time before each test.');

@Teardown
teardown() => print('Invoked one time after each test');

@Test('An example test case that passes.')
void testPass() {
  expect(true, isTrue);
}

Some notes on the above example:

  • The @TestGroup annotation is optional, and allows us to give a custom name to our test group. If we don’t apply a @TestGroup annotation Bench will still run our tests, using the library’s name by default.

  • We’ve included a main function in our library for brevity, as you’ll need at least one in your test project to serve as the entry point and to call reflectTests(). It is useful to include one in each test group library, so that it can be run individually, but this is not required. Instead you could structure your test application to have a single entry-point which imports all of your test group libraries. As you work and add new @Test functions to the different libraries in your test application, no additional wiring is needed.

  • Each top-level function annotated with @Test declares a test function, with an optional description. If no description is given, the name of the function will be used. To add a new test function to the test group, you simply start writing a new top-level function with this annotation applied and the next time you run the program it will be called.

  • The top-level functions annotated with @Setup and @Teardown are optional, and if you do include them in the library they are each called 1 time per test function. This is just syntactic sugar for the setup and teardown methods in the unittest library.

This simple example covers the basic functionality exposed in Bench; there is more there for you to explore, and it continues to evolve with the needs of real-world projects that are using it. One such evolution is the main subject of this post.

Testing Multiple Implementations

This recently added feature goes above and beyond syntactic sugar for the unittest library.

Let’s consider an example with an abstract Connection class:

abstract class Connection {
  bool get isConnected;
  Future connect();
  Future disconnect();
}

Our Connection class represents a very basic interface for a persistent connection. We may have multiple concrete implementations of this class, such as a TcpConnection and an HttpConnection. We would like to write a group of tests for all types of Connection, and then run that test group against each of our implementations.

Let’s start to write a test group for a Connection using what we’ve learned so far:

@TestGroup(description: 'Connection')
library connection.test;

import 'package:bench/bench.dart';
import 'package:unittest/unittest.dart';
import 'connection.dart';
import 'tcp_connection.dart';

void main() => reflectTests();

Connection connection;

@Setup
void setup() {
  connection = new TcpConnection();
}

@Test('Test that the connection isConnected')
void testIsConnected() {
  connection.connect().then(expectAsync1((_) {
    expect(connection.isConnected, isTrue);
  }));  
}

Our test function above tests the state of the connection variable, which is declared as a Connection. In our setup function we assign an instance of TcpConnection to this variable; notice how that is the only reference to TcpConnection in the entire test library. By decoupling our test function testIsConnected from the actual implementation we are paving the way to reuse this test library for other types of connections.

Declare Multiple Test Runs

Now that we have a basic test library for Connection we’d like to extend our test coverage to include an HttpConnection implementation.

The TestGroup annotation accepts an optional parameter named runs, which is a list of string identifiers. The first change we will make to our test library is to declare two runs of the test group:

@TestGroup(description: 'Connection', 
           runs: const ['tcp', 'http'])
library connection.test;

As we see above, we’ve chosen the identifiers tcp and http to declare our two runs. Running our test library now will execute our test function twice:

unittest-suite-wait-for-done
PASS: Connection[tcp] Test that the connection isConnected
PASS: Connection[http] Test that the connection isConnected

All 2 tests passed.
unittest-suite-success

Both test runs are identical at this point, but we can see that the identifiers we chose have been included in the output for each test to provide quick feedback.

Our next step will be to actually use the HttpConnection for the http test run.

Setup Test Runs

In order to configure the different runs of our test library, we need to modify its @Setup function as follows:

@Setup
void setup(TestRun run) {
  if (run.id == 'tcp') {
    connection = new TcpConnection();
  } else {
    connection = new HttpConnection();
  }
}

Notice how we have added a parameter of type TestRun to the declaration of our setup function. This tells Bench that we would like to receive the context of each test run. The TestRun object that we receive contains a field id where we can inspect one of our chosen identifiers. We use this information to create an instance of either TcpConnection or HttpConnection, as appropriate.

That is all that is required in order to run all of our test functions against both of our Connection implementations. We can iterate on our test library, adding new tests for the connection variable, and know that we are testing both of our implementations. If we write a new type of Connection, we can add it to the runs list and get instant coverage.

Test it!

You can find the example code from this article in this gist.

Please give bench a try and open issues to request features or report bugs. I use this library in all of my Dart projects, so rest assured that it is supported. The more people who use it and provide feedback, the better it will be.

by Ross Smith at October 16, 2013 12:00 AM

October 09, 2013

Shannon -jj Behrens

Pimsleur Spanish Phases 1-3

I just finished Pimsleur Spanish phases 1-3 which I bought on audible.com. In short, I thought they were fantastic!

Each phase consists of 30 units, each about 30 minutes long. Hence, I did 90 units altogether. That sounds like a lot, but I did almost all of them while driving to and from work when I worked in Mountain View. I streamed them from my phone through my stereo using bluetooth.

Before I started, I already had a decent grasp of Spanish. However, I started Pimsleur Spanish from scratch. I'm normally a very visual learner, and Spanish is a pretty easy language to learn visually since it's so phonetic. However, I needed something to do while driving upwards of three hours a day, and this fit the bill. I really like how conversational it is. It constantly pushes you to say new things in new situations using your existing knowledge of vocabulary and grammar.

I know that some people have said that they thought Pimsleur Spanish was a little boring compared to Rosetta Stone. However, Rosetta Stone requires you to be in front of a computer, and I needed something that I could do while driving. By the way, I recommend only attempting this on long, fairly boring freeway trips. It takes up a little too much mental bandwidth to attempt on city streets.

After studying Spanish for several months, I was able to give a technical talk in Spanish in Mexico City. Doing the talk live was terrifying, and I'll admit that my voice was shaking quite a bit. However, later I did a screencast of it, Esto es Dart. That went pretty well.

Updated: I had to disable comments because this blog post was getting too many spammy comments.


by Shannon Behrens (noreply@blogger.com) at October 09, 2013 05:09 PM

September 29, 2013

Seth Ladd

Forms, HTTP servers, and Polymer with Dart

(Update of this old Web UI post. Updated as of Jan 17, 2014 and Dart 1.1.)

Dart can be used on the client and the server. This post shows how to:

  • build a form as a custom element
  • bind input fields to a Dart object
  • build a Dart HTTP server
  • handle and parse a form submit


For lots more Polymer.dart examples, be sure to check out the Dart Polymer Samples. You can find the code for this post at my Github account.

Step 1: Install the packages

Open up pubspec.yaml (used by the pub package manager) and add the dependencies for Polymer.dart and http_server.

name: parse_form_submit
description: A sample Polymer application
dependencies:
polymer: any
http_server: any

Step 2: Create the model class

This class is for the "business object". It is bound to the form, so we make its fields observable.

library models;

import 'package:polymer/polymer.dart';

class Person extends Object with Observable {
@observable String firstName;
@observable String lastName;
@observable int age = 0;
}

Step 3: Create the custom element HTML


This custom element, brought to you by Polymer.dart, wraps the form and makes it easy to reuse. The <template> tag contains the structure of this custom element. The submit event runs the doSubmit() method of this custom component (see in the next step).

A Dart class, linked by the <script> tag, backs this custom element.

<!DOCTYPE html>

<polymer-element name="person-form" attributes="action">
<template>
<div id="message"></div>
<form method="post" on-submit="{{doSubmit}}">
<div>
First name: <input type="text" value="{{person.firstName}}" name="firstName">
</div>
<div>
Last name: <input type="text" value="{{person.lastName}}" name="lastName">
</div>
<div>
Age: <input type="number" value="{{person.age | asInteger}}" name="age">
</div>
<div>
<input type="submit">
</div>
</form>
</template>
<script type="application/dart" src="person_form.dart"></script>
</polymer-element>


Step 4: Create the custom element Dart code

If a custom element needs custom behavior, you can implement it with Dart. Each custom element tag you use on the page has an instance of its corresponding class. Here, the PersonForm class goes with the <person-form> tag.

The doSubmit() method is called when the form is submitted (see the on-submit binding from Step 3).

In this case, we disable the default behavior of form submission so we don't incur a page reload. We use HttpRequest to submit the form data, and update a div inside our custom element with the response text.

import 'package:polymer/polymer.dart';
import 'models.dart';
import 'dart:html';
import 'ui_filters.dart' show StringToInt;
import 'package:polymer_expressions/filter.dart' show Transformer;

@CustomTag('person-form')
class PersonForm extends PolymerElement {
final Person person = new Person();

PersonForm.created() : super.created();

@published String action;

doSubmit(Event e, var detail, Node target) {
e.preventDefault();

FormElement form = target as FormElement;
form.action = action;

HttpRequest.request(action,
method: form.method,
sendData: new FormData(form))
.then((HttpRequest req) {
shadowRoot.querySelector('#message').text = req.responseText;
})
.catchError((e) => print(e));
}

// Filters and transformers can be referenced as fields.
final Transformer asInteger = new StringToInt();
}

Step 5: Import and use the custom element

Use a <link> tag to import the custom element. You must also export polymer/init.dart, which helps to initialize the app.

<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8">
<title>Sample app</title>
<link rel="stylesheet" href="parse_form_submit.css">
<link rel="import" href="person_form.html">
<script type="application/dart">export 'package:polymer/init.dart';</script>
<script src="packages/browser/dart.js"></script>
</head>
<body>
<h1>Forms</h1>

<person-form action="http://localhost:8888/submit"></person-form>

</body>
</html>


Step 6: Write the server

Dart's dart:io library help you write command-line and server-side application. We use the http_server package for additional HTTP server functionality. The server listens for POST requests, parses the form data into a Map, enable CORS headers (so pages from any origin can submit to this server), and sends back a string version of the original form data.

import 'dart:io';
import 'package:http_server/http_server.dart';

echo(HttpRequest req) {
print('received submit');
HttpBodyHandler.processRequest(req).then((HttpBody body) {
print(body.body.runtimeType); // Map
req.response
..headers.add('Access-Control-Allow-Origin', '*')
..headers.add('Content-Type', 'text/plain')
..statusCode = 201
..write(body.body.toString())
..close();
});
}

main() {
HttpServer.bind('0.0.0.0', 8888).then((HttpServer server) {
print('Server is running');
server.listen((HttpRequest req) {
if (req.uri.path == '/submit' && req.method == 'POST') {
echo(req);
}
});
});
}


Summary

Ta da! You've just used Dart to create a live, data-bound form and wrapped it up in a web component. Then, you wrote a Dart server to parse the form data and return a simple response. Be sure to checkout the Github repo for this post for all the code. Is this the best we can do? Probably not, you probably want a more full-featured server-side framework. There are a few in pub.dartlang.org for you to explore.

Learning more

To learn more about Dart, try these resources:

by Seth Ladd (noreply@blogger.com) at September 29, 2013 12:38 AM

September 28, 2013

Daniele Salatti

Dart: static_file_handler 0.1.3 is out

A few days ago I released version 0.1.3 of the static_file_handler, my first real contribution to the open source community since ca. December 2005. It’s actually being used in a framework, and probably in a handful of projects – I’m saying that based on the fact that I received a pull request and someone opened a couple of issues1.

I must say that I’m enjoying doing it: I like the feeling of being part of something, releasing code that other developers are using somewhere else in the world on cool projects. Currently I’m working on version 0.2.0, whose to-do list already includes e.g. support for ETags, HTTP requests with multiple ranges, and few other improvements that you can see on the list of issues on GitHub. And that’s the reason for this post: what features would you like to see in it?


  1. if you are using it, please feel free to boost my ego by writing a comment to this post

September 28, 2013 11:30 AM

September 22, 2013

Future Perfect

Determined to Iterate a Set

Something funny started to happen in my Dart application this week. I was visually observing a problem on startup, but only on 50% of the launches. My code base is starting to get large, so I had to pause for a minute, but part of me already knew what was happening. What I later discovered with some experimentation surprised me.

A Nondeterministic Program

Consider the following Dart program:

class Box {
  final int i;
  const Box(this.i);
}

main() {     
  var set = new Set<Box>()
  ..addAll(
      [ const Box(1), 
        const Box(2), 
        const Box(3)]);  
  set.forEach((box) => print('${box.i}'));
}

Which might yield the following output (Dart SDK r27704):

2
3
1

Or it might yield the following output instead:

3
2
1

This kind of program is referred to as nondeterministic because for a given input it does not consistently yield the same output over multiple runs. This can lead to subtle bugs if it is not a conscious decision of the developer.

HashSet Iteration is Nondeterministic

As we saw above, iteration over a HashSet is nondeterministic. This is spelled out pretty clearly in Java but not so much in the current (r27704) Dart SDK. If you know this and you are writing all of your own code, then you should be okay. If you are dealing with a large code base full of collections written by a variety of folks, then this might catch you by surprise.

There is a remedy for this in Java with LinkedHashSet:

Hash table and linked list implementation of the Set 
interface, with predictable iteration order.

And in Dart we also have a LinkedHashSet:

The LinkedHashSet also keep track of the order that elements 
were inserted in, and iteration happens in first-to-last 
insertion order.

Let’s change our program to explicitly use a LinkedHashSet and see what happens:

import 'dart:collection';

class Box {
  final int i;
  const Box(this.i);
}

main() {     
  var set = new LinkedHashSet<Box>()
  ..addAll(
      [ const Box(1), 
        const Box(2), 
        const Box(3)]);  
  set.forEach((box) => print('${box.i}'));
}

This new program consistently yields the following output:

1
2
3

So you may be asking yourself at this point, what really went wrong in the original program? I would assert that the new Set factory constructor gave us an instance of the wrong type.

Asymmetric Factories

In order to make my case I need to first demonstrate the iteration behavior of Dart’s Map type:

class Box {
  final int i;
  const Box(this.i);
}

main() {  
  var map = new Map<Box, Box>()
  ..addAll({ 
    const Box(1) : const Box(1),
    const Box(2) : const Box(2),
    const Box(3) : const Box(3)
  });
  map.keys.forEach((box) => print('${box.i}'));
}

This program also consistently yields the following output:

1
2
3

This isn’t what I had expected after my experience with Set. As it turns out, the new Map factory constructor provides an instance of LinkedHashMap:

factory Map() = LinkedHashMap<K, V>;

But the new Set factory constructor provides an instance of HashSet (instead of LinkedHashSet):

factory Set() => new HashSet<E>();

I believe that this is both inconsistent and confusing. If users grow accustomed to reliable iteration order for the default Map objects, they will naturally expect a reliable iteration order for the default Set objects as well.

I’ve opened a Dart issue regarding this; please follow along there for the latest status.

by Ross Smith at September 22, 2013 12:00 AM

August 14, 2013

Dartwatch

Translating the Web-UI x-click-counter to Polymer.dart

This blog post shows how to take the Web UI sample "x-click-component" project created from Dart Editor wizard, and convert it into a Polymer.dart project.  Along the way, I'll highlight some of the differences between Web-UI and Polymer (and some of the similarities).

Dart's web components project, called Web-UI, is migrating over to the Polymer project's web component framework.

One of the key differences between the Dart's Web UI project and Polymer is that Polymer doesn't require a separate build step (or the /out/ folder), at least while you're developing (you'll still want a build step when you deploy, to combine all the external imports).

Note: This blog post was written using Dart 0.6.15 r25822 and Polymer 0.5.3.

Creating the project


Let's start by creating a new project in the editor.

Create a new Web Application (using the web_ui library) project
This creates you a web project structure containing a set of example files.  After a few seconds, pub has installed the various packages and build.dart has finished running, your folder structure probably looks something like this:
The starting web-ui folder structure

Removing Web UI and Build.dart

The first step (and I'm sure you'll do this with a smile on your face) is to stop build.dart running.  Right click it, and click the handy menu option "Don't run build.dart"

Next, open the pubspec.yaml file, and remove all the current dependencies (likely to be browser, js and web_ui).  Add a polymer dependency:

Changing the custom element to Polymer

In your project there will be two files that represent the existing Web UI x-click-counter custom element.  These are xclickcounter.html, which provides the layout, and xclickcounter.dart, which provides the script.  

The existing x-click-counter defines itself as a custom element, has a button that lets you click it to increment a data bound value.  It looks like the screenshot below:
Example screenshot of the x-click-counter component
We'll go through a couple of iterations to modify this to Polymer.  First, we'll just get the custom element to show up in the page, and then we'll come back and look at the interactivity and data binding.

Before modification, xclickcounter.html looks like this:

xclickcounter.html before modification:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>

<html>
<body>
<element name="x-click-counter" constructor="CounterComponent" extends="div">
<template>
<div>
<button on-click="increment()">Click me</button><br />
<span>(click count: {{count}})</span>
</div>
</template>
<script type="application/dart" src="xclickcounter.dart"></script>
</element>
</body>
</html>

There are three key parts that you need to be aware of in the original Web UI element:

  • Line 5: The <element> tag
  • Line 8: Calling an increment() function
  • Line 9: Databinding a {{count}} value
Start by modifying this to be a polymer element.  Change the <element> tag on line 5 to be a <polymer-element> and update the closing </element> tag on line 13. A polymer element is a like a supercharged custom element, with functionality provided by the Polymer framework.  It automatically uses things like the Shadow DOM and allows for simple component registration.
Notice also that the name is changed from x-click-counter to my-clickcounter, (for the sake of simplicity, I'm not going to rename the filenames).  I've also removed the {{count}} binding for now. We'll add it back again, soon

xclickcounter.html after modification:


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>

<html>
<body>
<polymer-element name="my-clickcounter">
<template>
<div>
<button on-click="increment()">Click me</button><br />
<span>(click count: )</span>
</div>
</template>
<script type="application/dart" src="xclickcounter.dart"></script>
</polymer-element>
</body>
</html>

Important:  Web Component custom elements names need to contain a hyphen. The intention is that the first part before the hyphen is a vendor prefix (to differentiate between different clickcounter components, for example).  See this discussion on the polymer mailing lists.
Let's change the associated script in the xclickcounter.dart file.  This represents our element in code.  Before modification it looks like this:

xclickcounter.dart before modification:

 1
2
3
4
5
6
7
8
9
10
import 'package:web_ui/web_ui.dart';

class CounterComponent extends WebComponent {
@observable
int count = 0;

void increment() {
count++;
}
}
First, let's change line 1 to import the polymer libary:


import 'package:polymer/polymer.dart';


Then let's change line 3 - CounterComponent class to extend PolymerElement instead of WebComponent


class CounterComponent extends PolymerElement {

Finally, we need to provide a method of registering our my-clickcounter element with the browser. The JavaScript version of Polymer elements do this using a JavaScript call, but in Dart, we can use a @CustomTag('my-clickcounter') class annotation.  The full changed xclickcounter.dart file is shown below (note, we'll return to the commented out functionality in a few steps:

xclickcounter.dart after modification:

 1
2
3
4
5
6
7
8
9
10
11
import 'package:polymer/polymer.dart';

@CustomTag("my-clickcounter")
class CounterComponent extends PolymerElement {
// @observable
// int count = 0;
//
// void increment() {
// count++;
// }
}

Now that the layout and script for the custom element is changed to use Polymer, let's see how you actually use them in your application's main page.

Using the Custom Element in your page

Currently, our main page (called polymerclicker1.html), and our main script (called polymerclicker1.dart) use Web UI.  The Web UI version of the files look like this

polymerclicker1.dart before modification:


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
import 'dart:html';
import 'package:web_ui/web_ui.dart';

// initial value for click-counter
int startingCount = 5;

/**
* Learn about the Web UI package by visiting
* http://www.dartlang.org/articles/dart-web-components/.
*/
void main() {
// Enable this to use Shadow DOM in the browser.
//useShadowDom = true;
}

polymerclicker1.html before modification


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8">
<title>Sample app</title>
<link rel="stylesheet" href="polymerclicker1.css">

<!-- import the click-counter -->
<link rel="import" href="xclickcounter.html">
</head>
<body>
<h1>Polymerclicker1</h1>

<p>Hello world from Dart!</p>

<div id="sample_container_id">
<div is="x-click-counter" id="click_counter" count="{{startingCount}}"></div>
</div>

<script type="application/dart" src="polymerclicker1.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>

It only takes a couple of simple modifications to change these to use Polymer.   To start with, you can remove everything from the .dart file apart from an empty main() function.  We'll add something back into this once we start data binding a little later.

polymerclicker1.dart after modification:

1
2
3
void main() {
// no content here yet.
}

Next, lets modify the HTML file.  This introduces a new piece of functionality, in the form of boot.js, found in the Polymer package.  The comments from that file explain fairly succinctly (we'll see it in action in a moment).

This script dynamically prepares a set of files to run polymer.dart. It usesthe html_import polyfill to search for all imported files, then it inlines all <polymer-element> definitions on the top-level page (needed by registerPolymerElement), and it removes script tags that appear inside those tags. It finally rewrites the main entrypoint to call an initialization function on each of the declared <polymer-elements>.
To get this working, replace the existing JavaScript script import on Line 22:  packages/browser/dart.js with polymer's packages/polymer/boot.js.

Let's also modify the #click_counter div to be an actual my-clickcounter element, by changing line 18 so that...


<div is="x-click-counter" id="click_counter" count="{{startingCount}}"></div>
<!-- becomes... -->
<my-clickcounter id="click_counter" count="{{startingCount}}">
                                                           </my-clickcounter>

Now, the polymerclicker1.html should look like this, with lines 18 and 22 changed.:

polymerclicker1.html after modification


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8">
<title>Sample app</title>
<link rel="stylesheet" href="polymerclicker1.css">

<!-- import the click-counter -->
<link rel="import" href="xclickcounter.html">
</head>
<body>
<h1>Polymerclicker1</h1>

<p>Hello world from Dart!</p>

<div id="sample_container_id">
<my-clickcounter id="click_counter" count="{{startingCount}}"></my-clickcounter>
</div>

<script type="application/dart" src="polymerclicker1.dart"></script>
<script src="packages/polymer/boot.js"></script>
</body>
</html>

Running in Dartium

You can go ahead and run this in now Dartium.  It doesn't have any interactivity (it will throw an error when you click the button), but it's worked without the build step
Tip: you might need to delete the web/out/ subfolder created by the old build.dart if you're being automatically redirected.

Let's take a look under the covers and see what's happened.  The old build.dart used to examine the static HTML page and combine all the HTML Imports into a runnable set of files before the application was run.  The polymer boot.js does this, but at runtime by replacing the our applications main() function (currently empty in polymerclicker1.dart) with a higher level main function that imports all the web componetns, initializes polymer and finally calls our own main() function (identified as userMain.main).  If you inspect elements in Dartium, you'll see the new script looks something like this:


1
2
3
4
5
6
7
8
9
import "http://127.0.0.1:3030/web/xclickcounter.dart" as i0;
import "package:polymer/polymer.dart" as polymer;
import "http://127.0.0.1:3030/web/polymerclicker1.dart" as userMain;

main() {
polymer.initPolymer([
"http://127.0.0.1:3030/web/xclickcounter.dart"
], userMain.main);
}

This new main() function passes in a list of all the polymer elements discovered through HTML Imports, and a callback to the original userMain.main() function.

From comments like this in the boot.js,
//TODO: rephrase when we split build.dart in two: analysis vs deploy pieces.
console.warn('boot.js only works in Dartium. Run the build.dart  tool to compile a depolyable JavaScript version')
it seems that the intention is that this is only used for development.

Adding data binding to the custom element

At the moment we're using the custom element, but it has no interactivity or data binding.  Remember that {{count}} we removed?  Let's put it back.  Polymer.dart uses an ObservableMixin to add the ability to observe changes to a variable through the @observable annotation.  This annotation allows two way data binding between the count field in the class instance, and any {{ count }} declarations in the template.
Uncomment the previously commented out section (lines 6 through 11), and add the ObservableMixin to the class definition (line 5) in xclickcounter.dart.

xclickcounter.dart after modification with functionality and observable mixin


 1
2
3
4
5
6
7
8
9
10
11
12
import 'package:polymer/polymer.dart';

@CustomTag("my-clickcounter")
class CounterComponent extends PolymerElement
with ObservableMixin {
@observable
int count = 0;

void increment() {
count++;
}
}

Let's also put the {{count}} binding value back into the xclickcounter.html at line 9.  The on-click="increment()" function call on line 8 changes as well - removing the parentheses (this is inline with the JavaScript version of Polymer).

xclickcounter.html after modification with functionality and data binding.


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>

<html>
<body>
<polymer-element name="my-clickcounter">
<template>
<div>
<button on-click="increment">Click me</button><br />
<span>(click count: {{ count }})</span>
</div>
</template>
<script type="application/dart" src="xclickcounter.dart"></script>
</polymer-element>
</body>
</html>

Finally, run the same polymerclicker1.html application, and you'll see that you can now click the "Click Me" button to increment the count.


Binding initial data values

The last step we need to take is to databind an initial value.  The original Web UI click counter initialized the counter with a value of startingCount=5. I've not found a way to do this exactly yet (and it may be that this part of Polymer hasn't been ported over yet), but you can achieve it through template binding.

The first step is to publish a public attribute on the my-clickcounter polymer element.  You do this using the attributes="" attribute on the <polymer-element> definition, making public any properties in the underlying Dart class.  Change Line 5 of xclickcounter.html as shown below:

xclickcounter.html after modification with published count attribute


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>

<html>
<body>
<polymer-element name="my-clickcounter" attributes="count">
<template>
<div>
<button on-click="increment">Click me</button><br />
<span>(click count: {{ count }})</span>
</div>
</template>
<script type="application/dart" src="xclickcounter.dart"></script>
</polymer-element>
</body>
</html>

Now that the count property is published, let's bind a value to it in our main polymerclicker1 page.  To do this, you need to wrap the my-clickcounter in a template binding and bind that template to a model object, accessible through the elements model property in Dart code.

The template wrapping looks like this, in the polymerclicker1.html file:

<template id="counter_template" bind>
<my-clickcounter id="click_counter" count="{{}}"></my-clickcounter>
</template>

Template binding uses the {{}} notation to bind to the model's value (rather than a property of the model).
We also need to modify the previously empty polymerclicker1.dart file to set the template model's value to 5.

polymerclicker1.dart after modification, setting a template model value


1
2
3
4
5
import 'dart:html';

void main() {
query("#counter_template").model = 5;
}

Now, when you run this with the changes, the counter starts with a value of 5, and increments in response to button clicks.

Summary

In this example, you saw how to import custom Polymer elements without requiring a build step by using the new boot.js file imported from the polymer package.  This dynamically imports the various elements at runtime, rather than requiring a static build.
You also saw some simple data binding within an element itself using the @observable annotation (unchanged from Web UI).
Finally, you saw how one way to bind data into a custom element by wrapping it in a template.

As ever, comments are welcome, especially if it's to correct something in this post.

References

Most of the documentation on Polymer currently exists on the www.Polymer-Project.org homepage, or in as comments in the various source code files in Dart's Web_UI's polymer branch.  For a more fully featured Polymer example, take a look at the TodoMVC project in the polymer branch (hint, start with index.html).

The Polymer-dev group and the Dart Web-UI group also provide a discussion forum and other information.

Get the Gist:

You can find the final versions of the files here:


by Chris Buckett (noreply@blogger.com) at August 14, 2013 01:43 PM

July 11, 2013

Dartwatch

Polymer.dart (very alpha) released to unify web components projects

TLDR: Polymer.dart released.

Web Components and Model Driven Views are a set of specifications that are being developed at the W3C.  Google's Dart team have been busy building their implementation of web components and model driven views under the Web UI name, and have built a nice framework for creating web applications.

Dart's Web UI

Using Web UI, you can define custom elements, like the Dart Editor's sample "Click Counter"

    <element name="click-counter" 
                constructor="CounterComponent" extends="div">
<template>
<div>
<button on-click="increment()">Click me</button><br />
<span>(click count: {{count}})</span>
</div>
</template>
<script type="application/dart">
import 'package:web_ui/web_ui.dart';

class CounterComponent extends WebComponent {
@observable
int count = 0;

void increment() {
count++;
}
}
</script>
</element>


And then import them into your application like any other HTML tag:

<click-counter count="5"></click-counter>


Dart's Web UI tool takes this and runs it through a compiler that inserts the required code to make this work cross-browser, even where web component spec's haven't been implemented.  You can read much more about Web UI on the Dart website.

Polymer Project

Separately, a group of bright Googlers have been working on the polymer project, announced at Google I/O this year.  The polymer project provides the underlying platform.js, which provides polyfills to fill in the gaps where native browser implementations of the various web components spec's don't yet exist.  This also lets you use web component technology across multiple browsers.

On top of the platform.js lives the Polymer libraries.  Polymer provides syntactic sugar to the underlying web components frameworks, in the same way that jQuery or dart:html provides syntactic sugar to the DOM.  It's also worth a note that last month Mozilla's also decided to use the Platform.js polyfills for their X-Tag project (which has similar goals to Polymer).

A Polymer web component looks like this:

<element name="click-counter" attributes="count">
<template>
<button on-click="increment">Click Me</button><br />
<span>click count: {{ count }}</span>
</template>
<script>
Polymer.register(this,{
count: 0,
increment : function(e) {
this.count++;
}
});
</script>
</element>

And is imported into your HTML in the same way:

<click-counter count="5"></click-counter>

The difference with this is that it doesn't need the underlying compile step that you get with Dart's Web UI tool (because the polyfills are applied at runtime rather than build time.

How does this affect Dart?

In an announcement this morning on the Dart Web UI mailing list, John Messerly announced the publishing of polymer.dart to pub, along with a number of the polyfill packages, such as observe, mdv, and shadow_dom. John notes:
"Today we continue our mission by publishing the beginnings of polymer.dart, our port of the Polymer stack. ... The Dart team is collaborating with the Polymer team to ensure that polymer.dart elements and polyfills are fully compatible with Polymer."
The compatible with polymer is great - hopefully this means you'll be able to take your Web Components  from Polymer and use it with Dart, and vice-versa.  At the very least, you'll be able to use your knowledge in both places.

Polymer.dart is at a very early stage (as indeed are the web components spec's themselves). John says:
"This is only the beginning. Polymer and web components are evolving, and we’re going to keep bringing that to you. Some of the things we’ll be working on are:
  • declarative <polymer-element> and custom elements.
  • more new, up-to-date polyfill packages, like html_imports.
  • removing the mandatory compiler step for polymer.dart. Just edit, save & refresh!
  • bring the Polymer UI elements to Dart.
  • up to date documentation for all of this shiny new stuff."

The removal of the compiler step is a going to be a great leap forward - it seems (to me at least) that's where a number of people have problems, both when developing and deploying.

John also says that:
It's still very early for polymer.dart, but we welcome you to try out the new packages. We’ll be maintaining the web_ui package for a considerable time, but will eventually be sunsetting it in favor of Polymer.
You can check out the source code in the polymer branch of Web UI, and take a look at some of the examples in the example subfolder.  You'll see that not much has changed at the moment, but watch this space!

by Chris Buckett (noreply@blogger.com) at July 11, 2013 12:48 PM

June 20, 2013

Future Perfect

A Case for Metadata

In case you may have missed the action, reflective access to metadata is now a reality in both the Dart VM and in dart2js. While it is not yet completely finished (some less common use cases are not yet implemented) the majority of use cases that I care about are now working since the 0.5.20.2_r24160 Beta release.

The public API for introspection of metadata could not be simpler; it consists of a single getter on DeclarationMirror:

List<InstanceMirror> get metadata;

As detailed in the dartdoc, the return value of this getter is a list of (instance mirrors on) constant objects. In other words, the annotations that you may apply to declarations in your source code and later retrieve using dart:mirrors must be defined in your program as constants. Let’s consider the two types of annotations that are set forth in the language specification.

Compile-Time Constant Variable

This is probably the most common form of annotation. As an example, let us define an annotation @test for marking methods as test functions:

const test = const _Test();
class _Test {
  const _Test();
}

The constant variable test which we have defined above serves as the identifier portion of the annotation. Notice how we have assigned to the test variable the sole instance of the private class _Test that we have also defined. While this private class is not strictly required to define a constant variable, this pattern seems to be the current convention used.

With this metadata defined, we can now use it to annotate some test functions in our source code:

@test
void testThatTheSkyIsBlue() {
  // look up
}

Now, you might want to run off and hack out a patch to the unittest package which detects such an annotation. But I haven’t gotten to my main point yet, so stick around!

Call to a Constant Constructor

The second form of annotation provided by the language specification is that of a call to a constant constructor. What this provides for is a way to pass arguments (other constants) to your annotation. As an example, let us define another annotation for marking test functions that we expect to throw an error:

class ExpectError {
  final Type errorType;
  const ExpectError(this.errorType);
}

The class ExpectError which we have defined above is actualy very similar to the private _Test class which we defined previously. The difference is that the const constructor of ExpectError takes an argument, the Type of error to expect.

With this metadata in hand, we can annotate test functions as follows:

@test
@ExpectError(StateError)
void testThatTheSkyIsBlue() {
  // do something bad which throws a StateError
}

Making a Case for Style

That brings me to the point in question, which is a matter of style. The astute reader has noticed that our two annotations differ in the case of their first letter: t for @test and E for @ExpectError(StateError). I think we may all agree that there are but two solutions to this problem!

1) lowerCamelCase identifiers.

This is the most common (only?) type of identifier in the wild in today’s Dart, so it is tempting to say that all identifiers should begin with a lower-case letter. However, that would entail naming classes such as ExpectError in lower-camel-case (class expectError ?) which violates the current dart style guide, and feels pretty wrong to me.

2) UpperCamelCase identifiers

This might require breaking users of existing metadata such as @observable, but I believe the libraries that are using metadata are all at an early enough stage where such breaking change is acceptable. The declaration of const test is actually in violation of the current dart style guide which states that constants should be named using ALL_CAPS_WITH_UNDERSCORES. There seems to be more wiggle room here, and a chance to clarify the preferred style for annotation identifier constants to be UpperCamelCase.

My preference is for #2, UpperCamelCase identifiers for metadata. What I am most interested in is consistency. The ability to reflect on metadata is a game-changing feature, and I believe we will see an explosion of new annotations now that it is available; so I would love to see this addressed in the Dart style guide sooner rather than later.

by Ross Smith at June 20, 2013 12:00 AM

May 25, 2013

Daniele Salatti

What's New in Dart: Your First-class Upgrade to Web Development

Yet another video from Google I/O 2013.

Come see what’s new in Dart with its comprehensive, open-source ecosystem for the modern web developer. Learn how to be more productive with a new language: future-based DOM, package manager, JS-interop, a tree-shaking compiler to JavaScript, SIMD, Web Components, a rich editor, and much more. You’ll leave this talk all caught up with Dart and ready to make the web awesome.

May 25, 2013 10:00 PM

May 21, 2013

Daniele Salatti

Web Components & Polymer

A couple of really interesting videos from Google I/O 2013.

Web Components are here to fundamentally change the way we think, build, and consume our web apps. This session will prepare you for the future of the web platform by discussing the lower level technologies that form the basis of Web Components (Shadow DOM, custom elements, MDV, new CSS primitives). Many of these tools have already landed in a modern browser near you!

This session builds on technologies and concepts discussed in a previous session, “Web Components: a tectonic shift for web development”. This year web development gets a whole lot better thanks to the incredible power of Web Components. Our goal in this session is to show you how to use polyfills to help you realize tomorrow’s web platform today. As browsers implement these new specifications, that shim layer gets smaller, better, and faster over time. We’ll talk about shadow DOM, custom elements, declarative data/event binding, touch input, smooth animations, and how you can combine them to create awesome apps. Write less boilerplate, target every platform, and be more productive by using the next generation of the web platform.

May 21, 2013 10:00 PM

May 15, 2013

Future Perfect

When Does a Completer Complete?

In the future, of course. It sounds obvious, but when this change was first announced, I wasn’t immediately sure how to cope with it in my undone library.

Undone is an asynchronous library, as I talked about in my last post, so you may want to read that first for some background on why I’m working with Completers. In developing my library I’ve sort of grown up with dart:async and things have started to stabilize now. It was non-trivial for me to do, and I have been responsible for the development of asynchronous processing libraries in other systems in the past. Many of the challenges to exposing an asynchronous API in Dart are well known and oft talked about in the community, so I don’t want to dwell on them in this post. I really like dart:async and I am confident the tools we’ll have for working with it will continue to advance and improve over time.

Warning, Don’t Use a Completer!

Its true, you really don’t want to use these unless you need to. Knowing when to pull one out of your async toolbag can be tricky, especially when you are new to Dart. When I first started designing async APIs in Dart, I always started out with a function body skeleton like the following:

Future task() {
  final completer = new Completer();

  // Complete some async task

  return completer.future;
}

This is 100% legitimate Dart code, and a careful investigator of my undone library will tell me that the majority of its functions still use this pattern. It is true, but undone is somewhat exceptional when compared to the majority of async libraries I have written in Dart. The majority of them use futures in their signatures in order to make calls to other async functions. This is the contagion that is async programming. If your code is async mostly because of interoperation with other async code, then you likely can and should avoid using completers.

There are a lot of ways to construct a Future these days, which is a good thing. There weren’t always as many options, but the API has matured since its inception. I don’t want to try and break it all down here for fear of veering way off topic, and there is plenty of official documentation and examples to get you started. Returning futures directly from the different branches of your code means that all the plumbing of how the values (and errors) propagate through the chain is managed for you, which is very helpful. When you use a completer, you are breaking that chain and you are now responsible for the propagation of both values and errors from the async code you call into back to the callee of your code.

Please Just Tell Me When They Complete

Okay, so you’re using a completer and you’re pretty sure that you should be (or you just don’t believe me and want to see for yourself!). That’s cool, I use them too sometimes. Up until very recently I was abusing them though, and that is the subject of this post - when do they complete?

Let’s consider the following small program:

import 'dart:async';

main() {
  int i = 42;  
  incrementAsync(i)
    .then((result) => squareAsync(result))
    .then((result) => print('result: $result'));    
}

Future incrementAsync(int value) {
  final completer = new Completer();
  int result = value + 1;
  runAsync(() {        
    completer.complete(result);
    print('$result');
  });
  return completer.future;
}

Future squareAsync(int value) {
  final completer = new Completer();
  int result = value * value;
  runAsync(() {
    completer.complete(result);
    print('$result');
  });
  return completer.future;
}

The above program has two async functions, incrementAsync and squareAsync, which both perform some async work (using the runAsync utility) on an integer value and complete the future result using a completer. In the main function, we start with the value 42 and we chain a computation interlaced with print calls to log the intermediate values. It is in the ordering of the print output where we can observe the recent change in completer behavior.

First, consider the output of this program using the Dart SDK 0.5.5_r22416:

43
result: 1849
1849

In order to understand the order of operations, we break down the computation into 3 microtasks, where (1) and (2) correspond to the anonymous closures that we pass to the runAsync function. We can then visualize better the sequence of events that leads to the printed output:

main            |   (1)             |   (2)       
incrementAsync  |   complete [43]   |   complete [1849]
runAsync(1)     |   then            |   then
                |   squareAsync     |   print [result: 1849]
                |   runAsync(2)     |   print [1849]
                |   print [43]      |

As we see in the microtask (1) above, there are three function calls that come between the call to completer.complete(result) with the value 43 from inside the scope of incrementAsync and the call to print('$result') with the value 43 from the next line of code in that same function. The reason for this is that the call to completer.complete(result) was synchronous in that version (and all prior versions) of the Dart SDK.

Next, consider the output of this program as of the Dart SDK 0.5.7_r22611:

43
1849
result: 1849

Whoa! Let’s break this into microtasks again before anyone panics:

main                |   (1)               |   (2)         
incrementAsync      |   complete [43](2)  |   then        
runAsync(1)         |   print [43]        |   squareAsync
                    |                     |   runAsync(3)

(3)                 |   (4)
complete [1849](4)  |   then
print [1849]        |   print [result: 1849]

As we can see above, we have two more microtasks than before. This is because each call to completer.complete(result) is now internally using runAsync to do its work. The result is that now our calls to print('$result') are called before the completer’s complete, and the output of our program has changed.

I think that this change is the right thing to do. Before, I was being lazy in some ways by relying on the synchronous behavior of the completer. Worse than that, however, is that my library was not robust because of it. I was assuming that when I completed the future to the caller of my API, that they would do all of their work synchronously. If the user had chained any futures with more async work onto the completer’s future, my old code would have blown up because I was assuming that everything was said and done when the call to completer.complete(value) returned. So I am very happy this change was made because it prompted me to dig in further and to perform this analysis.

Okay, so I hope that it is clear what behavior has changed. But, in undone I really need to do some cleanup work at a point in time where I know that the completer has completed. This includes the work of any other futures that the user might have chained onto my completer’s future. How can we know for certain that the sequence of async computations initiated by completing the completer has completed?!

The answer is by careful use of the whenComplete method on the completer’s future. Let’s hook this into our async example functions as follows:

...
Future incrementAsync(int value) {
  final completer = new Completer();
  int result = value + 1;
  runAsync(() {  
    completer.future.whenComplete(() => print('$result'));
    completer.complete(result);
  });
  return completer.future;
}
...

By changing incrementAsync and squareAsync as shown above, the output of our program returns to what we had originally:

43
result: 1849
1849

One subtle point regarding whenComplete is when we call it. Remember, our function returns the completer.future to the caller, who is free to chain other async computations onto that future. If we call whenComplete before we return to the caller, we will be at the front of the future chain. This might be desired in some situations, but for undone I want to be at the end of the future chain in order to cleanup internally. By calling whenComplete right before we call completer.complete(result) we can ensure that no other code can chain on after us.

That is my story of when the completer’s complete. The dart:async library is very powerful, but working with it requires a fair amount of patience. Hang in there, as I’m hopeful that the debugging story will improve and maybe we’ll even get some language support for this in future versions of Dart. Please do leave me comments or feedback, and don’t be overly harsh on my microtask charts; I know that they are far from scientific :)

by Ross Smith at May 15, 2013 12:00 AM

May 10, 2013

Shannon -jj Behrens

Personal: Links to My G+ and Twitter Accounts

If you enjoy my blog posts on Python, Ruby, Dart, etc., and you're looking for a new way to follow me now that Google Reader is going away, here are my Twitter and G+ accounts:

by Shannon Behrens (noreply@blogger.com) at May 10, 2013 06:15 PM

May 08, 2013

Christian Grobmeier

Review: Dart in Action

"Dart in Action" by Chris BuckettRecently I read “Dart in Action” by Chris Buckett. I know Chris from the early days of the Dart language. We both joined the community almost instantly. At the day of Darts arrival, he founded Dartwatch.com and blogs on all aspects of the language. Chris is definitely one of these guys who knows what he writes. After one year, a lot of blog posts, countless e-mails to the Dart mailing lists and doing a lot of other community related things, he finished a book on Dart.

A book? This alone is impressive. Dart is a kind of moving target. There is a lot of man-power behind its development and every day there are a lots of changes to Darts codebase. Dart arrived as a technical preview and as such it was allowed to have breaking changes. Chris was not only confronted with learning a language by looking at its specification and find out about hidden features in the bug trackers; he also had to rewrite whole sections over and over again just because the language changed. A simple example: suddenly the + operator for string concatenations was removed. A more complicated example: the whole library/import thing changed.

Still Chris kept on writing. Finally Dart became more stable in its core, and the book was released. What I got was a book from a dedicated and passionate Dart-developer, who knows the language, its ecosystem and the community from day 1.

The book itself reads like that. It’s a fantastic book which takes you by hand and leads you through the whole world of Dart. With that I mean it doesn’t stop at just explaining some grammar or how to use API $x. Dart is not “only a language”. Dart is a whole ecosystem consisting of language, APIs AND tools. Chris shows from the beginning where you need to look at, like using the Dart Editor or how to deal with third party dependencies.

You almost do not recognize how you get into all these new technologies. While he explains how to write code, he also shows how to debug it or what you can do with it in practice. It is far from boring grammar descriptions or rephrased API docs as one can often find in books. You can work on your program while reading this book. It’s for people like me, who do not want to read through 500 pages with boring examples just to make up something cool after the memorized all of the thousand keywords. This book shows you what you can do, how you do it, and what you should be aware of. It’s easy to connect the books content with your real-life-problems.

The writing style is clear, precise and well balanced. An easy read. The tune is one of a colleague who did find some great new toy to play with and now explains it to you. It is a motivating and inspiring text and very enjoyable. There was not a single chapter which made me bored or drifting away.

The content is a great mix of everything important in Dart.

You will learn about running Dart from the Browser but also how to run it from the shell, maybe when building your backend with Dart. You learn how you can write test driven code. Unit testing with Dart is especially something which I did not know much about before. In the early days of Dart it was not so much a topic, and due to work I did not follow it to closely later. Chris sent me back on track. Now I even know how to do browser testing, which is big win for me.

He explains on how properly to use classes, interfaces and constructors. Also he looks into libraries and shows possibilities here. What I like much is the fact he is also explaining best practices. Not only Darts best practice, but general ones. These are experiences he made maybe from his time as GWT developer. They are very helpful if you just start with your programming career.

In general, the core part of this book feels complete and balanced. There is even a part describing Futures and Completers. Both are heavily used async concepts in todays browser programming world, and with “Dart in Action” it is easy to get into them. Another bonus point is he is explaining how you can test asynchronous code. As this is a very difficult matter, I have not expected that.

The chapters on client development are also very good. One can first find a great introduction into single-page web apps. I wished I would have read this before a long time now. It also gives you a great view how you can actually build your Dart app. If you are coming from the classic approach of maintaining multiple pages, you might find this section very useful. He is also writing on how to use Cookies and Data Storage. Especially the browser db part I found very interesting.

One often asked question is how to interact with JavaScript from Dart and vice versa. You will find an answer in this book. Even more: Chris describes how to make apps for the Chrome web store. With this, you already have enough knowledge to start with your App, integrate it to existing libs and finally deploy it to its final destination. A complete cycle. But there is even more.

The book closes with looking at server side Dart. It’s shown how to interact with Apache CouchDB as data store and how one can serve HTTP requests with Dart. Everybody who is into Node.js knows that it is a great feeling to just use the same language for frontend and backend. Finally he looks into Isolates, one of my favorite topics. Even when I know a lot on Isolates (some kind of multithreading in Dart), I found this is a very competent introduction into it and  I did not regret to have it read.

My conclusion is this a great book. Usually I do not read books on programming languages anymore. They tend to be boring and quickly out of date. But this book is different. It shows you more than just grammar and APIs. It shows you how to move in the Dart world. How you solve things. It’s an enjoyable read from a very competent Dart programmer. If you want to learn Dart you already have the great docs on the website. But if you would like to get even more quickly into Dartlang, then you should definitely look at this book. Despite the language is still evolving, most of its content will be true for a long time. If not, then the author can be found in one of the Dart communities.

You can buy this book on Amazon.com or on Amazon.de (affiliate links).

by Christian Grobmeier at May 08, 2013 12:02 PM

May 04, 2013

Daniele Salatti

March 14, 2013

Shannon -jj Behrens

Irrduino: A Sprinkler System Built Using Arduino, Android, Google App Engine, Python, and Dart

Cross-posted from Dart News & Updates.



Developers frequently ask me if Dart is ready for the real world. Well, of course, that depends on the application. Check out this short video in which Joe Fernandez and I not only show that Dart can be used in the real world, we also show that it can be used to take the tedium out of watering your lawn!



The Dart code for Lawnville was originally written in January of 2012, a mere three months after Dart was launched as a "technology preview". That was six months before Dart's M1 release, so it's been updated a few times along the way. However, the code really hasn't fundamentally changed that much since the beginning.

Perhaps the most interesting piece of code is the use of a Queue (from the dart:collection library) to schedule watering tasks. You can click on different parts of the lawn, and the droid will fly over and water each section for a short amount of time:

_actionQueue = new Queue();
...
_actionQueue.add({'action': 'water', 'zone': el.id});
...
void _executeActionQueue() {
if (_actionQueue.isEmpty) {
_waitingForTimer = false;
_idle();
} else {
var action = _actionQueue.removeFirst();
_doAction(action);
_waitingForTimer = true;
new Timer(new Duration(milliseconds: TIMER_INTERVAL),
_executeActionQueue);
}
}
A Timer and window.requestAnimationFrame are used to control animations:

void _repositionDroid(int x, int y, [Callback callback = null]) {
x -= (HALF * DROID_WIDTH).toInt();
y -= DROID_HEIGHT;
_droid.src = "/static/images/droid-jetpack-on-front.png";
_droid.style.left = "${x}px";
_droid.style.top = "${y}px";
new Timer(new Duration(milliseconds: REPOSITION_DURATION), () {
if (callback != null) {
callback();
} else {
_droid.src = "/static/images/droid-waiting-front.png";
}
});
}

void _startAnimationLoop() {
_animationStartTime = new DateTime.now().millisecondsSinceEpoch;
window.requestAnimationFrame(_animationLoop);
}

void _animationLoop(int timestamp) {
_animationProgress = timestamp - _animationStartTime;
for (Callback callback in _animationCallbacks.values) {
callback();
}
window.requestAnimationFrame(_animationLoop);
}
An HttpRequest is used to send commands to IrrduinoServer which in turn sends commands to IrrduinoController in order to control the sprinkler system:

void _waterRpc(int zone) {
var req = new HttpRequest();
int secs = (TIMER_INTERVAL * SECS_PER_MS).toInt();
req.open("POST", "/?water-zone=true&zone=${zone}&secs=${secs}", true);
req.onReadyStateChange.listen((Event e) {
if (req.readyState == 4) {
if (req.status == 200) {
window.console.log("Watering was successful");
} else {
window.console.log("Watering was unsuccessful");
}
}
});
req.send();
}
In total, the complete Dart code is about 110 lines long, not counting comments and closing braces.

You might wonder why I chose to use Dart so soon after its release, especially since I wasn't even on the Dart team at the time. I've always gotten a kick out of coding in new languages. At the time, I figured that as long as I could talk to the DOM and make XMLHttpRequests, I could do almost anything. These days, Dart is a lot more useful thanks to the growing selection of pub packages available, but even before these things existed, Dart had enough functionality to help water a lawn ;)

If you want to download the complete source code for Irrduino, you can get it from bit.ly/waterjoeslawn.

by Shannon Behrens (noreply@blogger.com) at March 14, 2013 06:08 PM

February 28, 2013

Shannon -jj Behrens

Dart on a Chromebook: Success!

I finally have a viable approach to editing Dart directly on a Chromebook running ChromeOS! The usual approach to developing Dart code on a Chromebook is to use Chrome Remote Desktop to connect to another development machine. However, I wanted an approach that would let me develop in Dart while offline, for instance if I'm giving a talk on Dart and my internet connection goes down.

Crouton is a set of scripts based around debootstrap that bundle up into an easy-to-use, Chromium OS-centric Ubuntu chroot generator. Using Crouton, I was able to create a chroot running a basic Ubuntu setup. Within the chroot, I was able to install a JDK and then Dart Editor. Everything works, as you can see in the picture. I can switch back and forth between XFCE and ChromeOS's desktop using a key combination, and everything still runs at native speed since it's just a simple chroot.

I got everything working on my wife's Samsung Series 5 Chromebook running an Intel Atom processor. I have a newer ARM-based Chromebook, but there is currently no ARM port of the Dart VM. I used the 32-bit version of the JDK and the 32-bit version of Dart Editor.

I'm pretty excited that this works because this is one of the few things that was preventing me from fully switching to a Chromebook :) Now, all I need to do is get my hands on a Chromebook Pixel!

by Shannon Behrens (noreply@blogger.com) at February 28, 2013 06:57 AM

Dart Logo

Last updated: April 17, 2014 03:26 PM UTC

Dartosphere channels