CodeSmith Core: Beyond The Enum

I needed application launch logic for a Windows Forms control that would launch the appropriate application (from default and user preferences) based on document type. 

Enter CodeSmith.

The default DocTypes and their associated applications were located in a SQL table.  I needed to pull numbers and a string value from the table to generate an XML file and a Switch method.  This is similar to the Enum template I use occasionally, so I expanded this template to crank out the XML and Switch method.

The properties match the table ID and ApplicationType fields, add the table, the enum name (which also serves as the Switch Method name and XML element names), and click “Generate.”  The result is this code.   (Note, duplicate values make the enumerator generated unusable, but who cares when we’re talking microseconds. 🙂

I added two methods in my CodeSmith DBVTHelper.cs codebehind class to create the Switch and XML.  They look like so.

public string CreateEnumCases(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++)
    {
        sb.Append(“case ” + dt.Rows[p][memberValueField].ToString() + “:\r\n”);
        sb.Append(“\t” + GetLowerWithUnderscoreName(memberNameField) + ” = \”” + dt.Rows[p][memberNameField].ToString() + “\”;\r\n”);
        sb.Append(“\tbreak;\r\n”);
    }
    return sb.ToString();
}

                   
public string CreateEnumXML(TableSchema table, string memberNameField, string memberValueField, string enumName)
{
    StringBuilder sb = new StringBuilder();
    System.Data.DataTable dt = table.GetTableData();
   
    for (int p = 0 ; p < dt.Rows.Count; p++)
    {
        sb.Append(“<item id=\”” + dt.Rows[p][memberValueField].ToString() + “\”>\r\n”);
        sb.Append(“\t\t<” + enumName + “>” + dt.Rows[p][memberNameField].ToString() + “</” + enumName + “>\r\n”);
        sb.Append(“</item>\r\n”);
    }
    return sb.ToString();
}

which hands off the splendid strings to the template.cst code

No follow-up changes were required at all to apply this code to my application.  Definitely a timesaver and productivity booster.  That CodeSmith template gave an extra 20 minutes of dog walking time per week!

Technorati Tags: ,

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.