Using Merge Strategies to Enable Active Generation

A second way to enable active code generation with CodeSmith Generator is to use the CodeSmith Generator Console Application with merge strategies 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 Generator.

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" Category="Options" Description="Character set for the page." %>
<%@ Property Name="IncludeMeta" Type="System.Boolean" Default="True" Optional="False" Category="Options" Description="Include meta tags." %>
<%@ Property Name="Copyright" Type="System.String" Optional="False" Default="Copyright (c) MyCompany.com" Category="Options" Description="Character set for the page." %>
<html>
<head>
<% if (IncludeMeta)
{ %>
<meta http-equiv="Content-Type" content="text/html; charset=<%= CharSet %>">
<% } %>
<title><%= Title %></title>
</head>
<body>
<h1><%= Title %></h1>
<!- region Keep body ->
<!- endregion ->
<p><%= Copyright %></p>
</body>
</html>

Given this template, you can use the PreserveRegion Merge Strategy to enable active code generation. As long as the user limits their changes to the "Keep body" region, you can regenerate the meta tag, title, and copyright statement for the page as often as you like without destroying their changes.

To successfully use the PreserveRegion Merge Strategy with this template, you need to define the region markers for the HTML template:

<languageRegionDefinitions>
  <languageKeyList>
    <key>HTML</key>
  </languageKeyList>
  <regionStartRegex>[ \t]\<!--#?(?i:region)(?<name>[\r\n])?\r?\n</regionStartRegex>
  <regionEndRegex>^[ \t]\<!--#?(?i:endregion.\r?\n</regionEndRegex>
</languageRegionDefinitions>