Using Inheritance to Enable Active Generation
One way to enable active code generation with CodeSmith Generator is to use CodeSmith Generator to generate a base class, and then to customize a derived class. When you regenerate the base class, CodeSmith Generator doesn't touch the code in the derived class.
As a simple example, you might design this template to use in a financial application:
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Description="Base class generator." %> <%@ Property Name="ClassName" Type="System.String" Description="Name of the class." %> <%@ Property Name="ConstructorParameterName" Type="System.String" Description="Constructor parameter name." %> <%@ Property Name="ConstructorParameterType" Type="System.String" Description="Data type of the constructor parameter." %> class <%= ClassName %> { <%= ConstructorParameterType %> m_<%= ConstructorParameterName %>; public <%= ClassName %>(<%= ConstructorParameterType %> <%= ConstructorParameterName %>) { m_<%= ConstructorParameterName %> = <%= ConstructorParameterName %> } }
You might execute this template with the following metadata:
The resulting generated class looks like this:
class Account
{ int m_balance; public Account(int balance) { m_balance = balance } }
With the generated code stored in Account.cs, you could then write a second class by hand and store it in Checking.cs:
class Checking : Account
{ public Checking : base(0) { } }
Now, suppose that your requirements change and you decide that the account balance should really be a floating-point value. You can change the ConstructorParameterType property to double, regenerate the Account.cs file, and recompile without touching the handwritten code in Account.cs. As long as you don't insert any custom code directly in the base class, you can regenerate that class as often as you like.