PreserveRegions Merge Strategy
Use the PreserveRegions merge strategy when CodeSmith Generator writes most of a file, but you want to keep your own code in one or more regions of it. When you regenerate the file, Generator reads the matching regions from the existing file and copies their contents into the same regions of the new output. Everything else comes from the template.
Settings
Use the alias PreserveRegions and an initialization string in this format:
RegionNameRegex=<RegexExpression>;Language=<Language>
| Setting | Description | Default |
|---|---|---|
RegionNameRegex |
Regular expression that region names must match to be preserved. | ^[ \t]*(?i:Custom): regions whose names start with "Custom", in any case |
Language |
Language key that selects the region markers. | The template's TargetLanguage |
For example, this initialization string preserves every T-SQL region whose name starts with "Custom":
RegionNameRegex=^[ \t]*(?i:Custom);Language=T-SQL
Keep these rules in mind:
- The template output must contain an empty region with the same name for each region you want to keep. That's where Generator puts the preserved code.
- Each preserved region needs a unique name. Generator stops with an error if two matching regions in the existing file have the same name.
- If a preserved region no longer exists in the template output, Generator doesn't throw its code away. It appends it to the end of the file, between
Orphaned Custom Regionsmarker lines, so you can move it.
Example
The template, CustomClass.cst, defines two empty C# regions. These are where your custom code goes:
<%@ 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
}
#region Keep custom methods
#endregion
}
The existing output file, Engine.cs, has code in both regions:
#region Keep copyright
// Copyright (c) CodeSmith Tools, LLC
#endregion
class Engine
{
public Engine()
{
// Insert default constructor code here
}
#region Keep custom methods
public string UniqueID()
{
return("E8472");
}
#endregion
}
Generate Engine.cs again with ClassName set to Driver and the initialization string RegionNameRegex=^[ \t]*(?i:Keep);Language=C#. The class is regenerated, and the contents of both regions are kept:
#region Keep copyright
// Copyright (c) CodeSmith Tools, LLC
#endregion
class Driver
{
public Driver()
{
// Insert default constructor code here
}
#region Keep custom methods
public string UniqueID()
{
return("E8472");
}
#endregion
}