Generate your way to the solution via CodeSmith.

Why do we(my bad, I) need code generator ?
I really don’t want to get into this philosophical argument, whether code generation is good or not, but just think of your Code Generator as a silent programmer which REALLY loves to do your dirty repetitive work. Please read the following with an open mind to the subject, you’ve got nothing to lose.

 

Background

Way back, When I was still serving my country, I was “introduced” to the world of Code Generation. The concept was well familiar to me, but I didn’t saw a tangible implementation until my team leader at the time, Pavel Bitz, showed us his(great) implementation which later on became the first code generator (aka “CG”) I ever used. This CG was written in PL/SQL and ran, obviously, on our Oracle (9i) database. I wasn’t so happy about the extendability of this code, but we were in a tremendous stress to develop & deploy our projects so there was no time to develop something “cleaner”(in my opinion anyway). After few weeks, at my final days in the army, I was starting to build my own code generator just to understand more of the .NET framework power – i.e usage of templates, custom config files, Database reverse-engineering, reflection, practicing my OOD\OOP etc. After all, nothing teaches you better to “exploit” the framework than writing an application which will test its capabilities. After 2 weeks I had a nice CG which ran quite well and did everything the PL/SQL CG did and then some.
My time at the army was done and I was back in the free market.

2 days after I was employed for SQLink company, I talked with Amir Engel about the idea of code generation. He told me that he managed to write some templates with CodeSmith and he showed them to me. It looked great but I was hoping to use my CG for that purpose, still, I wanted to protect my “baby”. But this desire was gone when I read about CodeSmith’s SchemaExplorer. My god, I was shocked about how easy it is to write a template which will connect to my database with zero (0 !) effort. In addition, it has its own Studio which allows me to write,test and debug my templates with ease.

BUT the biggest advantage was that there were many open source templates out there – just for me to use !

 

Code Generation – safety first

Before you start to generate code, you must think about how to integrate the code generation usage in your every day work without the need to overwrite your “custom” writing. I’ll give you an example – Let’s say that we generate the Data Access Object for Users table in our database. This object does the CRUD (Create\Insert, Read, Update, Delete) operations for that table. Now I need to add a “specific” method named “GetUsersFromCity” which will return all the users from a given city id. So I’ll add the method to my UsersDAL class and I’m an happy programmer no ?   (think here…)  NO!

Why not ? because the next time I’ll want to generate this class again, because one of the fields in the table was changed or a new field was added to the table (whatever), I don’t want to overwrite the class and lose my custom changes !

The “Base” principle:
This is where the “Base” principle kicks in and help us to protect our custom changes. My correct “DAL” object class structure will be:


// File: UsersDALBase.cs
public class UsersDALBase
{
    // our “generated” code here – all the CRUD operations for example.
}

// in another file!
// File: UsersDAL.cs
public class UsersDAL : UsersDALBase
{
    // My custom behivors here.
}


Every time I’ll regenerate the code, I’ll overwrite the “Base” file and no harm done – my custom changes are safe !
In my “upper” layers, I always use UsersDAL(or [table]DAL for that manner) and not UsersDALBase.


Now that we’ve got the background, it’s time to introduce to you my amigo –


CodeSmith – harness its power for your own need


I’m not going to write here about how to use CodeSmith, there is too much information about this issue all over the web – just google a little and I’m sure you’ll do just fine. What I’m going to talked about is what’s the greatness of CodeSmith and my tips about easy development and debugging while using this tool.

 


  • SchemaExplorer – Stop doing all the reverse engineering for Oracle\SqlServer (via “system tables”), it’s already written for you. The only thing you need is to specify is the connection string and… thats it ! You want to see how easy it is? OK OK, relax:

      <%@ CodeTemplate Language=“C#” TargetLanguage=“C#”
        Src=“../OeCodeTemplate.cs” Inherits=“OrenEllenbogen.Templates.OeCodeTemplate”
        Debug=“False” Description=“Generate an entity class for a given table.” %>

      <%@ Property Name=“SourceTable” Type=“SchemaExplorer.TableSchema” 
         Category=“Connection” Description=“Table Object should be based on.” %>

      <%@ Assembly Name=“SchemaExplorer” %>
      <%@ Import Namespace=“SchemaExplorer” %>


      <%
      // Collection of all columns in the table.
      ColumnSchemaCollection Columns = new ColumnSchemaCollection(SourceTable.Columns); 
      %>


      <% 
      // Variables by table columns.
      for (int i=0; i < Columns.Count; i++) { %>
      /// <summary>
      /// <%=Columns[i].Name%><%=(Columns[i].Description.Length>0) ? ” : ” + Columns[i].Description : “”%>
      /// </summary>
      protected <%= GetCSType(Columns[i]) %> <%=VariableStyle(Columns[i].Name)%> = <%= GetCSDefaultByType(Columns[i]) %>;
      <% 
      } //end for 
      %>


         Some Explaining:



    • you can use “code behind” file (*.cs) which holds the common methods for all your templates files (mine is OeCodeTemplate.cs)
    • I use the methods GetCSType, VariableStyle and GetCSDefaultByType methods which are in my “code behind” file, but this are simple methods which you can copy\write by yourself.

         As you can see, it’s so easy to start dealing with the template itself instead of trying to remember 
         how to get all the indexes\columns\primary keys\(etc)  from a given table.


  • Templates GUI – You’ve seen that I’m using SourceTable property on the previous section, the great thing about it is when I’ll open this template with CodeSmith explorer I’ll be able to pick the table directly from my DataSource. So easy and comfortable.

   CodeSmithExplorer.JPG   

 

 


  • Huge community – you can find a lot of examples in CodeSmith forums. Don’t try to write something which was already written before you; You can always find a template and get some of its code for your specific need.
  • Its easy – believe me, my 4 years old cousin can write a template with CodeSmith, its that easy !
  • Its(was) free ! – version 2.6 is free for use, but the new one (3.0) costs (nothing you can’t afford though).

Developing with CodeSmith


  • Using Lut’z reflector with CodeSmith 2.6 – The main problem with this version (and former) is the lack of IntelliSense. This is a problem due to the simple fact that you can’t remember every method\member  in SchemaExplorer object for example which makes it harder for you to develop. The simple solution is to use the reflector over the SchemaExplorer.dll, which “sits” in CodeSmith directory, and explore your way to the required member\method.
  • Debugging – Debugging with CodeSmith 2.6 (and former)  isn’t so comfortable, but it doable – that’s enough for me. In order to do it, all you need to do is to put Debug=”True” in the page header directive and call Debugger.Break(); before the lines you want to debug.

NOTE: in the new version (3.0), Eric .J. Smith, the creator of this great tool, spoiled us with brand new features like built-in IntelliSense and easier debugging options and much more.



Summarize:
Code generation, in my humble opinion, is MONEY SAVER, simple as that, you can cut down the development time by half !

I’ve built full-spectrum templates for my N-Tier applications – Entities (object which represent table), Data Access objects, Business Object, Web forms, Utilities layer, Cache layer and stored procedures script generator. I’m now able to build 50%-60% of the project “foundation” before I need to write my first code line ! In addition,  I’m using my CodeSmith templates for my every day work – I did some helper templates like generating new “SqlParameter” with the parameter type\size\scale according to the column type, This is great for adding a new SqlParameter to SqlCommand with “full information” about the parameter in single click.
And finally, I’m not afraid to change the database because I know what I need to change and now – it’s even EASY to do.

 

 

Oren Ellenbogen