Category Archives: ASP.NET

Azure: A simple Application using Tables

Continuing with my Azure examples, this time I wrote a simple CRUD Web applications, using Tables, using Azure Storage Client.

It’s a classic ASP.NET application, this is the view for Customer/Index action:

You can download the solution from my AjCodeKatas Google project. The code is at:

If you want the current frozen version:

The simple entity Customer:

public class Customer : TableServiceEntity
    public Customer()
        : this(Guid.NewGuid().ToString())
    public Customer(string id)
        : base(id, string.Empty)
    public string Name { get; set; }
    public string Address { get; set; }
    public string Notes { get; set; }

I’m using the PartitionKey as the primary key, filling it with a Guid. The RowKey is the empty string. In a less simple application, I could save the invoices of a customer using the same partition key, and identifing each invoice with its RowKey.

A DataContext is in charge of expose an IQueryable of Customers:

public class DataContext : TableServiceContext
    public const string CustomerTableName = "Customers";
    public DataContext(string baseAddress, StorageCredentials credentials)
        : base(baseAddress, credentials)
        this.IgnoreResourceNotFoundException = true;
    public DataContext(CloudStorageAccount storageAccount)
        : base(storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials)
        this.IgnoreResourceNotFoundException = true;
    public IQueryable<Customer> Customers
            return this.CreateQuery<Customer>(CustomerTableName);

Note the IgnoreNotFoundException: if true, I can retrieve an inexistent customer, and instead of raise an exception, return a null value.

There is a service to access and manage Customers:

public class CustomerServices
    private DataContext context;
    public CustomerServices(DataContext context)
        this.context = context;
    public Customer GetCustomerById(string id)
        return this.context.Customers.Where(c => c.PartitionKey == id).SingleOrDefault();
    public IEnumerable<Customer> GetCustomerList()
        return this.context.Customers.ToList().OrderBy(c => c.Name);
    public void AddCustomer(Customer customer)
        this.context.AddObject(DataContext.CustomerTableName, customer);
    public void UpdateCustomer(Customer customer)
        this.context.AttachTo(DataContext.CustomerTableName, customer, "*");
    public void DeleteCustomerById(string id)
        Customer c = this.GetCustomerById(id);

Note the Attach using ETag (third parameter) of “*” (any). This way, I can update the customer attaching the “in-memory-created” one to the data context, without retrieving it from the database. This approarch is viable if I have all the data of the customer. In most application you change only some fields, so you should retrieve the object, change it, and then, save the changes.

Using the service to retrieve the customers:

CloudStorageAccount storage = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
CustomerServices services = new CustomerServices(new DataContext(storage));
this.grdCustomerList.DataSource = services.GetCustomerList();

Note: it’s a sample application, simple and direct. A real application should separate the view model from the business model, and maybe, use an ASP.NET MVC front end. I will write this example, using MVC. In another series (out of Azure), I want to write an app using ASP.NET MVC AND TDD.

Next steps in Azure: a distributed fractal application, a distributed web crawler, implement a distributed genetic algorithm, using worker roles.

Keep tuned!

Angel “Java” Lopez

AjClipper: a Clipper-like interpreter that uses .NET

You can find a Clipper-like (I wrote Remember Clipper; you’ll find more links in that post) interpreter source code at my Code Katas Google project:

It’s an interpreter, written in C#, that can create and use native .NET objects. I wrote the interpreter to:

– Practice TDD
– Create a simple tool to leverage Clipper knowledge in one of my teams, to learn more .NET concepts

I should write posts about internal implementation, access to .NET objects, manage of work areas, etc… One idea I’m exploring, is running the interpreter from an ASP.NET web page:


(There is a web app in the project containing the above test page).

My collected links about Clipper:

I should improve the access to database, and complete language command and features. Keep tuned!

Angel “Java” Lopez

ASP.NET example using Mere Mortals Framework

