Sunday, October 6, 2013

Generic Class is not a first class citizen?

I tried to complete fromJson implementation, a method to instantiate an object of given type from its serialized json string, then I found some interesting limitation of Dart language.
I guess this is not planed feature, but something which are to be improved later.

for instance, the support of getClass in Java is not supported in dart now. (this will be obj.type getter). but I read a proposal, this is going to be supported.

there are two issues.

if we have a function taking Type value as the argument,  like f(A), this works as expected. but we cannot write f(A<B>)!.
also Type a = A<B> is not allowed.
So in a sense, generic class is not a first class citizen in Dart now.

Also similar, but more strange problem is following:

  InstanceMirror immir = reflect(new List<B>());
  Type t = immir.type.reflectedType;
  print(">> ${t}");
  ClassMirror mirr = reflectClass(t);
  print("2>> ${mirr.reflectedType}");

Since we cannot use List<B>, we need to create this type by reflect(new List<B>()).type.reflectedType. and this will be shown as List<B>.
but if we use this type to create ClassMirror, the getter call, mirr.reflectedType will cause runtime error.

>> List<B>
Unhandled exception:
Unsupported operation: Declarations of generics have no reflected type
#0      _LocalClassMirrorImpl.reflectedType (dart:mirrors-patch/mirrors_impl.dart:304:7)
#1      test_generics (file:///opt/dart-workspace/reflective_web_dev_kit/sample_app/bin/sample_json_mapper_test.dart:77:21)
#2      main (file:///opt/dart-workspace/reflective_web_dev_kit/sample_app/bin/sample_json_mapper_test.dart:82:16)

This is actually not good for portable_mirror librray.
Since creating Type through dart:mirrors library is not allows in javascript mode.

For example, couchdb_client_dao(in browser side) need to convert json string of list to list of entity. So ideally, this should be parsed by jsonMapper's fromJson. and it requires type value in the first argument, e.g, fromJson(List<modelType>, json).

This issue would not be limited to javascript mode. but it would also affect to the Dart VM mode.
So in order to avoid this problem in DartVM mode(as well as JavaScript mode), it will be necessary to avoid using Type. Instead, it should always use IClassMirror.

Although that may fix the jsonMapper, but this issue may influence in entire application
So one approach is not to worry about the generic type case(including list/map), and wait until this mirror issue is fixed..

Saturday, October 5, 2013

Github: Reflective Web dev kit

Since several components based on reflection approach are now integrated, and working fine,  I uploaded the Dart project to Github:

https://github.com/calathus/reflective_web_dev_kit

There are a few more things to do, but this is not bad timing to clean up the project structure and store it to github.

here is the readme file:

Reflective Web Dev Kit

Overview

The goal of this project is to create a small end2end sample application using component based approach. Dart's mirror library will be applied to several area of web application, GUI, Database Access, client/server communication. Thus the project is called 'reflective' web dev kit.
See following blog site: http://dartathus.blogspot.com

1. portable_mirror

right now, darts:mirrors library cannot be used in javascript mode. So if we directly use this library, most of code cannot be run on browser. This lib provides a portable mirror API to support (small subset of) mirror features. There are two implementations for this API class. one depends on static classes, and the other depends on dart:mirror. No code changes are required to run application on javascripts mode or Dartium mode(using Dart VM).

2. json_mapper

json mapping based on mirror library. this automatically map json to corresponding entity instance

3.couchdb

dao api for couchdb based on mirror/json_mapper. this provides server side json_proxy, and client side couchdb dao library

4. gui_component

a framework to create web application using component based design, also table/form are implemented as generic class using mirror.

5. sample_app

This is a sample web application using these libraries. This web application supports CRUD operation using Table and Form.


Thursday, October 3, 2013

Generic Json Mapper(Part 2)

In the previous post, I showed how to generate entity object from json string and type information.
Although I have already written the reverse direction(generating json from entity object),  it was written from scratch(since it was simple), and I wanted to see how I can use dart:json library in a similar way.

Then I found there is a class _JsonStringifier in json.dart in Dart sdk lib.
But as the name shows, it is private class, so I cannot extend the class and override some of the methods. If it is possible, I can do the similar things.
 That was a bit of disappointment. Actually the class  should be changed to public class.

