Programmatically Executing Templates

CodeSmith comes with a sample project named EngineSample that demonstrates the most common uses of the CodeSmith API:

  • Compiling a template
  • Retrieving compile errors
  • Creating a new template instance
  • Filling in template metadata
  • Rendering a template

Here's the code for these operations:

CodeTemplateCompiler compiler = new CodeTemplateCompiler(".. 
..
StoredProcedures.cst");
compiler.Compile();
 
if (compiler.Errors.Count == 0)
{
    CodeTemplate template = compiler.CreateInstance();
 
    DatabaseSchema database = new DatabaseSchema(new SqlSchemaProvider(), @"Server=(local)\NetSDK;Database=Northwind;Integrated Security=true;");
    TableSchema table = database.Tables["Customers"];
 
    template.SetProperty("SourceTable", table);
    template.SetProperty("IncludeDrop", false);
    template.SetProperty("InsertPrefix", "Insert");
 
    template.Render(Console.Out);
}
else
{
    for (int i = 0; i < compiler.Errors.Count; i++)
    {
        Console.Error.WriteLine(compiler.Errors[i].ToString());
    }
}

In addition to the methods shown in this sample, you may also find the CodeTemplate.RenderToFile and CodeTemplate.RenderToString methods useful; they let you direct the output of your templates directly to a file or to a string variable.

This feature is only available in the Professional Edition of CodeSmith.