I was working reproducing the ASP.NET example described in Mere Mortals Framework Developer’s Guide, using Northwind MS SQL database, using VB.NET as implementation language (the guide explains the steps to create this app using VB.NET or C#).

You can download the result from my Skydrive:

Load the solution in VS 2008 (you must have Mere Mortals Fwk DLLs in your machine).

This is the CustomerOrders.aspx page:

The first column is a link, that points to OrderEdit.aspx, where you can edit

You can change the connection string at web.config:

In my current project, the team is working improving the validation process, specially in grid fields. I hope I will rewrite this example as templates and tasks using AjGenesis. Keep tuned!

Angel “Java” Lopez

Code Generation for LINQ and C# 3.0 with AjGenesis

AjGenesis, my open source code generation project, uses a user-defined model. You can define tasks and templates, to transform the model to code and text files. You can write your own model, new tasks and transformation. You can invoke custom code or .NET objects, in the middle of the generation process.

As the model is user-defined, the system is not limited to one kind of projects. It’s based in templates and tasks, and then, the generated text artifacts are not bound to only one technology. You can generate files for any technology, framework, line of business and platform. You can generate DDL scripts, or a full base application, or anything between. It’s your decision.

When I began to write and use the system, .NET 2.0 didn’t exist. When the new technology became public, I wrote additional tasks and templates to take advantage of new features, as master pages, themes and new ASP.NET controls, without touching the core code of the AjGenesis project. Once the new templates and tasks were written, the project began to generate web applications for ASP.NET 2.x.

Now, as a proof of concept, I wrote a new example, that generates code using LINQ, the new kid on the microsoft block for .NET 3.x. The result was published as in the page AjGenesis Examples in CodePlex. To run the example, you need the current release 0.5 (includes source code, initial examples, an binaries). (There is a new version under development in the code repository).

The example

There is only one model in the example folders: AjFirstExample, with a simple XML model describing two plain entities, Customers and Suppliers. It’s the same model I used in previous examples.

<Project> <Name>AjFirstExample</Name> <Description>First Example using AjGenesis</Description> <Prefix>AjFE</Prefix> <Domain>com.ajlopez</Domain> <CompanyName>ajlopez</CompanyName> <Model> <Entities> <Entity Source="Entities/Customer.xml"/> <Entity Source="Entities/Supplier.xml"/> </Entities> <Lists> <List Entity="Customer"/> <List Entity="Supplier"/> </Lists> <Forms> <Form Entity="Customer"/> <Form Entity="Supplier"/> </Forms> <Views> <View Entity="Customer"/> <View Entity="Supplier"/> </Views> </Model> </Project>

Templates folder contains two sets of .tpl files (AjGenesis templates). MsSql templates are used in DDL script generation. Inside CSharp3 folder, there are new templates that generates LINQ DataContext, and simple classes.

Running the example

In the main directory, there is a command file


that loads the model in memory, technology model, and execute two tasks, creating code and DDL scripts.

The solution resides in a new directory, Build, with source code and MS SQL scripts:

Build\AjFirstExample\CSharp3\Sql\CreateDatabase.sql creates database and table, fragment:

create database AjFirstExampleNet3 go ... use AjFirstExampleNet3 go ... -- -- Entity: Customer -- Description: Customer Entity -- if exists (select name from sysobjects where name = 'Customer' and type = 'U') drop table Customer go create table Customer ( [Id] [uniqueidentifier] not null CONSTRAINT [DF_Customer_id] DEFAULT (newid()), [Name] nvarchar(200), [Address] nvarchar(2048), [Notes] nvarchar(2048) CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) go

The solution can be loaded in VS2008:

AjFirstExampleDataContext.cs is a simple LINQ DataContext:

public partial class AjFirstExampleDataContext : System.Data.Linq.DataContext { public AjFirstExampleDataContext() .... public Table<Customer> Customers; public Table<Supplier> Suppliers; }


You can replace this DataContext by one generated via Linq To SQL wizard, in Visual Studio. There is an option in the technology model to specify the generation of this custom DataContext. But you can drop it, and replace by a more complete DataContext: the project will compile with both approach.

The solution has three projects: data, services and ASP.NET presentation. The initial page is spartan (you know, I’m a developer, not a graphic designer… :-)):

From Administration option, you can browse, add, edit and delete customers and suppliers:


Next steps

I want to convert other previous examples to this new templates (AjTest model is the more challenging, with one to many relations and many entities). It could be interesting to generate ASP.NET MVC pages, instead of plain ASP.NET. And some testing infrastructure. I’m taking the code of ScrumLite solution as a base example to follow.

Angel “Java” Lopez

Code Generation as a Service with AjGenesis

I’m back! I want to write in this post about the new features I’ve added to my code generation project AjGenesis. The main points are:

– A new interactive way to use it, a web based application

– Examples with that new interface, to generate C#, VB.Net, Java and PHP applications, all from the same abstract model

These features were published last January at release 0.5 in CodePlex

Using AjGenesis

Years ago, I began to work in this project. Those days, the only way to execute and use it were the console, with commands. Later, I adopted NAnt, and NAntGui, as interfaces to launch the system and execute tasks and transformations. The project can be used as a set of .DLLs, referenced from custom application. Carlos Marcelo Santos has published posts (in Spanish) about how to use AjGenesis from NAnt

Cómo generar código con AjGenesis sirviéndonos de NAnt
Cómo generar código con AjGenesis sirviéndonos de NAnt – Parte II

Last year, 2007, Jonathan Cisneros wrote a great Windows interface, named AjGenesis Studio:

AjGenesis Studio: una IDE para AjGenesis
AjGenesis Studio at CodePlex

As an exercise at the end of year 2007, I wrote a new project in the original solution, and I published last January inside the last release 0.5 at CodePlex.

It’s a new web project, that I called, inspired by the work of Jonathan, AjGenesis Web Studio

The main point is, with this project, to show that the functionality from the AjGenesis core can be used and exposed in our applications, this time from a web interface, using ASP.NET. With this approach, we can put a server in our internal network or at Internet, and create, edit, upload and download user defined models, generate source code, and download the results. We could call this, Code Generation as a Service.

Let’s look the project, its functions and some inners.

The project

It’s a web project, named AjGenesis.WebStudio.

To launch it, load the AjGenesis.sln solution (located at src directory inside the version 0.5 from CodePlex) with Visual Studio 2005, and build the complete solution.

(If you have errors in the AjGenesis.WebStudio project, probably you must add a reference to a .DLL that manages the file compressions. Add as reference to the project the file src\Libraries\Ionic.Utils.Zip.dll. This library generates .zip files, and expand them).

