Monthly Archives: June 2011

AjModel: Model by Code (Part 2) Models and Repositories

Previous Post

I was working on my AjModel project. You can download the source code from my AjCodeKatas Project under trunk/AjModel. I added a Model class, and enhanced Entity Model and Property Model:

The model refers all the entity models I want to have in the coded model. AjModel enrich the already coded classes of your model, adding information like human descriptions, legends, etc. The idea is to generate automatically a UI for the coded model, for different technologies. The enhanced model could have nothing new, and AjModel should generate the initial UI, at runtime. The enhanced model could be consumed from differents UI technologies: the “proof of concept” application is an ASP.NET MVC one.

There is a fluent interface for EntityModel, and PropertyModel. There are extension methods, and wrappers/builders, like:

Some usage examples, borrowed from my tests:

EntityModel<Customer> model = new EntityModel<Customer>();
FluentEntityModel<Customer> fluentModel = new FluentEntityModel<Customer>(model);
    .Descriptor("Business Customer")
    .SetDescriptor("Business Customers");
Model model = new Model();
var entityModel = model.ForEntity<Customer>();
entityModel.Descriptor("Business Customer")
    .SetDescriptor("Business Customers");
Model model = new Model();
    c => c.Name,
    pm => pm.Descriptor("Customer Name")
            .Description("The Customer Name")

Where pm is a FluentPropertyModel.

In the UI process, I want to retrieve an entity by its identity. Or I need to get a list of entities to build a grid. Then, I need something to manage the entities, as a list. I implemented repositories in a context, to be implemented by different technologies. The current implementation is an in-memory list:

I’m planning to write adapter examples to NHibernate, Entity Framework, but those ideas are still in blueprints 😉

Usage examples:

this.entityModel = new EntityModel<Customer>();
this.domain = new SimpleDomain();
this.repository = new Repository<Customer>(this.entityModel, this.domain.Customers);

Note that the repository is a typed one, using generics. And it needs an entity model, and (in the current implementation) an IList to manage. The context contains a list of repositories:

var entityModel = new EntityModel<Customer>();
var domain = new SimpleDomain();
var repository = new Repository<Customer>(entityModel, domain.Customers);
var context = new Context();
var repo = context.GetRepository("Customer");

SimpleDomain is a class I created for tests:

public class SimpleDomain
    public SimpleDomain()
        this.Customers = new List<Customer>();
        for (int k = 1; k <= 10; k++)
            Customer customer = new Customer()
                Id = k,
                Name = string.Format("Customer {0}", k)
    public IList<Customer> Customers { get; set; }
    public ProductList Products { get; set; }

A model can be created using a class like SimpleDomain. It discovers IList public properties:

var model = new Model(typeof(SimpleDomain));
var entityModel = model.GetEntityModel("Customer");
entityModel = model.GetEntityModel("Product");

I plan to add all types in an assembly that satisfied a predicate, like having “Entities” in their namespaces.

Entities can be added and retrieved to/from a repository:

Customer entity = new Customer() { Id = 1000 };
Customer newEntity = this.repository.GetEntity(1000);

And they can be removed, too.

Entity model has the info to create new entities from values: a feature I will use in the UI:

EntityModel<Person> model = new EntityModel<Person>();
IDictionary<string, object> values = new Dictionary<string, object>()
    { "Id", 1 },
    { "FirstName", "Joe" },
    { "LastName", "Doe" },
    { "Age", "30" }
object entity = model.NewEntity(values);

In the next posts, I will discuss MVC UI implementation. All is work in progress, but the project is taking shape. And I having fun coding it 😉

Keep tuned!

Angel “Java” Lopez

Algorithms: Links, News, Resources (1)

Sometimes, I found an article or paper about an algorithm, or a class of algorithms. These are some my recent discoveries:

Texture synthesis

First results from GHC’s new garbage collector – GHC


FunctionSource: Path finding with Canvas

F# Code: Hindley Milner Type Inference Sample Implementation

What is Hindley-Milner? (and why is it cool?) – Code Commit

compiler – implementing type inference – Stack Overflow

LEGO Mindstorms Rubik’s Cube Solver

Algorithmic Game Theory and Artificial Intelligence

Eternity II Solver

the { buckblogs :here }: Maze Generation: Growing Tree algorithm

Sorting Obsession

Las máquinas poéticas de los libros imaginarios (i): Raimundo Lulio (Spanish)

How many numbers are squares mod m

Maze Generation: Prim’s Algorithm

Maze Generation: Kruskal’s Algorithm

The Craig Web Experience: Understanding the Halting Problem Protein Structure Methods and Algorithms (Wiley Series in Bioinformatics) (9780470470596): Huzefa Rangwala, George Karypis: Books