By the way, I found Dartson was posted just 1 hour after I posted to Dartisans.
I think Json is quite universal data structure in web application, and this kind of binding are very powerful tool.

For the Dartson, I clone the project, and saw the code.
It is well written, although it is not yet supporting for javascript mode usage, it seemed planed to support it.

Essentially the main difference between our approaches is that  I took 'SAX' parser approach, and Dartson took DOM node approach. But right now, I just extended the library class, during the parsing it still creates maps, and uses the map to create an entity, then the map is immediately discarded.

If we use this approach, such an intermediate map creation can be avoided. We can just use stack to push all the key, value objects.
If we use such approach, it will be faster than Dartson.

Since Dartson is actually using json library to create intermediate json object(consisting List, Map, primitive values), the parsing quality will be as good as dart json library.

But Dartson seems not supporting irregular cases, like DateTime parsing/serialization, none Bean like classes where we need to call special factory/constructor(like ExpenseType).

I think it is better to have an ability to adjust such exceptional cases, otherwise, the tool's applicability will be unnecessarily limited.

//
// entity(including list, map) stringifier
//
class EntityJsonStringifier extends _JsonStringifier {
  final ISpecialTypeMapHandler mapHandler;
  
  EntityJsonStringifier(this.mapHandler): super(null);
  
  String toJson(final obj, {StringSink output}) {
     this..sink = (output != null)?output:new StringBuffer()
    ..seen = [];
    stringifyValue(obj);
    return sink.toString();
  }

  // @Override
  void stringifyValue(final object) {
    if (!stringifyJsonValue(object)) {
      checkCycle(object);
      try {
        // if toJson is defined, it will be used.
        var customJson = object.toJson();
        if (!stringifyJsonValue(customJson)) {
          throw new JsonUnsupportedObjectError(object);
        }
      } catch (e) {
        // if toJson is not defined..
        if (!stringifyJsonValue(object)) {
          stringifyEntity(object);
        }
      }
      seen.removeLast();
    }
  }
  
  void stringifyEntity(final object) {
    // this require dirt:mirrors
    Type t = ClassMirrorFactory.getType(object);
    StringifierFun stringfier = mapHandler.stringifier(t);
    if (stringfier != null) {
      sink.write(stringfier(object));
      return;
    }
    
    //
    IClassMirror cmirror = ClassMirrorFactory.reflectClass(t);
    IInstanceMirror iimirr = cmirror.reflect(object);
    
    sink.write('{');
    int idx = 0;
    Map fmap = cmirror.fieldTypes;
    int lastIdx = fmap.length-1;
    fmap.forEach((k, IFieldType ft){
      sink.write('"${ft.name}": ');
      stringifyValue(iimirr.getField(k).value);
      sink.write((idx == lastIdx)?"":",");
      idx++;
    });
    sink.write('}');   
  }
}

Wednesday, October 2, 2013

Generic Json Mapper(Part 1)

I finished the json mapper implementation based on restricted (my) mirror library.
 The idea is by providing a target class information for a given Json string, it automatically creates the instance of the given class filled with the json data.

Following is the sample codes:
 final Map<Type, ConstructorFun> entityCtors = {
    ExpenseType: (Map map)=>new ExpenseType(map['name'], map['code'])};

  final Map<Type, StringifierFun> stringifiers = {
    ExpenseType: (ExpenseType et) => '{"name": "${et.name}", "code": "${et.code}"}'};

var jsonMapper = new JsonMapper(new SpecialTypeMapHandler(entityCtors, stringifiers: stringifiers));

Expense e = new Expense.Default()
  ..id = "aaa"
  ..rev = "mmm"
  ..amount = 111
  ..date = new DateTime.now()
  ..detail = "asdjah"
  ..isClaimed = true
  ..expenseType = const ExpenseType("Hotel", "HT");

  String json = jsonMapper.toJson(obj);
  print(">> json: ${json}");
  Object obj = jsonMapper.fromJson(Expense, json);
  print(">> obj: ${obj}");
 
I have not yet finished two cases, when attribute has List or Map value.
I will do it later.
But actually there are a bit of difficulty for these cases.
In order to get List type's parameter type information, the current simple mirror API must be extended.
And a list may contains an instance of the different subclass of List's element type.
Map has a similar problem.
Also even if the field type is defined as ordinary class, the actual instance may be of subclass of that class.
So the current implementation is not covering such cases(yet).
But if we know all the available classes at the run time, we may be able to uniquely identify appropriate class. anyway if there are some ambiguity, that is inherent to the given json itself.

Also if we provide possible subclass information in the list value property as annotation, we can determine the class  efficiently.

This code was actually done by extending existing dart:json library. so it covers quite rigorously the spec of json.(but in fact, it uses old version of json code. what is the difference between the latest and older code?

This code does ot suport List, Map properties yet..
library json_mapper_v1;

import "dart:json";

import 'package:portable_mirror/mirror_api_lib.dart';

part 'src/dart_JsonStringifier.dart'; // this should be eliminated, dart:json should have pblic class JsonStringifier instead of _JsonStringifier

typedef dynamic ConstructorFun(Map map);
typedef dynamic StringifierFun(Object obj);
typedef dynamic ConvertFun(Object obj);

abstract class ISpecialTypeMapHandler {
  ConstructorFun entityCtor(Type type);
  StringifierFun stringifier(Type type);
  ConvertFun convert(Type type);
}

class SpecialTypeMapHandler implements ISpecialTypeMapHandler {
  final Map entityCtors;
  final Map _converts = {DateTime: (Object value)=>DateTime.parse(value)};
  final Map _stringifiers = {DateTime: (DateTime dt) => '"${dt.toString()}"'};
  
  SpecialTypeMapHandler(this.entityCtors, {Map converts, Map stringifiers}) {
    if (converts != null) _converts.addAll(converts);
    if (stringifiers != null) _stringifiers.addAll(stringifiers);
  }
  
  ConstructorFun entityCtor(Type type)=>(entityCtors == null)?null:entityCtors[type];
  ConvertFun convert(Type type)=>_converts[type];
  StringifierFun stringifier(Type type)=>_stringifiers[type];
}

//
//
//
abstract class IJsonMapper {
  Object fromJson(Type modelType, String json);
  
  String toJson(final object, {StringSink output});
}

class JsonMapper implements IJsonMapper {
  EntityJsonParser parser;
  EntityJsonStringifier stringifier;
  ISpecialTypeMapHandler mapHandler;
  
  JsonMapper(this.mapHandler, {_Reviver reviver}) {
    parser = new EntityJsonParser(mapHandler, reviver: reviver);
    stringifier = new EntityJsonStringifier(mapHandler);
  }

  Object fromJson(Type modelType, String json) => parser.parse(modelType, json);
  String toJson(final object, {StringSink output}) => stringifier.toJson(object, output: output);
}

//
// json parser
//
typedef _Reviver(var key, var value);

class EntityJsonParser {
  //EntityBuildJsonListener listener; // TODO.. this would be effcient way..
  ISpecialTypeMapHandler mapHandler;
  _Reviver _reviver;
  
  EntityJsonParser(this.mapHandler, {_Reviver reviver}) {
    _reviver = reviver;
  }
  
  EntityBuildJsonListener getListener(Type modelType) =>(_reviver == null)?new EntityBuildJsonListener(mapHandler, modelType)
      :new EntityReviverJsonListener(mapHandler, modelType, _reviver);

  dynamic parse(Type modelType, String json) { 
    EntityBuildJsonListener listener =  getListener(modelType);
    new JsonParser(json, listener).parse();
    return listener.result;
  }
}

class EntityBuildJsonListener extends BuildJsonListener {
  final ISpecialTypeMapHandler mapHandler;
  IClassMirror currentCmirror = null;
  List cmirrorStack = [];
  
  EntityBuildJsonListener(this.mapHandler, Type modelType) {
    currentCmirror = ClassMirrorFactory.reflectClass(modelType);
  }
  
  /** Pushes the currently active container (and key, if a [Map]). */
  void pushContainer() {
    super.pushContainer();
    cmirrorStack.add(currentCmirror);
  }

  /** Pops the top container from the [stack], including a key if applicable. */
  void popContainer() {
    super.popContainer();
    currentCmirror = cmirrorStack.removeLast();
  }
  
  void beginObject() {
    super.beginObject();
    if (key != null) {
      IFieldType ft = currentCmirror.fieldTypes[new Symbol(key)];
      if (ft != null) {
        currentCmirror = ClassMirrorFactory.reflectClass(ft.type);
      } else {
        print('>> beginObject ${key}');
        currentCmirror = null;
      }
    }
  }

  void endObject() {
    Map map = currentContainer;
    ConstructorFun spCtor = mapHandler.entityCtor(currentCmirror.type);
    if (spCtor != null) {
      currentContainer = spCtor(map);
    } else {
      // Dart Beans
      IInstanceMirror imiror = currentCmirror.newInstance();
      currentCmirror.fieldTypes.forEach((_, IFieldType ft){
        ConstructorFun vCtor = mapHandler.convert(ft.type);
        var value = map[ft.name];
        imiror.getField(ft.symbol).value = (vCtor != null)?vCtor(value):value;
      });
      currentContainer = imiror.reflectee;
    }
    super.endObject();
  }
}

class EntityReviverJsonListener extends EntityBuildJsonListener {
  final _Reviver reviver;
  EntityReviverJsonListener(ISpecialTypeMapHandler mapHandler, Type modelType, reviver(key, value))
    : super(mapHandler, modelType), this.reviver = reviver;

  void arrayElement() {
    List list = currentContainer;
    value = reviver(list.length, value);
    super.arrayElement();
  }

  void propertyValue() {
    value = reviver(key, value);
    super.propertyValue();
  }

  get result {
    return reviver("", value);
  }
}

Tuesday, October 1, 2013

Generic CouchDBDAO class

I cleaned up the CouchDB handling code which essentially provides a http proxy for CouchDB. since CouchDB itself is providing Restful API, this may be seen as unnecessary duplication.



But this is useful to avoid browser restriction(although there a some other techniques in Dart), and this can be used as a template to provide a restful API for other db.

One interesting aspect of current implementation is such DAO class is designed as generic class.Compared to Hibernate/JPA, this approach is very simple.

[web client]
ICouchDbClientDAO<Expense> dao = new CouchDbClientDAO<Expense>(fromMap, fromJson, toJson);

    loadButtom = new ButtonComp(this, "Load", (_) {
      dao.fetchAll().then((List<Expense> es){ table.load(es);});
    });

    newButtom = new ButtonComp(this, "New", (_) {
      Expense e = form.create();
    });
   
    saveButtom = new ButtonComp(this, "Save", (_) {
      if (form.e != null) {
        Expense e = form.save();
        // this part is tricky..
        // since e is fill from InputText, when it is an empty text, it will assign "" instead of null..
        if (e.id == "") e.id = null;
        if (e.rev == "") e.rev = null;
        ((e.id == null)?dao.insert(e):dao.update(e)).then((Expense e0){
          e.id = e0.id;
          e.rev = e0.rev;
          table.addOrUpdate(e);
        });
      }
    });
   
    deleteButtom = new ButtonComp(this, "Delete", (_) {
      Expense e = form.e;
      if (e != null) {
        dao.delete(e).then((ok){
          if (ok) {
            form.delete();
            table.delete(e);
          }
        });
      }
    });
Here, the argument of CouchDbClientDAO's constructor takes fromMap, fromJson, toJson. This is required since I have not provided Json binding library yet, these functions must be defined manually for each entity classes(e.g, Expense).

[server]
void main() {

  // register reflection factory
  initClassMirrorFactory();

  CouchDbDAO<Expense> couchDbDAO = new CouchDbDAO<Expense>(couchdb_host, couchdb_port, dbName, fromMap, toJson);
 
  CouchDbHttpServer server = new CouchDbHttpServer(couchDbDAO, fromJson, toJson);
 
  server.startHttpServer(http_server_host, http_server_port);
}
No other code are required to make such entity class persistent.

Monday, September 30, 2013

Injecting DBDriver/Logger, AOP in Dart

In order to have GUI component, each component should not have a direct dependency to a specific driver. For instance, in the sample app, AppController has reference to CouchDBClientDao, but we if want to allow other DB driver later, that should not be directly defined in the component class.
This issue can be handled in Java as annotation based injection. JPA entity factory etc can be injected through annotation.

In order to support this, there will be a few approaches.
One approach is to simulate Java's approach. but it requires a special run time lib support for actual injection. So these are actually not within an ordinal programming control, and create some opaqueness for the code behavior, so I actually do not like this idea much.

The other approach is to delegate this injection job to code(programmer) itself. Anyway entry program needs to do some environment setting job normally, adding a task to inject code to appropriate library is not much big deal. and it will allows programmer 100% control over what is happening in program execution time.

then how can we find the location of the class(instance) to inject db driver.
sometimes that component are in deeply nested from top level component node.

That time we may use query feature defined at Component class.
This approach is similar to query in Dart.
To inject to annotated filed for an instance, whenever instance is created, this injection code must be applied. So instance level injection is a bit costly operation.

Or the other hand, static class level injection can be done only once, so this should be efficient.
for instance, dbdriver, logger can be injected to a  static filed.



Saturday, September 28, 2013

Generic GUI Library in Dart (Part 3)

I could run the generic GUI lib application on browsers(in javascript mode).
Since Dart does not support mirror in JavaScript mode, I needed to do this kind of things(see previous post).
The following snapshot shows running the app on Dartium , Chrome and Firefox:


In order to achieve this, I re-factored the code so that it eliminates the direct reference to 'dart:mirrors' by introducing minimal mirror interfaces.

 library mirror_api;

typedef IClassMirror CMirrorFun(Type type);

class ClassMirrorFactory {
  static CMirrorFun _cmf;
  static IClassMirror create(Type type) => _cmf(type);
  static void register(CMirrorFun cmf) { _cmf = cmf; }
}

//
abstract class IClassMirror {
  IInstanceMirror newInstance();
  IInstanceMirror reflect(Object obj);
 
  Map<Symbol, IFieldType> get fieldTypes;
}

abstract class IFieldType {
  Symbol get symbol;
  String get name; // convert symol to string
  Type get type;
}

//
abstract class IInstanceMirror {
  IClassMirror get cmirror;
  Object get reflectee;
 
  IField getField(Symbol name);
}

abstract class IField {
  Symbol get symbol;
  String get name; // convert symol to string
 
  Object get value;
  void set value(Object obj);
 
  Type get type;
}
 Then I provided two implementations of this interfaces:
  •  mirror_dynamic_lib.dart
  •  mirror_static_lib.dart
 mirror_dynamic_lib will use 'dart:mirrors', so this will be useful to run on server side, and no extra information are required to use this lib.
the second one is for javascript mode, it require additional meta  information for the class which is to be used in a generic class.
Following dart file is to provide such information for Expense class.  As shown in the last part, there is a dart2js compiler bug, I could not use the simpler version(commented one), but if we use this code, I could avoid the compiler bug(compiler was crashed).(this bug was fixed after I reported this issue in rev 28044)

library sample_mirror;

import 'mirror_libs/mirror_api_lib.dart';
import 'mirror_libs/mirror_static_lib.dart';
import 'shared/models.dart';

/*
 * This must be invoked before calling any of these simple mirror APIs.
 */

void initClassMirrorFactory() {
  ClassMirrorFactory.register((Type type)=>(type == Expense)?
      new StaticClassMirror(()=>new Expense.Default(), expenseFieldInfo)
  :null);
}

Type _String = String;
Type _ExpenseType = ExpenseType;
Type _DateTime = DateTime;
Type _num = num;
Type _bool = bool;

Map<Symbol, FieldInfo> expenseFieldInfo =
[
 new FieldInfo(const Symbol('id'), _String, (Expense e)=>e.id, (Expense e, String value) { e.id = value; }),
 new FieldInfo(const Symbol('rev'), _String, (Expense e)=>e.rev, (Expense e, String value) { e.rev = value; }),
 new FieldInfo(const Symbol('expenseType'), _ExpenseType, (Expense e)=>e.expenseType, (Expense e, ExpenseType value) { e.expenseType = value; }),
 new FieldInfo(const Symbol('date'), _DateTime, (Expense e)=>e.date, (Expense e, DateTime value) { e.date = value; }),
 new FieldInfo(const Symbol('amount'), _num, (Expense e)=>e.amount, (Expense e, num value) { e.amount = value; }),
 new FieldInfo(const Symbol('detail'), _String, (Expense e)=>e.detail, (Expense e, String value) { e.detail = value; }),
 new FieldInfo(const Symbol('isClaimed'), _bool, (Expense e)=>e.isClaimed, (Expense e, bool value) { e.isClaimed = value; })
 ].fold({}, (Map map, FieldInfo fh) => map..[fh.symbol] = fh);

/*
//
// This works for DartVM, but it fails dart2js.
//
Map<Symbol, FieldInfo> expenseFieldInfo =
    [
     new FieldInfo(const Symbol('id'), String, (Expense e)=>e.id, (Expense e, String value) { e.id = value; }),
     new FieldInfo(const Symbol('rev'), String, (Expense e)=>e.rev, (Expense e, String value) { e.rev = value; }),
     new FieldInfo(const Symbol('expenseType'), ExpenseType, (Expense e)=>e.expenseType, (Expense e, ExpenseType value) { e.expenseType = value; }),
     new FieldInfo(const Symbol('date'), DateTime, (Expense e)=>e.date, (Expense e, DateTime value) { e.date = value; }),
     new FieldInfo(const Symbol('amount'), num, (Expense e)=>e.amount, (Expense e, num value) { e.amount = value; }),
     new FieldInfo(const Symbol('detail'), String, (Expense e)=>e.detail, (Expense e, String value) { e.detail = value; }),
     new FieldInfo(const Symbol('isClaimed'), bool, (Expense e)=>e.isClaimed, (Expense e, bool value) { e.isClaimed = value; })
     ].fold({}, (Map map, FieldInfo fh) => map..[fh.symbol] = fh);
*/
From the top level dart file, we can change the  library by just switching to import file as following. I'll attach the entire main dart file for this app. this is  all required codes  to run this application using the generic GUI library. the layout of several components like table, buttons etc, and the controlling logic  are defined here.


 library sample_generic_gui;

import 'dart:html';
import "shared/models.dart";
import "gui_generic_lib/gui_generic_lib.dart";
//import "mirror_libs/mirror_dynamic_lib.dart"; // <== use 'dart:mirrors'
import "sample_mirror_impl.dart";; // <== no use of 'dart:mirrors'

class AppController extends Component {
  static const String APP = "g_app_ctlr";
  final DivElement _uiRoot;
  DivElement _content;
  DivElement _actions;
 
  Table<Expense> table;
  Form<Expense> form;
  ButtonComp newButtom;
  ButtonComp saveButtom;
  ButtonComp deleteButtom;
 
  AppController(Component parent, this._uiRoot, {List<Expense> expenses}): super(parent, const[APP]) {
    table = new Table<Expense>.fromModelType(this, Expense, formatFunctionMap: {ExpenseType: ExpenseTypeComp.format});
    form = new Form<Expense>(this, Expense,
        specialInputCompMap: {ExpenseType: ExpenseTypeComp.inputCompFactory},
        adhocCompMap: {'detail': 'textarea'}  // temp
    );
  
    Expense e = null;
    newButtom = new ButtonComp(this, "New", (_) {
      e = form.create();
      _changeButtonState(false, create: true);
    
    });
    saveButtom = new ButtonComp(this, "Save", (_) {
      Expense e0 = form.save();
      if (e0 != null) {
        e = e0;
        table.addOrUpdate(e);
        _changeButtonState(true);
      }
    });
    deleteButtom = new ButtonComp(this, "Delete", (_) {
      Expense e = form.delete();
      if (e != null) {
        table.delete(e);
        _changeButtonState(true);
      }
    });
    _changeButtonState(true);
  
  
   table.row_listeners.add((ev, row){
      //print("row clicked.. ${ev}, row: ${row}");
      e = row.e;
      form.load(e);
      _changeButtonState(false);
    });
  
    if (expenses != null) {
      table.load(expenses);
    }
    _uiRoot.nodes.add(element); // this 'element' tiggers DOM node creation!
  }
 
  void _changeButtonState(bool isEmpty, {create: false}) {
    (newButtom.element as ButtonElement).disabled = !isEmpty;
    (saveButtom.element as ButtonElement).disabled = isEmpty;
    (deleteButtom.element as ButtonElement).disabled = (create)?true:isEmpty;  
  }

  Element createElement() => addSubComponents0(newElem("div"));
 
  Element update() => addSubComponents0(initElem());
    
  Element addSubComponents0(Element elm) => addListeners(
      elm
      ..classes.add("section")
      ..nodes.add(new Element.html("<header class='section'>${table.modelType} Table</header>"))
      ..nodes.add(_content = new Element.tag("div")
        ..nodes.add(table.element))
      ..nodes.add(_actions = new Element.tag("div")
        ..id = "actions"
        ..classes.add("section")
        ..nodes.add(newButtom.element)
        ..nodes.add(saveButtom.element)
        ..nodes.add(deleteButtom.element))
      ..nodes.add(form.element)
      ..nodes.add(new Element.html("<footer class='section' id='footer'></footer>")));
}

class ExpenseTypeComp extends SelectComp<ExpenseType> {
  static const String EXPENSE_TYPE_INPUT = "g_expense_type_input";
 
  static final Map<String, ExpenseType> _expenseTypes = {
    "TRV": const ExpenseType("Travel","TRV"),
    "BK": const ExpenseType("Books","BK"),
    "HT": const ExpenseType("Hotel","HT")                        
  };
 
  ExpenseTypeComp(Component parent, String label, {List<String> classes: const [SelectComp.SELECT_INPUT, EXPENSE_TYPE_INPUT]})
    : super(parent, label, ExpenseType, classes: classes);
 
  static ExpenseTypeComp inputCompFactory(Component c, String name, Type t)=>new ExpenseTypeComp(c, name);
  static String format(ExpenseType et) => (et == null)?'':et.name;
 
  Map<String, ExpenseType> get entityTypes => _expenseTypes;
 
  String getCode(ExpenseType et) => et.code;
  String getName(ExpenseType et) => et.name;
}

main() {
  // register reflection factory
  initClassMirrorFactory();
 
  List<Expense> expenses = [
                            new Expense.random(),
                            new Expense.random(),
                            new Expense.random(),
                            new Expense.random(),
                            new Expense.random()];
  Element uiContainer = document.query("#sample_generic_gui");
  AppController app = new AppController(null, uiContainer);
  app.table.load(expenses);
-------------------------------

here is the implementation classes:

library dynamic_mirror;

import 'dart:mirrors';
import 'mirror_api_lib.dart';

/*
 * This must be invoked before calling any of these simple mirror APIs.
 */
void initClassMirrorFactory() {
  ClassMirrorFactory.register((Type type)=>new DynamicClassMirror.reflectClass(type));
}

//
// IClassMirror implementations
//
class DynamicClassMirror implements IClassMirror {
  static Map<Type, DynamicClassMirror>  cmirrs = {};
 
  final Type type;
  ClassMirror _cmirror;
  MethodMirror _ctor;
  Map<Symbol, IFieldType> _fieldTypes = {};
 
  DynamicClassMirror(this.type) {
    _cmirror = reflectClass(type);
   
    reflectClass(type).constructors.forEach((k, v){
      if (v.parameters.length == 0 && (_ctor == null || getSymbolName(k) == "${type}.Default")) {
        _ctor = v;
      }
    });
   
    _cmirror.getters.forEach((Symbol symbol, MethodMirror md){
      _fieldTypes[symbol] = new DynamicFieldType(symbol, md);
    });
  }
 
  factory DynamicClassMirror.reflectClass(Type type) {
    DynamicClassMirror cmirr = cmirrs[type];
    if (cmirr == null) {
      cmirr = new DynamicClassMirror(type);
    }
    return cmirr;
  }
 
  IInstanceMirror newInstance() =>
      reflect(_cmirror.newInstance(_ctor.constructorName, []).reflectee);

  IInstanceMirror reflect(Object obj) => new DynamicInstanceMirror(this, obj);

  Map<Symbol, IFieldType> get fieldTypes => _fieldTypes;

}

class DynamicFieldType implements IFieldType {
  Symbol _symbol;
  String _name;
  MethodMirror _md;
 
  DynamicFieldType(this._symbol, this._md) {
    _name = getSymbolName(_symbol);
  }
 
  Symbol get symbol => _symbol;
  String get name => _name;
  Type get type => (_md.returnType as ClassMirror).reflectedType;
}

//
// IInstanceMirror implementations
//
class DynamicInstanceMirror implements IInstanceMirror {
  Map<Symbol, DynamicField>  dfs = {};
 
  final IClassMirror _cmirror;
  InstanceMirror _imirror;
 
  DynamicInstanceMirror(this._cmirror, Object obj) {
    _imirror = reflect(obj);
  }
 
  IClassMirror get cmirror => _cmirror;
 
  Object get reflectee => _imirror.reflectee;
  IField getField(Symbol name) => new DynamicField.create(name, this);
}

class DynamicField implements IField {
  DynamicInstanceMirror _parent;
  Symbol _symbol;
  String _name;
 
  DynamicField(Symbol this._symbol, this._parent) {
    _name = getSymbolName(_symbol);
  }
 
  factory DynamicField.create(Symbol symbol, DynamicInstanceMirror _parent) {
    DynamicField df = _parent.dfs[symbol];
    if (df == null) {
      _parent.dfs[symbol] = df = new DynamicField(symbol, _parent);
    }
    return df;
  }
 
  Symbol get symbol => _symbol;
  String get name => _name;
 
  Object get value => _parent._imirror.getField(_symbol).reflectee;
  void set value(Object obj) { _parent._imirror.setField(_symbol, obj); }
 
  Type get type => _parent._cmirror.fieldTypes[_symbol].type;
 }

//
// utils
//
String getSymbolName(Symbol symbol) => symbol.toString().substring('Symbol("'.length, symbol.toString().length-2);
 ----------------------------
 library static_mirror;

import 'mirror_api_lib.dart';

//
// IClassMirror implementations
//
typedef Object Getter(Object entity);
typedef void Setter(Object entity, Object value);

class FieldInfo implements IFieldType {
  final Symbol _symbol;
  String _name;
  final Type _type;
 
  final Getter getter;
  final Setter setter;
 
  FieldInfo(this._symbol, this._type, this.getter, this.setter) {
    _name = getSymbolName(_symbol);
  }
 
  Symbol get symbol => _symbol;
  String get name => _name;
  Type get type => _type;
}

typedef Object DefaultConstructor();

class StaticClassMirror implements IClassMirror {
  final DefaultConstructor ctor;
  final Map<Symbol, FieldInfo> fieldInfos;
 
  StaticClassMirror(this.ctor, this.fieldInfos);
 
  IInstanceMirror newInstance() => reflect(ctor());
  IInstanceMirror reflect(Object obj) => new StaticInstanceMirror(this, obj);

  Map<Symbol, IFieldType> get fieldTypes => fieldInfos;
}

//
// IInstanceMirror implementations
//
class StaticInstanceMirror implements IInstanceMirror {
  Map<Symbol, StaticField>  dfs = {};
 
  final IClassMirror _cmirror;
 
  final Object _obj;
 
  StaticInstanceMirror(this._cmirror, Object this._obj);
 
  IClassMirror get cmirror => _cmirror;
 
  Object get reflectee => _obj;
  IField getField(Symbol name) => new StaticField.create(name, this);
}

class StaticField implements IField {
  StaticInstanceMirror _parent;
  Symbol _symbol;
  String _name;
 
  StaticField(Symbol this._symbol, this._parent) {
    _name = getSymbolName(_symbol);
  }
 
  factory StaticField.create(Symbol symbol, StaticInstanceMirror _parent) {
    StaticField df = _parent.dfs[symbol];
    if (df == null) {
      _parent.dfs[symbol] = df = new StaticField(symbol, _parent);
    }
    return df;
  }
 
  Symbol get symbol => _symbol;
  String get name => _name;
 
  Object get value => _cmirror.fieldInfos[symbol].getter(_parent.reflectee);
 
  void set value(Object obj) { _cmirror.fieldInfos[symbol].setter(_parent.reflectee, obj); }
 
  Type get type => _cmirror.fieldInfos[symbol].type;
 
  StaticClassMirror get _cmirror => (_parent._cmirror as StaticClassMirror);
 }

//
// utils
//
String getSymbolName(Symbol symbol) => symbol.toString().substring('Symbol("'.length, symbol.toString().length-2);