This article describes Spleb (http://yuandong.cnblogs.com/archive/2006/02/01/324647.html) During development Codesmith Medium API Call some research and analysisCodeGeneration technology. In the end, we canProgramCalling Codesmith Of API As the basis for code generation. This article assumes that the reader can use it skillfully. Codesmith Compile templates and generate code in batches, and understand the dynamic compilation of code.
I,CodesmtihCode Generation Principle
CodesmithSimilarAsp.netTo compile the Template into a standard. NetClass, and then callRemderMethod to output the template. Procedure
CodesmithThe classes generated by the compiled template areCodesmith. Engine. codetemplateProvidesRenderMethod is used to output code files.
During compilation,CodesmithCallCodesmith. Engine. codetemplatecompilerClass to process template files and convert them to Standard. NetCode file, and then call. NetThe compiler. NetProgram.
CodetemplatecompilerGenerally. CSTFile, and then callCompiler ()Method. If the compilation is successful (accordingError. Count = 0Is called.Getinstance ()MethodCodetemplateClass Object.
CodetemplateIs the base class of all classes generated after template compilation. This class providesSetproperty ()Method To set the attributes of the template.Render ()The method outputs the template content as text or to a file based on the template attributes.
CodetemplatecompilerThe template compilation principles are not complex. The template header statements are parsed and converted.WritelineOutput (for example, if you write an empty row, it is convertedWriteline ();(<SCRIPT runat = template> </SCRIPT>) Directly copy;<%>For conversion. Of course, the actual implementation is not easy to describe.
The actually generated code can be passed throughIn codesmith studio, tools-compiletoassembly is generated as a DLL.
II,CodetemplateAndGui
. NetThe environment provides a control:PropertygridIs used to set the attributes of the class. The most important attribute of the control isSelectObjectThe control can use reflection to discover the attributes of the class and the design-time labels (Attribute.
CodetemplateClassCodetemplatecompilerObjects compiled by class can be directly boundPropertygridSet,CodesmithstudioThis method is used. HoweverCodesmithInCodesmith ExplorerUsing a self-developed, inherited fromPropertygridOfEnhancedpropertygridFor configuration and output.
CodetemplateClass inherited fromCodesmith. Engine. ControlClass. Add all attributes not used for client settingsBrowsable (false)Tag, not inPropertygrid.
In useCodesmith APIUse this andGuiIt works very well. (This is what we designed !)
Spleb development log-Analysis of codesmith principles (2)