Tips & Tricks: CodeSmith Maps

CodeSmith Maps allow developers to reduce the amount of plumbing code in their templates and increase the readability and re usability at the same time. Maps provide a named dictionary like semantic to template development.

While developing templates, a common scenario developers face is accessing a lookup list based on some sort of information. A common example is a mapping between CLR data types and SQL Server data types. Before CodeSmith maps, this functionality would have been accomplished by writing a method with a switch/Select Case statement.

Before CodeSmith Maps, your template code might contain methods like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public String GetFrameworkType(ColumnSchema columnwrap glyph
)
{
switch(column.DataType)
{
case DbType.AnsiString:
case DbType.AnsiStringFixedLength:
case DbType.String:
case DbType.StringFixedLength:
return "String";

case DbType.Binary:
return "Byte[]";

case DbType.Boolean:
return "Boolean";

case DbType.Byte:
return "Byte";

case DbType.Currency:
case DbType.Decimal:
case DbType.VarNumeric:
return "Decimal";

CodeSmith Map files allow us to create named Maps using the new Map Editor like this:

Once we have saved this mapping file (using the .csmap extension), we can reference it in our template using the Map directive.

<%@ Map
Name="SqlToClrTypes"
src="Sql-System.csmap"
Description="A Mapping of SQL Server data types to .NET Framework data types" %>

BigInt:<%=SqlToClrTypes["bigint"]%>
Binary:<%=SqlToClrTypes["binary"]%>
Bit:<%=SqlToClrTypes["bit"]%>

This code would result in the following output:
BigInt:System.Int64
Binary:System.Object
Bit:System.Boolean

Another scenario might involve mapping .NET Framework types to specific server control types. For example, on one project you might be required to use the standard ASP.NET server controls such as TextBox, DropDownList, or Menu, but another project might require ASP.NET Ajax controls. CodeSmith Maps allow you to write the code for your interface pages one time, but interchange mapping references to produce different results.

There are countless scenarios where CodeSmith Maps can drastically reduce the amount of effort needed during template development.