InsertRegion Merge Strategy

Use the InsertRegion merge strategy when you need to generate a single region of code inside a file that CodeSmith Generator doesn't otherwise write. The file must already exist and contain the region. Generator replaces the contents of that region with the template output and leaves the rest of the file, including the region markers, untouched.

Settings

Use the alias InsertRegion and an initialization string in this format:

RegionName=<RegionName>;Language=<Language>
Setting Description Default
RegionName Name of the region to replace. The match ignores case. CodeSmith Generated Code
Language Language key that selects the region markers. The template's TargetLanguage

For example, this initialization string makes Generator look for a region named Sample Generated Region, using C# region markers:

RegionName=Sample Generated Region;Language=C#

If the existing file doesn't contain the region, Generator leaves the file unchanged.

Example

This example inserts a copyright notice into a Visual Basic file.

The template, Copyright.cst, generates the notice:

<%@ CodeTemplate Language="VB" TargetLanguage="VB" Description="Copyright notice generator." %>
<%@ Property Name="CompanyName" Type="System.String" Category="Strings" Description="Your company name." %>
<%@ Property Name="ClientName" Type="System.String" Category="Strings" Description="Client company name." %>
' This module is delivered as licensed content as defined
' in the contract between <%= ClientName %> and <%= CompanyName %>.
' Copyright (c) <%= CompanyName %>
' All other rights reserved.

The property set, Copyright.xml, supplies the property values:

<?xml version="1.0" encoding="utf-8"?>
<codeSmith>
  <propertySet>
    <property name="CompanyName">CodeSmith Tools, LLC</property>
    <property name="ClientName">Doe Industries</property>
  </propertySet>
</codeSmith>

HelloWorld.vb is a hand-written file with a region for the notice. The rest of the file is code that Generator must leave alone:

Public Class HelloWorld
#Region "Copyright Notice"
    'CodeSmith will insert the copyright notice here
#End Region
    Public Sub New()
    End Sub
    Public Sub SayHello()
        ' CodeSmith will leave this code intact
        MessageBox.Show("Hello World")
    End Sub
End Class

Generate with RegionName=Copyright Notice;Language=VB, and HelloWorld.vb becomes:

Public Class HelloWorld
#Region "Copyright Notice"
' This module is delivered as licensed content as defined
' in the contract between Doe Industries and CodeSmith Tools, LLC.
' Copyright (c) CodeSmith Tools, LLC
' All other rights reserved.
#End Region
    Public Sub New()
    End Sub
    Public Sub SayHello()
        ' CodeSmith will leave this code intact
        MessageBox.Show("Hello World")
    End Sub
End Class

Because everything outside the region is preserved, you can change the property values and regenerate as often as you like.