
198
|
Chapter 6, Speed Hacks
#50 Define Templates for Generating Code
HACK
}
public bool Contains(int <%=className.ToLower( )%>ID)
{
return Dictionary.Contains(<%=className.ToLower( )%>ID);
}
public void Add(int <%=className.ToLower( )%>ID,
<%=className%> <%=className.ToLower( )%>)
{
Dictionary.Add(<%=className.ToLower( )%>ID,
<%=className.ToLower( )%>);
}
public void Remove(int <%=className.ToLower( )%>ID)
{
Dictionary.Remove(<%=className.ToLower( )%>ID);
}
}
This template will generate a strongly typed dictionary class based on a sin-
gle property. At the top of the template, you can see that it expects the name
of the type, its sole parameter. Using this property, CodeSmith will fill in
this template and create the output. If you look at the syntax of the tem-
plate, it is very similar to ASP.NET and you can see where the value of the
property will be inserted between the
<% and %> symbols.
This template could be executed as-is from the normal CodeSmith applica-
tion, but to use the custom tool, you need to do a little more work.
Creating the XML
The next step is to create an XML file that will be used by the custom tool.
First, add a new XML file (right-click on your project and click Add
➝ Add
New Item, then select XML File from the list) to your project and then enter
the following XML:
<?xml version="1.0" encoding="utf-8" ?>
<codeSmith>
<!-- template that will be used to generate code -->
<template ...