Using a Generator Project from MSBuild

CodeSmith Generator includes an MSBuild task, so you can add your own code generation steps to a build.

When to use the MSBuild task

Setting a Generator project's build action to Generate in Visual Studio covers most needs (see Generating on build). Use the MSBuild task directly when you need to customize the generation process during the build, such as generating only for certain configurations.

Installing the task

Install the CodeSmith.Generator.Task NuGet package in your project. The package contains the CodeSmith MSBuild task and a targets file that NuGet imports into your project automatically.

The targets file:

  • Defines the CodeSmithGenerate target, which runs before the build and generates every Generator project whose build action is Generate.
  • Adds Generate to the build actions you can choose in Visual Studio.

Note

When you set a project file's build action to Generate in Visual Studio, it's the CodeSmithGenerate target that runs the generation.

Running a Generator project

To run a Generator project from your MSBuild project file, call the CodeSmith task:

<CodeSmith ProjectFiles="MyProject.csp" />

Example

This example generates the metadata from a Generator project before building in Release mode:

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  ...
  <Target Name="BeforeBuild" Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
    <CodeSmith ProjectFiles="GenerateMetaData.csp" />
  </Target>
  ...
</Project>

Task parameters

Parameter Description
ProjectFiles One Generator project file, or several separated by semicolons (;).
Property A list of name=value pairs that override property values in the Generator projects.
Verbose true to show verbose messages.
Debug true to compile the templates in debug mode.
OutputFiles Output parameter: the output files produced by the Generator projects.

To run more than one project, separate them with semicolons:

<CodeSmith ProjectFiles="GenerateMetaData.csp;GenerateIndex.csp" />

You can also list your projects in an item group and pass them all to ProjectFiles:

<ItemGroup>
  <CspFiles Include="MyProject.csp" />
  <CspFiles Include="MyOtherProject.csp" />
</ItemGroup>

<Target Name="Build">
  <CodeSmith ProjectFiles="@(CspFiles)" Property="StringProperty=test;" />
</Target>

For more about MSBuild tasks and targets, see MSBuild tasks.