Codesmith User'S Guide
Codesmith User'S Guide
CodeSmith is a template-based code generator that can produce code for any text-based language. Whether your
target language is C#, Visual Basic .NET, T-SQL, Java or even FORTRAN, CodeSmith can help you produce higher-
quality, more consistent code in less time than writing code by hand. CodeSmith's familiar ASP.NET-based
template syntax means that you can be writing your first templates within minutes of installing the package. The
advanced CodeSmith Studio (Section 6.1) integrated development environment (IDE) helps you create and test
new templates in a rapid development setting. You can also join in CodeSmith's active online community
(http://community.codesmithtools.com/forums/) to download hundreds of ready-made templates for such
common development tasks as building strongly-type collection classes or creating data access layers.
CodeSmith Projects (Section 4.3) and ActiveSnippets (Section 8.1) are integrated within Visual Studio to
make code generation a breeze.
CodeSmith also includes a console version (Section 11.1) and an MSBuild task that you can easily integrate
into your automated build process, flexible strategies for merging generated code (Section 12.2.1) with
custom code, the SchemaExplorer API (Section 10.3.1) for integration with relational data sources, and the
ability to hook up your own custom metadata sources (Section 10.5.1).
If you're new to CodeSmith, Getting Started with CodeSmith (Section 2.3.2.1) will show you how to begin
generating code for your own projects immediately. If you're an experienced CodeSmith user, What's New
(Section 2.2) will point you at the major new features in this release.
CodeSmith User's Guide |
Table of Contents
1. Welcome to CodeSmith 1
2. Introduction and Tutorials 2
2.1. CodeSmith's Main Features 2
2.2. What's New 2-6
2.3. Tutorials 6
2.3.1. Working with CodeSmith 6
2.3.2. Getting Started with CodeSmith 6
2.3.2.1. Getting Started with CodeSmith 6
2.3.2.2. Launching CodeSmith Explorer 6-7
2.3.2.3. Opening a Template 7-9
2.3.2.4. Setting Properties 9-10
2.3.2.5. Generating Code 10-11
2.3.2.6. Inspecting the Template 11-12
2.3.2.7. Where to Go From Here 12
2.3.3. Writing Your First Template 12
6.2.7.1. Menus 54
6.2.7.2. The File Menu 54-55
6.2.7.3. The Edit Menu 55-58
6.2.7.4. The View Menu 58-59
6.2.7.5. The Tools Menu 59-60
1 Welcome to CodeSmith
CodeSmith is a template-based code generator that can produce code for any text-based language.
Whether your target language is C#, Visual Basic .NET, T-SQL, Java or even FORTRAN, CodeSmith can
help you produce higher-quality, more consistent code in less time than writing code by hand.
CodeSmith's familiar ASP.NET-based template syntax means that you can be writing your first templates
within minutes of installing the package. The advanced CodeSmith Studio (Section 6.1) integrated
development environment (IDE) helps you create and test new templates in a rapid development setting.
You can also join in CodeSmith's active online community
(http://community.codesmithtools.com/forums/) to download hundreds of ready-made templates
for such common development tasks as building strongly-type collection classes or creating data access
layers.
CodeSmith Projects (Section 4.3) and ActiveSnippets (Section 8.1) are integrated within Visual
Studio to make code generation a breeze.
CodeSmith also includes a console version (Section 11.1) and an MSBuild task that you can easily
integrate into your automated build process, flexible strategies for merging generated code (Section
12.2.1) with custom code, the SchemaExplorer API (Section 10.3.1) for integration with relational
data sources, and the ability to hook up your own custom metadata sources (Section 10.5.1).
If you're new to CodeSmith, Getting Started with CodeSmith (Section 2.3.2.1) will show you how to
begin generating code for your own projects immediately. If you're an experienced CodeSmith user,
What's New (Section 2.2) will point you at the major new features in this release.
CodeSmith User's Guide | 2
At its most basic, CodeSmith is an application to generate code by combining templates with metadata.
Within that framework, it includes a number of powerful features:
A powerful template language (Section 5.1) similar to ASP.NET.
A simple user interface (Section 3.1) for quick interactive code generation
An object model (Section 5.5.1) that allows your templates to interact directly with the CodeSmith
engine
A complete integrated development environment (Section 6.1) (IDE) for CodeSmith templates
Strong Integration within Visual Studio (Section 4.1) for executing and managing your code
generation.
Powerful code generation automation using CodeSmith Projects (Section 7.1), console-based
code generation (Section 11.1), and MSBuild task.
Interactive debugging features (Section 9.6.1) for tracking down template errors
Flexible metadata providers including .NET types (Section 10.2), database connectivity (Section
10.3.1), XML support (Section 10.4.1), and custom metadata sources (Section 10.5.1)
Console-based code generation (Section 11.1) for use in automated build processes
CodeSmith 5.1
Fixed a bug where removing a data source from Database Explorer wouldn't permanently remove the
data source.
Fixed a threading error when removing a data source from Database Explorer.
Fixed a bug where CodeSmith would throw an exception when it couldn't access the systems registry.
Fixed a bug where Copy Properties would throw an exception when called on a unsaved template.
Fixed a bug where the SqlCompactSchemaProvider connection string builder class could corrupted
additional connection string options.
Fixed a bug where the SqlCompactSchemaProvider timestamp/rowversion columns were returning a
"rowversion" native type name, should be "timestamp".
Added CodeSmith Customer Improvement Program.
Fixed a bug where CodeSmith Studio would attempt to save a csp for a unsaved template.
Fixed a bug where a NullReferenceException would be thrown when toggling the properties window
when no template properties existed.
Fixed a bug where extracting mapping files could cause an exception.
Added Widening, Narrowing, Like, Let, CUInt, CULng, CUShort, and Operator to the VB.NET keyword
list.
Added var to the C# keyword list.
Fixed a bug when using Intellisense and Math. or some variable names would throw an
ArgumentOutOfRangeException.
Updated CodeSmith Options dialog's.
CodeSmith User's Guide | 3
Added support to give feedback and send detailed error information from within CodeSmith.
Updated Menu in CodeSmith Explorer, Users can now view the mapping editor, submit feedback, help,
or configure options.
Updated Manage Outputs and child dialogs to save the window dimensions.
Added IndexedEnumerable, this is used to smartly enumerate collections and get a IsEven, IsLast,
IsFirst property.
Added Linq Querying support to all SchemaExplorer Collections.
Added MergeProperty functionality for parsing properties from a CodeTemplate that inherits from an
assembly.
Added Insert Class Merge Strategy.
Added CodeParser.
Added support to detect an embedded SDK License.
CodeSmith Configuration no longer uses xml files.
Updated the documentation for IDbSchemaProvider and DataObjectBase.
Fixed a bug in OracleSchemaProvider where AllowDBNull would always be set to true for view
columns.
Fixed a bug in OracleSchemaProvider where the TableSchema.PrimaryKeys collection wasn't being
populated correctly.
Updated OracleSchemaProvider's configuration to be configurable via the options dialog.
Added SQL CLR Support to the SqlSchemaProvider. To see if a command is a CLR procedure check
the "CS_IsCLR" extended property.
Fixed a bug in SQLSchemaProvider where an xml index would be set to null after upgrading a SQL
Server 2005 database to SQL Server 2008.
Fixed a bug in SQLSchemaProvider where the ExtendedData query was missing the PropertyBaseType
and Minor columns when querying SQL Server 2000 ExtendedData.
Added PostgreSQLSchemaProvider, SqlCompactSchemaProvider, SQLiteSchemaProvider,
VistaDBSchemaProvider.
Updated .netTiers to version 2.3 RTM.
CodeSmith 5.0
Added a tab for editing variables in the CodeSmith Project settings dialog.
Made it so that any .csp variables are automatically used when there is a string matching the variable
value in the property values.
Made it so that variables are automatically created for connection strings stored in .csp files so that
the connection string isn't repeated.
Made schema explorer designers load their data sources async so that the UI would not lock.
Changed all SchemaExplorer designers to display in Object (Owner) format so that you can type the
first couple letters to jump to the object you are looking for.
Added ability to override plural/singular forms of words to the StringUtil.ToPlural and
StringUtil.ToSingular methods.
Added ability to specify Filter="SomeTableSchemaProperty" on ColumnSchema directives which will
filter the list of columns in the designer based on the table selected in the specified property.
Added new RegisterReference method to CodeTemplate to indicate which assemblies your generated
code relies on so that they can be automatically added in Visual Studio.
Added a menu item for managing data sources to the Visual Studio CodeSmith menu.
Various improvements to the OracleSchemaProvider including full extended property support.
Changed ColumnSchema designer to use a treeview so that all columns for all tables aren't loaded at
once.
Added ability to deep load all schema information at once which results in huge performance
improvements. This is used by setting the DeepLoad attribute on any SchemaExplorer property in
your template. This would typically be used when you know you are going to use all of the schema
information from a database.
CodeSmith User's Guide | 4
Ability to use .net 3.5 features in templates including LINQ. This is accomplished by setting the
CompilerVersion attribute on CodeTemplate to "v3.5".
CodeSmith Projects now have a single file output mode to generate all template outputs into a single
file.
Added Ability to generate individual project outputs.
Made it so that files being generated from a CodeSmith Project are checked out of source control
before being edited.
Improved the custom tool upgrade process so that it works 100% in all scenarios without having to
make manual changes afterward.
CodeSmith Projects can now add files to Visual Studio as code behind files to other generated files.
CodeSmith 4.1
Auto property refresh when running your templates including SchemaExplorer objects and external
XML sources.
Added IDbConnectionStringEditor interface so schema providers can provide connection string editing
interfaces. A connection string editor was implemented for SqlSchemaProvider, ADOXSchemaProvider
and OracleSchemaProvider.
Added Indexes and Keys to the SchemaExplorer tool window in CodeSmith Studio.
Added support for Visual Studio 2008 (Orcas).
CodeSmith 4.0
CodeSmith Projects (Section 7.1) (.csp) - This feature makes automating your code generation
process really easy and consistent whether you are working from inside of Visual
Studio 2005, MSBuild, Windows Explorer, a command line / batch file, or CodeSmith itself.
ActiveSnippets (Section 8.1) - Imagine Visual Studio 2005 snippets, but with the full power of
CodeSmith available to execute any logic or access any complex metadata (including database
schema and XML data) to control the output of your snippets.
CodeSmith Maps (Section 6.7) (.csmap) - This feature will allow you to create dictionary style
maps of things like SQL to C# data type mappings.
.netTiers 2.0 (http://www.nettiers.com/) - The .netTiers templates have been greatly enhanced
and included with CodeSmith 4.0.
NHibernate Templates - NHibernate templates have now been included and are able to get you
started with using NHibernate.
CSLA .NET 2.0 Templates (http://www.codeplex.com/Wiki/View.aspx?
ProjectName=CSLAcontrib) - They latest CSLA .NET 2.0 templates have been included and are
greatly improved.
DbSnapshot Templates - Script all objects and table data out from a Microsoft SQL Server database.
CodeSmith User's Guide | 5
IntelliSense has been improved (including ctrl-space support) in both templates and code behind
files.
Added recent news items to the start page.
CodeSmith Explorer
Supports drag and drop to move/copy files.
Improved performance.
CodeSmith Engine
PropertyChanged event is now exposed on each template.
Added OnChanged attributes to Property and XmlProperty directives.
XmlProperty now stores a file reference to the source XML instead of the XML contents.
XmlProperty now shows the XML file name in the property grid and can be edited.
Added ContextData object to templates for storing various non-persistent state which is shared
with sub-templates.
IPropertySerializer interface has been changed to give property serializers access to more
contextual information.
Added a Initializing state to the template State enum.
SchemaExplorer
Improved handling of SQL Server BLOB DataTypes
Improved ParameterSchema meta-data in CommandParameterSchema now containing
DefaultValue Schema Information.
Ton of new system extended properties added to SchemaExplorer objects.
CodeSmith 3.2
Built and optimized for .NET 2.0 / Visual Studio 2005
CodeSmith MSBuild task
CodeSmith 3.1
New help file
Numerous other minor improvements and bug fixes
CodeSmith 3.0
Completely re-written parser/compiler which is faster and correctly reports line numbers from the
template instead of from the compiled template source. This results in a much nicer debugging
experience.
XML support (Section 10.4.1) - There is now an XmlProperty directive that makes working with
XML much easier. This directive will give you a strongly typed object model to work with if you
provide an XSD schema or it will give you an XmlDocument instance if you don't. This feature
combined with the new IntelliSense feature make working with XML a breeze.
Statement completion (Section 6.3.10) in CodeSmith Studio (similar to Visual Studio's
IntelliSense)
Template caching.
New Register directive (Section 9.7.1) that makes working with sub-templates much nicer.
Console client has been improved to include a batch mode, setting properties from the command
line (Section 11.4.2), and the ability to use any merge strategy ('Specifying a Merge Strategy'
CodeSmith User's Guide | 6
2.3 Tutorials
Although there's a lot of depth to CodeSmith, you can get started with it quickly. In this section of the
documentation, we'll walk you through four common scenarios:
Generating code from an existing template (Section 2.3.2.1)
The best way to understand the power of CodeSmith is to try it out. Although CodeSmith has many
advanced features, you can begin using it to help produce code without mastering all of those features. In
this section, you'll learn how to use CodeSmith to generate a useful piece of utility code - specifically, a
strongly-typed hash table class. This exercise should take you no more than five minutes to complete, but
it will introduce you to both CodeSmith Explorer (Section 3.1) and CodeSmith Studio (Section 6.1),
and show you the power of CodeSmith's template-based code generation scheme.
Next: Launching CodeSmith Explorer (Section 2.3.2.2)
One way to start a code generation session is with CodeSmith Explorer. Just as Windows Explorer serves
to organize files and folders stored on your computer, CodeSmith Explorer serves to organize templates.
To launch CodeSmith Explorer, select CodeSmith Explorer from the CodeSmith program menu. This will
open CodeSmith Explorer with an initial view showing all of the folders containing templates in your
CodeSmith installation.
CodeSmith User's Guide | 7
Templates are patterns for generated code. CodeSmith comes with a set of useful templates to get you
started. You can also download more templates from the CodeSmith Community
(http://community.codesmithtools.com/default.aspx), and as you work with CodeSmith you'll
develop your own custom templates. For now, click on the plus sign to the left of the CollectionGen folder
to see the list of templates stored in this folder.
CodeSmith User's Guide | 8
The .cst file extension stands for "CodeSmith Template." You can probably guess from the names what
the various templates do. For example, the HashTable.cst template generates C# code for a hash table
class. Double-click this template (or right-click and select Execute) to open it.
CodeSmith User's Guide | 9
A code generator that generated the exact same code every time wouldn't be very useful (you might as
well just paste in a saved code file, if that's what you want). CodeSmith templates use properties to let
you customize the generated code. When you open a template from CodeSmith Explorer, the template's
property sheet shows you all of the properties that the template requires. You need to supply values for
these properties before CodeSmith can generate the code for you. The CSHashTable template requires
four string properties (ClassName, ClassNamespace, ItemType, and KeyType) and one enumerated
property (Accessibility). You can type any value you like for a string property; an enumerated property
presents you with a drop-down list of choices when you click in it. For this first experiment, fill out the
property sheet this way:
CodeSmith User's Guide | 10
One of the best things about CodeSmith is that properties can be based on many different types of
metadata. For instance, you can create a property that presents a list of all of the tables in a database,
letting the user choose a table when they're generating the code. You can learn more about this in the
section on Driving Templates with Metadata (Section 10.1).
Next: Generating Code (Section 2.3.2.5)
When you've finished setting properties for the template, you're ready to generate code. To do this, click
the Generate button at the bottom of the template's property sheet. CodeSmith will take the property
values that you entered and combine them with the template to create the code, and display it in an
expanded window. The code will be selected so that you can copy it to the clipboard with a single click of
Ctrl+C.
In this case, the code window contains 320 lines of generated code for the hash table class, implementing
the IDictionary, ICollection, IEnumerable, and ICloneable interfaces. There's nothing there that you
couldn't write yourself if you're a reasonably experienced C# developer - but why bother? This is the sort
of routine work that CodeSmith is ideally suited for. With CodeSmith, you can devote your time and
energy to identifying patterns in your code, turning them into templates, and then reuse them with
maximum flexibility in the future.
CodeSmith User's Guide | 11
Advanced: Using a CodeSmith Project to Execute CodeSmith Templates from Anywhere (Section
7.1)
Let's take a peek behind the scenes at the HashTable.cst template itself. Remember, the template
contains the instructions that CodeSmith uses to generate the code. Return to CodeSmith Explorer, but
CodeSmith User's Guide | 12
this time right-click on the template and select Edit. This will open the template in CodeSmith Studio, the
full-featured IDE that CodeSmith provides for editing templates.
Later on in this help file you can learn more about CodeSmith Studio (Section 6.1) in detail. For now,
just poke around the source code for the template a bit: it's displayed in the main editing area. As you
can see, CodeSmith's template language is very similar to ASP.NET. The file starts off with a set of
directives, including some that declare the various properties that appear in the template. These
properties can be used later in the template by enclosing them in special tokens. For example, the line of
code in the template
namespace <%= ClassNamespace %>
instructs CodeSmith to output the literal string "namespace" followed by the value of the ClassNamespace
property when it is generating code.
If there's something you don't like about the HashTable template, you can change it here. For example,
you might like to add some comments to explain the reason why each interface is included. You can just
type these into the template and save your changes to have CodeSmith use the altered template in the
future.
Next: Where to Go from Here (Section 2.3.2.7)
That's all you need to know to generate code using the templates that are included with CodeSmith:
1. Launch CodeSmith Explorer
2. Select a template
3. Supply values for properties
4. Generate the code
But you can do much more than just use the included templates. Here are some places to continue your
exploration:
Visit the CodeSmith support site (http://community.codesmithtools.com/forums/) for more
templates
Learn more about template syntax (Section 5.1) to write your own templates
Get the details on editing templates with CodeSmith Studio (Section 6.1)
See how to enhance your templates with metadata (Section 10.1)
Knowing how to execute templates that others have written is the first step towards getting started
(Section 2.3.2.1) with CodeSmith, but to realize the full benefit of CodeSmith in your day to day
development tasks, you'll need to write your own templates. In this tutorial, you'll learn how to do just
that, working through the entire process of writing a CodeSmith template from start to finish.
Next: Spotting the Need (Section 2.3.3.2)
Think about your average day of software development. Some of it probably involves brand-new
innovative work that breaks new ground and doesn't resemble anything that you've ever done before. But
other parts are probably more routine. Whether it's writing the code for a public property backed by a
private variable, creating an About This Application dialog box for a new product, or designing a new page
for the corporate Web site, much of your day probably involves routine coding tasks that you've done
before with only minor variations.
Any time you find yourself doing one of these repetitive tasks, you've found a candidate for code
generation. Creating source code files (or Web pages, or SQL statements, or HTML pages, or any other
text file) with minor variations is exactly the sort of thing that CodeSmith is designed for. For example, if
you're writing C# code, you know that every C# project contains an AssemblyInfo.cs file with metadata
CodeSmith User's Guide | 13
about the project. Visual Studio .NET automatically creates a skeleton AssemblyInfo.cs file for you when
you create a new project, but it's full of comments designed for the novice developer, and attributes for
every conceivable purpose. That's fine as a teaching tool, but it's not what most developers want to see in
their source code. So typically, you'll start a new project by cutting out the junk, adding a few comments
of your own, and making a standard set of changes to the attributes that remain. That's a perfect
candidate for code generation: a process that you do over and over again with a few variations. Let's use
CodeSmith to generate just the AssemblyInfo.cs file that you need, without all the fluff.
Next: Creating the Template (Section 2.3.3.3)
CodeSmith templates are plain text files that contain three different types of content:
Directives to the CodeSmith engine
Static content that is copied directly to the template's output
More information:
The easiest way to build a CodeSmith template is to start with an example of the code that you want to
generate - in this case, a finished AssemblyInfo.cs file. Here's one that we'll use as we move through
this tutorial:
using System.Reflection;
using System.Runtime.CompilerServices;
//
// Created: Friday, November 06, 2009
// Author: Blake Niemyjski
//
[assembly: AssemblyTitle("User storage utility")]
[assembly: AssemblyDescription("Helps manage data in Isolated Storage files.")]
[assembly: AssemblyConfiguration("Retail")]
[assembly: AssemblyCompany("MegaUtilities, Inc.")]
[assembly: AssemblyProduct("StorageScan")]
[assembly: AssemblyCopyright("Copyright (c) 2009 MegaUtilities, Inc.")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0")]
[assembly: AssemblyDelaySign(true)]
When you're looking at the file that you want to generate, you need to break the file up into three
different types of content:
CodeSmith User's Guide | 14
More information:
Adding static content to a CodeSmith template is easy. If CodeSmith sees something in the template that
it doesn't recognize as dynamic scripting content, it copies that content directly to the template's output.
So the first step in building our new template is to tack the existing file on to the template without any
changes:
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Description="Create an AssemblyInfo.cs
file." %>
using System.Reflection;
using System.Runtime.CompilerServices;
//
// Created: Friday, November 06, 2009
// Author: Blake Niemyjski
//
[assembly: AssemblyTitle("User storage utility")]
[assembly: AssemblyDescription("Helps manage data in Isolated Storage files.")]
[assembly: AssemblyConfiguration("Retail")]
[assembly: AssemblyCompany("MegaUtilities, Inc.")]
[assembly: AssemblyProduct("StorageScan")]
[assembly: AssemblyCopyright("Copyright (c) 2009 MegaUtilities, Inc.")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0")]
[assembly: AssemblyDelaySign(true)]
At this point, you can run the template, and you'll get output: in fact, you'll get the original file back,
because there's no dynamic content in this template at all. Next, you need to modify the template to take
advantage of the power of CodeSmith's dynamic scripting and interactive metadata.
Next: Making the Content Dynamic (Section 2.3.3.6)
The next step is to let CodeSmith generate the parts of the output that it can calculate automatically. To
do this, we'll insert C# code into our template, using special scripting tags with the same syntax as
ASP.NET. CodeSmith looks for sections of your template surrounded with <%= and %> tokens, and treats
the contents of those tags as expressions to evaluate at runtime. The result of those expressions is then
inserted in the generated code in place of the scripting expression.
Here's the template with two expressions in place of the hard-coded dates in the original (the changes are
highlighted in bold):
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Description="Create an AssemblyInfo.cs
file." %>
using System.Reflection;
using System.Runtime.CompilerServices;
CodeSmith User's Guide | 15
//
// Created: <%= DateTime.Now.ToLongDateString() %>
// Author: Blake Niemyjski
//
[assembly: AssemblyTitle("User storage utility")]
[assembly: AssemblyDescription("Helps manage data in Isolated Storage files.")]
[assembly: AssemblyConfiguration("Retail")]
[assembly: AssemblyCompany("MegaUtilities, Inc.")]
[assembly: AssemblyProduct("StorageScan")]
[assembly: AssemblyCopyright("Copyright (c) <%= DateTime.Now.Year.ToString() %> MegaUtilities,
Inc.")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0")]
[assembly: AssemblyDelaySign(true)]
Now, the creation date and copyright date will be filled in automatically by CodeSmith whenever the
template is executed. But there are other parts of this file that can't be determined automatically by
CodeSmith, such as the assembly title and assembly description. For that sort of variable data, the
solution is to prompt the user at runtime, using CodeSmith properties.
Next: Adding Property Directives (Section 2.3.3.7)
CodeSmith uses property directives to define the metadata for a template. You need to add one property
directive to the template for each piece of information that you want to collect from the user when the
code is generated. Here are the property directives we'll need for our AssemblyInfo.cst template:
<%@ Property Name="Author" Type="System.String" Description="Lead author of the project."
%>
<%@ Property Name="Title" Type="System.String" Description="Title of the project." %>
<%@ Property Name="Description" Type="System.String" Description="Description of the
project." %>
<%@ Property Name="Configuration" Type="System.String" Default="Debug"
Description="Project configuration." %>
<%@ Property Name="Company" Type="System.String" Default="MegaUtilities, Inc." %>
<%@ Property Name="Product" Type="System.String" Description="Product Name." %>
<%@ Property Name="Version" Type="System.String" Default="1.0.*" Description=".NET
assembly version." %>
<%@ Property Name="FileVersion" Type="System.String" Default="1.0" Description="Win32
file version." %>
Each of these properties has a name (which we'll use to refer to the property in scripting code), and a
type (in this case, they're all strings). Some of the properties also have default values, although, as you
can see, you're not required to supply a default value for a property. Most of the properties also have a
description. When the user selects a property in the template's property sheet, CodeSmith displays the
description to help them enter the proper data.
The next step is to make the connection between these properties and the spots in the template where
we want to output their values.
Next: Using Properties in the Template (Section 2.3.3.8)
More information:
To insert the value of a property in the generated output from the template, use the same <%= and %>
syntax that you used with calculated fields, but this time use the name of the property for CodeSmith to
evaluate. Here's our final template:
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Description="Create an AssemblyInfo.cs
file." %>
<%@ Property Name="Author" Type="System.String" Description="Lead author of the project."
%>
<%@ Property Name="Title" Type="System.String" Description="Title of the project." %>
<%@ Property Name="Description" Type="System.String" Description="Description of the
CodeSmith User's Guide | 16
project." %>
<%@ Property Name="Configuration" Type="System.String" Default="Debug"
Description="Project configuration." %>
<%@ Property Name="Company" Type="System.String" Default="MegaUtilities, Inc." %>
<%@ Property Name="Product" Type="System.String" Description="Product Name." %>
<%@ Property Name="Version" Type="System.String" Default="1.0.*" Description=".NET
assembly version." %>
<%@ Property Name="FileVersion" Type="System.String" Default="1.0" Description="Win32
file version." %>
using System.Reflection;
using System.Runtime.CompilerServices;
//
// Created: <%= DateTime.Now.ToLongDateString() %>
// Author: <%= Author %>
//
[assembly: AssemblyTitle("<%= Title %>")]
[assembly: AssemblyDescription("<%= Description %>")]
[assembly: AssemblyConfiguration("<%= Configuration %>")]
[assembly: AssemblyCompany("<%= Company %>")]
[assembly: AssemblyProduct("<%= Product %>")]
[assembly: AssemblyCopyright("Copyright (c) <%= DateTime.Now.Year.ToString() %> <%=
Company %>")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("<%= Version %>")]
[assembly: AssemblyFileVersion("<%= FileVersion %>")]
[assembly: AssemblyDelaySign(true)]
Note that a single property (such as Company) can appear at multiple places in the template.
By now the template might look a good deal more complicated to you than the original file. But
remember: you only have to write the template once. Then you just use it whenever you need a new file.
The investment in time of adding property directives and other dynamic content will be repaid very
quickly as you use the template.
Next: Compiling the Template and Generating Code (Section 2.3.3.9)
At this point, the template is ready to use. Save the file, and then double-click it in Windows Explorer.
This will open the template's property sheet. Fill in values for the template's properties and click the
Generate button to build a new AssemblyInfo.cs file instantly:
There! Wasn't that easier than editing yet another file that Visual Studio .NET didn't build to your
standards?
We chose this example to be a simple "Hello World" type template. How much time it would save you
depends on how many new projects you create, of course. But this same technique - starting with the
CodeSmith User's Guide | 17
output you want to build, identifying the static content, making the content dynamic, and adding
properties for the dynamic content - works with a wide range of code. You can build code for remoting
and Web services, data access layers, standard user interfaces, and anything else you can imagine.
CodeSmith lets you replace repetitive hand-coding with code generation. That's a powerful productivity
booster that you'll wonder how you ever lived without.
One of the key uses for code generation is to build code based on database schema. CodeSmith enables
this scenario through the use of the SchemaExplorer assembly, which provides types for working directly
with SQL Server or ADO data as well as designers that can be used to access those types from
CodeSmith. In this tutorial, you'll see how you can use the information available through
SchemaExplorer, together with scripting code, to make short work of building a complex T-SQL script.
Next: HTTP Endpoints in SQL Server 2005 (Section 2.3.4.2)
More information:
Among the many new features in SQL Server 2005 is the ability to create HTTP endpoints by running T-
SQL code. HTTP endpoints have several uses, including setting up SQL Service Broker connections and
database mirroring over TCP/IP, but the one we'll be concerned with here is that HTTP endpoints make it
easy to build Web services that return SQL Server data. In fact, if your copy of SQL Server 2005 is
running on Windows Server 2003, you don't even need to have IIS installed to create a Web service that
returns SQL Server data. A stored procedure coupled with a CREATE ENDPOINT statement will do the trick.
As with many of the other advanced parts of T-SQL, though, the CREATE ENDPOINT statement has a
good many optional clauses and a lot of complexity. If you're going to need it more than once or twice,
that offers an ideal opening for code generation. Rather than deal with that complexity all the time, figure
it out once and embed your knowledge in a CodeSmith template. To begin with, you'll need an example of
the SQL that you want to create.
Next: The Desired SQL Statements (Section 2.3.4.3)
We're going to create an HTTP endpoint that returns all of the data from a particular table. Because HTTP
endpoints can only return information from stored procedures or functions, this means we'll actually have
to build two SQL statements: one to create a stored procedure, and one to create the endpoint itself. As
usual, the easiest way to build a CodeSmith template is to start with a copy of the output that you want
to produce. In this case, here are the SQL statements to build an HTTP endpoint based on the
Person.AddressType table in the AdventureWorks sample database:
CREATE PROC dbo.PersonAddressTypeProc
AS
SELECT
AddressTypeID,
Name,
rowguid,
ModifiedDate
FROM
Person.AddressType
GO
>CREATE ENDPOINT GetAddressType
STATE = STARTED
AS HTTP
(
PATH = '/AddressType',
AUTHENTICATION = (INTEGRATED),
PORTS = (CLEAR),
CodeSmith User's Guide | 18
SITE = 'localhost'
)
FOR SOAP
(
WEBMETHOD 'AddressTypeList'
(NAME='AdventureWorks.dbo.PersonAddressTypeProc'),
BATCHES = DISABLED,
WSDL = DEFAULT,
DATABASE = 'AdventureWorks',
NAMESPACE = 'http://AdventureWorks/AddressType'
)
GO
We've highlighted two types of information in the statements above. The red highlights show parts of the
SQL statements that the user can choose from small lists of possibilities. The green highlights show
information that CodeSmith can determine from the SQL Server database after the user specifies a
database table. The rest of the template will just be static text.
Now that we understand where we're headed, we can start the journey. This time, we'll use CodeSmith
Studio as our tool, to get a sense of the support that it offers for quickly writing templates.
Next: Creating the Template in CodeSmith Studio (Section 2.3.4.4)
The PATH clause specifies the URL on the server that clients will use to reach this Web service.
The AUTHENTICATION clause specifies how clients will authenticate themselves to the SQL Server:
BASIC, DIGEST, NTLM, KERBEROS, or INTEGRATED.
The PORTS clause specifies whether the service will listen on the CLEAR or SSL ports, or both (other
clauses, not shown here, let you specify non-standard port numbers)
The SITE clause lets you specify a hostname for the computer that will respond to requests.
The FOR SOAP clause states that this endpoint will respond to SOAP messages.
The WEBMETHOD clause defines a Web method, mapping a method name to the name of a stored
procedure
The BATCHES clause specifies that this endpoint won't process arbitrary SQL statements.
The DATABASE clause specifies the database that contains the data.
The NAMESPACE clause specifies the XML namespace for the messages.
This time, we'll use CodeSmith Studio to create the template. This will let you try out the tools in
CodeSmith Studio to see how they can speed up template development. To get started, launch
CodeSmith Studio and select File > New > VB Template. This will create a new template with some boiler
plate code in it to remind you how the various parts of a CodeSmith template fit together. Start by
modifying the CodeTemplate directive:
<%@ CodeTemplate Language="VB" TargetLanguage="T-SQL" Description="Create an HTTP
Endpoint." %>
The TargetLanguage attribute is used by CodeSmith to group the template with other T-SQL templates
when you use target language view in CodeSmith Explorer. This attribute is also used to determine how
to syntax highlight the static content of a template. The Description attribute is used to provide a tooltip
for the template.
Next, replace the rest of the sample template code with the T-SQL that we want to generate. Now we've
got the starting point: a template that turns out completely static SQL.
CodeSmith User's Guide | 19
More Information:
Several of the pieces of information that we want to collect from the user have a limited number of
acceptable choices. For example, the state of the endpoint can only be STARTED, STOPPED, or DISABLED;
anything else will lead to a T-SQL error. Rather than prompting the user for freeform input (and running
the risk of having them type an unacceptable value), it's much more sensible to offer a list of just the
acceptable choices. Fortunately, you can do this by defining an enumerated property.
To set up an enumerated property, you need to define a type that only allows the values you want. You
can do this by creating an enumeration. Start by moving to the end of the template and choosing Edit >
Insert Content > Script Block. Then create the new type:
<script runat="template">
Public Enum StateEnum
STARTED
STOPPED
DISABLED
End Enum</script>
Now you can use a CodeSmith Property directive to define a property that makes use of the new type:
<%@ Property Name="InitialState" Type="StateEnum" Category="Options" Default="STARTED"
Description="The initial state of the Web service." %>
There's one more piece that you need to add to make it all work, though. Under the covers, .NET treats
enumerations as integers, but you want to insert literal strings in the generated code. To make the
translation, you'll also need to add a helper function inside of the script block:
Public Function GetState (ByVal State As StateEnum) As String
Select Case State
Case StateEnum.STARTED
GetState = "STARTED"
CodeSmith User's Guide | 20
Case StateEnum.STOPPED
GetState = "STOPPED"
Case StateEnum.DISABLED
GetState = "DISABLED"
End Select
End Function
Having done this, you can get the string corresponding to the user's choice of InitialState property by
inserting <%= GetState(InitialState) %> anywhere in the template. After adding enumerations,
properties, and helper functions for the authentication and port properties, here's the current state of our
template:
<%@ CodeTemplate Language="VB" TargetLanguage="T-SQL" Description="Create an HTTP
Endpoint." %>
<%@ Property Name="InitialState" Type="StateEnum" Category="Options" Default="STARTED"
Description="The initial state of the Web service." %>
<%@ Property Name="Authentication" Type="AuthenticationEnum" Category="Options"
Default="INTEGRATED" Description="Authentication method." %>
<%@ Property Name="Port" Type="PortsEnum" Category="Options" Default="CLEAR"
Description="Port to use." %>
CREATE PROC dbo.PersonAddressTypeProc
AS
SELECT
AddressTypeID,
Name,
rowguid,
ModifiedDate
FROM
Person.AddressType
GO
CREATE ENDPOINT GetAddressType
STATE = <%= GetState(InitialState) %>
AS HTTP
(
PATH = '/AddressType',
AUTHENTICATION = (<%= GetAuthentication(Authentication) %>),
PORTS = (<%= GetPort(Port) %>),
SITE = 'localhost'
)
FOR SOAP
(
WEBMETHOD 'AddressTypeList'
(NAME='AdventureWorks.dbo.PersonAddressTypeProc'),
BATCHES = DISABLED,
WSDL = DEFAULT,
DATABASE = 'AdventureWorks',
NAMESPACE = 'http://AdventureWorks/AddressType'
)
GO
<script runat="template">
Public Enum StateEnum
STARTED
STOPPED
DISABLED
End Enum
Public Enum AuthenticationEnum
BASIC
DIGEST
NTLM
KERBEROS
INTEGRATED
End Enum
Public Enum PortsEnum
CLEAR
SSL
End Enum
Public Function GetState (ByVal State As StateEnum) As String
Select Case State
Case StateEnum.STARTED
GetState = "STARTED"
Case StateEnum.STOPPED
GetState = "STOPPED"
Case StateEnum.DISABLED
CodeSmith User's Guide | 21
GetState = "DISABLED"
End Select
End Function
Public Function GetAuthentication (ByVal Authentication As AuthenticationEnum) As String
Select Case Authentication
Case AuthenticationEnum.BASIC
GetAuthentication = "BASIC"
Case AuthenticationEnum.DIGEST
GetAuthentication = "DIGEST"
Case AuthenticationEnum.NTLM
GetAuthentication = "NTLM"
Case AuthenticationEnum.KERBEROS
GetAuthentication = "KERBEROS"
Case AuthenticationEnum.INTEGRATED
GetAuthentication = "INTEGRATED"
End Select
End Function
Public Function GetPort (ByVal Port as PortsEnum) As String
Select Case Port
Case PortsEnum.CLEAR
GetPort = "CLEAR"
Case PortsEnum.SSL
GetPort = "SSL"
End Select
End Function
</script>
So far, so good. But there's still one thing missing: a connection to the database. We'll tackle that next.
Next: Setting up a SQL Property (Section 2.3.4.6)
More information:
In order to generate code based on a database table, the template has to somehow know about the
database table. This means supplying metadata through a property that refers to the table. Fortunately,
CodeSmith includes the SchemaExplorer library, which contains a rich set of types designed specifically
for interacting with databases. One of these types, TableSchema, allows the user to pick a table from a
database. You can then use the object model in the SchemaExplorer library to retrieve just about any
information you need about the table and the database. Here's the Property directive that we need:
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context"
Description="Table that the Web service will access." %>
CodeSmith itself doesn't have any special knowledge of the types in the SchemaExplorer library, so we
need to tell it to load the assembly containing the library. It's also useful to import the SchemaExplorer
namespace to keep the amount of typing we have to do to a minimum:
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
When the user selects a table with SchemaExplorer, the TableSchema object will be populated and
returned to CodeSmith. For the most part, this particular template can be filled out just by retrieving the
names of the table, the table's owner, and the database from this object. All of those are easily available
by navigating around the SchemaExplorer object model:
<%= SourceTable.Name %>
<%= SourceTable.Owner %>
<%= SourceTable.Database.Name %>
Substituting those expressions in appropriate places will get you most of the way through writing this
particular template. But there's still one task left that requires a bit of coding: building the list of column
names for the stored procedure.
Next: Writing the Database Code (Section 2.3.4.7)
The trickiest part of writing this particular template is retrieving the list of column names for the stored
procedure definition. Those, too, are available from SchemaExplorer. The TableSchema object contains a
Columns collection, which you can iterate through in code. You can place scripting code directly in your
template by enclosing it within <% and %> tokens. Here's the code we need to build the list of columns,
complete with appropriate commas:
<% For i As Integer = 0 To SourceTable.Columns.Count -1 %>
<%= SourceTable.Columns(i).Name %><% If i < SourceTable.Columns.Count - 1 Then %>,<% End
If %>
<% Next %>
Note the difference here between code to execute (surrounded by <% %> tokens), expressions to evaluate
(surrounded by <%= %> tokens) and static content to copy to the output (not surrounded at all). You may
find keeping all this straight one of the more confusing aspects of working with CodeSmith at first. When
in doubt, use the Insert Content toolbar button or the Edit > Insert Content submenu to insert the
appropriate code blocks and write blocks. That way you'll get the syntax straight automatically, and can
spend your time worrying about the template's logic.
WSDL = DEFAULT,
DATABASE = '<%= SourceTable.Database.Name %>',
NAMESPACE = 'http://<%= SourceTable.Database.Name %>/<%= SourceTable.Name %>'
)
GO
<script runat="template">
Public Enum StateEnum
STARTED
STOPPED
DISABLED
End Enum
Public Enum AuthenticationEnum
BASIC
DIGEST
NTLM
KERBEROS
INTEGRATED
End Enum
Public Enum PortsEnum
CLEAR
SSL
End Enum
Public Function GetState (ByVal State As StateEnum) As String
Select Case State
Case StateEnum.STARTED
GetState = "STARTED"
Case StateEnum.STOPPED
GetState = "STOPPED"
Case StateEnum.DISABLED
GetState = "DISABLED"
End Select
End Function
Public Function GetAuthentication (ByVal Authentication As AuthenticationEnum) As String
Select Case Authentication
Case AuthenticationEnum.BASIC
GetAuthentication = "BASIC"
Case AuthenticationEnum.DIGEST
GetAuthentication = "DIGEST"
Case AuthenticationEnum.NTLM
GetAuthentication = "NTLM"
Case AuthenticationEnum.KERBEROS
GetAuthentication = "KERBEROS"
Case AuthenticationEnum.INTEGRATED
GetAuthentication = "INTEGRATED"
End Select
End Function
Public Function GetPort (ByVal Port as PortsEnum) As String
Select Case Port
Case PortsEnum.CLEAR
GetPort = "CLEAR"
Case PortsEnum.SSL
GetPort = "SSL"
End Select
End Function
</script>i
Next: Testing the Final Result (Section 2.3.4.8)
More Information:
Now that you've written the template, it's easy to test it out in CodeSmith Studio. First you'll need to
compile the template, so that CodeSmith will display the right properties in the Properties Window. Click
the Build button on the toolbar or press Ctrl+Shift+B to do this. Assuming that there are no errors in the
template, you'll see progress messages in the Output Window:
CodeSmith User's Guide | 24
To set the SourceTable property, click in the property value. CodeSmith will display a builder button with
three dots. Click the builder button to open the Table Picker dialog box.
Here you can select the data source, and the table within that data source, to use with the template. You
can also click the builder button next to the Data Source combo box to create new data sources
(Section 10.3.1) After choosing a table, click the Select button to return to CodeSmith Studio.
CodeSmith User's Guide | 25
When you're done setting properties, click the Run toolbar button or press F5 to run the template.
CodeSmith will generate the template's output and switch to the Output tab so that you can save or copy
the output.
More Information:
CodeSmith Explorer provides an easy interface for organizing and executing CodeSmith templates. Just as
Windows Explorer sorts your files into folders, CodeSmith explorer sorts templates into folders to make it
easier to find the templates that you want to work with.
Create a template folder shortcut. Clicking this button will open a Browse for Folder dialog box
that lets you select any existing folder on your computer. Click OK to add a shortcut to the selected folder
as a top-level node in CodeSmith Explorer. When you install CodeSmith, CodeSmith Explorer is pre-
populated with a single shortcut to the SampleTemplates folder in your installation.
Refresh. Clicking this button causes CodeSmith to refresh the folder and template display.
Toggle Top Most Window Mode. By default, CodeSmith Explorer behaves as a normal window
that can be overlaid by other windows. If you select this button, CodeSmith Explorer will float on top of all
other windows, remaining permanently visible even if another window that would otherwise hide it has
the focus. This is especially useful when you want to generate code by dragging and dropping templates
from CodeSmith Explorer to any application that supports dropping text (such as the Visual Studio IDE).
Folder View. With this button selected, CodeSmith displays templates organized into actual folders
(corresponding to the folders that you see in Windows Explorer) beneath each template folder shortcut.
This is the default view.
Target Language View. With this button selected, CodeSmith displays templates organized into
CodeSmith User's Guide | 27
folders according to their target language (such as C# or T-SQL). The target language is determined from
the TargetLanguage attribute of the CodeTemplate directive within the template. (Section
5.1) Folder view and target language view are mutually exclusive.
Select Template Editor When you click this button, CodeSmith will display a File Open dialog
box to let you pick an executable file to be used to edit templates. This is the editor that will be used
when you invoke template editing from CodeSmith Explorer. The default template editor is CodeSmith
Studio (Section 6.1).
CodeSmith Templates Only Filter Filters the templates in the Template Explorer to show only
CodeSmith related Templates.
About CodeSmith. This button displays the version and licensing information for your copy of
CodeSmith.
Folders may contain subfolders, templates, or both. At any time, one node in the folder tree will be
selected. The selected node is indicated by a highlight. In the screenshot below, the CSLA.NET subfolder
of the Frameworks subfolder of the CodeSmith Samples folder is selected. You can select a node by
clicking on it with the mouse. You can also move the selection by using the up or down arrow keys, or by
typing the first letter of the name of the node.
A folder that can be expanded is indicated by a plus sign to its left. To expand a folder, click the plus sign,
or double-click the folder or its name, or select the folder and click the right arrow or the plus sign on the
numeric keypad. A folder that can be collapsed is indicated by a minus sign to its left. To collapse a folder,
click the minus sign, or double-click the folder or its name, or select the folder and click the left arrow or
the minus sign on the numeric keypad.
You can perform a variety of other operations from the CodeSmith Explorer context menus. These menus
differ depending on which node you right-click on.
File. Create a new empty file. By default the file with have a .txt extension.
Folder. Create a new subfolder.
Refresh. Refresh the CodeSmith Explorer tree from this point downwards.
Delete. Deletes this folder shortcut from CodeSmith Explorer. This does not delete the underlying
files from your hard drive.
Rename. Lets you change the display name of the shortcut in CodeSmith Explorer. This does not
change the name of the underlying folder on your hard drive.
Sub Folders. When checked, CodeSmith Explorer will also display subfolders of the target folder.
Otherwise, it will only display templates in the target folder of the shortcut itself.
Exclude Global. Removes this template, and any others with the same name, from the CodeSmith
Explorer display.
If you accidentally Exclude a template, you can return it to CodeSmith Explorer by deleting
the parent template folder shortcut and then re-adding the template folder shortcut to
CodeSmith Explorer. This will reset all exclusions for the template folder shortcut.
There is no way to reverse the effects of an Exclude Global operation, so you need to be
extremely cautious when choosing this menu item.
To edit a template, right-click the template in CodeSmith Explorer or Window Explorer and select Edit.
This will open the template in the default template editor (by default, CodeSmith Studio (Section
CodeSmith User's Guide | 29
6.1)). CodeSmith Explorer will use an existing editor session if possible, otherwise it will launch a new
editor session.
To execute a template from CodeSmith Explorer, double-click the template, or right-click the template
and select Execute. You can also drag the template from CodeSmith Explorer and drop it on any
application that supports drag-and-drop (including Visual Studio) to generate code at the location where
you dropped the template. Any of these actions will open the template's property sheet. The template's
property sheet shows you all of the properties that you can set for this template. Properties can be
required or optional. You need to supply values for all required properties before CodeSmith can generate
the code for you. Depending on how a property is defined in the template, you may be able to type in an
arbitrary value, select a value from a predefined list, or choose a value by navigating to a dialog box from
a builder button within the property sheet. Properties may also have default values. As you select each
property, a description will appear at the bottom of the property sheet to tell you more about that
property.
In the screenshot above, the user has selected the SourceCommand property, and the description
indicates that this property specifies the Command that the wrapper class should wrap. With the property
selected, the right side of the property sheet shows the builder button (with three dots). Clicking this
button will open a separate dialog box (in this case, a dialog box supplied by CodeSmith's own
SchemaExplorer (Section 10.3.1) metadata extension) to help you pick a value for this property.
When you've finished setting properties for the template, you're ready to generate code. To do this, click
the Generate button at the bottom of the template's property sheet. CodeSmith will take the property
values that you entered and combine them with the template to create the code, and display it in an
expanded window. The code will be selected so that you can copy it to the clipboard with a single click of
Ctrl+C, or by clicking the Copy Template Output toolbar button in the output window.
Tip: By default, the properties in the property sheet are sorted by categories. If you'd prefer them in a
single alphabetical list, click the Alphabetic toolbar button at the top of the property sheet.
Advanced: Using a CodeSmith Project to Execute CodeSmith Templates from Anywhere (Section
7.1)
(Section 7.1)
CodeSmith Explorer will automatically display the output panel when you click the Generate button. You
can also display it by clicking the Expand (>>) button. This action changes the Expand button into the
Collapse (<<) button and displays the output panel.
CodeSmith User's Guide | 30
The output panel has two tabs at the top. The Compiler Output tab shows the result of CodeSmith
compiling the template. If there are any errors shown in this tab, you need to fix the errors by editing
the template (Section 3.4) before you ca generate code with the template. The Template Output tab
shows the actual generated code. This tab will be blank until you click the Generate button.
The output panel has its own toolbar with seven buttons:
Open Template. Opens a File Open dialog box to let you select any CodeSmith template to open in
the current window, replacing the template that is currently open.
Compile Template. Invokes the CodeSmith compiler to check the template for syntax errors. The
output from the compiler will be shown on the Compiler Output tab of the output panel.
Copy Template Output. Copies the current contents of the Template Output tab of the output
panel to the Windows clipboard.
Save Template Output. Opens a Save As dialog box to let you save the current contents of the
Template Output tab of the output panel as a new disk file.
Copy CodeSmith Project. Copies the settings from the property sheet into a CodeSmith Project
and to the Windows clipboard as an XML file. CodeSmith Project files can be used as input to the
CodeSmith console application (Section 11.2).
Save CodeSmith Project. Opens a Save As dialog box to let you save the settings from the
property sheet as an CodeSmith Project file.
Load CodeSmith Project. Opens a File Open dialog box to let you select an existing CodeSmith
Project file. The settings from the XML file will be loaded into the property sheet.
CodeSmith User's Guide | 31
4.1.3 ActiveSnippets
ActiveSnippets (Section 8.1) can be used to generate snippets of code similar to Visual Studio's
snippets except with the full power of CodeSmith templates and ability to use complex metadata like
database schema and XML.
CodeSmith User's Guide | 32
If you have Visual Studio installed when you install CodeSmith, CodeSmith will install itself as a Visual
Studio package.
To use CodeSmith Explorer from within Visual Studio, select CodeSmith Explorer from the Tools menu.
This will open the CodeSmith Explorer tool window. This window can be floating or docked, just like any
other Visual Studio tool window.
CodeSmith Explorer has the same functionality in Visual Studio .NET that it does as a standalone
program.
One very useful capability of CodeSmith Explorer within Visual Studio is drag-and-drop code generation.
For example, you could use this capability to quickly replace the autogenerated AssemblyInfo.cs file in a
new C# project with the one generated by the AssemblyInfo.cst (Section 2.3.3.8) template. Just
delete the autogenerated file contents and drag the template from the CodeSmith Explorer tool window to
the code window in the IDE. CodeSmith will display the template's property sheet. Fill in the required
properties and click the Generate button to generate code wherever you dropped the template.
Note: This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
CodeSmith User's Guide | 33
4.3.1 Introduction
The tight integration with Visual Studio allows you to fully manage any CodeSmith Project right from
Visual Studio! This means you can maintain a high Code Generation presence right within Visual Studio
and not have to switch applications to run code generation.
1. Add Outputs To Project - Will take any outputs from your CodeSmith Project and include
them in your Visual Studio project.
2. Hide Outputs - will take any outputs of your CodeSmith Project and make them child nodes,
dependant on your CodeSmith Project file (shown below). Hidden nodes can be collapsed,
and since much of the time generated code shoudln't be touched, it's a great way to hide the
temptation of other developers attempting to modify the generated code.
3. Generate On Build - A menu driven way to have your templates use Active Generation. You
can also specify the BuildAction value in the property sheet of your CodeSmith Project. (more
below)
Example:
Looking into the properties of the CodeSmith Project, you can view the Build Action of the file, and there
is an option to set it to Generate on Build. Meaning every time you need to tweak your Database meta-
data, XML Property meta-data, or CodeSmith template, the changes are picked up in your Visual Studio
project the very next time you build.
This enables you to alleviate much of the frequent developer problems with making changes across all of
your classes, during the development process.
To get your template to support this, you'll need to update the template to use the RenderToFile overload
that takes a parent file. Next, add the CodeSmith Project to the Visual Studio project and Generate
Outputs. CodeSmith will automaticly add the outputs to your Visual Studio project creating the hierarchy.
Sample Template Code
//Create Sub template using the Create method to automaticly wire everything up
EntityGeneratedClass entityClass = this.Create<EntityGeneratedClass>();
EntityEditableClass partialClass = this.Create<EntityEditableClass>();
Every CodeSmith template must start with a CodeTemplate directive. Every template must contain
precisely one CodeTemplate directive. The only thing that can appear before the CodeTemplate directive
in the template is one or more comments (Section 5.2).
The CodeTemplate directive is the only required directive and is used to specify the general properties of
the template, such as the language that the template is written in and the description that will show in
CodeSmith Explorer as a tooltip for the template. For example, here's the CodeTemplate directive from
the VBSortedList.cst sample template:
<%@ CodeTemplate Language="VB" TargetLanguage="VB" Description="Generates a strongly-
typed collection of key-and-value pairs that are sorted by the keys and are accessible by
key and by index." %>
This directive specifies that the template uses Visual Basic .NET as its own code-behind language, and
that it produces VB output. It also includes a description of the purpose of the template.
Language
The Language attribute specifies what language will be used to write the template. Possible values for this
attribute are:
C# to author the template in C#
TargetLanguage
The TargetLanguage attribute is used to specify the output language of the template. You can use any
string you like for the attribute; CodeSmith doesn't use it in any way to generate the template's output.
This attribute is used by CodeSmith Explorer to determine which folder to display the template in when in
template language view (Section 3.2). CodeSmith also uses this attribute to determine how to syntax
highlight the static content of a template.
Description
The Description attribute is used to describe your template in a general way. CodeSmith Explorer
displays this description as a tooltip for the template.
Inherits
By default all CodeSmith templates inherit from CodeSmith.Engine.CodeTemplate (Section 5.5.2.1).
This class provides the basic functionality of the template; much like the Page class provides the basic
functionality of an ASP.NET page. The Inherits attribute can be used to specify that a template inherits
from a different class. However, any class that a template inherits from must inherit, directly or indirectly,
from CodeSmith.Engine.CodeTemplate. CodeSmith must also be able to find this class. To ensure this,
you must either supply an Assembly (Section 9.2) directive pointing to the assembly that contains the
class, or a Src attribute that points to the source code for the class.
For an example of using template inheritance, see the CodeSmithBaseTemplates sample project included
with your CodeSmith installation. This project defines two new template classes,
OutputFileCodeTemplate which inherits directly from CodeTemplate and SqlCodeTemplate which inherits
from OutputFileCodeTemplate. To base a new template on SqlCodeTemplate you could include these
directives at the top of your template:
<%@ CodeTemplate Language="CS" Inherits="CodeSmith.BaseTemplates.SqlCodeTemplate" %>
<%@ Assembly Name="CodeSmith.BaseTemplates" %>
Having done this, all of the helper methods defined in the OutputFileCodeTemplate and
SqlCodeTemplate classes, such as GetSqlDbType(), IsUserDefinedType(),
GetSqlParameterStatements(), and many more, are available to your template. Template inheritance
thus provides a good way to reuse tested utility methods across multiple templates without cut-and-paste
duplication of code.
CodeSmith User's Guide | 37
Src
The Src attribute allows you to include functionality from another class in your template by dynamically
compiling that class file as part of your template. Set the value of the attribute to point to the source file
of the class that you want to include in the template. You use the Src attribute to enable the CodeSmith
code-behind model (Section 9.1).
Debug
The Debug attribute is used to determine whether or not debug symbols should be included in the
generated assembly. Setting this attribute to True will enable you to set break points in your template
using the System.Diagnostics.Debugger.Break( ) method.
LinePragmas
The LinePragmas attribute is used to determine whether or not line pragmas are generated during
template compilation. When this attribute is set to True, template errors will point to the template source
code. If it is set to False, then template errors will point to the compiled source code.
ResponseEncoding
The ResponseEncoding attribute is used to set the encoding for the template content and it's outputs.
The ResponseEncoding attribute supports values from the System.Text.Encoding.GetEncoding method.
By default, the encoding is set to ASCII.
OutputType
The OutputType attribute is used to set the output type of the template. The following values can be
used:
Normal - This is the default setting and will cause the output of the template to be written to the
normal Response stream.
Trace - This setting will cause the output of the template to be written to the Trace object.
None - This setting will cause the template to not output anything. This is useful in a master
template scenario where the template just calls other templates and outputs those to files and the
master template itself doesn't output anything.
NoWarn
Comma-delimited list of the warning ID numbers that the template compiler should suppress. These are
standard C# / VB compiler warning ID numbers.
CompilerVersion
The CompilerVersion attribute is used to specify which compiler to use. For example, to use the .net 3.5
compiler, add the CompilerVersion attribute with a value of v3.5
To include comments in a template, surround them with <%-- and --%> markers. Comments may span
multiple lines. For instance, this comment will have no effect on the template's output:
<%--
Name: TestHarness.cst
Description: Generates a standard test harness for an object
--%>
Inside of a script block, use the commenting syntax of the template's language. For instance,
if your template is written in C#, comments in script blocks should be prefaced with // or /*
commented */.
To include a comment in a template's output, treat it like any other string. The comment in
this template fragment will be copied directly to the generated code:
<%@ CodeTemplate Language="VB" TargetLanguage="VB">
' This class generated by CodeSmith
CodeSmith User's Guide | 38
The key to making templates flexible and useful is to define properties or metadata. CodeSmith uses
properties to customize the generated code. When the user opens a template in CodeSmith Explorer, they
must supply values (Section 3.5) for all of the required properties defined in the template before they
can generate the code. Note that properties can be defined as optional properties, in which case the user
need not supply a value before generating code.
Properties are specified in the template using a Property directive (Section 5.3.2). For example,
this directive specifies a property named Key which accepts a string value:
<%@ Property Name="Key" Type="System.String" %>
The value that the user enters for the Key property will be inserted into the template output any place
that the property name appears surrounded by the special characters <%= %>. For example, consider this
template:
<%@ CodeTemplate Language="VB" TargetLanguage="VB">
<%@ Property Name="Key" Type="System.String" %>
' The key is <%= Key %>
If the user enters Ham for the value of the Key property, then the output of this template would be:
' The key is Ham
Properties in CodeSmith can be simple or very complex. You can define enumerated properties
(Section 5.3.3) that allow the user to choose from a predefined selection of values. You can use
CodeSmith's SchemaExplorer (Section 10.3.1) to fill properties from database objects. You can create
properties based on the contents of an XML file (Section 10.4.1), or even define your own custom
properties (Section 12.8.1) complete with custom dialog boxes for user property editing.
To declare a property, you use a Property directive. For example, this directive defines a property named
ClassName of type System.String:
<%@ Property Name="ClassName" Type="System.String" Category="Context" Description="The
name of the class to be generated." %>
Name
The Name attribute is used as the name of the property when it is displayed on the template's property
sheet in CodeSmith Explorer. This is also the variable name that is used to store the value of the property
within the template. This must be a legal variable name within the template's language. For example, if
the template uses C# as its language, then the name must follow the rules for C# variables.
Type
The Type attribute specifies the .NET type of the property. This parameter can be any .NET data type,
though for complex types you may need to specify an Editor attribute to allow the user to successfully
supply a value for the property.
For scalar types, you must use Base Class Library types such as String or Int32 rather than
language-specific types such as string or int.
Default
The Default attribute is used to set the default value for this property. If you omit this attribute, then
CodeSmith does not supply a default value for the property.
Category
The Category attribute specifies what category this property should appear under in the CodeSmith
Explorer property sheet. If you omit this attribute, CodeSmith will place the property in a category named
Misc.
CodeSmith User's Guide | 39
Description
The Description attribute supplies descriptive text to be displayed at the bottom of the property sheet
when this property is selected.
Optional
The Optional attribute specifies whether or not this property is optional. If a user does not specify a
parameter that is not optional then CodeSmith will not let them proceed. A value of true means that a
value for the property is not required, and a value of false means that a value for the property is
required.
Editor
The Editor attribute specifies the GUI editor that will be used in the property grid for this property. This
is equivalent to placing an [EditorAttribute ] on a code property.
EditorBase
The EditorBase attribute specifies the base type for the editor. If none is specified, then UITypeEditor
is assumed.
Serializer
The Serializer attribute specifies the IPropertySerializer type to use when serializing the property's
values. This is equivalent to using a [PropertySerializerAttribute] on a code property.
Example:
private string aliasFilePath;
[Editor(typeof(System.Windows.Forms.Design.FileNameEditor), typeof
(System.Drawing.Design.UITypeEditor))]
[Category("01. General")]
[Optional(true)]
[DefaultValue("")]
[Description("Optional File Path to a table/object alias file.")]
public string AliasFilePath
{
get {return this.aliasFilePath;}
set {this.aliasFilePath = value;}
}
Sometimes it's convenient to have a property that limits the user to selecting from a fixed set of choices.
For instance, in the VBSortedList.cst template, the Accessibility property controls the accessibility of
the generated class:
CodeSmith User's Guide | 40
To accomplish this, you need to take two steps. First, define an enumeration in a <script> block in your
code:
<script runat="template">
Public Enum AccessibilityEnum
[Public]
[Protected]
[Friend]
[ProtectedFriend]
[Private]
End Enum</script>
Second, the Property directive should point to the enumeration:
<%@ Property Name="Accessibility" Type="AccessibilityEnum" Category="Options"
Description="The accessibility of the class to be generated." %>
That's all there is to it!
Because you can define a property as being optional (Section 5.3.2), you may want to validate the
property in your template to determine whether or not the user has entered a value. For example, you
might want to allow generating a class either with a namespace declaration or without, at the user's
option. To do this, you would first define an appropriate optional property:
<%@ Property Name="ClassNamespace" Type="System.String" Optional="True"
Category="Context" Description="The namespace that the generated class will be a member
of." %>
In your template, you can check to see whether there's a value in this property at runtime. If so, you
want to output the appropriate namespace declaration. If you're using C# as your template language,
you'd do that like this:
<% if (ClassNamespace != null && ClassNamespace.Length > 0) { %>
namespace <%= ClassNamespace %>
{
<% } %>
If your template is using VB, the equivalent code is:
<% If Not ClassNamespace Is Nothing AndAlso ClassNamespace.Length > 0 Then %>
Namespace <%= ClassNamespace %>
CodeSmith User's Guide | 41
If you're building ASP.NET code with CodeSmith, you'll run into the problem that the <% tags that you
want to output to your ASP.NET code are interpreted by CodeSmith as CodeSmith tags instead. The
solution is to escape the starting tags, replacing <% with <%%. This will be replaced with <% in the output,
and not seen by CodeSmith as an opening script tag.
Behind the scenes, the CodeSmith engine works by manipulating a rich object model. That object model
is exposed for your templates to work with as well. In this section, we'll explore some of the things that
you can do with the CodeSmith objects:
The CodeTemplate (Section 5.5.2.1) object
The CodeTemplate class represents your entire template as it's being processed by CodeSmith. You can
work with a CodeTemplate object to interact directly with the CodeSmith engine. For example:
Use the GetFileName (Section 5.5.2.2) method to specify the default output file name for a
template
Use the Render (Section 5.5.2.4) method to render the output of the template
Use events (Section 5.5.2.5.1) of the object to insert your own code into the CodeSmith processing
cycle
Use the Response (Section 5.5.2.6) property to write directly to the template output
CodeSmith uses the GetFileName method to provide a default output filename for the template when it's
called from the CodeSmith Console Application (Section 11.1). This is also used in CodeSmith Studio
as the default file name if you save the output of a template, and anywhere else that CodeSmith needs to
assign a filename to the output of your template. You can override this method in your code when you
want to build the default file name based on property input or other factors.
For example, if your C# language template contains a property named ClassName, you might include this
code to set the default output file name:
<script runat="template">
public override string GetFileName() {
return ClassName + ".cs";
}
</script>
You may sometimes want to define a property with a default value that cannot be automatically converted
from a string. In this case, you'll need to override the ParseDefaultValue method in your template to
handle parsing the default value from the template and assigning it to the property. This method is called
CodeSmith User's Guide | 42
by CodeSmith for each property in the template, and gets passed the property and the default value
string from the template. If you override the method, you can insert whatever custom logic you like to
assign values to the property that you care about, while passing other properties to the base
ParseDefaultValue method.
The CodeTemplate.Render method is where CodeSmith does the actual work of combining metadata with
your template to create the template's output. You can override this method if you want to modify the
way that CodeSmith ultimately handles that output. For example, overriding this event allows you to write
your template's output to multiple destinations instead of just to the default output window. Here's a
template that outputs some text to two files at the same time, as well as to CodeSmith's default output
window:
<%@ CodeTemplate Language="C#" TargetLanguage="Text" Description="AddTextWriter
Demonstration." %>
<%@ Import Namespace="System.IO" %>
This template demonstrates using the AddTextWriter method
to output the template results to multiple locations concurrently.
<script runat="template">
public override void Render(TextWriter writer)
{
StreamWriter fileWriter1 = new StreamWriter(@"C:\test1.txt", true);
this.Response.AddTextWriter(fileWriter1);
base.Render(writer);
fileWriter1.Close();
fileWriter2.Close();
}
</script>
Don't omit the call to the base.Render method. If you forget this, then you won't get the default
output!
You also have access to the default TextWriter if you override the Render method. This means that you
can write your own headers or other additional information directly to the output along with the
template's output.
The CodeTemplate object provides three events that you can use to insert logic during the template
processing cycle:
The OnInit (Section 5.5.2.5.2) event fires when the template instance is created
The OnPreRender (Section 5.5.2.5.3) event fires just before the template is rendered
The OnPostRender (Section 5.5.2.5.4) event fires just after the template is rendered
The OnPropertyChanged (Section 5.5.2.5.5) event fires after a template property has changed.
The OnInit event fires when the CodeSmith engine creates an instance of your template. You can
override this event to perform any necessary setup tasks for your template. For instance, suppose your
template uses an additional TextWriter (Section 9.8) to send a copy of its output to a socket on a
remote computer via the Internet. You could override the OnInit event to check for Internet connectivity,
and warn the user that the template will not succeed if you can't find an open Internet connection when
the template is instantiated.
The OnPreRender event is fired just before the CodeSmith engine merges metadata with your template to
produce the template's output. One use for this event is to perform "sanity checks" on metadata entered
by the user. You could, for example, check that a date entered was within an acceptable range, and
change it to the earliest or latest acceptable date if it is not.
Although you can modify metadata in the OnPreRender event, you cannot prevent the template from
being rendered.
The OnPostRender event is fired after CodeSmith has merged metadata with your template to produce
the output. You can use this event to perform any additional processing you would like after CodeSmith
has finished its job. For example, the StoredProcedures.cst sample template included with CodeSmith
uses this event to autoexecute the generated SQL script (Section 12.1):
protected override void OnPostRender(string result)
{
if (this.AutoExecuteScript)
{
// execute the output on the same database as the source table.
CodeSmith.BaseTemplates.ScriptResult scriptResult =
CodeSmith.BaseTemplates.ScriptUtility.ExecuteScript(
this.SourceTable.Database.ConnectionString,
result,
new System.Data.SqlClient.SqlInfoMessageEventHandler(cn_InfoMessage)
);
Trace.Write(scriptResult.ToString());
}
base.OnPostRender(result);
}
The OnPropertyChanged event is fired after a template property has been modified. You can use this
event to perform any additional processing or validation for the property that has been changed.
<script runat="template">
protected override void OnPropertyChanged(string propertyName)
{
Response.Write(propertyName + "has changed");
base.OnPropertyChanged(result);
}
</script>
The Response property of the CodeTemplate object returns an instance of the CodeTemplateWriter class.
This object represents the actual response stream for the template output. You can write to the stream
programmatically using this property, thus inserting your own output directly into the generated
template. For example:
<%@ CodeTemplate Language="C#" TargetLanguage="Text" Description="This template
demonstrates writing directly to the Response property" %>
<% RenderDirect(); %>
<script runat="template">
public void RenderDirect()
{
Response.WriteLine("Written directly to the Response property.");
Response.WriteLine("Hello " + System.Environment.UserName + "!");
}
</script>
Useful methods of the CodeTemplateWriter class include:
AddTextWriter - Add an additional output destination (Section 9.8)
The Progress object lets you show a progress bar to the template user when CodeSmith is rendering the
template. This is useful when a template takes a long time to render, as it provides a visual cue to the
user that CodeSmith has not ceased responding. If you're using CodeSmith Explorer, the progress bar is
displayed to the left of the Generate button:
If you're using CodeSmith Studio, the progress bar is displayed in the status bar, to the left of the line
and column indicators:
To use the Progress object, you'll typically set the maximum value and the amount of change
represented by one progress step:
this.Progress.MaximumValue = 25;
this.Progress.Step = 1;
Each time you want to increment the progress indicator on screen, you then call the PerformStep
method:
this.Progress.PerformStep();
The CodeTemplateInfo object (available through the CodeTemplateInfo property of the CodeTemplate
(Section 5.5.2.1) object) can be used to retrieve a variety of information about the current template:
Property Returns
CodeBehind Gets the full path to the code-
behind file for the template (or an
empty string if there is no code-
behind file).
ContentHashCode Gets the hash code based on the
template content and all template
dependencies.
CodeSmith User's Guide | 45
CodeSmith Studio provides a complete integrated development environment (IDE) for CodeSmith
templates. You can use CodeSmith Studio to edit, compile, and run CodeSmith templates. The CodeSmith
Studio editor includes features designed to make building and debugging templates easier.
CodeSmith Studio offers a superset of the functionality of CodeSmith Explorer (Section 3.1). When
you just want to execute templates and generate code, you'll find it's faster to use CodeSmith Explorer to
get your work done. But when you have templates under active development, CodeSmith Studio should
be your tool of choice.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
The CodeSmith Studio user interface includes a number of separate elements, each with its own purpose.
CodeSmith User's Guide | 47
Template Windows allow you to edit CodeSmith templates, as well as to view the generated code from
CodeSmith User's Guide | 48
templates and the compiled source code that CodeSmith creates from templates. Each template window
can have up to three tabs:
The Template tab (Section 6.2.2.2) contains the template itself.
The Output tab (Section 6.2.2.3) contains the code generated from the template.
The Compiled Source tab (Section 6.2.2.4) contains the source code that CodeSmith builds from
the template.
You can have multiple template windows open at the same time in CodeSmith Studio. When you do the
tabs at the top of the Template Window are used to switch between different templates, and the tabs at
the bottom of the Template Window are used to switch between different views of the selected template.
In the screenshot below, CodeSmith Studio is displaying the output of the CSSortedList.cst template.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
The Template tab of the Template window is the editing surface of CodeSmith Studio. You can navigate to
the Template tab of the current template by selecting Code from the View menu or by pressing F7.
CodeSmith User's Guide | 49
The CodeSmith Studio Editor includes a wide variety of features to make editing code easier and more
productive. These include:
Syntax color-coding for all supported languages
Easy insertion of CodeSmith directives and blocks
Incremental search
Find and replace with RegEx support
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
The Output tab of the Template window displays the generated code produced by combining the template
with the property values entered by the user in the Properties window. You can navigate to the Output
tab of the current template by selecting Output from the View menu or by pressing F8.
CodeSmith User's Guide | 50
The Output tab will be blank until you have generated code from the current template by selecting Run
from the Tools menu, pressing F5, or clicking the Run toolbar button.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
The Compiled Source tab of the Template window displays the source code that CodeSmith generates
when you build the template. This source code can be useful when you are trying to debug problems with
a template's output. You can navigate to the Compiled Source tab of the current template by selecting
Compiled Source from the View menu.
By default, CodeSmith Studio does not display the Compiled Source tab when you open a template.
CodeSmith User's Guide | 51
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
The Template Explorer provides a list of your CodeSmith templates arranged into folders, similar to the
list that you'll see in CodeSmith Explorer. You can navigate to the Template Explorer by selecting
Template Explorer from the View menu or by pressing Ctrl+Shift+X.
In fact, you'll find all the functionality in Template Explorer that you're familiar with from the standalone
CodeSmith Explorer (Section 3.1). The only difference is that when you right-click a template and
select edit, it will automatically open in CodeSmith Studio even if you have specified a different editor
from the CodeSmith Explorer toolbar (Section 3.2).
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
The Schema Explorer provides a way to explore the schema of databases so that you can retrieve the
names of tables, views, commands, and their components. You can navigate to the Schema Explorer by
selecting Schema Explorer from the View menu or by pressing Ctrl+Shift+D.
CodeSmith User's Guide | 52
2. Click the Add button to open the Data Source dialog box.
CodeSmith User's Guide | 53
3. Enter a name for the new data source, select an appropriate provider, and enter a connection string.
4. Click Test to verify your settings.
5. Click OK to create the new connection.
6. Click Close to close the Data Source Manager.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
6.2.4.1
Extended Properties
Extended Properties are a way to create and customize the metadata from your Schema Provider Types.
A feature new to 4.0, the Schema Explorer provides an easy and graphical way to manage your schema
extended properties inside of CodeSmith Studio.
Read More: Managing Extended Properties through Schema Explorer ('Manage Extended
Properties Through Schema Explorer' in the on-line documentation)
The Properties Window lets you view and edit the property settings for the current template, similar to the
property sheet you can get by invoking Execute from CodeSmith Explorer. You can navigate to the
Properties Window by selecting Properties Window from the View menu or by pressing F4.
Before you can generate code from a template, you must supply values for all of the non-optional
properties in the Properties window. The Properties Window also supplies a shortcut menu that allows you
to work with property set XML files (Section 6.5).
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
The combo box at the top of the Output Window can be used to switch between the Build pane and the
Debug pane.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
6.2.7 Menus
6.2.7.1 Menus
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
New
The New command displays a submenu with four choices:
C# Template
VB Template
JScript Template
Blank Template
Each of these choices creates a new template of the specified type.
If you'd like to modify the default contents of the C#, VB, or JScript templates, you'll find them in the
NewFileTemplates subfolder of your CodeSmith installation.
Open
The Open command opens a File Open dialog box to allow you to load an existing CodeSmith template or
code-behind file.
Save
The Save command saves the current template. If the template has not yet been saved, this command
opens a Save As dialog box to allow you to assign a name to the template. Otherwise, it saves the
template with its existing name.
Save As
The Save As command opens a Save As dialog box to allow you to save the current template with a new
file name.
CodeSmith User's Guide | 55
Save All
The Save All command saves all changes to any files open in CodeSmith Studio.
Close
The Close command closes the current template.
Close All
The Close All command closes all files open in CodeSmith Studio.
Recent Files
The Recent Files command displays a submenu of up to eight files that you have recently loaded in
CodeSmith studio. Select a file from the menu to reload it.
Save As HTML
The Save As HTML command opens a Save As dialog box to allow you to save the current template as an
HTML file.
Save As RTF
The Save As RTF command opens a Save As dialog box to allow you to save the current template as a
Rich Text Format (RTF) file.
Print
The Print command opens the Print dialog box to allow you to print the current template.
Page Setup
The Page Setup command opens the Page Setup dialog box to allow you to set margins and other
properties of the printed output.
Print Preview
The Print Preview command displays the current template in a Print Preview window.
Exit
The Exit command closes CodeSmith Studio. If you have unsaved changes in any open files, you will be
prompted to save those changes.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
Undo
The Undo command reverses the effects of the most recent editing operation.
Redo
The Redo command reverses the effects of the most recent Undo command.
Cut
The Cut command removes the selection from the active window and places it on the Windows clipboard.
Copy
The Copy command places the selection from the active window on the Windows clipboard.
Paste
The Paste command replaces the selection in the active window with the current contents of the Windows
clipboard.
Delete
The Delete command deletes the selection from the active window.
CodeSmith User's Guide | 56
Select All
The Select All command selects the entire contents of the active window.
Find/Replace
The Find/Replace command opens the Find and Replace (Section 6.3.5) dialog box:
Go to Line
The Go to Line command opens the Go To Line dialog box:
Enter a line number and click OK to position the cursor on that line in the active window.
If the specified line is in a collapsed block, the block will be expanded.
Advanced
The Advanced command displays a submenu with nine commands:
Bookmarks
The Bookmarks command displays a submenu with four commands:
If the current line already has a bookmark, the Toggle Bookmark command removes the bookmark.
Bookmarks are not saved with CodeSmith templates. When you close a template, all bookmarks are
automatically cleared.
Outlining
The Outlining command displays a submenu with four commands:
Insert Content
CodeSmith User's Guide | 58
The Insert Content command displays a submenu with 11 commands designed to help you write
templates more quickly:
</script>
Code
The Code command displays the Template tab (Section 6.2.2.2) of the current template window.
Output
The Output command displays the Output tab (Section 6.2.2.3) of the current template window.
Compiled Source
The Compiled Source command displays the Compiled Source tab (Section 6.2.2.4) of the current
template window.
Template Explorer
The Template Explorer command moves the focus to the Template Explorer (Section 6.2.3) window.
Schema Explorer
CodeSmith User's Guide | 59
The Schema Explorer command moves the focus to the Schema Explorer (Section 6.2.4) window.
Properties Window
The Properties Window command moves the focus to the Properties window (Section 6.2.5).
Output Window
The Output Window command moves the focus to the Output window (Section 6.2.6).
Web Browser
The Web Browser command opens a submenu with four commands:
Build
The Build command compiles the current template. The Output window (Section 6.2.6) will show the
results of the build operation.
Run
The Run command executes the current template, using values from the Properties window (Section
6.2.5) together with the template to create the generated code. At the end of the Run operation,
CodeSmith Studio will display the generated code in the Output tab (Section 6.2.2.3).
Copy Output
The Copy Output command copies the contents of the current Output tab to the Windows clipboard.
Save Output
The Save Output command opens a Save As dialog box to let you save the contents of the current Output
tab directly to a new file.
Compile to Assembly
The Compile To Assembly command opens the Compile to Assembly dialog box:
Fill in an assembly name, namespace name, and type name, and click OK to create the assembly.
CodeSmith will output a .dll which you can then reference from any .NET project. You will then be able to
create an instance of your compiled template by using the type name that you specified. You can then set
CodeSmith User's Guide | 60
the properties on the template via code and call the Render or RenderToFile methods to execute the
template.
You can select any language in the current template from the Languages combo box. After you select a
language, select any style from the listbox and use the controls on the right side of the dialog box to
specify how CodeSmith should display that item in the editor.
Options
The Options command displays the Options dialog box (Section 6.6) so that you can customize the
CodeSmith Studio editor.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
Split Window
The Split Window command splits the current window into two panes, one above the other.
Dockable
The Dockable command toggles tool windows (Template Explorer, Schema Explorer, Properties Window,
and Output Window) between their normal mode and acting like tabs in the editor. For example, if you
select the Template Explorer window and then select the Dockable command on the Window menu,
Template Explorer will become a tab in the main editing area:
CodeSmith User's Guide | 61
To return a tool window from a tab to its normal mode, select the Dockable command a second time.
The Dockable command has no effect on other windows.
Hide
The Hide command removes a tool window (Template Explorer, Schema Explorer, Properties Window, or
Output Window) from the editor. To return the window to the editor, choose the appropriate command on
the View menu (Section 6.2.7.4). The Hide command has no effect on other windows.
Floating
The Floating command undocks a tool window (Template Explorer, Schema Explorer, Properties Window,
or Output Window) from the editor shell and lets it float free. A floating window can be moved anywhere,
including outside of the CodeSmith Studio window entirely.
To return a floating window to its docked state, right-click on the floating window's title bar and
uncheck the Floating item on the shortcut menu. Alternatively, select Options from the Docking menu
and click the Reset Docking Layout button on the Options dialog box (Section 6.6).
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
CodeSmith Help
The CodeSmith Help command opens this help file.
CodeSmith Website
The CodeSmith Website command opens a Web browser tab inside of CodeSmith Studio and loads the
CodeSmith Website (http://www.codesmithtools.com/).
Fill in the details and click Send to send your bug report directly to CodeSmith.
You can also search previously entered items by entering your text into the above dialog. To add your
CodeSmith User's Guide | 64
Click the Check for Updates link to find out whether a newer version of CodeSmith has been released.
Click the Deactivate button to deactivate your license.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
New Document. Clicking this button creates a new blank template. Alternatively, you can use the
dropdown arrow to select a particular template type (C#, VB, or JScript) to create.
Open Document. Clicking this button opens a File Open dialog box to allow you to load an existing
CodeSmith template or code-behind file.
Save Document. Clicking this button saves the current template. If the template has not yet been
saved, this command opens a Save As dialog box to allow you to assign a name to the template.
Otherwise, it saves the template with its existing name.
Save All Documents. Clicking this button saves all changes to any files open in CodeSmith Studio.
Cut. Clicking this button removes the selection from the active window and places it on the Windows
clipboard.
CodeSmith User's Guide | 65
Copy. Clicking this button places the selection from the active window on the Windows clipboard.
Paste. Clicking this button replaces the selection in the active window with the current contents of
the Windows clipboard.
Undo. Clicking this button reverses the effects of the most recent editing operation. The
dropdown arrow lets you select multiple operations to undo at one time.
Redo. Clicking this button reverses the effects of the most recent Undo command. The dropdown
arrow lets you select multiple operations to redo at one time.
Decrease Indent. Clicking this button removes a tab character from the start of the selection.
Increase Indent. Clicking this button inserts a tab character at the start of the selection.
Build. Clicking this button compiles the current template. The Output window (Section 6.2.6) will
show the results of the build operation.
Run. Clicking this button executes the current template, using values from the Properties window
(Section 6.2.5) together with the template to create the generated code. At the end of the Run
operation, CodeSmith Studio will display the generated code in the Output tab (Section 6.2.2.3).
Copy Output. Clicking this button copies the contents of the current Output tab to the Windows
clipboard.
Save Output. Clicking this button opens a Save As dialog box to let you save the contents of the
current Output tab directly to a new file.
Insert Content. Clicking this button inserts standard blocks such as code blocks or script blocks.
Use the dropdown arrow to select the block that you want to insert, or click the button to repeat the last
insert operation.
Toggle Bookmark. Clicking this button inserts a visible bookmark to the left of the current line. If the
current line already has a bookmark, the Toggle Bookmark command removes the bookmark.
Next Bookmark. Clicking this button moves the cursor to the start of the next line in the current file
that is marked with a bookmark. The search "loops around" to the top of the file if it reaches the bottom
of the file.
Previous Bookmark. Clicking this button moves the cursor to the start of the previous line in the
current file that is marked with a bookmark. The search "loops around" to the bottom of the file if it
reaches the top of the file.
Clear Bookmarks. Clicking this button moves the cursor to the start of the previous line in the
current file that is marked with a bookmark. The search "loops around" to the bottom of the file if it
reaches the top of the file.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
The CodeSmith Studio editor is a modern, full-featured IDE with advanced capabilities that rival those of
Visual Studio .NET. Features of the editor include:
Bookmarks (Section 6.3.2)
Bracket highlighting (Section 6.3.3)
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
6.3.2 Bookmarks
Bookmarks provide a way for you to easily navigate between scattered sections of your code. You can
manipulate bookmarks using the Bookmarks submenu of the Edit menu, using buttons on the CodeSmith
Studio, or using keyboard shortcuts.
If the current line already has a bookmark, the Toggle Bookmark command removes the bookmark.
Bookmarks are not saved with CodeSmith templates. When you close a template, all bookmarks are
automatically cleared.
When the cursor is in front of a bracket, the editor will outline both that bracket and the corresponding
open or close bracket:
CodeSmith User's Guide | 67
Content Insertion is available from the Insert Content submenu of the Edit menu or from the Insert
</script>
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
Type Ctrl+F or Ctrl+H to open the Find and Replace dialog box:
Enter the text that you wish to find in the Find What textbox.
Enter the text that you wish to replace the found text with in the Replace With textbox.
To limit your search to an exact case match, check the Match Case checkbox. Otherwise, text will
match regardless of case.
To limit your search to whole word matches, check the Match Whole Word checkbox. Otherwise, text
will match in partial words.
To search from the current cursor position to the top of the file, check the Search Up checkbox.
Otherwise, the search will be from the current cursor position to the end of the file.
To search hidden text, check the Search Hidden Text checkbox. Otherwise, only text in currently
expanded regions will be searched.
To search only currently-selected text, check the Search in Selection checkbox. Otherwise, all text
from the cursor position to the start or end of the file will be searched.
To mark found or replaced text in the left margin, check the Mark with Bookmarks checkbox
To search using regular expressions, check the Use checkbox and select Regular Expressions. You can
use the following regular expression syntax:
. Any single
character
* Zero or more
+ One or more
^ Beginning of line
$ End of line
\b Word boundary
\s White space
\n Line break
| Or
CodeSmith User's Guide | 69
\ Escape special
character
To search using wildcards, check the Use checkbox and select Wildcards. You can use the following
wildcard syntax:
* Zero or more of
any character
To replace the next match in the file, click the Replace button.
To replace all matches in the file, click the Replace All button.
To insert bookmarks at all matches in the file, click the Mark All button.
To close the dialog box, click the Close button.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
Incremental search can be activated from the Advanced submenu of the Edit menu, or by pressing Ctrl+I
(for forward incremental search) or Ctrl+Shift+I (for backward incremental search). The cursor icon
changes to a binocular with an arrow indicating the search direction.
Begin typing the text that you want to search for. As you type, the editor highlights the first occurrence
that matches the text. As you continue typing, the editor moves to the next match and highlights it. If no
matches are available, the highlight will stop moving.
During incremental search, the following special keys are active:
Key Meaning
Key Command
Ctrl+X, Cut
Shift+Del
CodeSmith User's Guide | 70
Ctrl+V, Paste
Shift+Ins
Ctrl+Z Undo
Ctrl+Y, Redo
Ctrl+Shift+Z
Ctrl+Down Scroll down
Ctrl+Up Scroll up
Shift+Up Select up
Ctrl+P Print
Ctrl+G Go to line
F7 View code
F8 View output
Ctrl+Shift+X View Template Explorer
Ctrl+Shift+B Build
F5 Run
F9 Copy output
Lines of code that have been edited during the current session are indicated with a yellow line in the left
margin of the editor:
When you save the file, the yellow markers turn green. Thus at any time, yellow markers show changed
but unsaved lines of code, and green markers show changes in this session that have been saved.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
6.3.9 Outlining
Outlining provides a way to hide detail in your code until you want it.
Outlining in CodeSmith is of two types: automatic and manual. By default, CodeSmith automatically
creates outline blocks for every script block, property, enumeration, and object in your code. You can
disable automatic outlining from the Outlining submenu of the Edit menu. You can also create manual
outline blocks by inserting #region and #endregion (or in VB, #region and #end region) lines in your
code.
To collapse an outline block, click the minus sign at the left margin of the block or place the cursor in the
block and press Ctrl+M. To expand an outline block, click the plus sign at the left margin of the block or
place the cursor in the block and press Ctrl+M.
In this code, CodeSmith has automatically created outline blocks for the script block and the function, and
CodeSmith User's Guide | 72
Clicking the minus sign to the left of the script block collapses the entire outline, and shows the script
block grayed out. If you hover the mouse over the collapsed outline, CodeSmith Studio will display a
tooltip with the first few lines of the code contained within the collapsed block:
Expanding the script block and then collapsing the region displays the text after the #region keyword:
Expanding the region and collapsing the function displays the function name but not its argument list:
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
CodeSmith User's Guide | 73
Statement completion is very similar to the IntelliSense feature of Visual Studio. With Statement
Completion, CodeSmith Studio prompts you with member names as you type:
The dropdown list of members appears as soon as you type the dot after an object name. To select a
member, click it with the mouse or select it with the arrow keys or by typing enough letters to uniquely
identity it and then type a space or other separator character.
Statement completion depends on reflection to gather the information that it presents. This means that
your template must compile successfully for statement completion to work on types defined in the
template. Types defined in an external assembly will show up in the statement completion lists whether
the current template compiles or not.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
The CodeSmith Editor provides you with two ways to edit in multiple locations at the same time. Tab
groups allow you to open two or more files for editing. Split windows allow you to have two editing panes
open in to the same file at the same time.
Tab Groups
To create a tab group, select New Horizontal Tab Group or New Vertical Tab Group on the Window menu
(Section 6.2.7.6). Alternatively, click and hold the mouse cursor on an existing tab at the top of an open
code window, and drag the tab down into the code-editing area. When you drop the tab, the shortcut
menu will offer you the choice of creating a new vertical tab group or a new horizontal tab group. In any
case, the active tab when you perform the operation will become the first tab in the new tab group.
You can move a tab from one tab group to another tab group by dragging and dropping the tab. You can
also create additional tab groups by repeating the process that creating the initial tab group. However, all
tab groups must be of the same type; you cannot mix horizontal and vertical tab groups. If you close or
remove the last tab in a tab group, CodeSmith Studio will eliminate the tab group.
Split Windows
To create a split window, select Split Window from the Window menu (Section 6.2.7.6), or grasp the
splitter handle at the top of the vertical scroll bar with the mouse and drag it downwards. The result will
be a single window with two panes, both of which open on the same file:
CodeSmith User's Guide | 76
You can scroll and edit in the two panes of a split window independently. Because the two panes are both
views into the same underlying file, any changes in one pane are immediately reflected in the other pane.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
CodeSmith Studio allows you to build, run, and compile your templates.
Building Templates
To compile the current template, select Build from the Tools menu (Section 6.2.7.5), or press
Ctrl+Shift+B, or click the Build button on the toolbar (Section 6.2.8). The Output window (Section
6.2.6) will show the results of the build operation.
Running Templates
To run the current template, select Run from the Tools menu (Section 6.2.7.5), or press F5, or click
the Run button on the toolbar (Section 6.2.8). This will execute the current template, using values
from the Properties window (Section 6.2.5) together with the template to create the generated code.
At the end of the Run operation, CodeSmith Studio will display the generated code in the Output tab
(Section 6.2.2.3).
Compiling Templates
To compile a template, select Compile To Assembly from the Tools menu (Section 6.2.7.5). This will
open the Compile to Assembly dialog box:
CodeSmith User's Guide | 77
Fill in an assembly name, namespace name, and type name, and click OK to create the assembly.
CodeSmith will output a .dll which you can then reference from any .NET project. You will then be able to
create an instance of your compiled template by using the type name that you specified. You can then set
the properties on the template via code and call the Render or RenderToFile methods to execute the
template.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
CodeSmith can store all of the property settings for a given template in an XML file known as a property
set XML file. CodeSmith Studio provides commands for working with property set XML files on the
shortcut menu for the Properties Window (Section 6.2.5). This menu contains six items:
Copy Template Values. Copies the settings from the property sheet to the Windows clipboard as a
CodeSmith Project file.
Paste Template Values. Pastes the current settings from the Windows clipboard to the property sheet.
Save Template Values. Opens a Save As dialog box to let you save the settings from the property sheet
as an CodeSmith Project file.
Load Template Values. Opens a File Open dialog box to let you select an existing CodeSmith Project
file. The settings will be loaded into the property sheet.
Reset. Resets the property sheet to its default settings.
Description. Toggles the description display at the bottom of the Properties Window on or off.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
There are several ways that you can customize CodeSmith Studio:
You can customize the behavior and placement of the various tool windows using mouse operations or
the commands on the Window menu (Section 6.2.7.6).
You can customize the color choices in the editor by selecting the Highlighting Style Editor command
on the Tools menu (Section 6.2.7.5).
You can change many editor settings by selecting the Options command on the Tools menu
(Section 6.2.7.5):
CodeSmith User's Guide | 78
The Options dialog box allows you to change the following settings:
Font: Select the font to use in all editor windows.
Size: Select the font size to use in all editor windows.
Enable Unicode Support: Check this checkbox to enable the display of Unicode characters.
Show Line Numbers: Check this checkbox to display line numbers to the left of each line of code.
Convert Tabs to Spaces: Check this checkbox to convert each tab to spaces automatically.
Tab Size: Select the number of spaces to be used for each tab on screen.
Bracket Matching: Check this checkbox to enable the bracket highlighting (Section 6.3.3) feature.
Outlining: Check this checkbox to enable the outlining (Section 6.3.9) features.
Indentation Guides: Check this checkbox to display light vertical lines each time you indent code
Line Modification Markers: Check this checkbox to enable line modification markers (Section
6.3.8).
Auto Collapse Regions: Check this checkbox to ????
Enable Output Editing: Check this checkbox to allow editing the contents of the Output tab (Section
6.2.2.3).
Highlight Current Line: Check this checkbox to show a highlight behind the line where the cursor is
currently located.
Auto Save on Compile: Check this checkbox to save the template each time it is compiled.
Close Start Page on File Open: Check this checkbox to close the Start Page as soon as you open any
file.
Show Start Page at Startup: Check this checkbox to show the Start Page when you launch CodeSmith
Studio.
Code Behind Option: Select an option for the treatment of code-behind pages associated with
templates.
Auto Copy Output to Clipboard: Check this checkbox to copy the contents of the Output tab
(Section 6.2.2.3) to the Windows clipboard whenever you run a template.
Display Semantic Information: Check this checkbox to display semantic information about the current
cursor location in the status bar.
Enable IntelliPrompt: Check this checkbox to turn on Statement Completion (Section 6.3.10).
CodeSmith User's Guide | 79
Enable IntelliPrompt Summaries (slow): Check this checkbox to have CodeSmith parse the XML
comment summaries for methods and properties and display them in tooltips with statement
completion.
Enable Compiled Source: Check this checkbox to always show the compiled source tab of a template
document.
Check File Associations: Check this checkbox to have CodeSmith Studio ensure that it is the
registered handler for its file types at startup.
Display Splash Screen On Startup: Check this checkbox to display the splash screen when you launch
CodeSmith Studio.
Reset File Associations: Click this button to make CodeSmith Studio the registered handler for its file
types.
Restore Defaults: Click this button to restore the default settings in the Options dialog box.
Reset Docking Layout: Click this button to restore all of the tool windows to their original position,
docking, and autohide status.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
6.7.1 Introduction
A CodeSmith Map provides an easy way to manage dictionary maps for doing word translation lookups in
code. This used to be a a frequent and cumbersome challenge that a template writer must face when
trying to map types from disparate systems. A prime example is working from data types from
an RDBMS which don't match those of the programming language you are writing for. Typically, what
happens is the template writer would have to create a long switch case statement for every lookup.
Example:
Example:
The map depicted to the right is a map of fully qualified system types
to their C# language keyword type.
Name:
The map name is also the filename so consider choosing a name that is fairly
descriptive of what the map's intent is.
NOTE: When CodeSmith attempts to discover a map by name, it first looks in the
configuration directories, the template directories and you can also give it a
relative or full path.
Description:
A description field of what the maps intent is for.
Return Key:
The return key check box indicates whether or not to return the original key from the map if the key is
not found within the map. This is important because there can be many situations where there might not
be an entry for the key and it's value, but you would still like the key returned instead of null.
Example:
In the image to the left, it's converting a fully qualified type to it's C# equivalent keyword. In cases
where one doesn't exist, such as System.DateTime or System.Guid, you could still use the original
key, System.DateTime, which would be completely valid.
Case Sensitive:
The Case sensitive check box determines whether or not to search for the key and consider case
sensitivity. Often, word dictionaries do not require case sensitivity since most use keys that are unique
by name.
Find More:
Launches a browser session to browse the online gallery of community collaborated maps.
Reverse Map:
Call the overloaded Load method when requiring to load the map with the key value pairs swapped.
NOTE: See the CodeSmith API help for more API Coverage.
A great new feature of CodeSmith is cached property set values for each template you open up in
CodeSmith. This feature gives the ability to persist property set (Section 2.3.2.4) values from one
CodeSmith session to the next for that particular template. This includes when you change a template,
recompile a template, close and re-open CodeSmith.
CodeSmith Project
A new feature in CodeSmith 4.0 is the ability to manage groups of CodeSmith templates and their outputs
all in a single CodeSmith Project file. CodeSmith Projects are files that enable you to run an entire
generation process at anytime in a simplistic manner from many different environments.
7.1.1 About
A CodeSmith Project file uses a .csp file windows extension, and stores XML metadata about your
CodeSmith Project.
See: Anatomy of a CodeSmith Project File (Section 7.6)
7.1.2
Generation Capabilities
CodeSmith Project files enable the management and execution of a generation process in many
environments.
Managing a CodeSmith Project right from Windows Explorer is simple and doesn't
require you to use CodeSmith Studio to manage a project. Options are available
through the right-click context menu your CodeSmith Project file (.csp).
Windows
Explorer The menu options include:
(Section 7.4) 1. Generate Outputs (Section 7.8)
2. Manage Outputs (Section 7.7)
3. Add Outputs (Section 7.7)
You can Generate Outputs of a CodeSmith Project in the command line by using the
Command-Line CodeSmith Console application.
(Section 11.2) You would simply call:
cs MyCodeSmithProject.csp
The tight integration with Visual Studio allows you to fully manage any CodeSmith
Project right from Visual Studio! To manage a CodeSmith Project, you can use the
Right-Click context menu of a CodeSmith Project file from the Solution Explorer
window.
The menu options include:
1. Generate Outputs (Section 7.8)
Visual Studio
(Section 4.3) 2. Manage Outputs (Section 7.7)
3. Add Outputs (Section 7.7)
4. Output Options
You can use ActiveGeneration quite easily in your Visual Studio projects now, simply
by specifying the BuildAction of your CodeSmith Project. Setting the BuildAction =
"Generate" in the properties of you CodeSmith Project file in the Solution Explorer will
cause your entire build process to occur prior to your project building.
To manage a CodeSmith Project, you can use the Right-Click context menu of a
CodeSmith Project file from the CodeSmith's Template Explorer window.
CodeSmith The menu options include:
Studio (Section
1. Generate Outputs (Section 7.8)
7.3)
2. Manage Outputs (Section 7.7)
3. Add Outputs (Section 7.7)
CodeSmith projects can be manually expected from your MSBuild project file by
executing:
<CodeSmith ProjectFile="MyProject.csp" />
CodeSmith User's Guide | 84
When you set the BuildAction to Generate in Visual Studio, you're actually using the
CodeSmithGenerate Target, located in:
{{Program Files}}\MSBuild\CodeSmith\CodeSmith.targets
MSBuild (Section You can import this target in your Visual Studio Projects by using the Import tag.
7.5)
<Import Project="$(MSBuildExtensionsPath)
\CodeSmith\CodeSmith.targets" />
7.2.1 Introduction
The tight integration with Visual Studio allows you to fully manage any CodeSmith Project right from
Visual Studio! This means you can maintain a high Code Generation presence right within Visual Studio
and not have to switch applications to run code generation.
1. Add Outputs To Project - Will take any outputs from your CodeSmith Project and include
them in your Visual Studio project.
2. Hide Outputs - will take any outputs of your CodeSmith Project and make them child nodes,
dependant on your CodeSmith Project file (shown below). Hidden nodes can be collapsed,
and since much of the time generated code shoudln't be touched, it's a great way to hide the
temptation of other developers attempting to modify the generated code.
3. Generate On Build - A menu driven way to have your templates use Active Generation. You
can also specify the BuildAction value in the property sheet of your CodeSmith Project. (more
below)
Example:
We have a BusinessObject.csp CodeSmith Project in our class library Visual Studio project. This CSP has 4
outputs, that generate from the same BusinessObject.cst CodeSmith template.
Order.cs
Product.cs
Profile.cs
Supplier.cs
Looking into the properties of the CodeSmith Project, you can view the Build Action of the file, and there
is an option to set it to Generate on Build. Meaning every time you need to tweak your Database meta-
data, XML Property meta-data, or CodeSmith template, the changes are picked up in your Visual Studio
project the very next time you build.
This enables you to alleviate much of the frequent developer problems with making changes across all of
your classes, during the development process.
To get your template to support this, you'll need to update the template to use the RenderToFile overload
that takes a parent file. Next, add the CodeSmith Project to the Visual Studio project and Generate
Outputs. CodeSmith will automaticly add the outputs to your Visual Studio project creating the hierarchy.
Sample Template Code
//Create Sub template using the Create method to automaticly wire everything up
EntityGeneratedClass entityClass = this.Create<EntityGeneratedClass>();
EntityEditableClass partialClass = this.Create<EntityEditableClass>();
7.3.1 Introduction
The tight integration with CodeSmith Studio allows you to fully manage any CodeSmith Project right from
CodeSmith Studio, along with Windows Explorer and Visual Studio!
7.4.1 Introduction
A CodeSmith Project gives you the ability to control all aspects of your CodeSmith project from Windows
Explorer. This is extremely useful because it does not require you to launch CodeSmith Studio, just to
manage your projects, change or add outputs, etc. This type of flexibility make using a CodeSmith
Project very useful.
7.4.2
CodeSmith Projects from Windows Explorer
CodeSmith Projects expose a right-click context menu from within Windows Explorer.
The menu options include:
1. Generate Outputs (Section 7.8)
2. Manage Outputs (Section 7.7)
3. Add Outputs (Section 7.7)
7.5.1 Introduction
You can create your own custom pre-generation build logic by utilizing the CodeSmith Task within
MSBuild. MSBuild tasks help manage the build process within your Visual Studio projects.
7.5.2
Why would I want to roll my own when you integrate it with Visual Studio?
There might be times when you need to customize some aspect of the generation process during it's
consuming build process. During these time you might have to call CodeSmith from Ms-Build using the
CodeSmith task that's shipped for you.
7.5.3
CodeSmith MSBuild Targets
An MSBuild target file is used to define your own tasks during the build process. CodeSmith ships their
own targets file which defines all the capabilities of using generating CodeSmith Projects during the
generation process. The CodeSmith.targets file defines how to use the Generate BuildAction from your
Generate Items and also defines how to call CodeSmith with your CodeSmith Project file and run the
generation process.
NOTE: When you set the BuildAction to Generate in Visual Studio, you're actually using the
CodeSmithGenerate Target and set the project item to use the Generate Build Task.
7.5.4 Configuration
In order to use the CodeSmith Generation task you must import the CodeSmith.targets file for usage in
your Ms-Build Project file.
CodeSmith User's Guide | 90
You can import this target in your Visual Studio Projects by using the Import tag in your Visual Studio
Project file.
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003 ">
...
7.5.5 Generate
CodeSmith projects can be manually executed from your MS-Build project file by executing:
<CodeSmith ProjectFile="MyProject.csp" />
In this example we will be showing how to call a custom CodeSmith Project that will generate necessary
meta-data prior to building in release mode.
Example:
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003
">
...
<Import Project="$(MSBuildExtensionsPath)\CodeSmith\CodeSmith.targets "/>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets "/>
<Target Name="BeforeBuild" Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<CodeSmith ProjectFile="GenerateMetaData.csp" />
</Target>
...
</Project>
7.5.6 Usage
The CodeSmith Task exposes a few properties to assist you in your CodeSmith tasks.
ProjectFiles - is the property that can accept a single or ";" separated values of names of CodeSmith
Projects that will be used for Code Generation.
Example:
<CodeSmith ProjectFile="GenerateMetaData.csp;GenerateIndex.csp"/>
OutputFiles - is the property that specifies all of the OutputFiles specified in your CodeSmith Project
files.
Verbose - a boolean property that indicates whether or not to receive verbose messages.
Debug - a boolean property that indicates if the templates should be compiled in debug mode.
You can also specify your own templates to run during this custom build process by using the CspFiles
tag. This will let you specify your items in an ItemGroup and pass them all into ProjectFiles.
Example:
<ItemGroup>
<CspFiles Include="MyProject.csp" />
<CspFiles Include="MyOtherProject.csp" />
</ItemGroup>
<Target Name="Build">
<CodeSmith ProjectFiles ="@(CspFiles)" />
</Target>
(http://msdn.microsoft.com/msdnmag/issues/06/06/InsideMSBuild/default.aspx).
Every CodeSmith Template uses a Property Sheet (Section 6.2.5) that help drive template meta data
in your generation process. When the property sheet is saved, it is saved as a Property Set, an XML
serialized version of your properties and their values. Saving an XML version enables you easily recover
all of the options you designated while configuring your Property Sheet when this file was created.
Header
The XML Header specifies the current XML Schema Definition for a CodeSmith Project. The codeSmith
node also encapsulates the entire body of the codeSmithProject XML Files.
<?xml version="1.0"?>
<codeSmith xmlns="http://www.codesmithtools.com/schema/csp.xsd">
This csp.xsd can be found at {{INSTALL DIR}}/Schemas/csp.xsd
Defaults
Default Template - You can configure a CodeSmith Project to use Default Template, when configured,
each of the Property Sets that do not have a Template assigned to them will automatically use the Default
Template to execute and run.
<defaultTemplate path="businessobject.cst" />
Default Properties - You can configure default properties to use within your CodeSmith Project. These
properties are available to all of the templates assigned within your CodeSmith Project. These are
especially useful to define properties that are fairly static in nature.
<defaultProperties>
<property name="ClassNamespace">CompanyName.RootNamespace</property>
</defaultProperties>
Variables
The CodeSmith Project supports variables that can be used in the property sets. Variables are an easy
way to have a common piece of data that is stored in only one place.
You can edit the CodeSmith Project manually to place variables. The variable for format is its name
surrounded by $(), ie, $(ConnectionString1).
<variables>
<add key="ConnectionString1" value="Data Source=(local);Initial Catalog=PetShop;Integrated Securit
<add key="ProviderType" value="SchemaExplorer.SqlSchemaProvider,SchemaExplorer.SqlSchemaProvider"
</variables>
Property Sets
For every template output you will see the associated PropertySet and it's output. The PropertySet may
or may not have a template defined, if it does not, it will use the default template value for generation.
The Properties defined within each of the property sets are specific to this Output and are not shared with
any other Outputs.
CodeSmith User's Guide | 92
<propertySets>
<propertySet output="Product.cs">
<property name="SourceTable">
<connectionString>Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Petshop.mdf;</connectionString>
<providerType>SchemaExplorer.SqlSchemaProvider,SchemaExplorer.SqlSchemaProvider</providerType>
<table>
<owner>dbo</owner>
<name>Product</name>
</table>
</property>
</propertySet>
<propertySet output="Order.cs">
<property name="SourceTable">
<connectionString>Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Petshop.mdf;</connectionString>
<providerType>SchemaExplorer.SqlSchemaProvider,SchemaExplorer.SqlSchemaProvider</providerType>
<table>
<owner>dbo</owner>
<name>Orders</name>
</table>
</property>
</propertySet>
</propertySets>
Selecting the ability to add or edit an Output, you are able to configure the all aspects of an Output.
There are four panels that cover all of the options for configuring an Output. Below is the entire Add/Edit
Output Form.
7.7.5
Choose a Template
If a Template has been configured from in the Main Manage Outputs screen, then you will see the
template name listed under the Use Default Template option. Otherwise, you will have a File Chooser
control to select your template that you want the output to be generated from.
Details - Toggle Details Button for verbose progress and feedback of your generation process.
Close - Closes the window.
7.9.4 Variables
The CodeSmith Project supports variables that can be used in the property sets. Variables are an easy
way to have a common peace of data that is stored in only one place.
When saving a CodeSmith Project in the Manage Output dialog, the CodeSmith Project will automatically
create variables for all the unique connection strings in the project. This allows for easy updating of the
connection string for complex projects.
<?xml version="1.0"?>
<codeSmith xmlns="http://www.codesmithtools.com/schema/csp.xsd">
<singleOutput enabled="true" path="Data.cs" />
<variables>
<add key="ConnectionString1" value="Data Source=(local);Initial Catalog=PetShop;Integrated Secur
<add key="ProviderType" value="SchemaExplorer.SqlSchemaProvider,SchemaExplorer.SqlSchemaProvider"
</variables>
<defaultProperties>
<property name="DbmlFile">PetShop.dbml</property>
</defaultProperties>
<propertySets>
<propertySet name="Dbml" template="CSharp\Dbml.cst">
<property name="IncludeViews">False</property>
<property name="IncludeFunctions">False</property>
<property name="EntityBase">LinqEntityBase</property>
<property name="DisableRenaming">False</property>
<property name="SourceDatabase">
<connectionString>$(ConnectionString1)</connectionString>
<providerType>$(ProviderType)</providerType>
</property>
<property name="EntityNamespace">PetShop.Data</property>
<property name="ContextNamespace">PetShop.Data</property>
</propertySet>
<propertySet name="Entities" template="CSharp\Entities.cst">
<property name="IncludeDataContract">True</property>
<property name="OutputDirectory">PetShop\PetShop.Data</property>
</propertySet>
</propertySets>
</codeSmith>
CodeSmith User's Guide | 100
8 Using ActiveSnippets
8.1.1 Introduction
CodeSmith 4.0 delivers strong integration within Visual Studio and ActiveSnippets are a driver toward
increasing developer productivity. ActiveSnippets, at a high level, are CodeSmith templates with
exposure to the entire .Net Framework which you can utilize with a few keystrokes inside of Visual
Studio. The output of your ActiveSnippet will be rendered right where you expanded on the code editor.
NOTE: Visual Studio currently offers support for simple template based snippets. This is a great feature
for simple snippets of code, however these templates do not contain any advanced logic or access to rich
meta-data. For simple snippets such as creating a simple property shell without any logic, we still
recommend using the Visual Studio snippet.
Requirements:
My required output needs to look like this for every column in a table.
private int _orderId;
public int OrderId
{
get { return _orderId; }
set { _orderId = value; }
}
Steps:
1. Iterate through the Columns (ColumnSchemaCollection) of the template property SourceTable
(TableSchema).
2. Create both a field and a property to encapsulate the column.
3. Use a CodeSmith Map to get the correct type for the field and property.
4. Ensure my field is CamelCased and my Property Name is PascalCased.
Template:
Ensure that the template compiles and runs fine from CodeSmith Studio/Explorer before trying to use it in
Visual Studio.
CodeSmith User's Guide | 101
ActiveSnippet Options
Syntax
Calling an ActiveSnippet is easy. Once configured (see Configuring ActiveSnippets), you simply have to
enter the alias or name along with any argument parameters.
Example:
alias param1, param2
You can also access an ActiveSnippet by referring to it's full name.
You can use complex objects, such as a TableSchema by referring to it's fully qualified name
Petshop.dbo.Orders
NOTE: An ActiveSnippet will always have to be compiled the first time prior to being executed.
Notable Information
Notable Information
Executing Usage with no alias on the editor will display all ActiveSnippets.
Executing Usage using part of the prefix, will display a list of all ActiveSnippets starting with that
prefix
For Example, using "t" by itself will show a list of all ActiveSnippets beginning with a "T".
Template:
The full path
to the
CodeSmith User's Guide | 104
CodeSmith
template.
Alias:
The ActiveSnippet Alias is the command to be used as the alias representing the selected CodeSmith
template.
Description:
Specifies the friendly name description of the ActiveSnippet. It will be shown during the Output Usage
information.
Target Extensions:
The template target language is used as a hint for ActiveSnippets that have the same name.
Template Language:
The template language shows the selected CodeSmith Template Output Language.
Arguments Box:
A window of all the arguments that will be required to use your ActiveSnippet.
Example:
Given a template with two properties, SourceTable, UseCamelCasing.
SourceTable is a TableSchema property used as the base meta-data object to use for the template.
UseCamelCasing is a boolean property representing whether or not to use CamelCasing for the field.
You would then only really want to expose SourceTable as a required argument since UseCamelCasing is
a fairly static property that only changes by developer style preference.
IMPORTANT:
Values that
you want to
be required
properties for
ActiveSnippet
arguments
would not be
filled in as a
default value.
Example:
Using the example above, I would set the value of UseCamelCasing since it's a static property value.
CodeSmith User's Guide | 106
When you're writing a CodeSmith template, you're dealing with two distinct kinds of code:
1. The code being generated
2. The scripting code that controls the generation process
As far as CodeSmith is concerned, the first of these is just text, and can be any language at all: VB, SQL,
Fortran, COBOL, Esperanto...as long as it can be represented by a string of characters, CodeSmith can
generate it. This generated code is stored in the CodeSmith templates, and copied at runtime to the
output file, or created on the fly by CodeSmith.
The scripting code is both more and less limited than the generated code. It's more limited in that it can
only be VB, C#, or JScript code. But it's less limited in that you have two choices about where to store it.
You can either mix it in to the template directly, storing it in <script> blocks, or you can store it in
separate code behind files. A code behind file is a source code file containing nothing but scripting code
that's attached to a template file by use of attributes within the CodeTemplate directive (Section 5.1).
For example, here's a template that makes use of a code behind file:
<%@ CodeTemplate Src="VBCodeBehind.cst.vb" Inherits="UtilityCodeTemplate" Language="VB"
TargetLanguage="VB" %>
<%@ Property Name="ClassName" Type="System.String" Category="Options" Description="The
name of the generated class." %>
' This class generated by CodeSmith on <%= DateTime.Now.ToLongDateString() %>
<%= GetAccessModifier(Accessibility) %> Class <%= ClassName %>
End Class
Note that this template makes use of a function GetAccessModifier and a property Accessibility, even
though neither one of them is defined in the template. That's because they're defined in a separate code-
behind file. Here are the contents of the code-behind file:
Imports System.ComponentModel
Imports CodeSmith.Engine
<Category("Options"), _
Description("Accessibility of the generated class")> _
Public Property Accessibility As AccessibilityEnum
Get
Return _Accessibility
End Get
Set
_Accessibility = value
End Set
End Property
GetAccessModifier = "Public"
Case AccessibilityEnum.Protected
GetAccessModifier = "Protected"
Case AccessibilityEnum.Friend
GetAccessModifier = "Friend"
Case AccessibilityEnum.ProtectedFriend
GetAccessModifier = "Protected Friend"
Case AccessibilityEnum.Private
GetAccessModifier = "Private"
Case Else
GetAccessModifier = "Public"
End Select
End Function
End Class
The CodeTemplate directive ties the code-behind file to the template. The Src attribute of the directive
specifies the filename of the code-behind file, and the Inherits attribute of the directive specifies the
class in the file that the template is based on. Note that this class must itself inherit, directly or indirectly,
from CodeSmith.Engine.CodeTemplate (Section 5.5.2.1).
Because Accessibility is defined as a property of the UtilityCodeTemplate class, CodeSmith includes
it in the template's property sheet when the template is opened in CodeSmith Studio or CodeSmith
Explorer:
There are two main advantages to moving code to a code-behind file. First, it makes your templates
easier to understand by separating the generated code from the scripting code that drives the generation
process. Second, it makes it possible to easily reuse utility functions across many templates by moving
them to shared code-behind files.
You can use the Assembly directive to reference an external assembly from a template, or to include a
source file for dynamic compilation. For example, CodeSmith ships with an assembly named
CodeSmith.CustomProperties.dll that includes custom editors for file names and string collections. If you'd
like to use one of these editors from your own template's property sheet, you need to reference the
assembly:
<%@ Assembly Name="CodeSmith.CustomProperties" %>
The source code for the CustomProperties assembly is in the SampleProjects folder of your CodeSmith
installation.
Name
The Name attribute specifies the file name of an assembly to reference from the current template. The
assembly must exist in the Global Assembly Cache, in the same directory as CodeSmith, in the
CodeSmith\bin directory, in the CodeSmith\AddIns directory, or you can specify a path relative to the
template location. If you're working with templates within CodeSmith Studio, the preferred location is the
CodeSmith\AddIns directory.
Src
The Src attribute specifies the relative path to a source file that should be dynamically compiled along
with the template.
Path
The path attribute is a directory path to the assembly being used.
The Import directive is used to import a namespace for use in your template. This lets you refer to types
in other assemblies more conveniently. For instance, when you're using the SchemaExplorer (Section
10.3.1) assembly, you probably don't want to have to prefix every type from that assembly with the
name of the assembly. The solution is to include an Import directive in your template along with the
Assembly directive:
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
Namespace
The Namespace attribute specifies the fully qualified name of the namespace to be imported.
You can cause CodeSmith to compile the contents of an external file into your template by using an
include statement. This can be useful when you have common functions that you want to share between
several templates. The include statement takes a single argument which specifies the relative path from
the current template to the file to be included:
<!-- #include file="CommonScript.cs" -->
You can also use an include statement to bring in static template content. It doesn't matter what is in
the file that you include; CodeSmith simply inserts the file contents into the template.
There are other ways (Section 9.5) to share common code between templates. In most cases, you
should use other methods for code-sharing, such as the Src attribute on the CodeTemplate (Section
5.1) directive or an Assembly (Section 9.2) directive that imports a source file. That's because
these methods require full .NET class files that are easier to edit in other code editors, while an
include statement will accept malformed source files.
Template code can become quite complex. CodeSmith offers several facilities to help you debug problems
with your templates:
You can write information to the Output window (Section 6.2.6) using Trace and Debug
statements
You can set breakpoints (Section 9.6.4) and step through your templates using an external
debugger
To use CodeSmith's debugging features, you need to compile your template in debug mode. You do this
by setting the Debug attribute of the CodeTemplate (Section 5.1) directive to True:
<%@ CodeTemplate Debug="True" Language="VB" TargetLanguage="VB" Description="A simple
template." %>
One useful way to gather debugging information when a template is not behaving as you expect is to use
the methods of the .NET Trace and Debug objects. These objects let your code interact with the Debug
pane of the CodeSmith Studio Output window (Section 6.2.6). The two objects have exactly the same
members; the only difference between the two is that the Trace object is active at all times, while the
Debug object is only active when you compile your code in debug mode (Section 9.6.2).
This table summarizes some of the useful members of the Trace and Debug objects:
information
WriteIf Method Writes the given
information only if a
condition is true
WriteLine Method Same as Write but
appends a new line
character after the
information.
WriteLineIf Method Same as WriteIf but
appends a new line
character after the
information.
If the static information provided by the Trace and Debug objects is not sufficient, you can set a
breakpoint in your template and interactively debug the template's execution. To do this, insert a
Debugger.Break() statement at the point where you would like to suspend the template's execution.
If your template is compiled in Debug mode and CodeSmith hits a Debugger.Break() statement, it will
cease template execution and display the Just-In-Time Debugging dialog box:
Depending on the software installed on your computer and the applications that you have running, you
may see a different selection of possible debuggers
The debugger you choose will open with the code for your CodeSmith template loaded. At that point, you
can use all of the tools supplied by the selected debugger to step through code, examine variables, and so
on.
Always save your templates before debugging them with this technique! When you stop debugging in
the external debugger, CodeSmith Studio will be terminated.
Sub-templates provide a way for you to organize complex code generation processes from a single
template. Just as subroutines in a computer program let you call bits of logic from a main program flow,
sub-templates let you call bits of code generation logic from a main template.
To use a sub-template, you must first register the sub-template (Section 9.7.2) in the parent
template. You can then merge properties from the sub-template (Section 9.7.3) into the parent
template, copy properties from the parent template (Section 9.7.4) to the sub-template, set
properties (Section 9.7.5) in the sub-template, and render the sub-template (Section 9.7.6).
To register a sub-template, you include a Register directive in the master template. You can include as
many Register directives as you like, so one master template can include multiple sub-templates. Sub-
templates can be nested.
<%@ Register Name="Header" Template="Header.cst" MergeProperties="True"
ExcludeProperties="IncludeMeta" %>
Name
The Name attribute specifies the type name for the sub-template in the master template. It can be used to
create an instance of the sub-template.
Template
The Template attribute specifies the relative path to the sub-template.
MergeProperties
The MergeProperties attribute specifies whether the properties of the sub-template should be
dynamically added to the master template's properties. If you omit this attribute, it defaults to False.
ExcludeProperties
The ExcludeProperties attribute specifies a comma-delimited list of properties to be excluded from
merging to the master template's property list. You may use * as a wildcard in the property list.
To merge the properties of a sub-template with a master template, include the MergeProperties="True"
attribute in the Register (Section 9.7.2) directive for the sub-template. When you do this, the
properties of the sub-template will be displayed on the property sheet of the main template when the
main template is open in CodeSmith Explorer or CodeSmith Studio. This makes it easy to prompt for all
the properties that are required for the entire code-generation process on a single property sheet.
You may want to share properties between a master template and sub-templates. For example, suppose
you are working with a set of database-oriented templates, and each template defines a string property
named Server. When you prompt for this property in the master template, only the master template's
copy of the property receives a value.
To set the property in the sub-template, you use the CopyPropertiesTo method of the master template.
This method matches properties from the master template to the sub-template on the basis of name and
type. If it finds an exact match, it copies the value from the master template to the sub-template. This
code snippet shows how you can use this method:
// instantiate the sub-template
Header header = this.Create<Header>();
// copy all properties with matching name and type to the sub-template instance
this.CopyPropertiesTo(header);
CodeSmith User's Guide | 112
You can set properties in a sub-template from the main template easily, because they're all available as
properties of the instantiated sub-template object. Here's an example:
// instantiate the sub-template
Header header = this.Create<Header>();
// include the meta tag
header.IncludeMeta = true;
In this case, IncludeMeta is a boolean property defined with a Property (Section 5.3.2) directive in
the sub-template.
After you've registered a sub-template and set its properties, you can render the sub-template. There are
several ways to do this. The first is to render the sub-template directly to the output of the main
template:
// instantiate the sub-template
Header header = this.Create<Header>();
// render the sub-template to the current output stream
header.Render(this.Response);
Alternatively, you can render the sub-template to a separate file. This is useful when you want to create
multiple output files as part of a single code-generation process.
// instantiate the sub-template
Header header = this.Create<Header>();
// render the sub-template to a separate file
header.RenderToFile("Somefile.txt");
Here's a simple example so you can see how the various sub-template pieces fit together. This example
generates an HTML file from two templates. First, there's a sub-template that generates an HTML header:
<%@ CodeTemplate Language="C#" TargetLanguage="HTML" %>
<%@ Property Name="Title" Type="System.String" Optional="False" Category="Options"
Description="Page title." %>
<%@ Property Name="CharSet" Type="System.String" Optional="False" Default="windows-1252"
Category="Options" Description="Character set for the page." %>
<%@ Property Name="IncludeMeta" Type="System.Boolean" Default="True" Optional="False"
Category="Options" Description="Include meta tags." %>
<html>
<head>
<% if (IncludeMeta) { %>
<meta http-equiv="Content-Type" content="text/html; charset=<%= CharSet %>">
<% } %>
<title><%= Title %></title>
</head>
Next, the main template generates the body of the HTML file. Note that it uses the sub-template to
generate the header:
<%@ CodeTemplate Language="C#" TargetLanguage="HTML" %>
<%@ Property Name="Title" Type="System.String" Optional="False" Category="Options"
Description="Page title." %>
<%@ Property Name="Placeholder" Type="System.String" Optional="True" Category="Options"
Description="Main placeholder text." %>
<%@ Register Name="Header" Template="Header.cst" MergeProperties="True"
ExcludeProperties="IncludeMeta" %>
<% OutputHeader(); %>
<body>
<h1><%= Title %></h1>
<p><%= Placeholder %></p>
</body>
</html>
<script runat="template">
public void OutputHeader()
{
CodeSmith User's Guide | 113
The template's output seamlessly merges the output of the sub-template and the output of the main
template:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>My Web Page</title>
</head>
<body>
<h1>My Web Page</h1>
<p>Lorem Ipsit</p>
</body>
</html>
CodeSmith lets you send the same output to multiple destinations at one time. To do this, you use the
AddTextWriter method of the CodeSmith Response object. This method lets you add additional
TextWriter objects (or objects of any class derived from TextWriter) to the list that CodeSmith renders
its output to. For example, here's a template that outputs some text to two files at the same time, as well
as to CodeSmith's default output window:
<%@ CodeTemplate Language="C#" TargetLanguage="Text" Description="AddTextWriter
Demonstration." %>
<%@ Import Namespace="System.IO" %>
This template demonstrates using the AddTextWriter method
to output the template results to multiple locations concurrently.
<script runat="template">
public override void Render(TextWriter writer)
{
StreamWriter fileWriter1 = new StreamWriter(@"C:\test1.txt", true);
this.Response.AddTextWriter(fileWriter1);
CodeSmith User's Guide | 114
base.Render(writer);
fileWriter1.Close();
fileWriter2.Close();
}
</script>
This technique is quite general. You could have a TextWriter that streams to a socket or to the Windows
clipboard or to file or to a database or to your source code repository or to any other destination you like.
This technique is useful for generating multiple identical copies of the same file. When you need to
generate multiple different files as part of a single code-generation process, you should use one sub-
template (Section 9.7.1) for each file. Call the sub-templates from a master template and use the
RenderToFile (Section 9.7.6) method to output each sub-template.
CodeSmith User's Guide | 115
One of the key features of CodeSmith is that you can use many types of metadata in your templates.
Template metadata provides the means for users to interact with templates and customize the output of
those templates. You have many choices when defining the metadata in a template:
You can use any .NET type (Section 10.2)
You can use CodeSmith's SchemaExplorer (Section 10.3.1) to interact with a database
You can use the XML support (Section 10.4.1)
You can build your own custom metadata sources (Section 10.5.1), complete with designer and
property set support
The easiest way to define metadata is to use one of the scalar .NET types such as System.String or
System.Boolean. To define a property using a .NET type, you use a Property directive (Section
5.3.2). CodeSmith automatically allows editing such scalar types directly in its property sheet when the
user executes a template.
Advanced: Using Extended Properties to Define Custom Metadata ('Manage Extended Properties
Through Schema Explorer' in the on-line documentation)
SchemaExplorer is CodeSmith's built-in interface for working with metadata from databases. You can use
the classes in SchemaExplorer either programmatically or interactively; often, you'll combine the two
approaches. For example, you may want to allow the user to interactively select a database, and then
programmatically build a list of all of the tables in the selected database. Here's a template that
demonstrates using SchemaExplorer for this purpose:
<%@ CodeTemplate Language="C#" TargetLanguage="Text" Description="List all database
tables" %>
<%@ Property Name="SourceDatabase" Type="SchemaExplorer.DatabaseSchema"
Category="Context" Description="Database containing the tables." %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
Tables in database "<%= SourceDatabase %>":
<% for (int i = 0; i < SourceDatabase.Tables.Count; i++) { %>
<%= SourceDatabase.Tables[i].Name %>
<% } %>
Before you can execute this template, you must supply a value for the SourceDatabase property. When
you place your cursor in the property sheet row for this property, CodeSmith will display a builder button,
indicating that there is an external editor hooked up for this property. CodeSmith automatically uses
editors built into SchemaExplorer:
Clicking the builder button opens the Database Picker dialog box. A dropdown list lets you choose from all
of the data sources that you have previously defined on your computer. There's also a builder button to
CodeSmith User's Guide | 116
If you click the builder button, SchemaExplorer opens the Data Source Manager dialog box. Here you can
see the type of each existing data source, and manage your data sources. You can copy, add, edit, or
remove data sources from this dialog box.
If you choose to add a new data source, SchemaExplorer opens the Data Source dialog box. To add a new
data source, you must provide a name for the new data source, then select a provider type and type in a
connection string. CodeSmith ships with providers for SQL Server and ADOX data sources.
Here's a sample of the output for this template when it's used with the SQL Server Northwind sample
database:
Tables in database "Northwind":
Orders
ComponentTypes
Products
Order Details
CustomerCustomerDemo
CustomerDemographics
Region
Territories
EmployeeTerritories
Employees
Categories
Customers
Shippers
Suppliers
After the user specifies the SourceDatabase, CodeSmith is able to use it as the root of an object model of
the entire database.
Refer to the CodeSmith API Reference for a complete listing of the classes and members within the
CodeSmith User's Guide | 117
SchemaExplorer library.
Advanced: Using Extended Properties to Define Custom Metadata ('Manage Extended Properties
Through Schema Explorer' in the on-line documentation)
Valid connection strings in Schema Explorer depend on the provider you're using for a given connection:
If you're using the SqlSchemaProvider, connection strings follow the format used by the .NET
SqlConnection.ConnectionString (http://msdn.microsoft.com/library/default.asp?
url=/library/en-
us/cpref/html/frlrfSystemDataSqlClientSqlConnectionClassConnectionStringTopic.asp)
property.
If you're using the ADOXSchemaProvider, connection strings follow the format used by the ADO
ConnectionString (http://msdn.microsoft.com/library/default.asp?url=/library/en-
us/ado270/htm/mdproconnectionstring.asp) property.
SchemaExplorer implements designers for four other database object types. These are useful when you
need to let users select a particular object or set of objects within a database as part of your template
metadata.
Starting with a DatabaseSchema object, you can drill down into an object model to obtain further
information about the contents of a database selected by the user. This diagram shows the major
components of the SchemaExplorer object model.
CodeSmith User's Guide | 120
SchemaExplorer provides a rich set of collections, objects, and properties that correspond to this object
model. For example, the DatabaseSchema object exposes a Commands property, through which you can
retrieve a CommandSchemaCollection object. The Item property of this object gives you access to
individual CommandSchema objects, each of which corresponds to a single command in the database. The
properties of the Command object allow you to explore the details of the command, retrieving the metadata
that you might need to build code based on the command.
SchemaExplorer retrieves the various collections in the order that the database presents them. For all
practical purposes, this means that the collections are in a random order. Often, you'll want a collection
sorted by name instead. This is easily accomplished by creating a second collection of the same type and
using the Sort method:
TableSchemaCollection tables = new TableSchemaCollection(SourceDatabase.Tables);
tables.Sort(new PropertyComparer("Name"));
After running this code, the new tables collection will contain all of the tables from the source database,
sorted by name.
10.3.6.1 Introduction
SchemaExplorer allows you to retrieve a great deal of information about objects within your database. If
you're using a SQL Server database, you'll find some of the most useful information in the
ExtendedProperties collections of the various objects. These collections contain the extended properties
that SQL Server defines for database objects. For example, SQL Server defines an extended property that
tells you whether a table column is an identity column, which you can retrieve with the CS_IsIdentity
extended property:
Identity Field = <% foreach(ColumnSchema cs in SourceTable.Columns) {
if( ((bool)cs.ExtendedProperties["CS_IsIdentity"].Value) == true)
{
Response.Write(cs.Name);
}
}
%>
CodeSmith defines standard extended properties for table columns, view columns, and command
CodeSmith User's Guide | 121
parameters:
Table Column:
CS_IsRowGuidCol
CS_IsIdentity
CS_IsComputed
CS_IsDeterministic
CS_IdentitySeed
CS_IdentityIncrement
CS_Default
View Column:
CS_IsComputed
CS_IsDeterministic
Command Parameter:
CS_Default
In addition, every object has a CS_Description extended property, but the standard Description
property provides a shortcut to the same information.
CodeSmith allows you to store metadata in external XML files. To incorporate XML metadata in your
templates, you use an XmlProperty directive:
<%@ XmlProperty Name="PurchaseOrder" Schema="PO.xsd" Optional="False"
Category="Data" Description="Purchase Order to generate packing list for."
%>
Name
The Name attribute is used as the name of the property when it is displayed on the template's property
sheet in CodeSmith Explorer. This is also the variable name that is used to store the value of the property
within the template. This must be a legal variable name within the template's language. For example, if
the template uses C# as its language, then the name must follow the rules for C# variables. If a schema
is specified, the variable will point to a strongly typed object model that CodeSmith generates based on
CodeSmith User's Guide | 122
the schema. If no schema is specified, it will point to an instance of the XmlDocument class.
Schema
The Schema attribute specifies an XSD schema to be used to parse the XML file chosen by the user at
runtime.
Specifying a schema file allows CodeSmith to supply IntelliSense help for the XmlProperty instance
within your template.
If you do not specify a value for the Schema attribute, then the user can select any XML document at
runtime, and the property will return an instance of the XmlDocument class.
Default
The Default attribute is used to set the default value for this property. If you omit this attribute, then
CodeSmith does not supply a default value for the property.
Category
The Category attribute specifies what category this property should appear under in the CodeSmith
Explorer property sheet. If you omit this attribute, CodeSmith will place the property in a category named
Misc.
Description
The Description attribute supplies descriptive text to be displayed at the bottom of the property sheet
when this property is selected.
Optional
The Optional attribute specifies whether or not this property is optional. If a user does not specify a
parameter that is not optional then CodeSmith will not let them proceed. A value of true means that a
value for the property is not required, and a value of false means that a value for the property is
required.
XmlProperty does not support all variations and features of XSD schemas. In general, if an XSD
schema can be successfully loaded into the Visual Studio .NET schema designer then it should work in
CodeSmith.
Using this schema file, you can define an XML property that accepts purchase order files at runtime for its
metadata:
Selecting an appropriate XML file generates the packing list. For example, the user might choose this XML
file:
<?xml version="1.0" encoding="UTF-8"?>
<PurchaseOrder xmlns=http://www.codesmithtools.com/PO
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<PONumber>5271</PONumber>
<CustomerName>John Nelson</CustomerName>
<CustomerCity>Gamonetta</CustomerCity>
<CustomerState>MS</CustomerState>
<Items>
<Item ItemNumber="HM85" Quantity="12"/>
<Item ItemNumber="JR82" Quantity="4"/>
<Item ItemNumber="PR43" Quantity="6"/>
</Items>
</PurchaseOrder>
With this resulting generated packing list:
Packing List
ref: PO#5271
CodeSmith User's Guide | 124
Ship To:
John Nelson
Gamonetta, MS
Contents:
HM85, Quantity 12
JR82, Quantity 4
PR43, Quantity 6
When you need something beyond the built-in support for .NET types, SchemaExplorer, and XML
properties, it's time to explore custom metadata sources. CodeSmith lets you hook just about anything
you like to the property grid to use as a metadata source. You'll need to do some coding to enable your
custom metadata sources to work smoothly with the rest of CodeSmith, though. The two tasks you may
need to accomplish are:
Adding designer support (Section 10.5.2)
Adding property set support (Section 10.5.3)
If your custom metadata requires a complex user interface (anything beyond the simple text edit control
provided by the property grid) to edit, you'll need to add designer support. Otherwise, there won't be any
way for the user to enter values for properties that make use of your metadata type. To add designer
support, you'll need to build an editor for your type. An editor is simply a class that subclasses the .NET
CodeSmith User's Guide | 125
System.Drawing.Design.UITypeEditor class.
You can find several examples of implementing custom designers in the SampleCustomProperties project
in the SampleProjects folder installed by CodeSmith. For example, DropDownEditorProperty is a class
that wraps up a string and a boolean value together into a single piece of metadata. To edit this data, it
provides a class, DropDownEditorPropertyEditor, which derives from UITypeEditor. The declaration of
DropDownEditorProperty is decorated to indicate that this is the editor class that CodeSmith should use
in the property grid:
[Editor(typeof(CodeSmith.Samples.DropDownEditorPropertyEditor), typeof
(System.Drawing.Design.UITypeEditor))]
public class DropDownEditorProperty
In a template, you can use this metadata type just like any other (although you need to remember to
reference its assembly, because CodeSmith doesn't know about this type by default):
<%@ Property Name="DropDownEditorProperty"
Type="CodeSmith.Samples.DropDownEditorProperty" Category="Options" Description="This
property uses a custom dropdown editor." %>
<%@ Assembly Name="SampleCustomProperties" %>
When the user wants to edit the DropDownEditProperty and clicks in the property sheet, CodeSmith will
display the custom designer:
Note: For more information on building custom designers, refer to Michael Weinhardt and Chris Sells'
article "Building Windows Forms Controls and Components with Rich Design-Time Features,
Part 2 (http://msdn.microsoft.com/msdnmag/issues/03/05/Design-
TimeControls/default.aspx)" on the MSDN Web site.
If your custom metadata requires special formatting to save to XML (for instance, it includes information
that you want to format in a particular way in the XML file), you'll need to add property set support.
Otherwise, there won't be any way for the user to save an XML property set file that includes an instance
of your metadata type. To add property set support, you'll need to build a serializer for your type. A
serializer is simply a class that implements the CodeSmith.IPropertySerializer interface.
You can find several examples of implementing custom designers in the SampleCustomProperties project
in the SampleProjects folder installed by CodeSmith. For example, DropDownEditorProperty is a class
that wraps up a string and a boolean value together into a single piece of metadata. To serialize this data,
it provides a class, DropDownEditorPropertySerializer, which implements IPropertySerializer. The
declaration of DropDownEditorProperty is decorated to indicate that this is the serializer class that
CodeSmith should use:
[PropertySerializer(typeof(CodeSmith.Samples.DropDownEditorPropertySerializer))]
public class DropDownEditorProperty
CodeSmith User's Guide | 126
Using CodeSmith Explorer (Section 3.1), CodeSmith Studio (Section 6.1), or the Visual Studio
integration interactively to generate code can significantly boost your productivity, but that's only part of
what CodeSmith can do for you. In many cases, you'll see even more benefit by incorporating CodeSmith
directly into your build process. To facilitate this, CodeSmith includes a console (Section 11.2) version
that you can call from a CodeSmith Project, a build tool such as NAnt. or a Visual Studio pre-compile task
in MSBuild (Section 7.5). This helps you ensure that any generated files in your application are always
up-to-date.
For example, suppose you are using CodeSmith to automatically create a data access layer and business
objects in C# based on selected tables in your database. What happens if you change the schema of
those database tables? If you're using CodeSmith manually, you must remember to regenerate the DAL
and business objects. But if you've hooked up the CodeSmith Console Application to your build process,
the changes in the database schema will automatically be reflected in your final .NET application the next
time that you compile the application, without any further effort on your part.
In this section of the help file, you can learn how to:
Use the CodeSmith Console Application (Section 11.2)
11.2.1 Introduction
Since a CodeSmith project contains all necessary metadata to run the execution of the most complicated
of code generation projects. It makes it possible to call your CodeSmith Project through any batch file,
command-prompt, or any application that let's you launch a process with arguments.
The CodeSmith Console Application (Section 11.1) supports these command-line switches:
CodeSmith User's Guide | 127
Input Options
<file> Project File to be used for generation
/property:<name>=<value> or /p:<name>=<value> Assign a property value from the command line.
Only property types which support conversion to and from string can be assigned in this way.
Compiler Options
/debug[+|-] Emit (or suppress) debugging information (allows attaching a debugger to a running
template)
/tempfiles[+|-] Keep (or delete) temporary files (if debug is on then tempfiles will also automatically
be on)
Miscellaneous Options
/verbose or /v Display verbose messages
/help or /? Display usage information
/nologo Suppress generator copyright message
The CodeSmith console application enables executing CodeSmith Project files from the command line in a
very simple manor. Here is an example of executing the PersonArray CodeSmith Project file:
CodeSmith User's Guide | 128
To make effective use of the CodeSmith Console Application, you must supply the appropriate metadata
for the template that you are using as the basis for the generated file. There are two ways that you can
do this:
By supplying a CodeSmith Project File (Section 7.1)
By supplying properties on the command line (Section 11.4.2)
You can specify individual properties on the command line, using the syntax
/property:<name>=<value>
or
/p:<name>=<value>
Only property types which support conversion to and from string can be assigned in this way.
You can include multiple instances of the /property switch on the command line to define multiple
properties in this way.
If you specify both a property set XML file and a property value on the command line, the property
value will override any setting in the property set XML file.
To use a template's default file name for the output file, specify the /out:default command-line switch.
Within a template, you can specify the default output file name by overriding the GetFileName method.
For example, if your C# language template contains a property named ClassName, you might include this
code to set the default output file name:
<script runat="template">
public override string GetFileName() {
return ClassName + ".cs";
}
</script>
The CodeSmith Console Application allows you to pass two options to the CodeSmith compiler:
/debug[+|-] Emit (or suppress) debugging information (allows attaching a debugger to a running
template)
/tempfiles[+|-] Keep (or delete) temporary files (if debug is on then tempfiles will also automatically
be on)
CodeSmith User's Guide | 129
12 Advanced Topics
If you're generating SQL scripts, it can be useful to execute those scripts right after you've generated
them. That way, when you generate scripts that build new objects in a database, you can finish the
process by actually building the objects.
The BaseTemplates.ScriptUtility object provides an ExecuteScript method that you can use for this
purpose. If you want to execute the script immediately after it's been generated, it's convenient to
override the template's OnPostRender method to do so. Here's an example of doing so, adapted from the
StoredProcedures.cst template that ships with CodeSmith:
protected override void OnPostRender(string result)
{
// execute the output on the same database as the source table.
CodeSmith.BaseTemplates.ScriptResult scriptResult =
CodeSmith.BaseTemplates.ScriptUtility.ExecuteScript
(this.SourceTable.Database.ConnectionString,
result, new System.Data.SqlClient.SqlInfoMessageEventHandler(cn_InfoMessage));
Trace.Write(scriptResult.ToString());
base.OnPostRender(result);
}
In this example, SourceTable is a property of type SchemaExplorer.TableSchema. Depending on what
metadata you're prompting the user for, you'll need to adjust that part of the code to get a connection to
the database where the generated script should be executed.
Merge strategies answer the question: how do I customize generated code without losing my
customizations when the code is regenerated? CodeSmith offers you a choice of two different merge
strategies:
InsertRegion Merge Strategy (Section 12.2.2)
Merge strategies are supported using the CodeSmith Console Application (Section 11.1) and
CodeSmith Project File (Section 7.1) to generate code.
Merge strategies are carried out by classes that implement the CodeSmith.Engine.IMergeStrategy
interface. If you like, you can create your own merge strategy by implementing this interface. To register
your merge strategy with CodeSmtih, you'll want to make an entry in the CodeSmithEngine.config file,
which is located by default at C:\Documents and Settings\{username}\Application Data\CodeSmith\v5.0
in Windows 2000/XP or C:\Users\{username}\AppData\Roaming\CodeSmith\v5.0 in Windows Vista.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
The InsertRegion merge strategy is useful when you need to generate a single region of code within a file
that is otherwise not authored by CodeSmith. The file must already exist with the appropriate region
marked. CodeSmith preserves the rest of the file untouched. When using the InsertRegion merge
strategy, you specify an initialization string in this format:
RegionName=<RegionName>;Language=<Language>
For example,
/merge:InsertRegion="RegionName=Sample Generated Region;Language=C#;"
Given this initialization string, CodeSmith will search for a region named "Sample Generated Region"
marked by C# style region markers. The generated code will be inserted in place of the contents of this
region. The Language attribute in the initialization string is a key into the CodeSmithEngine.config file,
which is located by default at C:\Documents and Settings\{username}\Application Data\CodeSmith\v4.1
CodeSmith User's Guide | 130
The PreserveRegions merge strategy is useful when you need to preserve multiple custom regions in a file
that is otherwise authored by CodeSmith. The file must already exist with the custom sections marked by
appropriate region markers. CodeSmith transfers the marked regions to the template output when
regenerating the file. When using the PreserveRegions merge strategy, you specify an initialization string
CodeSmith User's Guide | 131
in this format:
RegionNameRegex=<RegexExpression>;Language=<Language>
For example,
RegionNameRegex=^[ \t]*(?i:Custom);Language=T-SQL;
Given this initialization string, CodeSmith will search for regions whose names match the RegionName
Regex, marked by T-SQL style region markers. The contents of such regions are copied to corresponding
regions in the template's output; if there is no corresponding region, any matching region will be
appended to the end of the template's output. The Language attribute in the initialization string is a key
into the CodeSmithEngine.config file, which is located by default at C:\Documents and
Settings\{username}\Application Data\CodeSmith\v4.1 in Windows 2000/XP or C:\Users\{username}
\AppData\Roaming\CodeSmith\v4.1 in Windows Vista. This file contains regular expressions defining the
region markers for each supported language. By default, CodeSmith recognizes region markers for VB,
C#, and T-SQL, but you can add your own regular expressions to the file to extend this support if you
need to.
If you do not specify a Language attribute in the initialization string, then the TargetLanguage
attribute in the template's CodeTemplate directive is used as a key instead.
Here's an example so you can see how all the pieces fit together. First, a template, CustomClass.cst.
Note that the template defines two empty C# regions. These are the regions that will be used to preserve
custom code that already exists in the output file.
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Description="Custom class generator."
%>
<%@ Property Name="ClassName" Type="System.String" Description="Name of the class." %>
#region Keep copyright
#endregion
class <%= ClassName %>
{
public <%= ClassName %>()
{
// Insert default constructor code here
}
{
return("E8472");
}
#endregion
}
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
To define regions in non-default languages, you need to edit the CodeSmithEngine.config file, which is
located by default at C:\Documents and Settings\{username}\Application Data\CodeSmith\v5.0 in
Windows 2000/XP or C:\Users\{username}\AppData\Roaming\CodeSmith\v5.0 in Windows Vista. This file
contains regular expressions defining the region markers for each supported language. By default,
CodeSmith recognizes region markers for VB, C#, and T-SQL, but you can add your own regular
expressions to the file to extend this support if you need to. Here are the default contents of the file:
<?xml version="1.0"?>
<codeSmith xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<applicationDirectory>C:\Program Files\CodeSmith\v5.0\</applicationDirectory>
<mergeStrategyAliasList>
<alias>
<name>InsertRegion</name>
<typeName>CodeSmith.Engine.InsertRegionMergeStrategy,CodeSmith.Engine</typeName>
</alias>
<alias>
<name>PreserveRegions</name>
<typeName>CodeSmith.Engine.PreserveRegionsMergeStrategy,CodeSmith.Engine</typeName>
</alias>
</mergeStrategyAliasList>
<languageRegionDefinitionList>
<languageRegionDefinitions>
<languageKeyList>
<key>C#</key>
<key>CSharp</key>
<key>CS</key>
</languageKeyList>
<regionStartRegex>^[ \t]*#region(?:[ \t]+(?<name>[^\r\n]*))?\r?
\n</regionStartRegex>
<regionEndRegex>^[ \t]*#endregion.*\r?\n</regionEndRegex>
</languageRegionDefinitions>
<languageRegionDefinitions>
<languageKeyList>
<key>VB</key>
<key>VB.NET</key>
<key>VisualBasic</key>
</languageKeyList>
<regionStartRegex>^[ \t]*#(?i:region)(?:[ \t]+"(?<name>[^\r\n"]*)")?.*\r?
\n</regionStartRegex>
<regionEndRegex>^[ \t]*#(?i:end region).*\r?\n</regionEndRegex>
</languageRegionDefinitions>
<languageRegionDefinitions>
<languageKeyList>
<key>SQL</key>
<key>T-SQL</key>
</languageKeyList>
<regionStartRegex>^[ \t]*--#?(?i:region)(?<name>[^\r\n]*)?\r?
\n</regionStartRegex>
<regionEndRegex>^[ \t]*--#?(?i:end ?region).*\r?\n</regionEndRegex>
</languageRegionDefinitions>
</languageRegionDefinitionList>
</codeSmith>
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
Merge strategies are carried out by classes that implement the CodeSmith.Engine.IMergeStrategy
interface. You can find the details of this interface in the CodeSmith API help file.
CodeSmith User's Guide | 133
After defining your own merge strategy, there are two ways that you can use it. First, you can specify a
fully-qualified assembly name when calling the merge strategy from the command line:
/merge:MyMergeAssembly.MyMergeStragegy="MergeParameters=Sample Merge
Parameters;Language=C#;"
Alternatively, you can register your merge strategy with CodeSmtih by making an entry in the
CodeSmithEngine.config file, which is located by default at C:\Documents and Settings\{username}
\Application Data\CodeSmith\v4.1 in Windows 2000/XP and {username}:
<mergeStrategyAliasList>
<alias>
<name>MyMergeStrategy</name>
<typeName>MyMergeAssembly.MyMergeStrategy,MyMergeAssembly</typeName>
</alias>
</mergeStrategyAliasList>
Adding your merge strategy to the alias list allows you to call it by name when you use the /merge switch.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
Broadly speaking, there are two different types of code generators: passive code generators and active
code generators.
Passive code generators generate code once and then give up all responsibility for it. The wizards and
builders that you find in modern IDEs are typically passive code generators. They're good for coming up
with code that the developer later customizes, but once the code has been generated, a passive code
generator can't regenerate it with changes.
In contrast, active code generators are designed to maintain a link with the code that is generated over
the long term by allowing the generator to be run multiple times over the same code. The key point to
keep in mind about active code generators is that the template is the source code. Suppose you're
generating 500 class files from a single template. With an active code generator, if you find a bug in the
architecture of those classes (say, you've made a mistake in the way that you're handling object
persistence), it's not a huge problem. You just fix the one template and regenerate the 500 classes. This
obviously saves you an incredible amount of time over fixing the same bug over and over again in 500
separate class files.
But what happens when a template can't generate everything that needs to appear in the source code
file? Suppose some of those 500 classes need custom methods, and the custom methods are different in
different classes. For an active code generator to be effective, it must provide some way for a developer
to customize its output, and then allow code regeneration without destroying those customizations.
By default, CodeSmith doesn't allow for custom code in the files that it generates. When you execute a
template, it overwrites any existing output file completely. But there are ways to use CodeSmith in
conjunction with custom code. Here are three strategies to enable active code generation and custom
code together with CodeSmith:
Use inheritance (Section 12.3.2)
Use merge strategies (Section 12.3.3)
Use .NET 2.0 partial classes (Section 12.3.4)
One way to enable active code generation with CodeSmith is to use CodeSmith to generate a base class,
and then to customize a derived class. When you regenerate the base class, CodeSmith doesn't touch the
code in the derived class.
As a simple example, you might design this template to use in a financial application:
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Description="Base class generator." %>
<%@ Property Name="ClassName" Type="System.String" Description="Name of the class." %>
<%@ Property Name="ConstructorParameterName" Type="System.String"
Description="Constructor parameter name." %>
<%@ Property Name="ConstructorParameterType" Type="System.String" Description="Data type
CodeSmith User's Guide | 134
A second way to enable active code generation with CodeSmith is to use the CodeSmith Console
Application (Section 11.1) with merge strategies (Section 12.2.1) to generate code. Merge
strategies allow you to generate specific portions of a file, while allowing the developer to customize the
remainder of the file. Merge strategies provide a flexible way to enable active code generation, provided
that developers maintain the discipline to avoid putting custom code inside of the regions that will be
overwritten by CodeSmith.
For example, consider this template for generating HTML pages with some standard scaffolding around a
user-entered body:
<%@ CodeTemplate Language="C#" TargetLanguage="HTML" %>
<%@ Property Name="Title" Type="System.String" Optional="False" Category="Options"
Description="Page title." %>
<%@ Property Name="CharSet" Type="System.String" Optional="False" Default="windows-1252"
CodeSmith User's Guide | 135
.NET 2.0 offers a new feature that enables active code generation scenarios in both C# and Visual
Basic .NET: partial classes. With partial classes, the code for a single class can be split across multiple
class declarations, in one or more files. At compile time, the compiler locates all of the pieces of the class
and assembles them into a single complied class.
In C#, partial class definitions look like this:
partial class Class1
{
public void Method1
{
// code to implement Method1
}
}
In either case, you can enable active generation by generating the code for Method1, while keeping the
handcrafted code for Method2 in a separate file, untouched by CodeSmith. At compile time, the
appropriate compiler will knit the two files together into a single unified class.
CodeSmith exposes the entire operation of the CodeSmith engine through an API. Through this API, you
can compile templates, retrieve any errors, create instances of templates, get the generated source code,
fill in template metadata, and ultimately render a template's output to a TextWriter, file, or string. This
API allows you to perform many CodeSmith operations from your own code in any .NET language, and
lets you programmatically execute CodeSmith templates from within your own code.
Remember, CodeSmith is licensed on a per-developer basis. If your application depends on
programmatically executing CodeSmith templates, each user must have a license (Section 17.2) to
use CodeSmith.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
CodeSmith comes with a sample project named EngineSample that demonstrates the most common uses
of the CodeSmith API:
Compiling a template
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();
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 (Section 17.3) of CodeSmith.
The Standard Edition of CodeSmith compiles your templates each time your execute them. The
CodeSmith User's Guide | 137
Professional Edition streamlines this process in many circumstances by using template caching. If the
template's content and dependencies have not changed, CodeSmith is able to use the already compiled
assembly to render the template's output, rather than recompiling the template.
For CodeSmith to be able to use template caching, the template must be unchanged since the last time it
was compiled. To determine this, CodeSmith checks the source code of the template for changes, and
also recurses into any templates and source files referenced through Assembly (Section 9.2) or
Register (Section 9.7.1) directives.
Template caching makes a big difference in the performance of CodeSmith when you're repeatedly
executing the same template without modifying the template itself. You'll see a nice performance boost
when you just execute a template (the Properties window will open more quickly), but the real benefit
comes when you integrate CodeSmith into your build process. With template caching, using CodeSmith
through the batch generation (Section 7.1) process or CodeSmith Console Application (Section
11.1) is substantially faster.
This feature is only available in the Professional Edition (Section 17.3) of CodeSmith.
Although CodeSmith 5.x templates are almost 100% compatible with CodeSmith 2.x templates, there are
a couple breaking changes that CodeSmith 2.x users should be aware of when upgrading. You may need
to make minor changes to your CodeSmith 2.x templates to have them work perfectly in CodeSmith 5.x.
CodeSmith 5.x requires every template to have a CodeTemplate directive (Section 5.1). The
CodeTemplate directive must be the first thing in the file, with the possible exception of template
comments.
CodeSmith 2.x allowed you to use several formats for template comments that CodeSmith 5.x does not
allow. In particular, these two formats are no longer accepted for template comments:
<% // some template header %>
<%-- some comment %>
In CodeSmith 5.x, the only acceptable format for template headers and comments is as follows:
<%-- some template header --%>
<%-- some comment --%>
Note that other formats are still valid when you want to include a comment in the generated source code.
This is distinct from including a comment in the template that does not appear in the generated code. To
generate a C# comment, you still use the format
<% // some C# comment %>
and to generate a VB comment, you still use the format
<% ' some VB comment %>
Although you can still programmatically compile sub-templates, it is more efficient to use the new
Register directive instead. (Section 9.7.2)
If you have a custom data source that looks like a database (that is, it exposes data in tables and
columns, perhaps with indexes, views, and commands), you may find it convenient to hook your data
source into SchemaExplorer. If you do this, users will be able to use the standard SchemaExplorer user
interface components (Section 10.3.3) to retrieve data from your data source, and you can use the
SchemaExplorer object model (Section 10.3.4) to work with the data in your templates.
You can integrate your own data with SchemaExplorer by building a custom schema provider. To create
your own schema provider simply create a new assembly which includes a public class that implements
the SchemaExplorer.IDbSchemaProvider interface. Also, the assembly name must end with
SchemaProvider.dll (for example, MySampleSchemaProvider.dll). Once you have done this, just put
the assembly in the SchemaProviders sub-directory in your CodeSmith installation directory and
SchemaExplorer will automatically make your provider available in the Data Source dialog box.
You can find the source code for a working schema provider in the
SampleProjects\ADOXSchemaProvider folder.
You can find user-contributed schema providers for databases including Oracle and MySQL in the
CodeSmith Support Forum (http://community.codesmithtools.com/forums/).
CodeSmith User's Guide | 138
CodeSmith ships with a sample project, CodeSmith.CustomProperties, that includes some useful
property types for your templates:
FileNameEditor (Section 12.8.2) can be used to let the user select a filename as the value for a
property
StringCollection (Section 12.8.3) can be used to let the user enter a collection of strings as the
value for a property
You can find this project in the SampleProjects/CustomProperties folder.
12.8.2 FileNameEditor
The FileNameEditor class lets you provide your users with a standard open file dialog box or save file
dialog box from the CodeSmith property grid. To use this class, you must include a reference to the
CodeSmith.CustomProperties assembly in your template. You'll make the code simpler if you import the
namespace as well:
<%@ Assembly Name="CodeSmith.CustomProperties" %>
<%@ Import Namespace="CodeSmith.CustomProperties" %>
After you include the appropriate assembly reference, you can define a property in a script block that uses
the FileNameEditor:
<script runat="template">
private string _userFileName = @"c:\temp\test.txt";
[Editor(typeof(FileNameEditor), typeof(System.Drawing.Design.UITypeEditor)),
Category("Custom"), Description("User selected file.")]
public string UserFileName
{
get {return _userFileName;}
set {_userFileName= value;}
}
</script>
When the user executes the template, the specified property will display a builder button on the property
sheet:
Clicking the builder button will open the specified file dialog box:
CodeSmith User's Guide | 139
You can customize the appearance of the file dialog box by applying the FileDialogAttribute to the
property. For example, consider this property definition:
private string _openFileName = @"c:\temp\test.txt";
[Editor(typeof(FileNameEditor), typeof(System.Drawing.Design.UITypeEditor)),
FileDialogAttribute(FileDialogType.Open, Title="Select Input File"),
Category("Custom"), Description("User selected file.")]
public string OpenFileName
{
get {return _openFileName;}
set {_openFileName= value;}
}
The resulting file dialog box looks like this:
CodeSmith User's Guide | 140
To select a folder name instead of a file name, use the FolderNameEditor class from the .NET
Framework instead:
<%@ Assembly Name="System.Design" %>
<script runat="template">
private string _outputDirectory = @"c:\temp";
[Editor(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof
(System.Drawing.Design.UITypeEditor)),
Category("Custom"), Description("Output directory.")]
CodeSmith User's Guide | 141
12.8.3 StringCollection
The StringCollection provides a way for users to enter a list of strings. In your code, you can refer to
these strings as members of an array. To use this class, you must include a reference to the
CodeSmith.CustomProperties assembly in your template:
<%@ Assembly Name="CodeSmith.CustomProperties" %>
After you include the appropriate assembly reference, you can define a property in a script block that uses
the StringCollection
<%@ Property Name="List" Type="CodeSmith.CustomProperties.StringCollection"
Category="Custom" Description="This is the list." %>
When the user executes the template, the specified property will display a builder button on the property
sheet:
Clicking the builder button will open an editor that allows the user to type strings on separate lines:
You can also edit the members of the collection directly in the property grid as a comma -separated
list.
In your code, you can iterate through the collection as an array:
The list is:
<% for (int i = 0; i < List.Count; i++) { %>
<%= List[i] %>
<% } %>
12.9 CodeSmith.BaseTemplates
12.9.1 CodeSmith.BaseTemplates
CodeSmith User's Guide | 142
The CodeSmith.BaseTemplates sample project contains two classes that inherit from CodeTemplate.
These classes can be used to add functionality to your templates by referencing them in the Inherits
attribute of the CodeTemplate (Section 5.1) directive:
The OutputFileCodeTemplate (Section 12.9.2) class saves its output to a file
The SqlCodeTemplate (Section 12.9.3) class includes utility functions for working with data stored
in a SQL database
In addition, the project includes two utility classes that you can use via a reference to the
CodeSmith.BaseTemplates assembly (Section 9.2):
The StringUtil (Section 12.9.4) class includes methods for working with strings
The ScriptUtility (Section 12.9.5) class includes methods for working with SQL scripts
12.9.2 OutputFileCodeTemplate
To base a template on the OutputFileCodeTemplate class, you inherit from this class in your template's
CodeTemplate (Section 5.1) directive:
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Inherits="OutputFileCodeTemplate"
Description="Build custom access code." %>
<%@ Assembly Name="CodeSmith.BaseTemplates" %>
The OutputFileCodeTemplate class does two things. First, it adds a property named OutputFile to your
template. This property requires you to select a filename. Second, the template overrides the
OnPostRender (Section 5.5.2.5.4) method to write the output of your template to the specified file
after CodeSmith has finished generating code.
If you want to customize the Save File dialog box used by the OutputFile property, you can override
the OutputFile property in your own template. For example, if you want to force the user to select
a .cs file for output, you'd include this code in your template:
<script runat="template">
// Override the OutputFile property and assign our specific settings to it.
[FileDialog(FileDialogType.Save, Title="Select Output File", Filter="C# Files (*.cs)
|*.cs", DefaultExtension=".cs")]
public override string OutputFile
{
get {return base.OutputFile;}
set {base.OutputFile = value;}
}
</script>
12.9.3 SqlCodeTemplate
To base a template on the SqlCodeTemplate class, you inherit from this class in your template's
CodeTemplate (Section 5.1) directive:
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Inherits="SqlCodeTemplate"
Description="Build data access layer." %>
<%@ Assembly Name="CodeSmith.BaseTemplates" %>
The SqlCodeTemplate class contains numerous utility methods designed to make it easier to work with
SQL databases. These include:
GetCSharpVariableType - Returns the equivalent C# variable type for a database column.
GetPropertyName - Returns the name of the public property for a given column.
GetReaderMethod - Returns the name of the typed reader method for a given column.
GetSqlParameterExtraParams - Generates any extra parameters that are needed for the ADO
CodeSmith User's Guide | 143
parameter statement.
GetSqlParameterStatement - Returns a T-SQL parameter statement based on the given column.
IncludeEmptyCheck - Determines if a given column should use a check for an Empty value.
IncludeMaxLengthCheck - Determines if the given column's data type requires a maximum length to
be defined.
IsUserDefinedType - Determine if the given column is using a UDT.
12.9.4 StringUtil
To use the functions in the StringUtil class, you should set a reference to the CodeSmith.Engine
assembly and import its namespace:
<%@ Assembly Name="CodeSmith.Engine" %>
<%@ Import Namespace="CodeSmith.Engine" %>
The StringUtil class includes these static methods:
IsPlural - returns True if a string is plural.
StringUtil ToPlural and ToSinglular supports overriding the converted word with a special csmap file. The
default override file is called Plural-Overrides.csmap. It will be used by default. However, you can use a
different Map file if needed. The following is a sample of how to use the overrides.
12.9.5 ScriptUtility
To use the functions in the ScriptUtil class, you should set a reference to the CodeSmith.Engine
assembly and import its namespace:
<%@ Assembly Name="CodeSmith.Engine" %>
CodeSmith User's Guide | 144
When you need to generate multiple files as part of a single code-generation process, consider using
one sub-template for each file. Call the sub-templates from a master template and use the
RenderToFile (Section 9.7.6) method to output each sub-template.
To generate multiple output files as part of an automated process, you can use the CodeSmith
Project (Section 7.1) support from the console or MSBuild.
You can use CodeSmith Explorer (Section 3.6) or CodeSmith Studio (Section 6.5) to create
property set XML files for use by the CodeSmith Console Application (Section 11.1).
You can drag and drop a template from CodeSmith Explorer (Section 3.1) or from the Template
Explorer (Section 6.2.3) window in CodeSmith Studio to any application that supports dropping
text (including Visual Studio .NET). When you drop the template, CodeSmith will display the
template's property sheet. Fill in the metadata for the template, click the Generate button, and the
template's output will be rendered directly to the application where you dropped the template.
The new XmlProperty directive (Section 10.4.1) gives you a strongly-typed object model and
statement completion for metadata stored in XML files.
You can mix your own custom code with generated code by employing one of several different active
generation strategies (Section 12.3.1).
If you're generating SQL Scripts, CodeSmith can execute the scripts (Section 12.1) for you
immediately after generating them.
Use merge strategies (Section 12.2.1) to preserve custom code while regenerating from
templates as part of an automated build process.
Use Ctrl+Shift+M (Section 6.3.7) in CodeSmith Studio to collapse all template code blocks. This is
useful to quickly see all static template content.
Use the StoredProcedures.cst template to generate standard create, retrieve, update, and delete
stored procedures for a given table instantly.
You can use Trace.WriteLine (Section 9.6.3) to output messages to the Debug output window.
CodeSmith User's Guide | 147
15 Internet Links
CodeSmith User's Guide | 148
16 Reference
CodeSmith requires the .NET Framework (version 3.5), but it has no other hardware or software
prerequisites. It should run fine on any system that meets Microsoft's minimum requirements
(http://msdn.microsoft.com/en-us/library/bb882520.aspx) for installing the .NET Framework.
Assembly Directive
You can use the Assembly directive to reference an external assembly from a template, or to include a
source file for dynamic compilation. For example, CodeSmith ships with an assembly named
CodeSmith.CustomProperties.dll that includes custom editors for file names and string collections. If you'd
like to use one of these editors from your own template's property sheet, you need to reference the
assembly:
<%@ Assembly Name="CodeSmith.CustomProperties" %>
The source code for the CustomProperties assembly is in the SampleProjects folder of your CodeSmith
installation.
There are two attributes that you can supply to the Assembly directive. You must supply one or the
other, but not both.
Name
The Name attribute specifies the file name of an assembly to reference from the current template.
Path
The path attribute is a directory path to the assembly being used.
Src
The Src attribute specifies the relative path to a source file that should be dynamically compiled along
with the template.
CodeTemplate Directive
Every CodeSmith template must start with a CodeTemplate directive.
The CodeTemplate directive is the only required directive and is used to specify the general properties of
the template, such as the language that the template is written in and the description that will show in
CodeSmith Explorer as a tooltip for the template. For example, here's the CodeTemplate directive from
the VBSortedList.cst sample template:
<%@ CodeTemplate Language="VB" TargetLanguage="VB" Description="Generates a strongly-
typed collection of key-and-value pairs that are sorted by the keys and are accessible by
key and by index." %>
This directive specifies that the template uses Visual Basic .NET as its own code-behind language, and
that it produces VB output. It also includes a description of the purpose of the template.
There are seven attributes that you can supply to the CodeTemplate directive. The Language parameter is
required; all of the rest are optional.
Language
The Language attribute specifies what language will be used to write the template. Possible values for this
attribute are:
C# to author the template in C#
TargetLanguage
The TargetLanguage attribute is used to specify the output language of the template. You can use any
CodeSmith User's Guide | 149
string you like for the attribute; CodeSmith doesn't use it in any way to generate the template's output.
This attribute is used by CodeSmith Explorer to determine which folder to display the template in when in
template language view (Section 3.2). CodeSmith also uses this attribute to determine how to syntax
highlight the static content of a template.
Description
The Description attribute is used to describe your template in a general way. CodeSmith Explorer
displays this description as a tooltip for the template.
Inherits
By default all CodeSmith templates inherit from CodeSmith.Engine.CodeTemplate (Section 5.5.2.1).
This class provides the basic functionality of the template; much like the Page class provides the basic
functionality of an ASP.NET page. The Inherits attribute can be used to specify that a template inherits
from a different class. However, any class that a template inherits from must inherit, directly or indirectly,
from CodeSmith.Engine.CodeTemplate. CodeSmith must also be able to find this class. To ensure this,
you must supply an Assembly (Section 9.2) directive pointing to the assembly that contains the class,
or a Src attribute that points to the source code for the class.
For an example of using template inheritance, see the CodeSmithBaseTemplates sample project included
with your CodeSmith installation. This project defines two new template classes,
OutputFileCodeTemplate which inherits directly from CodeTemplate and SqlCodeTemplate which inherits
from OutputFileCodeTemplate. To base a new template on SqlCodeTemplate you could include these
directives at the top of your template:
<%@ CodeTemplate Language="CS" Inherits="CodeSmith.BaseTemplates.SqlCodeTemplate" %>
<%@ Assembly Name="CodeSmith.BaseTemplates" %>
Having done this, all of the helper methods defined in the OutputFileCodeTemplate and
SqlCodeTemplate classes, such as GetDqlDbType(), IsUserDefinedType(),
GetSqlParameterStatements(), and many more, are available to your template. Template inheritance
thus provides a good way to reuse tested utility methods across multiple templates without cut-and-paste
duplication of code.
Src
The Src attribute allows you to include functionality from another class in your template by dynamically
compiling that class file as part of your template. Set the value of the attribute to point to the source file
of the class that you want to include in the template. You use the Src attribute to enable the CodeSmith
code-behind model (Section 9.1).
Debug
The Debug attribute is used to determine whether or not debug symbols should be included in the
generated assembly. Setting this attribute to True will enable you to set break points in your template
using the System.Diagnostics.Debugger.Break( ) method.
LinePragmas
The LinePragmas attribute is used to determine whether or not line pragmas are generated during
template compilation. When this attribute is set to True, template errors will point to the template source
code. If it is set to False, then template errors will point to the compiled source code.
ResponseEncoding
The ResponseEncoding attribute is used to set the encoding for the template content and it's outputs.
The ResponseEncoding attribute supports values from the System.Text.Encoding.GetEncoding method.
By default, the encoding is set to ASCII.
OutputType
The OutputType attribute is used to set the output type of the template. The following values can be
used:
Normal - This is the default setting and will cause the output of the template to be written to the
normal Response stream.
Trace - This setting will cause the output of the template to be written to the Trace object.
None - This setting will cause the template to not output anything. This is useful in a master
template scenario where the template just calls other templates and outputs those to files and the
master template itself doesn't output anything.
CompilerVersion
The CompilerVersion attribute is used to specify which compiler to use. For example, to use the .net 3.5
CodeSmith User's Guide | 150
Import Directive
The Import directive is used to import a namespace for use in your template. This lets you refer to types
in other assemblies more conveniently. For instance, when you're using the SchemaExplorer (Section
10.3.1) assembly, you probably don't want to have to prefix every type from that assembly with the
name of the assembly. The solution is to include an Import directive in your template along with the
Assembly directive:
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
There is one required attribute that you must supply to the Import directive.
Namespace
The Namespace attribute specifies the fully qualified name of the namespace to be imported.
Property Directive
To declare a property, you use a Property directive. .For example, this directive defines a property
named ClassName of type System.String:
<%@ Property Name="ClassName" Type="System.String" Category="Context" Description="The
name of the class to be generated." %>
The Property directive has nine possible attributes. The Name and Type attributes are required, and the
other attributes are optional.
Name
The Name attribute is used as the name of the property when it is displayed on the template's property
sheet in CodeSmith Explorer. This is also the variable name that is used to store the value of the property
within the template. This must be a legal variable name within the template's language. For example, if
the template uses C# as its language, then the name must follow the rules for C# variables.
Type
The Type attribute specifies the .NET type of the property. This parameter can be any .NET data type,
though for complex types you may need to specify an Editor attribute to allow the user to successfully
supply a value for the property.
For scalar types, you must use Base Class Library types such as String or Int32 rather than language-
specific types such as string or int.
Default
The Default attribute is used to set the default value for this property. If you omit this attribute, then
CodeSmith does not supply a default value for the property.
Category
The Category attribute specifies what category this property should appear under in the CodeSmith
Explorer property sheet. If you omit this attribute, CodeSmith will place the property in a category named
Misc.
Description
The Description attribute supplies descriptive text to be displayed at the bottom of the property sheet
when this property is selected.
Optional
The Optional attribute specifies whether or not this property is optional. If a user does not specify a
parameter that is not optional then CodeSmith will not let them proceed. A value of true means that a
value for the property is not required, and a value of false means that a value for the property is
required.
Editor
The Editor attribute specifies the GUI editor that will be used in the property grid for this property. This
is equivalent to placing an [EditorAttribute ] on a code property.
EditorBase
The EditorBase attribute specifies the base type for the editor. If none is specified, then UITypeEditor
is assumed.
CodeSmith User's Guide | 151
Serializer
The Serializer attribute specifies the IPropertySerializer type to use when serializing the property's
values. This is equivalent to using a [PropertySerializerAttribute ].on a code property.
Register Directive
To register a sub-template, you include a Register directive in the master template. You can include as
many Register directives as you like, so one master template can include multiple sub-templates. Sub-
templates can be nested.
<%@ Register Name="Header" Template="Header.cst" MergeProperties="True"
ExcludeProperties="IncludeMeta" %>
There are four attributes that you can supply to the Register directive. The Name and Template
parameters are required; the others are optional.
Name
The Name attribute specifies the type name for the sub-template in the master template. It can be used to
create an instance of the sub-template.
Template
The Template attribute specifies the relative path to the sub-template.
MergeProperties
The MergeProperties attribute specifies whether the properties of the sub-template should be
dynamically added to the master template's properties. If you omit this attribute, it defaults to False.
ExcludeProperties
The ExcludeProperties attribute specifies a comma-delimited list of properties to be excluded from
merging to the master template's property list. You may use * as a wildcard in the property list.
XmlProperty Directive
CodeSmith allows you to store metadata in external XML files. To incorporate XML metadata in your
templates, you use an XmlProperty directive:
<%@ XmlProperty Name="PurchaseOrder " Schema="PO.xsd" Optional="False"
Category="Data" Description="Purchase Order to generate packing list for."
%>
The XmlProperty directive has six possible attributes. The Name attribute is required, and the other
attributes are optional.
Name
The Name attribute is used as the name of the property when it is displayed on the template's property
sheet in CodeSmith Explorer. This is also the variable name that is used to store the value of the property
within the template. This must be a legal variable name within the template's language. For example, if
the template uses C# as its language, then the name must follow the rules for C# variables. If a schema
is specified, the variable will point to a strongly typed object model that CodeSmith generates based on
the schema. If no schema is specified, it will point to an instance of the XmlDocument object.
Schema
The Schema attribute specifies an XSD schema to be used to parse the XML file chosen by the user at
runtime.
Specifying a schema file allows CodeSmith to supply IntelliSense help for the XmlProperty instance
within your template.
If you do not specify a value for the Schema attribute, then the user can select any XML document at
runtime, and the property will return an instance of the XmlDocument class.
Default
The Default attribute is used to set the default value for this property. If you omit this attribute, then
CodeSmith does not supply a default value for the property.
Category
The Category attribute specifies what category this property should appear under in the CodeSmith
Explorer property sheet. If you omit this attribute, CodeSmith will place the property in a category named
Misc.
CodeSmith User's Guide | 152
Description
The Description attribute supplies descriptive text to be displayed at the bottom of the property sheet
when this property is selected.
Optional
The Optional attribute specifies whether or not this property is optional. If a user does not specify a
parameter that is not optional then CodeSmith will not let them proceed. A value of true means that a
value for the property is not required, and a value of false means that a value for the property is
required.
XmlProperty does not support all variations and features of XSD schemas. In general, if an XSD
schema can be successfully loaded into the Visual Studio .NET schema designer then it should work in
CodeSmith.
When you install CodeSmith, you also get a wide variety of useful samples. These samples are of two
types. Sample templates, located under the Documents\CodeSmith\Samples\vX.X\Projects\Templates
folder, can be loaded into CodeSmith and used to generate code. Sample projects, located under the
Documents\CodeSmith\Samples\vX.X\Projects\Samples folder, show you how you can extend and
customize CodeSmith.
Sample Templates
CodeSmith installs sample templates in five folders. Each of these folders contains multiple sub
directories templates.
ActiveSnippets - Templates demonstrating basic CodeSmith concepts in C#, Visual Basic, and JScript for
use in Visual Studio.
Database - A collection templates that will generate Stored Procedures, Command Wrappers, Typed
DataSets and more. The DBDocumenter templates are also located in this folder and can be used to
document your database!
Examples - These examples show you how to use merge strategies, mapping file, master and sub
templates, XMLProperty and much more.
Frameworks - The Frameworks folder contains all of our Framework templates. They include: PLINQO
(LINQ to SQL), .netTiers, CSLA.NET, NHibernate, NuSoft and the Wilson ORMapper.
Other - Contains miscellaneous templates as well as the collection templates. The collection templates
are set of collection classes from Christoper Nahr, based on work by Chris Sells. These include ArrayList,
DictionaryList, HashTable, Queue, SortedList, and Stack, all with C# as their target language. See the
ReadMe.html file in this folder for more information on using these templates.
Tip: You'll find many more useful templates contributed by CodeSmith users in the File Share forums at
the CodeSmith Community Forums (http://community.codesmithtools.com/forums/).
Sample Projects
Framework Samples - Contains sample projects like PetShop and Tracker implemented with our various
Framework templates.
SchemaProvider source code - All schema provider (Section 12.7) source code can be found under
the CSharp folder.
CSharp\BaseTemplates - This project includes the source code for the CodeSmith.BaseTemplates
(Section 12.9.1) classes.
ConsoleSamples - This folder contains samples for use with the CodeSmith Console Application
(Section 11.1).
VSIntegrationSample - This project contains a sample of using the VS.NET integration to simulate
generics with the CodeSmith Project (Section 7.1) integration.
CustomPropertiesSample - This project includes the source code for the CodeSmith.CustomProperties
(Section 12.8.1) classes.
APISample - This project demonstrates the use of the CodeSmith API (Section 12.4.1).
TypedDataSetSample - This project contains a test application for the typed DataSet templates
CodeSmith User's Guide | 153
Therefore, you must treat the SOFTWARE PRODUCT like any other copyrighted material except that you
may install the SOFTWARE PRODUCT.
6. U.S. GOVERNMENT RESTRICTED RIGHTS. All SOFTWARE PRODUCT provided to the U.S. Government
pursuant to solicitations issued on or after December 1, 1995 is provided with the commercial license
rights and restrictions described elsewhere herein. All SOFTWARE PRODUCT provided to the U.S.
Government pursuant to solicitations issued prior to December 1, 1995 is provided with "Restricted
Rights" as provided for in FAR, 48 CFR 52.227-14 (JUNE 1987) or DFAR,48 CFR 252.227-7013 (OCT
1988), as applicable.
7. EXPORT RESTRICTIONS. You acknowledge that the SOFTWARE PRODUCT is subject to U.S. export
jurisdiction. You agree to comply with all applicable international and national laws that apply to these
products, including the U.S. Export Administration Regulations, as well as end-user, end-use and
destination restrictions issued by U.S. and other governments.
8. DISCLAIMER OF WARRANTY
To the maximum extent permitted by applicable law, CODESMITH provides the SOFTWARE PRODUCT and
support services (if any) AS IS AND WITH ALL FAULTS, and hereby disclaim all other warranties and
conditions, whether express, implied, or statutory, including, but not limited to, any (if any) implied
warranties, duties or conditions of merchantability, of fitness for a particular purpose, of reliability or
availability, of accuracy or completeness of responses, of results, of workmanlike effort, of lack of viruses,
and of lack of negligence, all with regard to the SOFTWARE PRODUCT, and the provision of or failure to
provide support or other services, information, software, and related content through the SOFTWARE
PRODUCT or otherwise arising out of the use of the SOFTWARE PRODUCT. ALSO, THERE IS NO
WARRANTY OR CONDITION OF TITLE, QUIET ENJOYMENT, QUIET POSSESSION, CORRESPONDENCE TO
DESCRIPTION, OR NON-INFRINGEMENT WITH REGARD TO THE SOFTWARE PRODUCT.
9. EXCLUSION OF INCIDENTAL, CONSEQUENTIAL, AND CERTAIN OTHER DAMAGES.
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL CODESMITH BE LIABLE
FOR ANY SPECIAL, INCIDENTAL, PUNITIVE, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER
(INCLUDING, BUT NOT LIMITED TO, DAMAGES FOR LOSS OF PROFITS OR CONFIDENTIAL OR OTHER
INFORMATION, FOR BUSINESS INTERRUPTION, FOR PERSONAL INJURY, FOR LOSS OF PRIVACY, FOR
FAILURE TO MEET ANY DUTY INCLUDING OF GOOD FAITH OR OF REASONABLE CARE, FOR NEGLIGENCE,
AND FOR ANY OTHER PECUNIARY OR OTHER LOSS WHATSOEVER) ARISING OUT OF OR IN ANY WAY
RELATED TO THE USE OF OR INABILITY TO USE THE SOFTWARE PRODUCT, THE PROVISION OF OR
FAILURE TO PROVIDE SUPPORT OR OTHER SERVICES, INFORMATION, SOFTWARE, AND RELATED
CONTENT THROUGH THE SOFTWARE PRODUCT OR OTHERWISE ARISING OUT OF THE USE OF THE
SOFTWARE PRODUCT, OR OTHERWISE UNDER OR IN CONNECTION WITH ANY PROVISION OF THIS EULA,
EVEN IN THE EVENT OF THE FAULT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY, BREACH OF
CONTRACT, OR BREACH OF WARRANTY OF CODESMITH, AND EVEN IF CODESMITH HAS BEEN ADVISED
OF THE POSSIBILITY OF SUCH DAMAGES.
10. LIMITATION OF LIABILITY AND REMEDIES. NOTWITHSTANDING ANY DAMAGES THAT YOU MIGHT
INCUR FOR ANY REASON WHATSOEVER (INCLUDING, WITHOUT LIMITATION, ALL DAMAGES
REFERENCED ABOVE AND ALL DIRECT OR GENERAL DAMAGES), THE ENTIRE LIABILITY OF CODESMITH
UNDER ANY PROVISION OF THIS EULA AND YOUR EXCLUSIVE REMEDY FOR ALL OF THE FOREGOING
SHALL BE LIMITED TO THE GREATER OF THE AMOUNT ACTUALLY PAID BY YOU FOR THE SOFTWARE
PRODUCT OR U.S.$5.00. THE FOREGOING LIMITATIONS, EXCLUSIONS AND DISCLAIMERS SHALL APPLY
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, EVEN IF ANY REMEDY FAILS ITS ESSENTIAL
PURPOSE.
11. APPLICABLE LAW. This EULA is governed by the laws of the State of Texas.
12. ENTIRE AGREEMENT. This EULA (including any addendum or amendment to this EULA which is
included with the SOFTWARE PRODUCT) is the entire agreement between you and CODESMITH relating to
the SOFTWARE PRODUCT and support services (if any), and it supersedes all prior or contemporaneous
oral or written communications, proposals, and representations with respect to the SOFTWARE PRODUCT
or any other subject matter covered by this EULA. To the extent the terms of any CODESMITH policies or
programs for support services conflict with the terms of this EULA, the terms of this EULA shall control.
There are 2 editions of CodeSmith available. Both editions are licensed per-user.
template IDE, batch code generation, template caching, Visual Studio integration, the ability to use the
CodeSmith API in custom internal applications, and merging support. From small to large complex code
generation scenarios CodeSmith Professional is the perfect tool.
CodeSmith Features:
Execute custom
templates
(Section 2.3.2.5)
Extensible
Metadata
(Section 10.1)
SchemaExplorer
schema discovery
API (Section
10.3.1)
XML support
(Section 10.4.1)
Sub-template
support (Section
9.7.1)
Sample templates
(Section 16.3)
Console client
(Section 11.1)
CodeSmith
Explorer GUI
client (Section
3.1)
CodeSmith Studio
IDE (Section 6.1)
Visual
Studio integration
(Section 4.1)
CodeSmith API
(Section 12.4.1)
Template caching
(Section 12.5)
Merging support
(Section 12.2.1)
CodeSmith must be activated on each computer where you will use it. Activation issues a unique license
code to the computer to permanently unlock CodeSmith's functionality. The activation technology that
CodeSmith uses is designed to be as painless as possible, and to never lock you out from your legitimate
use of the product. By default, you can activate CodeSmith on three different computers, but you can
obtain additional activations simply by sending an e-mail to [email protected]. When you
install a new copy of CodeSmith, you have a 30-day trial period to register the product, and then another
30-day grace period to complete the product activation process.
When you first launch CodeSmith Explorer, CodeSmith Studio or Visual Studio. CodeSmith will display the
Enter Registration Information dialog box:
CodeSmith User's Guide | 156
If you are using a Trial version of CodeSmith you need to enter in your trial key and click the Try button.
If you already own a license you must click the register button.
Please enter your name, organization information, email address and the serial number that your received
at the time of purchase. Click the Register button to continue.
Please contact Support if you need a trial key or you have lost your serial number.
If you proceed in trial mode, CodeSmith will display the Trial Mode dialog box:
CodeSmith User's Guide | 157
Click the Copy to Clipboard to copy the information from this dialog to paste in an email. Please send an
e-mail message with the above information to [email protected].
You can also click the Copy to Email to send us an Email prepopulated with the above information.
You will receive your unlock code by return e-mail. Type the unlock code into this dialog box and click
Continue to finish the activation process.
The serial number and machine key shown are for illustration only. Be sure to use the information from
your own computer when contacting support.
Deactivation
To deactivate your license you need to open the About CodeSmith dialog.
If you are upgrading from CodeSmith Standard to CodeSmith Professional. You will need to deactivate
your license by opening the About dialog from CodeSmith Explorer.
CodeSmith User's Guide | 159
Please note that the following generated key should be ignored. To activate CodeSmith on a new
machine please use your original serial number.