Introduction

A code generator takes text files and executes parts of it like it would be small fragments of code inserting the results of expressions back into the original text file.

simple.png

The markup language

Code statements are surrounded by <. and .> and comprise of any statement that can be added into a typical C# function body. Their result is not included in the generated file.

Expressions that should be evaluated and included into the generator output are surrounded by <= and => . The result of expression evaluation is added back to the text file in place of the expression statement. E.g. <= "Word count:" + count.ToString() =>

Here is an example of extremely simple code generator input file:

class Code
{
   public static int Main(){

      int[] arr = new int[]{
         <. for(int j = 0; j < 10; j++){ .><= j =><=(j<9)?",":"" =><. } .>
      };
   }
}


and the output file generated by the generator:

class Code
{
   public static int Main(){

      int[] arr = new int[]{
         0,1,2,3,4,5,6,7,8,9
      };
   }
}

Namespaces and assemblies

Namespaces can be added using the following statement:
<@ namespace="System.Text" @>
 

This adds the System.Text namespace to the current namespace of the add in code. (In original C# code namespace inclusion takes the form of using System.Text . ) This example would give you for the possibility to make a <. StringBuilder s = new StringBuilder() .> statement.


Assemblies can be added with similarly with this statement:
<@ assembly="System.Xml.dll" @>

This example adds the System.Xml.dll assembly to the code executed when evaluating the code addins.

Properties

Properties can be added to the main generator class with the expression below.
<@ property="propName" type="System.String" @>

Where the propName parameter is the name of the property and System.String is its type. Those two should be changed to your liking.

The config file

The PyroGen.vshost.exe.config file contains the configuration parameters of the code generator.
You can change the starting and ending tokens such as <. and .> and change various other source editor related parameters. The file has a simple XML markup structure. It should be noted that standard XML escape sequences are needed for some charters as noted here XML escaping -Wikipedia.

External links and materials

A similar approach is taken by: A good books about building .net generators: