Start with the Result
The easiest way to build a CodeSmith template is to start with an example of the code that you want to generate - in this case, a finished AssemblyInfo.cs file. Here's one that we'll use as we move through this tutorial:
using System.Reflection; using System.Runtime.CompilerServices; // // Author: Blake Niemyjski // [assembly: AssemblyTitle("User storage utility")] [assembly: AssemblyDescription("Helps manage data in Isolated Storage files.")] [assembly: AssemblyConfiguration("Retail")] [assembly: AssemblyCompany("MegaUtilities, Inc.")] [assembly: AssemblyProduct("StorageScan")] [assembly: AssemblyCopyright("Copyright (c) MegaUtilities, Inc.")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("1.0")] [assembly: AssemblyDelaySign(true)]
When you're looking at the file that you want to generate, you need to break the file up into three different types of content:
- Content that will never change
- Content that can be automatically generated.
- Content that you will prompt the user for
In the sample above, we've marked the parts that we want to automatically generate red, and the parts that we'll prompt the user for green. The rest of the file we'll treat as static text. Of course, you need to make these decisions with an understanding of how you'll use your template. In this case, for example, we've decided to hard-code the AssemblyDelaySign attribute to always be true. If your use of that attribute varied from project to project, you would want to make that a dynamic part of the template that you prompted the user for.
Now that we know what we want to build, it's time to get the content into the template.
Note: Although we're not using the capability in this example, CodeSmith templates can easily contain conditional logic. For example, you could prompt the user for a value for the AssemblyDelaySign attribute, and then include additional attributes in the template's output if they set that attribute to true.
Next: Static Content in the Template