Sweet . . . Nourishing . . . CodeSmith
I usually avoid the "yah, what they said . . ." blog entries since there are plenty of those around, but I'm making an exception in this case. Mark "Bonafiglio" Bonafe was very impressed with CodeSmith, and I have to agree with him.
I had heard good things about CodeSmith, and after I read Mark's blog on the topic a few weeks ago I figured I should add "Checking Out CodeSmith" to my todo list. When it came time to add some more entity objects to an application I'm working on, I decided to fire CodeSmith up and give it a whirl. The architecture my project uses frequently maps business objects directly to database objects, so there's lots of repetitive coding involved with the creation of properties; object creation and persistance is handled by my home grown DataAgent object that uses Reflection and custom Attributes to handle SQL SELECT, INSERT, and UPDATE statements. The plumbing to work with this DataAgent is simple, but involves placing parameterized attributes on each class and property like so:
namespace EntityObjects
{
[DBTableAttribute( "tblTask" )]
public class TaskData
{
public TaskData()
{
}
private int _intID = -1;
[DBColumnAttribute( "TaskID", true )]
public int TaskID
{
get{ return _intID; }
set{ _intID = value; }
}
private string _strTitle;
[DBColumnAttribute( "Title" )]
public string Title
{
get{ return _strTitle; }
set{ _strTitle = value; }
}
}
}
Once I created the proper CodeSmith template (I modified the BusinessObject template) the tedious work of typing everything was completed in seconds, including the strongly typed collections for my objects -- everything!
I was so giddy, I added proper comments to the Template and some other bells and whistles, regenerated the entire set of EntityObjects from the database, and now my EntityObjects are 100% consistent with eachother and completely uniform. For many programmers, myself included, that "uniformity" is a thing of pristine beauty. Knowing that all the curly braces and indentations line up straight, all the member variables are properly prefixed and formatted (admittedly, I'm still a Hungarian notation guy), and that each class is literally cut from the same cloth are additional reasons to use a good code generator like CodeSmith.
I should also point out, that my framework allows for the recreation of these EntityObjects at any time (provided the database names don't change!), so if I add a column I can just regenerate the class and I'm all set with the business object. On an architectural aside, any modifications to these EntityObjects are made in derived classes; so if I want to add a specific behaviour to the object (an "AssignTask" method, for example), I'd keep the functionality outside the generated class and in a derived “Task” object:
public class Task : TaskData
Anyway, now that I've drank the CodeSmith kool-aid, I'm sure I'll discover many interesting applications for it.
Happy .Netting!