Algorithm and data-structure library for .NET 3.5 and up. Algorithmia contains sophisticated algorithms and data-structures like graphs, priority queues, command, undo-redo and more.

Azul’s Pauseless Garbage Collector

Rete Algorithm

Next generation of algorithms inspired by problem-solving ants

Langton’s Ant

An Events Based Algorithm for Distributing Concurrent Tasks on Multi-Core Architectures

YouTube – What different sorting algorithms sound like

To Trie or not to Trie – a comparison of efficient data structures

How to differentiate a non-differentiable function — The Endeavour

The greatest program ever written

My links:

Angel "Java” Lopez

Writing An Application Using TDD (Part 5) Adding Views

Previous Post
Next Post

Now I have some tests in place, I add some MVC views in this step. You can download the code from my AjCodeKatas Google Project, under trunk/AppTdd/Step04. So, this post has few new tests: it shows how we can build the interface AFTER the tests, and WITHOUT having a database or service layer, yet.

First, I added a new Site.master master page and style.css (borrowed from another ASP.NET MVC project)

I added a new Home controller:

Then, I added a view using the context menu over the Index method:


I modified the master page code, to have a new entry in its menu:

I added a new view associated to Index action in Subject controller:

I selected the “List” view content, and “Subject” as the type to use in the model.

But the controller method is:

public ActionResult Index()
    return View(subjects);

It uses a subject list, that is injected in the constructor by the tests:

public SubjectController(IList<Subject> subjects)
    this.subjects = subjects;

But wait! That list is injected by the tests. Now, I should inject in the normal process of the controller, in its parameter-less constructor:

public SubjectController()
    : this(Domain.Instance.Subjects)

I added a Domain.Instance to use as our in-memory domain:

public class Domain
    private static Domain instance = new Domain();
    private Domain()
        this.Subjects = new List<Subject>()
            new Subject() { Id = 1, Name = "Mathematics" },
            new Subject() { Id = 2, Name = "Physics" },
            new Subject() { Id = 3, Name = "Biology" },
            new Subject() { Id = 4, Name = "Literature" }
    public static Domain Instance { get { return instance; } }
    public IList<Subject> Subjects { get; set; }

I changed the links generated in the Index view from:

to use the Id property as primary key:

This is the result:

I created the other views using the Visual Studio “Add View…” wizard:

I had some missing actions, I wrote a new:

public ActionResult Edit(int id)
    var model = this.subjects.Where(s => s.Id == id).FirstOrDefault();
    return View(model);

With tests! 😉

public void GetSubjectForEdit()
    IList<Subject> subjects = GetSubjects();
    SubjectController controller = new SubjectController(subjects);
    ActionResult result = controller.Edit(1);
    Assert.IsInstanceOfType(result, typeof(ViewResult));
    ViewResult viewResult = (ViewResult)result;
    Assert.IsInstanceOfType(viewResult.ViewData.Model, typeof(Subject));
    Subject model = (Subject)viewResult.ViewData.Model;
    Assert.AreEqual(1, model.Id);
    Assert.AreEqual("Mathematics", model.Name);

Curiously, I detected a “bad” test. I had written in my AddSubject test:

Assert.IsTrue(subjects.Any(s => s.Name == "Chemistry"));
Assert.AreEqual(4, subject.Id);

But the new id should be 5 (our testable list has 4 predefined subjects):

Assert.IsTrue(subjects.Any(s => s.Name == "Chemistry"));
Assert.AreEqual(5, subject.Id);

I fixed the code and the controller action, run the web application, and voila!

Main points:

– I am using an in-memory domain.

– The views run over the already tested actions

No service layer or persistence yet. Next steps: add more classes to domain (Books), service layer (using test), and some persistence.

Interesting related post about development with TDD without a database (or adding it after the tests) by @RonJeffries:

But We Need a Database … Don’t We? |

See? We Don’t Need a Database … Yet |

Keep tuned!

Angel “Java” Lopez

OAuth, OAuth2 and Azure Access Control Service (ACS): Links

The past two weeks I was working in a proof of concept application for a customer of mine, implementing OAuth2 using ACS (Azure Access Control Service). These are the principal links I used.

First, links about what is OAuth, its history, etc:

OAuth (Open Authorization) is an open standard for authorization. It allows users to share their private resources (e.g. photos, videos, contact lists) stored on one site with another site without having to hand out their credentials, typically username and password.

The Authoritative Guide to OAuth 1.0

The new OAuth 2:

OAuth in ACS and WCF:

Windows Azure AppFabric Access Control Service (ACS): WCF SWT/REST OAuth Scenario
Securing WCF Services with ACS

ACS (Azure Access Control Service) Added Support for OAuth 2.0 Protocol

This is the key web scenario example with code I studied [1]:
It uses SWT (Simple Web Token) tokens to protect REST services. Read the setup to understand what it’s needed (Service Identity configuration) at Azure ACS.

The second key scenario example is desktop flow:

DataMarket OAuth Samples – Rich Client (2)
DataMarket OAuth Samples – Web Client
Again, these examples uses SWT

I found these last two examples at:

I should review the code at:
Code Sample: OAuth 2.0 Certificate Authentication
contained in
Access Control Service Samples and Documentation

I could extend example [1] to support a WinForm client.

Keep tuned!

Angel “Java” Lopez

Links, News and Resources: Windows Azure (1)

Next Post

Some links I found interesting about Azure:

Inside Windows Azure, the Cloud Operating System with Mark Russinovich

Introducing System.Web.Providers – ASP.NET Universal Providers for Session, Membership, Roles and User Profile on SQL Compact and SQL Azure – Scott Hanselman

Is Apple iCloud Powered by Microsoft Windows Azure?

Remote Desktop in Windows Azure–what’s it doing?

Node.js, Ruby, and Python in Windows Azure: A Look at What’s Possible

Node.js, CoffeeScript, and the Windows Azure Service Management API — Gist

Windows Azure Q&A with Roger Jennings — Visual Studio Magazine

Windows Azure Toolkit for Windows Phone 7

Azure VM Assistant (AzureVMAssist) : Windows Azure VM Information, Investigation and Diagnostics Utility

Edit and Apply New WIF’s Config Settings in Your Windows Azure WebRole… Without Redeploying!

Getting started with SQL Azure Development

Windows Azure | Pricing Estimator | Cost Calculator | Pricing Calculator

How to Deploy a Hadoop Cluster on Windows Azure

Scalable and Simple CQRS Views in the Cloud – Blog – CQRS and Cloud Computing

Patterns: Windows Azure – Upgrading your table storage schema without disrupting your service

My Azure Links:

Keep tuned! More links coming soon 😉

Angel “Java” Azure

AjModel, Model by Code (Part 1) Inception

Next Post

I’m a big proponent of raise the level of abstraction, separate problems from solutions. One of my project, AjGenesis, is dedicated to design free models that can produce (via code generation) applications in different platforms and technologies. Now, I want to explore another way: instead of code generation, I want to use simple runtime code to define and use an enhanced model.

First ideas

It’s natural to have a model (domain model, business model, you can name it):

You can have main classes (entities), associations, collection associations, services with methods, etc. And you can build all these artifacts using TDD, or not. But these artifacts ARE the system core. But you need to enhance the model, if you want to expose in a user interface. An example from AjGenesis:


This abstract model has attributes like Name, SetName to be uses as names in code generation, and Descriptor, Description to be used in interface (user communication) code generation. These additional attributes is part of I named “Enhanced Model”: a model with additional properties, information that help to describe the model in human terms. Maybe, I could add some additional data (SQL field lengths, etc), to be used in persistence, but it is not a target in my initial steps:

Interface models depend of the base technology to use. Once the enhanced model describe the entities and properties in user terms, view models can be built based on such information. And if the “human name” of an entity or property is missing, the code name can be used. There is “default” data and behavior in an enhanced model: use the model, Luke! In the following paragraphs are code that shows the way to enhance the model. But one key design decision is: if the model is not enhanced, I could generate all the interface from the plain model.

Some code

Then, I began to code AjModel. You can see my progress in my AjCodeKatas Project under trunk/AjModel. My first enhanced models are dedicated to Entities (main objects in the model) and their Properties:

This is a test model class, a simple Customer:

public class Customer
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Notes { get; set; }

Then, one test:

public void GetProperties()
    EntityModel model = new EntityModel(typeof(Customer));
    var properties = model.Properties;
    Assert.AreEqual(4, properties.Count);
    Assert.AreEqual("Id", properties.First().Name);
    Assert.AreEqual("Name", properties.Skip(1).First().Name);
    Assert.AreEqual("Address", properties.Skip(2).First().Name);
    Assert.AreEqual("Notes", properties.Skip(3).First().Name);

Upcoming: ServiceModel (describing services), and Model (containing the list of Entity and Service Models). More properties in EntityModel, like .Descriptor, .SetDescriptor, etc.

Each interface model depends of the final technology. As a proof of concept, I started to define an ASP.NET MVC interface model, in AjModel.WebMvc project. There is an EntityController, now dedicated to Customer:

public ActionResult Index()
    var model = new EntityListViewModel();
    model.Entities = Domain.Instance.Customers;
    model.EntityModel = new EntityModel(typeof(Customer));
    return View(model);

