Dave Burke : Freelance .NET Web Developer specializing in Online Communities

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");
    
  else
   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....
}

Comments (2) | Post RSS RSS comment feed

Posted on 6/26/2005 2:05:00 PM by Dave Burke
Categories: .NET | CodeSmith
Tags:

Related posts

Comments (2) -

6/27/2005 10:29:25 AM Permalink

Great post Dave!  I'm glad that you are finding CodeSmith useful.

Eric J. Smith |

6/27/2005 10:30:20 AM Permalink

You 'da Man, Eric!  Thanks for visiting.

daveburke |


Powered by BlogEngine.NET 2.0.0.36
Theme by Dave Burke