CodeSmith Template Datatable content example

I’ve used CodeSmith to build business objects and collections, mostly.  There’s so much more it can do.  In my Smart Client Synchronization logic I am using an EventLog Table and EventTypes with TimeStamps to determine what needs updated.  (I’ll blog on that later.)  I needed an Enum and know it would be changing throughout the development process as the app would gain or lose certain EventTypes.  CodeSmith Time.

But I needed to access the data in a SQL table, not just that table’s columns and extended properties.  Thanks to the wonderful CodeSmith Template Share Forum contributors I found a great example to do just that.  Reading the content of a table (or delimited text file, or whatever) opens up a lot of capabilities in Code Generation.  (Yeah, I know.  Sorry I’m such a lightweight Code Genner.  I promise to get better.) 

The heart of the CodeSmith template to access the datatable values is the following.

public string CreateEnumMembers(TableSchema table, string memberNameField, string memberValueField)
 StringBuilder sb = new StringBuilder();
 System.Data.DataTable dt = table.GetTableData();
 for (int p = 0 ; p < dt.Rows.Count; p++)
  if (p < dt.Rows.Count – 1)
   sb.Append(dt.Rows[p][memberNameField].ToString().Replace(” “,””) + “=” + dt.Rows[p][memberValueField].ToString() + “,\r\n\t\t”);
   sb.Append(dt.Rows[p][memberNameField].ToString().Replace(” “,””) + “=” + dt.Rows[p][memberValueField].ToString() + Environment.NewLine);
 return sb.ToString();

Which produces something like the following.

public enum EventType
 UserNew = 1,
 UserUpdate = 2,
 LocationNew = 3,
 LocationUpdate = 4,
 // etc….

Article written by

A long time developer, I was an early adopter of Linux in the mid-90's for a few years until I entered corporate environments and worked with Microsoft technologies like ASP, then .NET. In 2008 I released Sueetie, an Online Community Platform built in .NET. In late 2012 I returned to my Linux roots and locked in on Java development. Much of my work is available on GitHub.