Domain.Instance.Customers is a in-memory list of customers. Some code in view:

    <%= this.Model.Title %></h2>
        <% foreach (var property in this.Model.EntityModel.Properties)
            <%= Html.Encode(property.Name) %>
        <%} %>
    <% foreach (var entity in this.Model.Entities)
       { %>
       <% foreach (var property in this.Model.EntityModel.Properties)
          { %>
          <td><%= property.GetValue(entity) %></td>
       <%} %>
    <%} %>

Next steps

I want to have a fluent interface like:


And I want to use Expression<Func…> to leverage code validation (define properties by code instead by name):

     .ForProperty(c => c.Name)
         .Description("Customer Name")

Or something like:

     .Property(c => c.Name,
          pm => pm.Description("Customer Name")
     .Property(c => c.Address,
          pm => pm.Description("Customer Address")

where pm is a PropertyModel. .ForProperty returns a PropertyModel fluent interface. But .Property returns a fluent EntityModel builder, so it uses the second parameter to extended the selected property.

But no committed code in repo, yet. You know, I’m working in my free time, I’m still need to work, family fortune dissolved in Montecarlo tables 😉

Code Generation vs Runtime

I’m still prefer code generation from an free-defined model: it makes a clear distinction of the problem and the technological solution. And it can be easily adapted to the changes of technologies and language (Java vs Scala vs C# vs … whatever upcoming combination.. ;-). But most developers prefer to work with code. That’s the reason for this experiment. Since late nineties, I know morphic  in Smalltalk world (thanks to SUGAR Smalltalk User Group Argentina meetings, now defunct) See History of Morphic. And Naked Objects is another way to expose the model to the user/developer. See Naked Objects, Wikipedia. I read:

1. All business logic should be encapsulated onto the domain objects. This principle is not unique to naked objects: it is just a strong commitment to encapsulation.

2. The user interface should be a direct representation of the domain objects, with all user actions consisting, explicitly, of creating or retrieving domain objects and/or invoking methods on those objects. This principle is also not unique to naked objects: it is just a specific interpretation of an object-oriented user interface (OOUI).

The original idea in the naked objects pattern arises from the combination of these two, to form the third principle:

3. The user interface should be created 100% automatically from the definition of the domain objects. This may be done using several different technologies, including source code generation; implementations of the naked objects pattern to date have favoured the technology of reflection.

The naked objects pattern was first described formally in Richard Pawson’s PhD thesis[1] which includes a thorough investigation of various antecedents and inspirations for the pattern including, for example, the Morphic user interface.

This century, I found Magritte.

Now, it’s time to explore the runtime/reflection way in .NET. Pros: developers can enhanced the model using their IDEs and code; their can create new interface models. Cons: it’s limited to the underlying technology, in my case: .NET; new dynamic interface models can be hard to create; custom extension by manual code could be not easy.

Ok, enough for today, back to coding (and to work).

Keep tuned!

Angel “Java” Lopez

Links, news, Resources: Node.js (1)

Next Post

You know: I’m a link collector. This is a short selection of my Node.js links:

Evented I/O for V8 JavaScript.

An example of a web server written in Node which responds with "Hello World" for every request.

var http = require(‘http’);
http.createServer(function (req, res) {
  res.writeHead(200, {‘Content-Type’: ‘text/plain’});
  res.end(‘Hello World\n’);
}).listen(1337, "");
console.log(‘Server running at’);

Modules <– Key feature

Mastering Node – Open Source Nodejs eBook

The CommonJS API will fill that gap by defining APIs that handle many common application needs, ultimately providing a standard library as rich as those of Python, Ruby and Java.

CommonJS Modules implementation
To understand modules in CommonJs

Learning Server-Side JavaScript with Node.js

A package manager for node

Learning Server-Side Javascript with Node.js

V8 JavaScript Engine

Playing with Node.js, Ubuntu, Sqlite3 and node-Sqlite

A geek with a hat » Comparing clojure and node.js for speed

Felix’s Node.js Guide

Why a JavaScript hater thinks everyone needs to learn JavaScript in the next year

Nave: version manager for node.js
It’s like rvm for ruby

The Node Ahead: JavaScript leaps from browser into future

Up and Running with Node.js

First Steps with Node.js: exciting stuff

NodeJS Tutorial with CouchDB and Haml – ErdNodeFlips

Node Tutorial Part 2

Deep inside Node.js with Ryan Dahl

JavaScript require in 100 lines of code
To understand scope and function of require() in Javascript

How to Install Node.JS on Windows – David Trejo’s Thoughts

Node.js, CoffeeScript, and the Windows Azure Service Management API

Node.js, Ruby, and Python in Windows Azure: MIX Talk

Node.js, Ruby, and Python in Windows Azure: A Look at What’s Possible | MIX11 | Channel 9

My links

Keep tuned!

Angel "Java" Lopez