Using merge strategies in CodeSmith enables you to combine both user and machine generated code in a single file. You can also regenerate the machine generated code while still preserving your custom code modifications.
CodeSmith comes with two types of merge strategies out of the box:
· InsertRegion – Allows you to insert a region of generated code into an otherwise custom code file. You can modify the code outside of the target region and your changes will be preserved during regeneration while overwriting the contents of the target region.
Public Class InsertRegionSample
Public Sub SomeCustomMethod()
‘ This is my custom code that I want to
‘ preserve. I can make changes to it and
‘ my changes will not be overwritten.
#Region "Sample Generated Region"
‘ This region will be overwritten during each
‘ template execution.
· PreserveRegions – Allows you to designate multiple regions inside of the file as custom code regions. You can modify the code inside of these regions and your changes will be preserved during regeneration while the rest of the file will be regenerated. Any regions whose name matches against the supplied regular expression will be preserved during regeneration.
Public Class PreserveRegionsSample
#Region "Custom Region 1"
‘ This is my custom code that I want to preserve.
‘ I can make changes to it and my changes will
‘ not be overwritten.
Public Sub SomeGeneratedMethod()
‘ This section and all other regions that do not
‘ match the region name regular expression that you
‘ supply to the merge strategy will be overwritten
‘ during each template execution. In this sample,
‘ the regular expression being used matches any region
‘ who’s name starts with "Custom".
#Region "Custom Region 2"
‘ The contents of this region will also be preserved
‘ during generation.
· IMergeStrategy – Allows you to implement your own merging logic.
The attached samples show an example of using both kinds of merge strategies as well as a CodeSmith Project file to execute them. Simply, right click on the MergeSamples.csp file and select Generate Outputs to regenerate. You can also see the merge settings being used by right-clicking the MergeSamples.csp, selecting Manage Outputs, and then clicking edit on each output to see the settings.