Angel \”Java\” Lopez on Blog

January 29, 2007

Code Generation with AjGenesis: A Hello World application

Filed under: .NET, AjGenesis, Code Generation, Java, Software Development — ajlopez @ 10:02 pm

My favourite project is AjGenesis, and I’m improving its examples every month. AjGenesis is a code generation engine, written in VB.NET. It’s an open source project, with a BSD-like license. The license allows you to use in any of your projects, commercial or not. It can be used as a library, invoked from your own application, or it can be run from the command line. It can be launched with NAnt tasks, so you can write powerful scripts to generate, compile, and deploy solutions in different technologies (not only .NET).

At the project page http://www.ajlopez.com/ajgenesis (and in the project .zip itself), there are lot of examples, that generates text artifacts and source code, starting from a free-form model. The generation process uses templates, written in an interpreted language, affectously named AjBasic. The examples generate PHP, Java, JSP, VB.NET, C#, ASP.NET code, and database scripts, with stored procedures and more. You can modify or create your own templates, at any moment. I want to stress two points:

- The model is form-free: you can define in any way you want

- The tasks and templates to run and apply are totally programmable and under your full control

This makes a difference with other code generation tools. You can define your own model, your own templates, to generate the text artifacts of your preference. Other tools start from the database schema, only to produce few code, as entities and DAOs. But with AjGenesis, sky (a textual sky) is the limit! :-).

Lets take an example. This post is dedicated to model an application, as a proof on concept for the power of this tool. The target is to produce the most citated application: a Hello World app (my first encounter with such app was with the mytical book “The C Programming Language”, by Kernighan and Ritchie).

The example can be download from HelloWorld1.zip

First, the model. The model is a simplification of reality. A model, for example, a map, is not the territory, the reality. For AjGenesis, we need to write a model that manages the variable part of our system. In this case, a Hello World-like application, we want to model the message as variable. Then, create in a working directory, the file Project.xml:

<Project>
<Message>Hello World, by AjGenesis</Message>
</Project>

This is the first step, in a long journey. We didn’t use a predefined model. It’s simpler: we just write the model, in a well-formed XML file. No schemas, no DTDs, or weird things. Only our idea.

Second step: choose the target technology (programming language, platform, frameworks to use, databases….), to use in our example. Then, write (or reuse) templates. Now, we’ll use a VB.NET example, a simple console app. The template to write resides in the file HelloVb.tpl


‘ Hello World demo
‘ generated by AjGenesis
http://www.ajlopez.com/ajgenesis

Module HelloWorld
 Public Sub Main()
  System.Console.WriteLine(“${Project.Message}”)
 End Sub
End Module

Here, a feature from the templates: in the code, you can access and use in the output, the model data. If you write Project.Message between ${ and }, the AjGenesis processor will replace that text by the value of that branch of the model. You don’t use the XML syntax or something like XPath to access the model. The initial model was serialized in an XML file, but during processing, it’s brought to memory, as an object model, accesible via the familiar property syntax.

We would write the model as

<Project Message=”Hello World, by AjGenesis”/>

The memory model would be the same. Altough now Message is an attribute, for our template it’s still a Message property in the Project object.

Well, now we have the model, and the template. We must download and expand AjGenesis-0.4.3.zip (version currently under development, other versions are under the source code directory at the SourceForge project). In this version, there is a bin directory containing libraries and executables. The program AjGenesis.Console.exe can be invoked to load the model and to read the template, then, it generates a source code file. We enter at command line and run:

AjGenesis.Console Project.xml HelloWorldVb.tpl HelloWorld.vb

The paramaters can be:

An .xml file: when AjGenesis process a parameter that refers to an XML file, the represented model is loaded in its variable environment. The name of the root node is used as the name of the variable that contains the model. In our example, the variable is Project.

A .tpl file: it’s used as a template, is processed, generating a file with name equals to the next parameter.

The bin directory of AjGenesis distribution must be included in the path environment variable of your system.

The parameters are processed in order. We could have more than a model, using two or more XML files as input. For example, a second XML file could be used to describe the database technology to use, or the enterprise name and information to put in the generated source code, or anything else you want to model. In this case, the second XML file should have a different root node (not a Project one), so it will be loaded in a different global variable. We could put many template files with its corresponding generate files, in the same invocation, to generate more than one text artifact in one run.

After running the above command (we need a .NET framework installed in our system, remember that AjGenesis is written in VB.NET)), the file HelloWorld.vb is generated, with content:


‘ Hello World demo
‘ generated by AjGenesis
http://www.ajlopez.com/ajgenesis

Module HelloWorld
 Public Sub Main()
  System.Console.WriteLine(“Hello World, by AjGenesis”)
 End Sub
End Module

Well, it’s not a “Wow, what an application!!”, :-), but it’s a first success.

Move forward. Now, with the same model, we want to generate our big system in Java. The market pressures, our customer needs, all point to use Java for the next version of our killer application. AjGenesis is here to help us! Lets go, create a file HelloWorldJava.tpl with

/**
* Hello World demo
* generated by AjGenesis
*
http://www.ajlopez.com/ajgenesis
*/

public class HelloWorld {
 public static void main(String [] args) {
  System.out.println(“${Project.Message}”);
 }
}

and run at the command line

AjGenesis.Console Project.xml HelloWorldJava.tpl elloWorld.java

Voilá! The file HelloWorld.java is generated:

/**
* Hello World demo
* generated by AjGenesis
*
http://www.ajlopez.com/ajgenesis
*/

public class HelloWorld {
 public static void main(String [] args) {
  System.out.println(“Hello World, by AjGenesis”);
 }
}

We’re in the road. Go for a more flexible example: we want to create the VB.NET program, and the Java file. We make the class and file name a variable (in the preceding templates, the name was fixed to HelloWorld).

The files for this second example can be download from HelloWorld2.zip.

To do that, in other working directory, create a file Project.xml with content:

<Project>
 <Name>HelloWorld</Name>
 <Description>Hello World Demostration</Description>
 <Message>Hello World, by AjGenesis</Message>
</Project>

Then, write the templates ModuleVb.tpl


‘ ${Project.Description}
‘ generated by AjGenesis
http://www.ajlopez.com/ajgenesis

Module ${Project.Name}
 Public Sub Main()
  System.Console.WriteLine(“${Project.Message}”)
 End Sub
End Module

and ClassJava.tpl

/**
* ${Project.Description}
* generated by AjGenesis
*
http://www.ajlopez.com/ajgenesis
*/

public class ${Project.Name} {
 public static void main(String [] args) {
  System.out.println(“${Project.Message}”);
 }
}

We’ll use another feature of AjGenesis: the capability to execute an script, in an interpreted language informally named AjBasic. I think that this a powerful feature, that open a new horizon, beyond the command line. With that feature, we can programmaticaly manipulate the model, and the tasks to execute. In the available examples, this capability is used at any point, producing complete solutions, with dozens of auto generated files. But, back to our example

The program is written in the file Build.ajg

PrintLine “Generating ${Project.Name}”

TransformerManager.Transform(“ModuleVb.tpl”, “${Project.Name}.vb”, Environment)
TransformerManager.Transform(“ClassJava.tpl”,”${Project.Name}.java”, Environment)

The AjBasic language has some predefined verbs, like the autodescriptive PrintLine. You must take note that, as in other scripting language, this one has expression expasion inside the strings. That is, when a text is between double quotes (a string constant), an expression inside ${ and } is located, and replaced by the corresponding value in the model. You can recognize her a behaviour similar to others languages, like Unix scripting languages, PHP, or JSP Expression Language.

The variable TransformerManager is one of a few predefined ones. I didn’t define a lot, and you can add new variables, if needed. The TransformerManager object is used to programmaticaly invoke what we used to run from the command line. Then, the first parameter of its Transform method is the template file name, the second is the file name to generate, and the third and last is the variable collection, known as the AjGenesis environment (Environment is a predefined variable that points to the current environment).

We run the above file with the command line

AjGenesis.Console Project.xml Build.ajg

The console program is prepared to execute each parameter that refers to an .ajg file, as an AjBasic program.

Lets go forward. During 2005 (AjGenesis project has years in development), I added NAnt support. That is, I wrote AjGenesis tasks that can be invoked from that great tool. Additionally, I use the NAnt-GUI utility to execute the .build files from a graphic interface.

Write a default.build file with the content (update the ajgenesis.dir property to point to your AjGenesis installation directory):

<?xml version=”1.0″?>
<project name=”Example 1″ default=”build”>
<property name=”ajgenesis.dir” value=”c:/ajlopez/dev/AjGenesis-0.4.3″/>
<property name=”nanttasks.dir” value=”${ajgenesis.dir}/bin”/>

<target name=”clean” description=”cleans build directory”>
   <delete dir=”${build.dir}” verbose=”true” if=”${directory::exists(build.dir)}” />
</target>
<target name=”loadtasks” description=”loads AjGenesis tasks”>
   <loadtasks assembly=”${nanttasks.dir}/AjGenesis.NAnt.dll” />
</target>

<target name=”init” depends=”loadtasks” description=”init the AjGenesis model”>
   <loadmodel model=”Project.xml”/>
</target>

<target name=”build” depends=”init”>
   <executetask task=”Build.ajg”/>
</target>
</project>

Then, invoke from the command line:

nant

If we configured the NAnt tool, this utility process the default target from the build.xml file. You can use the NAnt-GUI utility, that shows a window like this:

I hope this article helps you to a quick start up in AjGenesis development. In a future post, I’ll explain more examples, model manipulation in memory, intensive use of NAnt, and complete solution generation, in different platforms and technologies.

If you find this utility useful, you can collaborate spreading the word, writting some comment or post about your AjGenesis experience.

Suggestions, and ideas, welcome!

Thanks for all!

Angel “Java” Lopez
http://www.ajlopez.com/en
http://www.ajlopez.com/ajgenesis

12 Comments »

  1. [...] Code Generation with AjGenesis: A Hello World Application [...]

    Pingback by Preserving Code in AjGenesis « Angel “Java” Lopez on Blog — November 13, 2007 @ 10:07 am

  2. [...] Code Generation with AjGenesis- A HelloApplication Generation using AjGenesisCode Generation as a Service with AjGenesisMore post about AjGenesis… [...]

    Pingback by Code Generation for NHibernate using AjGenesis « Angel “Java” Lopez on Blog — August 12, 2008 @ 8:24 am

  3. [...] simplest example I can imagine is a model for a Hello World application in AjGenesis. The model in XML is [...]

    Pingback by Textual model for code generation in AjGenesis « Angel “Java” Lopez on Blog — September 28, 2008 @ 4:42 pm

  4. [...] Code Generation with AjGenesis- A Hello World application [...]

    Pingback by Code Generation for Mere Mortals Framework « Angel “Java” Lopez on Blog — June 21, 2009 @ 2:38 pm

  5. [...] Code Generation with AjGenesis- A Hello World application Generando Código- Hello World con AjGenesis [...]

    Pingback by Generación de código con AjGenesis para Mere Mortals Framework - Angel "Java" Lopez — June 22, 2009 @ 10:39 am

  6. [...] More info about this particular example in my post A Hello World Application in AjGenesis. [...]

    Pingback by Models for Code Generation in AjGenesis « Angel “Java” Lopez on Blog — February 27, 2010 @ 12:45 pm

  7. [...] información sobre este ejemplo sencillo en A Hello World Application in AjGenesis. (Generando Código: Hello World con [...]

    Pingback by Modelos para Generación de Código en AjGenesis - Angel "Java" Lopez — March 12, 2010 @ 10:01 am

  8. Thanks a lot for sharing this with all folks you actually realize what you are speaking about!
    Bookmarked. Kindly additionally talk over with my web site =).
    We may have a hyperlink exchange agreement between us

    Comment by cheap airsoft pistols with silencers — August 26, 2013 @ 4:41 am

  9. I’m impressed, I must say. Rarely do I encounter a blog that’s both educative and interesting, and without a doubt,
    you have hit the nail on the head. The problem
    is something which not enough people are speaking intelligently about.
    I am very happy that I stumbled across this during my hunt for something
    regarding this.

    Comment by airsoft pistols craigslist — August 27, 2013 @ 11:12 am

  10. Thank you for any other informative blog. Where else may I am getting that type of
    info written in such a perfect method? I’ve a venture that I am simply
    now working on, and I’ve been at the glance out for such info.

    Comment by site — September 13, 2013 @ 11:03 pm

  11. Apple’s i – Phone 5 S is more advanced than its predecessor.
    Pegatron have also started recruiting more manpower for their
    plants in China too, apparently already receiving some of the components that
    will produce the much anticipated arrival. But with the purpose of, intended for me is the no more than chief flaw I observe.

    Comment by Eleanore — October 3, 2013 @ 9:04 pm

  12. I visited several web pages except the audio feature for audio songs current at this web page
    is in fact wonderful.

    Comment by comments powered by Facebook. — October 11, 2013 @ 12:50 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Shocking Blue Green Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 66 other followers

%d bloggers like this: