Template events

The CodeTemplate object raises events at points in the template processing cycle. To run your own code at those points, override the matching method in a <script runat="template"> block or a code-behind file.

Event When it fires
OnInit When CodeSmith Generator creates an instance of the template.
OnPreRender Just before the template is rendered.
OnPostRender Just after the template is rendered.
OnPropertyChanged After a template property changes.

OnInit

OnInit fires when the Generator engine creates an instance of your template. Override it to do any setup the template needs.

For example, suppose your template uses an additional TextWriter to send a copy of its output to a socket on a remote computer. You could override OnInit to check for a network connection when the template is created, and warn the user that the template won't succeed without one.

OnPreRender

OnPreRender fires just before the Generator engine merges metadata with your template to produce the output. One use for it is to sanity-check the values the user entered. For example, you could check that a date is within an acceptable range, and change it to the earliest or latest acceptable date if it isn't.

Note

You can change property values in OnPreRender, but you can't stop the template from rendering. To stop generation when a value is invalid, use custom validation errors.

OnPostRender

OnPostRender fires after Generator has merged metadata with your template to produce the output, and receives the output as a string. Use it for any processing you want to do once generation is finished.

For example, the StoredProcedures.cst sample template uses OnPostRender to run the generated SQL script against the source database:

protected override void OnPostRender(string result)
{
    if (this.AutoExecuteScript)
    {
        // execute the output on the same database as the source table.
        CodeSmith.BaseTemplates.ScriptResult scriptResult = CodeSmith.BaseTemplates.ScriptUtility.ExecuteScript(
            this.SourceTable.Database.ConnectionString,
            result,
            new System.Data.SqlClient.SqlInfoMessageEventHandler(cn_InfoMessage));

        Trace.Write(scriptResult.ToString());
    }

    base.OnPostRender(result);
}

This is an excerpt: AutoExecuteScript, SourceTable and the cn_InfoMessage handler are defined elsewhere in the sample template.

OnPropertyChanged

OnPropertyChanged fires after a template property has been modified, and receives the name of the property. Use it for extra processing or validation of the changed property.

<script runat="template">
protected override void OnPropertyChanged(string propertyName)
{
    Response.Write(propertyName + " has changed");
    base.OnPropertyChanged(propertyName);
}
</script>

Tip

To react to a single property, you can also name a handler in the OnChanged attribute of its Property directive.