In the web solution, I used Master Pages, and a default Theme. It doesn’t manage a database, only files and directories. We’ll see below that the project has a mini wiki, to write help pages that can be defined by the user.

The look and feel is simple, but you can change the theme and master page to obtain a better result.

The system can generate code in the fly, and download it as a .zip file. You can use the classic AjGenesis system, as I explained in past post, but now, we can use it from any browser. You don’t need .NET in your client machine, and you can work from other operating systems.

After the build of the solution, click right mouse button on the file \Default.aspx in project AjGenesis.WebStudio, and choose View in browser…:

This is preferred to launch the project in debug mode: if you debug the project, it will execute the code generation task in very slow way.

Working Directory

The system uses a working directory, with a structure that resembles the examples at (to download from examples at CodePlex). The default working directory is AjGenesis.WebStudioWorkingDirectory:

Some directories:

Projects: There is a directory here for each project model.
Templates: Containing the template files to process during the code generation phase
Build: The code generated code resides in this directory.

The working directory can be changed using the left menu option Working Directory and then, choosing the option Change Working Directory:

Generating Hello World

As I used to comment in my speeches, the acid test of all code generation system is to help us to model and produce the most simple and universal software system, the reknowed Hello World example. There is an explanation on how to do this with classic AjGenesis in my post

Code Generation with AjGenesis- A Hello World application

In AjGenesis Web Studio, select the left menu option Generate. This is the result page

There are two dropdown list. We’ll see how they are filled. At the first list, there are the defined projects:

Choose HelloWorld. Then, go to technology list, showing:

In this project, only Java and Net20 are the defined technologies. Other projects have more technologies. Choose Java and the press the Generate button. After a while, the page shows a result.

How this works?

First point, the system manage a working directory, the default is AjGenesis.WebStudioWorkDirectory, a syster directory of the web project. There is a Projects project, cointaining more directory, each one is a project for the system.

The directory AjGenesis.WebStudioWorkDirectory\Projects\HelloWorld has a Project.xml file that describes the free model we use in this case:

<Project> <Name>HelloWorld</Name> <Description>HelloWorld Example</Description> <GenerateTask>GenerateHelloWorld</GenerateTask> <Message>Hello World</Message> </Project>

Inside the directory project, there is a Technologies directory. Each XML file that is found there it’s managed as a technology model in the system. Again, as I explained in my posts on AjGenesis , this file has a free model, you can put here anything to process from code generation process. The concepts of project and technology is not mandatory, but AjGenesis Web Studio takes them as special directories, and read them to obtain the list of project and associated technologies.

The technology Java.xml file contains:

<Technology> <Name>Java</Name> </Technology>

and Net20.xml contains:

<Technology> <Name>Net20</Name> </Technology>

Nothing special. The value Name inside Technology drives what steps to execute during code generation phase.

After press the generate button, the system loads the project and technology model in memory. Then, it executes the file GenerateCode.ajg located in directory Tasks. But if the project file contains a  GenerateTask tag, as in this project, that file is executed instead the default one. This is the content of Tasks\GenerateHelloWorld.ajg:


PrintLine "Generating HelloWorld..." if not Project.BuildDir then Project.BuildDir = "${WorkingDir}Build/${Project.Name}" end if if not Project.Title then Project.Title = Project.Name end if if not Project.Version then Project.Version = "1.0.*" end if if not Project.Language then Project.Language = "en" end if if not Project.SystemName then Project.SystemName = Project.Name end if PrintLine "Creating Directory ${Project.BuildDir}" FileManager.CreateDirectory("${Project.BuildDir}") Include "Tasks\BuildHelloWorld${Technology.Name}.ajg"

This file is written in an scripting language, a pillar of AjGenesis, affectously named AjBasic. The Project variable is the representation in memory of the tag <Project> loaded from the Project.xml file, described above. In memory, it is as an object, with properties. It’s not an static object: you can add properties in runtime, as Project.Version in the above text. If in an if sentence we asks the value of  Project.Version and this doesn’t exist, it’s not an error, the result is simply Nothing and that value is treated as false for boolean evaluations (like in other languages, notably PHP).

Finally, the last line includes an additional file to process dinamically. The string contants in AjBasic have expression expansion: all between ${ and } is evaluated. Using the value of Technology.Name (obtained from loading in memory the XML technology file), it executes BuildHelloWorldJava.ajg or BuildHelloWorldNet20.ajg. The first one contains the steps to generate a .java file:

<# PrintLine "Generating Solution ${Project.Name}" if not Project.Title then Project.Title = Project.Name end if if not Project.Version then Project.Version = "1.0.*" end if PrintLine "Creating Directories" FileManager.CreateDirectory("${Project.BuildDir}") FileManager.CreateDirectory("${Project.BuildDir}\${Technology.Name}") TransformerManager.Transform("Templates\HelloWorld\ClassJava.tpl", "${Project.BuildDir}\${Technology.Name}\", Environment) #>

This code uses inner AjGenesis utilities that create directories and expand a template file. ClassJava.tpl contains:

// // Automatically generated by AjGenesis // // public class HelloWorld { public static void main(String[] args) { System.out.println("${Project.Message}"); } }

All this produces the directory Build\HelloWorld\Java:

If we choose the Net20 technology, more files would be generated:

This is a more complete result. It has a VS 2005 solution file, two project directories, one in VB.NET and the other in C#, with source code and project files:

To see the generated code, its files and directories, go to left menu option Builds:

There is a directory for each project. You can download a complete directory, as a .zip file. We can create a file, download a directory, upload and expand a .zip file, and consult a help page. We can read, edit, and delete each file, in this case readme.txt.

Go to the View at HelloWorld directory:

You can browse directories, upload and download files. You can move a directory, or make a copy, to experiment without loosing the original content.

Generating C# and VB.NET solutions

After this simple example, let’s go for more. For more information about the next examples and their models, read:

Application Generation using AjGenesis

Go again to left menu Generate option. Now, we choose a project, AjSecondExample. Its technology list is more complete:

Choose CSharp2 and generate. This process creates a complete solution inside Builds\AjSecondExample\CSharp2. There is an Sql directory with DDL script to create a MS SQL Server database. Inside the Src directory, you’ll find the solution, composed of a set of projects:

This projects follows a layered archictecture, that you can modify from the templates. They use a data access layer, based on my AjFramework project, but you can change to access Enterprise Library or your own data services.

You must create the database using the generated scripts, and modify the connection string in the web.config to match your environment. The application can be compiled and executed:

The administration page shows:

Back to generate page, execute the VbNet2 technology, obtaining a directory with the same structure, now with Visual Basic.NET code:

All these depend of the specified technology inside the files at Projects\AjSecondExample\Technologies. The content of VbNet2.xml is:

<Technology> <Programming> <Dialect>VbNet2</Dialect> </Programming> <Database> <Dialect>MsSql</Dialect> <Name>AjSecondExample</Name> <Username>sa</Username> <Prefix>ajse_</Prefix> <Host>(local)</Host> </Database> </Technology>

and CSharp2.xml:

<Technology> <Programming> <Dialect>CSharp2</Dialect> </Programming> <Database> <Dialect>MsSql</Dialect> <Name>AjSecondExample</Name> <Username>sa</Username> <Prefix>ajse_</Prefix> <Host>(local)</Host> </Database> </Technology>

These data are used during the code generation process.

Note: inside Tasks\BuildTechnology.ajg file, you’ll find a new variable, injected from the web project:

if not Project.BuildDir then Project.BuildDir = "${WorkingDir}Build/${Project.Name}/${Technology.Programming.Dialect}" end if

This is the WorkingDir variable that points to the working directory we selected in AjGenesis Web Studio.

Genarating Java and JSP applications

Many projects (AjFirstExample, AjSecondExample, AjTest….) can be generated in Java with JavaServer Pages. A build.xml file is generated to be modified and used to compile the generated code using the ant utility (you can use this file from an IDE, like Eclipse or NetBeans).

The target build  makes a .war deploy file. You can browse and modify the build.xml file to install the .war in a Tomcat web container.

The generated code is composed of .jsp files (web pages in Java) and Java code to compile that implements a service layer and a data access layer, exchanging simple JavaBeans between layers. The DDL script, in these examples, is a MySql one.

If you build and deploy the application, and install the database in a MySql server, you can see it working fromn a Tomcat server:

Generating application using Domain-Driven Design ideas and Hibernate, NHibernate

Many example projects (AjFirstExample, AjSecondExample, AjTest…) have defined technologies CSharp2DDDNh, JavaDDDHb, VbNet2DDDNh, and even VbNet2Nh. The DDD ones implement some concepts from Domain-Driven Desigg, as Application, Domain and Infrastructure layer, but the templates could be improved. The *Nh projects generate code for entities using NHibernate mapping. The *Hb projects use Hibernate.

An example of NHibernate generated mapping:


<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.0"> <class name="AjFirstExample.Domain.Customer, AjFirstExample.Domain" table="ajfe_customers"> <id name="Id" column="Id" type="Int32" unsaved-value="0"> <generator class="native"/> </id> <property column="Name" type="String" name="Name" length="255"/> <property column="Address" type="String" name="Address" length="255"/> <property column="Notes" type="String" name="Notes" length="255"/> </class> </hibernate-mapping>

These solution can be built as the previous examples. You’ll see better generator templates for NHibernate in the AjOmar example at CodePlex. Post (in Spanish) explaining the process at

Generando código para NHibernate (Parte 1)
Generando código para NHibernate (Parte 2)
Generando código para NHibernate (Parte 3)

Generating PHP applications

If you choose PHP technology, web page with PHP code are generated, using MySql as database. The generated code can be copied to a directory in a web site that supports PHP, Apache, or IIS. AjTest example running in a IIS with PHP4:

Other directories

In the working directory, there are other directories:

SourceCode: Containing some source code that is copied into the solution during code generation.

Libraries: Additional .dlls, to copy and use in the generated applications.

The larger subdirectory  is Templates:

In previous posts I described in detail the creation and use of a template file. This is the content of a template that generate a C# entity:

<# rem Entity Generator rem for C Sharp include "Templates/CSharp2/CSharpFunctions.tpl" message "Processing Entity ${Entity.Name}" include "Templates/CSharp2/Prologue.tpl" #> /* * Project ${Project.Name} * ${Project.Description} * Entity ${Entity.Name} * ${Entity.Description} * */ using System; namespace ${Project.SystemName}.Entities { public class ${Entity.Name} { // Private Fields <# for each Property in Entity.Properties message "Processing Field ${Property.Name}" #> private ${CSharpType(Property)} ${CSharpFieldName(Property)}; <# end for #> // Default Constructor public ${Entity.Name}() { } // Public Properties <# for each Property in Entity.Properties message "Processing Property ${Property.Name}" #> public ${CSharpType(Property)} ${Property.Name} { get { return ${CSharpFieldName(Property)}; } set { ${CSharpFieldName(Property)} = value; } } <# end for #> } }

Help pages

I’m testing some ideas in this web project. There are code to create “wiki” pages, that can be used as help pages in the system.

You can edit this kind of pages:

There is a way to insert links to other wiki pages and to external ones. The page data is represented as a .NET object in memory, and that object is serialized in an XML file in Pages application directory. There is no database to store page: each one is an object, serialized in a .xml file.


I hope this system helps to a better understanding of AjGenesis project features and potential. With a more user friendly interface, the project can be used by more people. We can generate code from command line, or using NAnt utility, or AjGenesis Studio.

I ever remark a point: all these are examples, AjGenesis is not limited to generate only this kind application. You are in charge: you can define the model that matches your project requirements, using any technology you choose. You can codify DDD ideas in a different and better way. You can generate Hibernate/NHibernate mappins using other patterns and mapping idioms. You can use other ORM utilities, and generate code for them. You can generate PHP5 pages that use Prado, instead of plain PHP4. You can generate stored procedures for Oracle, instead of my examples that use MS SQL Server. Or write better ones. You can generate WinForms code, instead of ASP.NET page. You can generate JavaServer Faces pages, views, beans, and abandon JavaServer Pages. You can generate the code or text you want: e.g., unit tests, or documentation pages. I recommend that the generated code resembles the code you could generate manually.

I invite anyone that uses this system, to post his/her work, or leave comments here. You can participate in the Spanish list:

Next steps

Back to develop, I have some ideas:

– Improve the templates to generate more technologies, as VS 2008 projects, solutions, templates for Struts 1/2, Spring, better mapping for Hibernate, NHibernate, and code generation for the new ASP.NET MVC.

– Write posts about these templates

– Publish the new examples

– Write down a useful documentation (now, it’s minimal: you can found more details in this posts)

Enjoy the project!

Angel “Java” Lopez

Application Generation using AjGenesis

These days, I wrote new examples for my open source project AjGenesis

Using AjGenesis, we can produce, starting from our own model, applications for ASP.NET 1.x/2.x, JSP, using SQL Server in .NET, with ADO.NET or NHibernate, or MySql with Java and Hibernate. The sample generated applications use a layered architecture (but remember: these are sample applications, you can write and use your own models, tasks, and templates). Other option: it can generate layers following ideas from Eric Evans’ Domain-Driven Design.

I’m still writing those examples, but now, you can download the current version from

The examples require the use of AjGenesis last release:

AjGenesis Version 0.4.3

but you can try the current version under development:

AjGenesis Version 0.5

In this post, I want to comment how AjGenesis works and some of its inner structure, using one of those examples. Although I will concentrate in producing VB.NET code, you’ll find that the example is able to produce C Sharp and Java/JSP solutions, as well.

First, let’s review first some points about the project. The big picture:

AjGenesis Version 0.4.3 is written using VB.NET V1.x, but version 0.5 is the current version under development, and it was rebuilt using .NET 2.0. The project is open source, and has a BSD-like license, that allows to use it in any project what you want: you only need to comply with the license (in short, put some reference to the original project). It is possible to be used like a library, invoked from your own project, or it is possible to be invoked from command line, or even it can be used from using NAnt (this tool gives you a better organization of the code generation tasks).

There are several samples in the page of the project (inside the project zip source file and in additional files). They generate code from a model, invoking tasks and processing templates. The samples generate code PHP, Java, JSP, VB.NET, C#, ASP.NET, and even scripts of procedure and data base stored. I want to emphasize two points:

The model to use is totally definible by you. It’s a free model, it’s not a fixed one. You can model what you want to model.

– The tasks and templates to apply are totally programmable and controlable. You are in charge. 

That’s make a difference from other generators. We can create our own model, and its own templates and tasks, to generate any text artifacts. Other systems start from the data base, and they only generate a group of predefined text files (as POJOs, plain old java objects, or DAOs, Data Objects Access). But with AjGenesis you can generate any text file you need.

In order to better understandind the free model concept, read a previous post:

Generating Code Hello World with AjGenesis

In that post, the initial steps are described, using a free model, totally oriented to the domain to represent: a typical Hello World application, implemented in different technologies.

Creating an application

Let’s do something more complete in this post. Suppose we need to create a simple solution simple, with two tables, in a MS SQL Server databse, source code in VB.NET 2,0, web interface, layer of services, layer of data, business components and business entities a la Microsoft. We want to generate the solution, the projects, scripts for database creation, and stored procedures. This example is included in the examples First step: to write the model.

The project

In a directory of projects of the examples that accompany this article, there is a Projects/AjFirstExample directory.

In that directory it is the Project.xml file that contains the model.

    <Description>First Example
    using AjGenesis</Description>

Remember: the model is free. Here we define the templates that we are going to use. The model contains two simple entities: customers and suppliers.

The entities

The XML file is not terribly long: AjGenesis allows that any node of the model is specified apart in a file. This is a criterion that I have used to define how the model is written: the resulting XML does not have to hurt at sight, must be understandable and abarcable in a reading.

In the Project.xml, that feature is used in the case of the entities, with the Source attribute. Let us examine an entity, written in Entities/Customer.xml:

    <Description>Customer Entity</Description>







There are attributes of the entities, like its name and description, in plural and singular. This data serve to name them in the resulting pages, or within the code. The properties are the fields to maintain in each entity..

Aside from the entities, in another directory, Technologies, specifies the dependent model of the technology, like VbNet2:

The templates

The templates to use are at the Templates/VbNet2 directory:

They are the templates for generation of code VB.Net 2.0. Also we will find groups for C# 1/2, Vb.NET 1,2, Java (although I’m thinking to drop templates for .NET 1.x: I don’t see any reason to maintain these). There are templates to use Nhibernate, Hibernate, JSP, MySql, and concepts of Domain-Driven Design, too. Let’s review a template as an example, the one that generates the organization in Visual BASIC, EntityVb.tpl:


message "Generating Entity ${Entity.Name}" 

include    "Templates/VbNet2/VbFunctions.tpl" 

include    "Templates/VbNet2/Prologue.tpl"

'    Project ${Project.Name}
'        ${Project.Description}
'    Entity    ${Entity.Name}
'        ${Entity.Description}

Public Class ${Entity.Name} 

'    Private Fields

for each Property in Entity.Properties
    message    "Procesando Campo ${Property.Name}"
    Private m${Property.Name} as ${VbType(Property)}
end for

'    Default Constructor

    Public Sub New()
    End Sub 

'    Public Properties

for each Property in Entity.Properties
    message    "Procesando Propiedad ${Property.Name}"
    Public Property ${Property.Name}() as ${VbType(Property)}
            Return m${Property.Name}
        End Get
        Set(ByVal Value As ${VbType(Property)})
            m${Property.Name} = Value
        End Set
    End Property
end for

End Class 

Like before, control structures are used. XML is the serialized format of the model. During the code generation process, the model is loaded in memory, ready to be accesible via dynamic variables.

The steps

We have more files to generate: from the pages ASPX, and their associated code, the projects of facade on watch, organizations, access to data, the file of solution, and more. In order to automate this generation, the example has several files of tasks, in the Tasks directory, where the steps are described to execute. There are two great tasks: the steps to execute independently of the chosen technology, like completing the model, reviewing it, and the employees of the technology, like generating such file JSP or ASPX, depending on if we want Java or .NET.

The task of completing the model is in charge of Tasks\BuildProject.ajg, that begins with:

' Build Project
'    Complete the Project Data
'    Project must be loaded in global variable Project

PrintLine "Completing Project ${Project.Name}" 

include "Templates/EntityFunctions.tpl"
include "Templates/Utilities.tpl" 

if not Project.Title then
    Project.Title = Project.Name
end if 

if not Project.Version then
    Project.Version = "1.0.*"
end if 

if not Project.SystemName then
    Project.SystemName = Project.Name
end if 

The template includes some auxiliary functions, and then, it begins to complete the model that resides in the Project variable. For example: if the project lacks Project.Title the program set Project.Name as Project.Title. The program continues:

for each Entity in Project.Model.Entities
    PrintLine "Entity " + Entity.Name 

    for each Property in Entity.Properties
        PrintLine "Property " & Property.Name
        if Property.Type="Id" and not Property.SqlType then
        end if
        if Property.SqlType and not Property.SqlColumn then
            Property.SqlColumn = Property.Name
        end if
        if Property.Type="Id" and not Entity.IdProperty then
            Entity.IdProperty = Property
        end if
        if Property.Reference then

After that process, the technology tasks are executed. The example use Tasks\BuildVbNet2.ajg, here a fragment:


include "Templates/Utilities.tpl"
include "Templates/VbNet2/UtilitiesVb.tpl" 

message "Creating Directories..." 

FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Entities/My Project")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Data/My Project")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Services/My Project")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Business/My Project")

message "Defining Solution and Projects..." 


In this fragment, the directories necessary are created to lodge the solution. The name of the directory is extracted of the model from Project.BuildDir. Note that ${ } in a string is used to expand the inside expression into the string value.

Technology Model

Under the directory Project\AjFirstExample\Technologies they are some models that describes the technology parameters to use:


Let’s examine VbNet2.xml:


These data is used during the template generation phase. It indicates the language, and the database to use.

Generating the solution

We could send the tasks from the command line, but we have a .build file for Nant, one for each technology to generate. We execute the tasks build, buildsql, and deploysql of with the command line:

nant build buildsql

(You must adjust the line

<property name=”ajgenesis.dir” value=”…./AjGenesis-0.5″/>

to reflect your AjGenesis installation directory)

Note the following lines in the build file:

    <target name="loadtasks" description="loads AjGenesis tasks">
        <loadtasks assembly="${nanttasks.dir}/AjGenesis.NAnt.dll" />

    <target name="init" depends="loadtasks" description="init the AjGenesis model, create build directory">
        <mkdir dir="${build.dir}"/>
        <loadmodel model="${project.dir}/Project.xml"/>
        <loadmodel model="${project.dir}/Technologies/${technology}.xml"/>
        <executetask task="${tasks.dir}/BuildProject.ajg"/>
        <executetask task="${tasks.dir}/BuildTechnology.ajg"/>

These tasks load an AjGenesis NAnt tasks, load the models, and execute the tasks.

In the Build/AjFirstExample/VbNet2/Sql directory they are left scripts of creation of the base and stored procedures. And in the directory Src brother, surprise! We’ll have the generated solution:

There were generated several projects, into a solution. We can load the solution into the Visual Studio 2005:

Using another NAnt file,, we can generate the same solution in CSharp:

You will find other projects and examples of .build files, that generate solutions using NHibernate, Hibernate use, JSP, and concepts of Domain-Driven Desing a la Eric Evans.


Sure, everything cannot be generated automatically. It is important to remember always that fact. But in the day to day, we recognize that we have amount of repetitive text, tasks that we can well delegate to software.

A key point: the model in AjGenesis is free. The presented examples are only examples: we can general the model that we want, and to write the templates we need. It is important to write the templates so that the generated code is similar to what we had manually generated. If we don’t feel comfortable with the generated code, if it does not have our style, our experience, we’ll end up generating something that we do not understand.

Another thinking: the model must be independent of the technology. In the final example, we have seen how, from the same model, we can generate solutions for VB.NET, CSharp and other technologies.

Software can help us to generate software. More: it MUST help us. Our experience counts: what we learned to make applications, we can overturn it in this species of expert system, code generation tools. In the future, I hope to be able to incorporate to the project, in the templates and tasks, more decision making: as well as we gain experience in writing of applications, we can incorporate our accumulated knowledge on patterns, architecture and styles of programming.

And as it is an open source project, AjGenesis allows us extend it, to our taste and necessity.

Suggestions, use case stories, comments are welcome. You can write as comments to this post, or write directly to me. Thanks to all that tested and adopted this project, and helped me to write it.

Angel “Java” Lopez

Interview preparation

Augusto Alvarez (a good guy that shares his knowledge, and who deserves to be in the NBA, he’s doubles me in height…. ;-), sent me this interesting link:

a blog that contains most common interview questions from different fields:

SQL Server Interview Questions
.NET Interview Questions
JAVA Interview Questions
SQL Server
Software Testing
Basic .NET Framework
SAP Interview Questions
ABAP Interview Questions
C++ interview Questions
C Interview Questions
PHP Interview Questions Interview Questions
Java Interview Questions

I liked the “less technical” posts:

Points to remember
Salary Negotiation
Resume Preparation Guidelines

In my opinion, you must prepare a blog, where you must post about your knowledge, researchs, studies, interesting things you found, and more. You are you and your blog.

Just curious:

The Bloggers Business School

Angel “Java” Lopez

Learning AJAX

A month ago, I gave an speech about AJAX, at Club de Programadores, here, in Buenos Aires, Argentina. I published the examples, presentation (in spanish) and resources that I used to prepare the speech. I hope that they will be useful as an introduction to AJAX:

Source: Adaptive Software

The initial post written by Jesse James Garret, from Adaptive creating the term AJAX, and explainint it:

Ajax: A New Approach to Web Applications

More about Garret at: (his book about The Elements of User Experience)

Sites about AJAX

Technologies related to AJAX

Standard ECMA JavaScript
The XMLHttpRequest Object

JavaScript Libraries





Yahoo User Interface Library

PHP Libraries


Ejemplo en


Java Libraries

Google Web Toolkit

AjaxTags – AjaxTags Usage
AjaxTags – AjaxTags Quick Start


Dynamic Faces


.NET Libraries

ASP.NET Ajax (Microsoft version for Net 2.x)


During the speech, I search some chat implementations using Ajax:

I visited some websites with AJAX:

My links about AJAX:

I read the excelent book from Francisco Minera, MP Ediciones:

An alternative, the new Microsoft baby, Silverlight:
Moonlight – Mono

Examples from the speech, presentation, at

Angel “Java” Lopez

C# Corner 3.0 Launched

I’ve received an email from the C# corner website, announcing:

A long awaited C# Corner 3.0 is live now. This version of C# Corner is rewritten and redesigned using ASP.NET 2.0, C# 2.0, and Visual Studio 2005. Not only we have improved the performance and appearance, we have also added many new feautures to the site. And guess what? Blogs are live now.

 Some interesting articles, recently submitted:

Extending ASPX Panel Control to produce Rounded Corners by Mike Clark. Mar 05, 2007.

This article shows how to create a custom control which encapsulates scripts. Also shows how to add method attributes to interact with VS Designer and ToolBox as well as providing intellisense dropdowns.

Extending ASP.NET 2.0 Menu Control To Have Tabs With Rounded Corners by Mike Clark. Feb 26, 2007.

The ASP.NET Menu Control normally produces tabs which have rectangular edges. The techniques presented extend the control to create tabs with rounded corners.

WPF Application for Importing ESRI Shapefiles by nschan . Feb 26, 2007.

A standalone application for reading ESRI shapefiles and displaying them on a WPF Canvas.

Put ASP.NET AJAX Timer and UpdatePanel with RssToolKit all in action by Muhammad Mosa. Feb 22, 2007.

This is simple article to show how ASP.NET AJAX 1.0 Timer Control can be used in conjunction with UpdatePanel Control and RssToolKit to achieve real usage scenario. It also shows how to maintain ViewState across page postbacks.

Using a Web User Control inside the GridView control by Michael Livshitz. Feb 21, 2007.

In this article I will share how a Web User Control can be used in the GridView control. The examples are written using C# .

Getting Started with AJAX 1.0 by Mahesh Chand. Feb 09, 2007.

After fruition of this article, you will have a better understanding of AJAX 1.0 extensions and will learn how to build AJAX enabled Web applications using ASP.NET 2.0 and Visual Studio 2005.

Access Sharepoint Portal Server using Web Services in .NET by Mahesh Chand. Feb 05, 2007.

This article discusses how we can leverage Sharepoint Portal Web Services to work with WSS in Microsoft .NET. The sample code used in this article shows how to access Lists Web Service to get the available lists in WSS. The sample code also shows how to add and update list items.

Passing Data Between Forms Without Events and Delegates by Scott Lysle. Jan 31, 2007.

This article describes a simplified approach to allowing communication between forms without the use of events and delegates.

Integrated Security with Web Application  by Shrikant Utekar. Jan 30, 2007.

This article will give you an idea about how Integrated Security works with Web Application using Active Directories.

Message Queuing using C# 2005 by Rajkumar Krishnan. Jan 29, 2007.

Message Queuing is a message infrastructure and a development platform for creating distributed messaging applications for the Microsoft Windows Operating System.

Image Processor by Mihai Popescu. Jan 25, 2007.

This article shows a light-weight image processor.

An Easy Way to Embed Word in a Web Page by Scott Lysle. Jan 24, 2007.

This article describes an approach to displaying word documents within a web page using a simple custom server control.

Interoperability between WCF and Oracle Application Server : Part I by John Charles Olamendy. Jan 24, 2007.

This article is part of series intended to show how to use Web Services related technologies to interoperate applications running in different platforms, in this case, the most common scenario between Microsoft.NET and Oracle AS platforms.

Embed PDFs into a Web Page with a Custom Control by Scott Lysle. Jan 23, 2007.

This article describes an approach to embedding and displaying PDF documents in a web page through the use of a simple ASP.NET 2.0 custom server control.

Snap it! – How to take a screen shot using .NET by Thiagarajan Alagarsamy. Jan 23, 2007.

This article explains how to create a snapshot tool in .NET and Windows Forms.

Embedding and Playing WAV Audio Files in a Win Forms Application by Scott Lysle. Jan 18, 2007.

This article describes an approach to embedding WAV audio files into an application and playing them through the use of the System.Media class library.

The difference between the two GOF patterns “Strategy” and “State” by Matthew Cochran. Jan 18, 2007.

The GOF Strategy and State patterns are remarkably similiar and it is really only a minor implementation detail that distinguishes the two.

The GOF “Chain of Responsibility” Design Pattern by Matthew Cochran. Jan 18, 2007.

The Chain of Responsibility pattern is used to pass responsibility for handling a call to another class. This article gives a basic overview of the pattern.

Simple FTP demo application using C#.Net 2.0 by Mohammed Habeeb. Jan 18, 2007.

An article to demonstrate common FTP functionalities using C#.Net 2.0

Introduction of ASP.NET AJAX Toolkit – CollapsiblePanel by James Wu. Jan 17, 2007.

The ASP.NET AJAX Toolkit is a new and powerful control in ASP.NET 2.0. It is designed for you to develop web applications that are more responsive, faster, and put fewer loads on the network, and in particular took .NET-based Ajax framework. This article will use one of ASP.NET AJAX Toolkit’s controls – CollapsiblePanel to demonstrate the benefit by using it.

Periodic Reminder App for the Windows Taskbar by Mike Gold. Jan 17, 2007.

This article features an application that allows you to set up a periodic reminder in your windows task bar. The application will show a balloon message periodically and optionally will produce a reminder beep.

C# ASP.NET Server Control: Rollover Image Button by Matthew Cochran. Jan 16, 2007.

This article demonstrates how to extend the ImageButton ASP.NET server control to provide rollover functionality.

ASP.NET 2.0 Visio Custom Control by Scott Lysle. Jan 15, 2007.

This article describes a quick and simple approach to creating a custom web control used to display Microsoft Visio files within an ASP.NET page using Internet Explorer.

Angel “Java” Lopez

Free .NET Tutorials and Technical Articles

David Hayden have a post with a list of his published articles:

There are many topics in the list: Agile, ADO.NET 2.0, ASP.NET, Back to Basics, Blog Engines, C# 3.0 Tutorials, Design Patterns, Enterprise Library 2.0 y 3.0, C# Business Objects, patrones GRASP, High Performance ASP.NET Web Sites, Object Oriented Principles, SQL Server, SQL Server Management Objects. Great work!

Go and learn!

Angel “Java” Lopez