May 18, 2008

Output a tempalte to file

You can output the result of a template to file system but use the command line and the code smith project file. The default behavior is that code smith engine, call the template's GetFileName method, and output the result to a text file with that file name. CodeTemplate also has a method RenderToFile(fileName). This method is not to be called inside the template itself, because it will fall into infinitive loop, because itself will call Render method. RenderToFile(fileName) is to be called by external client. But the fileName logic should be maintained inside the template. So we can create the follow the code to implement our requirement.

            public class BaseTemplate: CodeTemplate
            {
            //this make the file name both read and write
            // you can encapsulate the logic in the getter method
            public string OutputFile
            {
            get
            {
            return fileName;
            }
            set
            {
            fileName = value;
            }
            }

            //this override the base method
            public override string GetFileName()
            {
            return OutputFileNmae;
            }

            //this is new method, it should be also called by client
            public void GenerateFile()
            {
            this.RenderToFile(this.GetFileName(), true);

            }
            }