Untitled

Random thoughts about everything and nothing

Compiling CodeSmith templates to assemblies

leave a comment »

Introduction

There’s an option in CodeSmith studio to compile your template to an assembly.  This has some advantages over the “normal” way of working like referencing the template in a project, no compilation time when running…

You can find the option under Tools | Compile To Assembly

compileoption

Fill texboxes in the Compile To Assembly window, being:

  • Assembly Name: Output filepath
  • Namespace:  Namespace in which the template class will be placed
  • Type Name:  Class name of the template

compiletoassembly

Press OK to start the compilation.

Using the Codesmith API

Another way to compile your templates is to use the CodeSmith API.  The  CodeSmith.Engine dll contains the CodeTemplateCompile class, which exposes the same properties  as the CodeSmith Studio variant.  Take a look at the following snippet:

 
            string templatePath = @"C:outputCompileThis.cst";
            string outputNamespace = "Demo.CodeSmith.Templates";
            string outputTypeName = "CompileThis";
            string outputAssembly = @"c:outputCompileThis.dll";
 
            CodeTemplateCompiler compiler = new CodeTemplateCompiler(templatePath);
            compiler.Namespace = outputNamespace;
            compiler.TypeName = outputTypeName;
            compiler.Compile(outputAssembly, true);
 
            Console.WriteLine("#Errors: {0}", compiler.Errors.Count);
 
            if (compiler.Errors.Count > 0)
            {
                Console.WriteLine(compiler.Errors[0].ErrorText);
            }
 
 
            Console.ReadKey();

Watch out

No matter how you compile your templates, there are some things you should keep in mind:

  1. More than ones i needed to restart CodeSmith Studio (or use unlocker) when recompiling the template, i.e. a lock might held by CodeSmith Studio
  2. Any dependencies you have in the template must be placed in the ouput directory (except for the typical framework dll’s and the ones placed in the GAC) 
Advertisements

Written by Michael

June 22, 2007 at 9:53 pm

Posted in .NET, CodeSmith

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: