Click here to Skip to main content
Click here to Skip to main content

XEML (Entity Markup Language) for Code Generation

, 13 Feb 2009
Rate this:
Please Sign up or sign in to vote.
XEML (Entity Markup Language) for Code Generation

Introduction

Generating complete code from models has been an industry goal for many years. Model-driven architecture approach provides a set of modeling notations, most based on UML, for specifying different layers of a system namely user interface, business logic and database in a platform independent manner. A set of code generators then transforms these models into platform-specific implementations.

The two most popular models for code generation are:

  • UML for program modeling, part of the OMG’s Model Driven Architecture (MDA) 
  • Domain-Specific Languages (DSLs), little languages that are created specifically to model some problem domain.

A UML model normally serves as basis of a MDA based development approach. UML is designed and specified as a general-purpose modeling language for object-oriented software system. UML has several general advantages. It is the most widely known object-oriented modeling notation, it has graphical notations which are readily understood, and a rich set of standards for capturing key features of OO systems.

DSM (Domain-Specific Model) is an alternative approach to modeling and code generation. Domain-Specific modeling raises the level of abstraction beyond programming by specifying the solution directly using domain concepts. The final software product is then generated from these high-level specifications. This is achieved through DSL (Domain-Specific Languages) that follows domain abstraction semantics, allowing developers to focus on the solution rather than the technical implementation of the solution.

United or Domain-Specific modeling languages? There is a war brewing among modeling methodologists. Neither approach is perfect. UMLs are based on the code world and offer only modest possibilities to raise design abstraction and to achieve full code generation. UML focus on visualizing the code and therefore fail to produce a significant improvement in overall productivity when compared to code in C# or Java. With DSM, you need to create more complex DSLs and generators as well as the DSLs need to be constituted evolved. This creates a new kind of complexity and different DSLs and generators make the standardization of software development much difficult if not impossible. Using models in automation depend on high quality DSLs, if free or cheap standard DSLs for key problem domains do not exist, the model automation is not going to happen. Developing all the needed DSLs in the organization is not appealing for companies with limited budgets.

XEML – Entity Markup Language

We propose a general-purpose modeling language named XEML, an Entity Markup Language based on XML for business applications. XML is a meta-language that can be used to develop general purpose modeling languages. It is a reasonable language for representing models and achieves separation of concerns about model and implements business software. XML has been embraced enthusiastically by all the major IT suppliers and user groups. Its standardization and rapid uptake have been the major developments in IT over the past ten years. Industry rivals like IBM, Microsoft, SUN and Oracle all support the core XML standard, are developing major products based on it, and collaborate to develop related standards. XML helps the case for declarative modeling in several ways as stated below:

  • Its standardization and rapid uptake simplify the standards development process. 
  • There is a multitude of software tools and APIs specifically designed for handling XML. 
  • XML is text-based (therefore platform-independent). 
  • XML is extensible allowing more meaningful description of the underlying data.

Since the XEML model is actually XML documentation, the XSLT templates are used to create different code generators. With XSLT you have scripted access to the XML DOM, the XSLT processor parses the XML document to construct the DOM, and XSLT scripts manipulate the DOM input to construct the DOM output. It’s possible to construct plaintext source code files from the DOM output. The plaintext output forms one to many source code files.

Another important advantage of using an XSL style sheet for translating the XEML model into code is that XSL is a declarative language. XSL is declarative (as compared to procedural) in the sense that it describes results of the translation rather than the steps to perform it. This pervades in a higher -level of abstraction. These facts make the source code generation task extremely easy since the tasks of parsing, validating, and generating code can all be performed with freely available tools in the manner of rapid scripting-based development.

Like any other Markup languages, XML tags and attributes are used to define XEML models. In XEML, models are called entities, the components of an entity are called attributes, the references to other models are called relationships, and the keys (both primary and foreign keys) are defined for database system. This section provides an overview of the most commonly used XEML tags.

Schema Tag

A SCHEMA is the outer most container of an XEML file. A schema is the model generally created for a business application. It defines the general and global information for the models.

 <schema name="Order System" owner="Sales">

Entity Tag

An ENTITY is an object in the business applications that encapsulates specified data. For example, an entity model can be used to depict a company’s customer base. A customer entity has attributes-such as the name, the contact and the address and relationships to other entities-such as the order. In theory, if the parts of system can be identified, the system can be expressed as an entity model. Essentially, entities defined in XML become classes in the object-oriented application system or tables in the database.

 <entity name="Customers" tableschema="dbo">

Attribute Tag

An ATTRIBUTE represents structures that contain data. The ATTRIBUTE tags define the database entity fields or application object properties. An attribute of an entity may be a simple value, such as a scalar (for example, a string, an integer or decimal), but can also be a BLOB (for example, binary), or date and time (such as date, or timestamp).

 <attribute name="CompanyName" type="string" />

Key Tag

A PRIMARY KEY is used to uniquely identify each record within a database table. It consists of one or more entity attributes.

 <pkey name="PK_Customers">
   <key name="CustomerID" />
 </pkey>

A FOREIGN KEY is a reference to a PRIMARY KEY in another database table. The foreign key consists of one or more entity attributes that are reference to fields in other tables.

 <fkey name="FK_Orders_Customers">
     <key name="CustomerID" parent="Customer" />
 </fkey>

Relationship Tag

In object-oriented applications, not all properties of a model are attributes, your applications are typically modeled by multiple classes. At runtime, your object model is a collection of related objects that make up an object graph. The relationships between these model objects can be traversed at runtime to access the properties of the related objects.

 <relationship source="Customer" target="Order" type="1..*" />

One specification and multiple source files are then generated. Some examples of artifacts that can be generated from these XEML entity models are:

  • UI Components 
  • Domain Object in C#, Java, PHP or whatever you prefer 
  • Database DDL and procedures
  • Schema Reports in Word or HTML format
  • Entity-Relationship and UML class diagrams

How it Works

The central processing step of code generation logic is tree walking. Any XML document is structured like a tree with the nodes having a name, a text value, named attributes, and child sub-nodes. Even we can generate the XEML models from database using the tool we built (LatticeFramework Studio); here we just create the XEML model manually to describe the customer entity:

 <entity name="Customer">
   <attributes>
      <attribute name="CustomerID" type="string" length="5" />
      <attribute name="CompanyName" type="string" length="40" />
      <attribute name="ContactName" type="string" length="30" />
      <attribute name="ContactTitle" type="string" length="30" />
      <attribute name="Address" type="string" length="60" />
      <attribute name="City" type="string" length="15" />
      <attribute name="Region" type="string" length="15" />
      <attribute name="PostalCode" type="string" length="10" />
      <attribute name="Country" type="string" length="15" />
      <attribute name="Phone" type="string" length="24" />
      <attribute name="Fax" type="string" length="24" />
   </attributes>
   <keys>
      <pkey name="PK_Customers">
         <key name="CustomerID"/>
      </pkey>
   </keys>
 </entity>

An XSLT style sheet consists of a set of rules that determine how specific elements from the XML document should be processed. Each rule has matching criteria that specifies the pattern of elements for which the rule is activated. Each rule also has an associated transformation that acts on the matching elements. Rules are composed hierarchically because each rule can trigger other rules by using the tag that indicates the hot spots where other rules can bind and become active.

The following XSL tags are most frequently used:

  • <xsl:value-of>: Used to select the value of an element from the XML document
  • <xsl:if>: The XSL analog of if-then-else and switch control structures
  • <xsl:for-each>: Iterates through a collection of XML elements
  • <xsl:text>: Used to specify custom text
  • <xsl:include>: Simply includes the contents of one style sheet into another

An XSL processor is required to apply an XSL style sheet to an XML document. The XSL processor reads both the XML document and the XSL stylesheet, and then applies a set of transformation rules from the stylesheet to the XML document in order to produce the desired output.

To generate the stored procedures and business objects from XEML models is straightforward. Below, I will show you how to generate the database schema report in Microsoft Word format and entity-relationship diagram in PDF format from XEML models.

Generate Database Schema Report in Word format

XML support in Word 2003 is new exciting feature. Word 2003 now supports native XML vocabulary called Word Markup Language (WordML). The simplest WordprocessingML document consists of just five elements (and a single namespace). The five elements are:

  • WordDocument element: The root element for a WordprocessingML document
  • body element: The container for the displayable text
  • p element: A paragraph
  • r element: A contiguous set of WordprocessingML components with a consistent set of properties
  • t element: A piece of text

The namespace for the root WordprocessingML Schema (also known as the XML Document 2003 Schema) is "http://schemas.microsoft.com/office/word/2003/wordml". This namespace is normally associated with the WordprocessingML elements by using a prefix of "w." The simplest possible WordprocessingML document looks as follows:

<?xml version="1.0"?>
<w:wordDocument xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml">
    <w:body>
        <w:p>
            <w:r>
                <w:t>Hello, World.
            </w:r>
        </w:p>
    </w:body>
</w:wordDocument>

We can write an XSLT stylesheet to translate XEML models into WordML. The following shows how to generate a list of tables from XEML models.

<xsl:for-each select="entities/entity">
 <w:p>
  <w:r>
   <w:rPr>
    <w:b w:val="on"/>
    <w:color w:val="6495ed" />
   </w:rPr>
   <w:t>
    <xsl:value-of select="@name"/>
   </w:t>
  </w:r>
 </w:p>
</xsl:for-each>

Generate Entity-Relationship Diagram in PDF Format

Graphviz is a package of open source tools initiated by AT&T Research Labs for drawing graphs specified in DOT language scripts. Graphviz consists of a graph description language named the DOT language and a set of tools that can generate and/or process DOT files. DOT is a plain text graph description language. It is a simple way of describing graphs that both humans and computer programs can use.

