Click here to Skip to main content
15,860,943 members
Articles / Web Development / ASP.NET

Code Generation in Visual Studio From XML Files - A Simpler Approach

Rate me:
Please Sign up or sign in to vote.
5.00/5 (13 votes)
21 Feb 2012CPOL6 min read 44.1K   44   6
In this post, we'll explore how to generate code from a simple XML model, with in Visual Studio - For a lot of scenarios

imageCode generation should be simple, and I wanted to do it by using a simple XML file as my model from with in Visual Studio. So, here is a quick wrapper I’ve created for Xml driven code generation for minimalists/minimal scenarios.

Source code

Introducing Super Simple XML driven code generation

Here we go – this is based on my ElasticObject implementation to generate code using Text Templates (TT/T4), by using simple XML files as a model. It is so simple that it won’t support the entire XML schema ;) - But I’ll live with that for now. So, the steps are simple, thanks to Nuget.

Step 1 - Get the ElasticObject Nuget Package

Install AmazedSaint.ElasticObject, run the following command in the Package Manager Console

PM> Install-Package AmazedSaint.ElasticObject

Or you can install this via the Nuget Package manager, it is your choice.

Step 2 – Enjoy

This should add the reference to ElasticObject library, and will add an Xml model file and a T4 template in the Solution Explorer (See the image). The xml file can be your model, and the TT file has a bit of code that wraps the model for generating what ever you need (source code, views, scaffolding etc). You can modify the xml and the TT file. Also, there is a ReadMe-ElasticObject.cs.txt which you can re-name to a CS file and view/run the tests to see the usage of ElasticObject.

What is in the Xml model file and TT generator?

The example model file contains some sample xml, it can be anything (infact, a reasonable subset of xml ;))

XML
<model>
<class name="MyClass1">
  <property name="MyProperty1" type="string"/>
  <property name="MyProperty2" type="string"/>
</class>
  <class name="MyClass2">
    <property name="MyProperty1" type="string"/>
    <property name="MyProperty2" type="string"/>
  </class>
</model>

So, as you can see, the model can be anything, with in a valid root element. The example just mimics few classes and properties in that. Now, let us have a quick look at the example TT file added by the Nuget package. Don't get afraid, it is some simple T4 syntax - Refresh your T4 Skills from here, Oleg has everything for you to start with the T4 syntax (and much more).

Did I tell you you can use Visual T4 Editor Free edition to reduce the pain when you work with T4 Templates? Get it today from the VS Extensions gallery, otherwise you’ll end up sending hate mails to the guys who created the Visual Studio T4 editor.

In the below code, you could see that we are creating an elastic object from the xml, and then iterating the elements for generating the code – In case you are not familiar with ElasticObject, see my post here – It is just a wrapper dynamic object I created for loosely wrapping stuff like xml. Also, you could see this LIDNUG presentation where Shey is demoing the ElasticObject in between his dynamic talk.

Anyway, here is the T4 code you’ll find in the tt file added by our Nuget package.

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ Assembly Name="System.Xml.dll" #>
<#@ Assembly Name="System.Xml.Linq.dll" #>
<#@ Assembly Name="System.Core.dll" #>
<#@ Assembly Name="Microsoft.CSharp.dll" #>
<#@ Assembly name="$(SolutionDir)packages\AmazedSaint.ElasticObject.1.0.0\lib\net40\AmazedSaint.Elastic.dll" #>
<#@ Import Namespace="System.Xml" #>
<#@ Import Namespace="System.Xml.Linq" #>
<#@ Import Namespace="AmazedSaint.Elastic" #>
<#@ Import Namespace="AmazedSaint.Elastic.Lib" #>
<#@ output extension=".cs" #>

<#
var model=FromFile("ElasticDemoModel.xml");

foreach(var c in model["class"])  //get all classes
    WriteClass(c);
#>


<#+ 
//Create an elastic object
private dynamic FromFile(string file)
{
   var path= Host.ResolvePath(file);
   return XDocument.Load(path).Root.ToElastic();
}


//Write a class
private void WriteClass(dynamic c)
{ 
#>
//Class generated 
class <#= c.name #> 
{
<#+
    foreach(var p in c["property"])
       WriteProperty(p);  
#>            
}
<#+
}

//Write a Property
private void WriteProperty(dynamic p)
{
#>
public <#= p.type #> <#= p.name #>  {get;set;}
<#+   
}
#>

And you guessed it, the generated file is here.

C#
//Class generated 
class MyClass1 
{
public string MyProperty1  {get;set;}
public string MyProperty2  {get;set;}            
}
//Class generated 
class MyClass2 
{
public string MyProperty1  {get;set;}
public string MyProperty2  {get;set;}            
}

Note that this requires C# dynamic support, and hence targets the .NET 4.0 runtime – So if you want to have code generation in other platforms with out dynamic support, add a .NET 4.0 project, keep your models and TT/T4s there, and add/link the generated files to other projects. This example just shows C# code generation from the model, but you can imagine what all things you can do ;)

A More Productive Example - CanML

In this example, we’ll explore how to create a simple Xml based markup language for defining shapes for HTML5 Canvas. We’ll achieve this by generating JavaScript code from the Xml definition, and this post is intended to be a pointer towards how you can leverage scaffolding and meta programming to simplify a lot of scenarios. If you don’t have a lot of kids to look after, modify this to create your own version of full fledged CanML (take that name) and let me know

Coming back - We’ll be using my Elastic Object Nuget package and T4 templates for code generation as I explained in my last post [Using AmazedSaint.ElasticObject Nuget Package for code generation], so reading that post will help for sure. I also suggest you to read quickly this Basic Canvas tutorial in MDN

image

What we are going to achieve?

You’ll be able to declare your canvas shapes using XML, for example see how I’m declaring a Heart shape and a Triangle slice. In the heart shape, I’m using absolute co-ordinates, and I’m using variables for triangle slice so that you can draw it anywhere.

XML
<?xml version="1.0" encoding="utf-8" ?>

<shapes>

  <!--Normal Heart Shape, Fixed Coords-->
  <shape name="shapeHeart" type="fill" params="fillColor">
    <fillStyle value="fillColor"/>
    <to params="75,40"/>
    <bcurve params="75,37,70,25,50,25"/>
    <bcurve params="20,25,20,62.5,20,62.5"/>
    <bcurve params="20,80,40,102,75,120"/>
    <bcurve params="110,102,130,80,130,62.5"/>
    <bcurve params="130,62.5,130,25,100,25"/>
    <bcurve params="85,25,75,37,75,40"/>
  </shape>

  <!--Triangle Slice with variables-->
  <shape name="shapeTriangleSlice" type="fill" params="fillColor,firstX,firstY,delta">
    <fillStyle value="fillColor"/>
    <to params="firstX,firstY"/>
    <line params="firstX,firstY+delta"/>
    <line params="firstX+delta,firstY"/>
  </shape>


  <!--Draw both-->
  <shape name="allShapes">
    <shape name="shapeHeart" params="'yellow'"/>
    <shape name="shapeTriangleSlice" params="'red',200,200,100"/>
    <shape name="shapeTriangleSlice" params="'red',200,200,-100"/>
  </shape>
  
</shapes>

And this will be rendered to an HTML5 Canvas as below. This trick is, we are generating the required JavaScript code from the above markup, using the technique I explained above

What about the Generated JavaScript?

If you are interested to see the JavaScript getting generated from the above Markup, see that below. If you examine the generated code closely along with the xml model we’ve above, you can see that we are following a couple of simple conventions to generate the code from the above markup.

  • Each <shape/> definition is wrapped as a method, with a canvas parameter (along with other parameters if param element is present)
  • The type attribute of the Shape
  • We are having some short cut notations (like to –> moveTo and bcurve-> bezierCurveTo)
  • If an element has a param attribute, it’ll be rendered as a method (example is moveTo)
  • If an element has a value attribute, it’ll be rendered as a property (example is
JavaScript
//Method generated 
var shapeHeart = function (canvas, fillColor) 
{
if (canvas.getContext){  
    var ctx = canvas.getContext('2d');  
    ctx.beginPath();
    ctx.fillStyle=fillColor;
    ctx.moveTo(75,40);
    ctx.bezierCurveTo(75,37,70,25,50,25);
    ctx.bezierCurveTo(20,25,20,62.5,20,62.5);
    ctx.bezierCurveTo(20,80,40,102,75,120);
    ctx.bezierCurveTo(110,102,130,80,130,62.5);
    ctx.bezierCurveTo(130,62.5,130,25,100,25);
    ctx.bezierCurveTo(85,25,75,37,75,40);
    ctx.fill();            
}
}
//Method generated 
var shapeTriangleSlice = function (canvas, fillColor,firstX,firstY,delta) 
{
if (canvas.getContext){  
    var ctx = canvas.getContext('2d');  
    ctx.beginPath();
    ctx.fillStyle=fillColor;
    ctx.moveTo(firstX,firstY);
    ctx.lineTo(firstX,firstY+delta);
    ctx.lineTo(firstX+delta,firstY);
    ctx.fill();
            
}
}
//Method generated 
var allShapes = function (canvas) 
{
if (canvas.getContext){  
    var ctx = canvas.getContext('2d');  
    ctx.beginPath();
    shapeHeart(canvas,'yellow');
    shapeTriangleSlice(canvas,'red',200,200,100);
    shapeTriangleSlice(canvas,'red',200,200,-100);            
}
}
Note that all methods are generated with a canvas input parameter. And now, you may call these methods by linking to the generated CanvasShapes.js script file in your html page – See my index.cshtml ASP.NET MVC razor view where I invoke the allShapes method. Just get your actual canvas element, and pass it to draw, as shown below.
HTML
@{
    ViewBag.Title = "Home Page";
}

@section headerSection{
    <script src="@Url.Content("~/CanvasShapes/CanvasShapes.js")" type="text/javascript"></script>
     <style type="text/css">  
      canvas { border: 1px solid black; margin-left:auto; margin-right:auto;}  
    </style>  
}

<canvas id="myCanvas" width=800 height=480></canvas>

<script>
    var canvas = document.getElementById("myCanvas");
    allShapes(canvas);
</script>

Tell me about the Actual Generation of JS from XML?

The actual generation is super simple – In fact this was just intended to be an sample use case for using the Elastic Object Nuget package for code generation.

To try this out manually,

  • Create a new ASP.NET MVC Project in Visual Studio.
  • Install the AmazedSaint.ElasticObject package as explained in my previous post – This will also add an Xml file and a TT (Text template file) to your project
  • Rename the Xml file to CanvasModel.xml – and copy the above XML code to the same
  • Rename the TT file CanvasShapes.tt, and add the below T4 code to the TT File

Here is the simple T4 code we are using for generating the JS Code. Oops, the actual conversion code is not even 25 lines, but this is enough to convey the idea, right? You can beef this up further, by adding some support for gradiants, transitions etc to make this full fledged. Keep the MDN Canvas documentation handy.

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ Assembly Name="System.Xml.dll" #>
<#@ Assembly Name="System.Xml.Linq.dll" #>
<#@ Assembly Name="System.Core.dll" #>
<#@ Assembly Name="Microsoft.CSharp.dll" #>
<#@ Assembly name="$(SolutionDir)packages\AmazedSaint.ElasticObject.1.2.0\lib\net40\AmazedSaint.Elastic.dll" #>
<#@ Import Namespace="System.Xml" #>
<#@ Import Namespace="System.Xml.Linq" #>
<#@ Import Namespace="AmazedSaint.Elastic" #>
<#@ Import Namespace="System.Collections.Generic" #>
<#@ Import Namespace="System.Collections" #>
<#@ Import Namespace="AmazedSaint.Elastic.Lib" #>
<#@ output extension=".js" #>

<#
var model=FromFile("CanvasModel.xml");
foreach(var c in model["shape"])  //get all classes
    WriteShapeMethod(c);

#>

<#+ 
//Create an elastic object
private dynamic FromFile(string file)
{
   var path= Host.ResolvePath(file);
   return XDocument.Load(path).Root.ToElastic();
}

//Write a shape method
private void WriteShapeMethod(dynamic c)
{ 
#>
//Method generated 
var <#= c.name #> = function (<#=c.HasAttribute("params")
                         ?"canvas, " + c.@params :"canvas"  #>) 
{
if (canvas.getContext){  
    var ctx = canvas.getContext('2d');  
    ctx.beginPath();
<#+    
var tokens = new System.Collections.Generic.Dictionary<string, string>()
            {
                {"bcurve","bezierCurveTo"},
                {"qcurve","quadraticCurveTo"},
                {"line","lineTo"},
                {"to","moveTo"},
                {"arcTo","arcTo"}
            };
    foreach (var member in c[null])
    {
        string mname = tokens.ContainsKey(member.InternalName) 
               ? tokens[member.InternalName] : member.InternalName;
        if (member.HasAttribute("params"))
        {
           if (member.InternalName=="shape")
        WriteLine("\t" + member.name + "(canvas," + member.@params + ");");
           else
           WriteLine("\tctx." + mname + "(" + member.@params + ");");
   }
        else if (member.HasAttribute("value"))
            WriteLine("\tctx." + mname + "=" + member.@value + ";");
        else
            WriteLine("\tctx." + mname + "();"); 
    }

    if (c.HasAttribute("type"))
        WriteLine("\tctx." + c.type + "();");
        
#>            
}
}
<#+
}

#>

All right, Happy coding as usual. Enjoy these simple meta coding cookies. See some of my previous posts if you are interested in more 'dynamic'

And you love .NET and C#? Don't miss my blog http://www.amazedsaint.com

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
Architect, Developer, Speaker | Wannabe GUT inventor & Data Scientist | Microsoft MVP in C#

Comments and Discussions

 
GeneralMy vote of 5 Pin
Praveen Nair (NinethSense)30-Mar-12 21:30
Praveen Nair (NinethSense)30-Mar-12 21:30 
Questionvery nice Pin
BillW3312-Mar-12 5:04
professionalBillW3312-Mar-12 5:04 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey29-Feb-12 18:08
professionalManoj Kumar Choubey29-Feb-12 18:08 
Nice
GeneralMy vote of 5 Pin
All Time Programming27-Feb-12 23:19
All Time Programming27-Feb-12 23:19 
QuestionCool Pin
Sacha Barber22-Feb-12 2:23
Sacha Barber22-Feb-12 2:23 
GeneralMy vote of 5 Pin
Mahmud Hasan22-Feb-12 0:23
Mahmud Hasan22-Feb-12 0:23 

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

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