views:

201

answers:

2

I've got to develop a multi-language code generator in C#. Well actually the idea is, we have several in house application frameworks for database access in various languages (Java, Python, C++). But their basic working principle is same. And we feel that a code generator will help us to reduce our development time. So I have decided to write a code generator for the ease of our development.

What are the standard basic technical steps I should follow to generate classes from database tables?

Should I use \t,\r,\n?

What are the techniques to achieve fastest speed?

I don't want to use RegEx.

Please let me know from your personal experience.

+4  A: 

It really depends on what you mean; there are lots of options:

  • CodeDOM - provides an object model that can generate code for multiple languages, but can be tricky to use
  • T4 (aka TT) - the "in fashion" codegen of the moment
  • xslt - a useful fallback; not as fashionable as T4, but workable - tricky for whitespace-dependent languages like VB

In all cases, I would build a basic object-model that represents the data and work from there. I have known somebody write code-gen from a database just with SELECT, but it was ugly as sin, and painful in the extreme to maintain.

Re your questions about \t, \r, \n etc - I don't understand the question, but: whatever the target language wants! VB is the tricky one here (C# etc are easier as they don't care much about whitespace).

I've used xslt successfully, but largely because I already knew xslt, and needed to support 2.0 (T4 isn't in 2.0); otherwise T4 would have been my next stab, simply because I want to learn it ;-p

Marc Gravell
T4 is nice, I am using a heavy modified linq2SQL template (from codeplex) to tweak it exactly to my needs :)
leppie
+1  A: 

It seems that you need templating capability, so T4 as Marc Gravell suggested is quite good. SubSonic currently uses T4 to generate code. In the past, SubSonic used Asp.Net as a template system to generate code.

This may seem a bit out of left field, but John Resig has mirco-template function he wrote for Javascript that allows you to process templates that have a syntax like:

<script type="text/html" id="item_tmpl">
  <div id="<%=id%>" class="<%=(i % 2 == 1 ? " even" : "")%>">
    <div class="grid_1 alpha right">
      <img class="righted" src="<%=profile_image_url%>"/>
    </div>
    <div class="grid_6 omega contents">
      <p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p>
    </div>
  </div>
</script>

You feed the template a JSON object as a data source. The nice thing with this approach is that you can quickly create a template system without having to compile and deploy - simply fire up a browser and generate your code.

David Robbins