It is very easy to write an XSLT stylesheet to translate the XEML models into DOT file and use GraphViz tools to generate ER diagrams in PDF format.

digraph G {
        fontsize = 6;
	fontname = "Tahoma";
	node [shape = "record", style = "filled"];
	edge [arrowhead = "none" fontsize = 6];
	
	"Customer" [
		fillcolor = "lightblue"; 
		label = <
			<table>			
			<tr><td>Customer</td></tr>
			<tr>
				<td align="left"> + CustomerID</td>
				<td align="left"> : integer</td>
			</tr><tr>
				<td align="left"> + Name</td>
				<td align="left"> : string</td>
			</tr><tr>
				<td align="left"> + Address</td>
				<td align="left"> : string</td>
			</tr><tr>
				<td align="left"> + Phone</td>
				<td align="left"> : string</td>
			</tr>
			</table>
		>

Generate ASP.NET MVC + Entity Framework Application

Based on XEML model, ASP.NET MVC views and controllers as well as SQL DDL script to create tables can be generated.

Generated view

<%@ Page Title="" Language="C#" 
	MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" 
	CodeBehind="Customer.aspx.cs" Inherits="Test.Views.Customer.Customer" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<!--
//
// Entity: Customer
// Author: Julie
// Date: Thursday, February 12, 2009
// Time: 9:48:17 AM
//
// Web: http://www.latticesoft.com
// Email: studio@latticesoft.com
//
// The code was generated by LatticeFramework Studio
// Copyright © 2008 Lattice Business Software.
// All Rights Reserved.
//
-->
<h2><%= Html.Encode(ViewData["Message"]) %></h2>
<p>
The code was generated by LatticeFramework Studio.
</p>
<p>
    To learn more about LatticeFramework Studio visit 
	<a href="http://www.latticesoft.com" title="LatticeFramework Studio Website">
	http://www.latticesoft.com</a>.
</p>
<h2>Customer List</h2>
<table>
	<tr>
		<th>Customer ID</th>
		<th>Name</th>
		
	</tr>
    <%foreach (var c in ViewData.Model ){ %>
    <tr>
        <td><%= c.CustomerID %></td>
		<td><%= c.Name %></td>
		
	</tr>
    <% } %>
</table>
</asp:Content>

Generated Controller

#region CustomerController.cs -- Copyright © 2009 Lattice Business Software
//-----------------------------------------------------------------------------------
//
// Class: CustomerController.cs
// Author: Julie
// Date: Friday, February 13, 2009
// Time: 9:47:57 AM
//
// Web: http://www.latticesoft.com
// Email: studio@latticesoft.com
//
// The code was generated by LatticeFramework Studio
// Copyright © 2008 Lattice Business Software.
// All Rights Reserved.
//
//------------------------------------------------------------------------------------
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Test.Models;

namespace Test.Controllers 
{
    public class CustomerController : Controller
    {
    	TestEntities db = new TestEntities();
    	public ActionResult Index()
	{
	   ViewData["Title"] = "Customer Page";
           ViewData["Message"] = "Welcome to LatticeFramework Studio!";

            return View();
	}
		
	public ActionResult Customer()
        {
            List<test.models.customer /> list = db.Customer.ToList();
            return View(list);
        }
   }
}

Generated DDL to Create Sample Table

CREATE TABLE [dbo].[Customer] (	
	[CustomerID] [int] NOT NULL,
	[Name] [varchar](100) NOT NULL
) ON [PRIMARY]


ALTER TABLE [dbo].[Customer] WITH NOCHECK ADD 
	CONSTRAINT [PK_Customer] PRIMARY KEY  CLUSTERED 
	(
		[CustomerID]
	)  ON [PRIMARY]

Points of Interest

The heart of model-driven architecture is model. Model raises the level of abstraction beyond programming by specifying the solution directly using domain concepts. The two most popular models for code generation are UML and Domain-Specific Model (DSM). UML or DSM? There is a war brewing among modeling methodologists. Neither approach is perfect. Can we take the best of both sides? We advocate combining both approaches. In this article, we introduce XEML (Entity Markup Language) for automating software development in the domain-specific world using general-purpose modeling language.

History

  • August 25th, 2008
    • Initial release
  • January 12th, 2009
    • Updated generating ASP.NET MVC + Entity Framework application
    • Uploaded the complete VS 2008 project

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

Share

About the Author

latticesoft
Software Developer (Senior) Lattice Business Software
United States United States
I am developer of LatticeFramework Studio, fully implemented in C#, a model-driven rapid application development tool.

Comments and Discussions

 
GeneralXML for modeling is the way to go PinmemberSerghei Sarafudinov4-Oct-08 17:20 
GeneralRe: XML for modeling is the way to go Pinmemberlaverrod15-Dec-08 3:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 13 Feb 2009
Article Copyright 2008 by latticesoft
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid