Codesmith Template code Generation practical explanation

Source: Internet
Author: User

Preface

The company project is based on SOA service-oriented Architecture thinking, the project decomposition of a number of sub-projects is inevitable. However, the sub-project has too many shelf structure, it will be the development and maintenance of the later generation porridge feeling. To avoid this confusion as much as possible at the structural level, we made a decision to make the project management simple by using a unified shelf structure.

In this way, there will be a lot of duplicated code or repetitive logic in the structure, for improving development efficiency and saving development time, we use Codesmith to generate code functionality based on custom templates. Let the single table and additions and deletions of the function from the data access layer to the UI display layer of a key batch generation. Here's my review of the Codesmith template authoring process.

codesmith Installation Download

Website address: http://www.codesmithtools.com

: Http://www.codesmithtools.com/downloads

I use the Codesmith link with the hack registration tool: HTTP://PAN.BAIDU.COM/S/1DDDNDSD.

Fool-type installation, not to do the introduction. It's just that you need a lot of code when you install. So annoying, just use my Baidu cloud inside. With the registration software, after installation, do not rush to open codesmith, first go with registration software registration.

Installation completed, cracked successfully.

Open the Codesmith main interface as follows.

Note: Open the new CSharp template, and then the suffix named CST is the template file, write your own template code, in this suffix format of the file. Then the cursor is placed in the template file, F5 can generate the file you want to code.

Write your own codesmith template code.

1. Custom parameter Templates

Note: From here we can see the declaration of the parameters, with the basic syntax of the use of rules, need to take <%%>. After familiarity, in the lower right corner of the parameter assignment, and then the cursor into the template, click F5 Generate code, look down, under scrutiny.

2. Iterate through the templates of tables in the database

Note: The image shows how to set up the database configuration

The template code is as follows

<%--introduction of C # templates--%><%@ codetemplate language="C #"Targetlanguage="C #"debug="False"description="Create an enum of tables."%><%--declare the parameters of the database, in the database attribute in the lower-left corner, select the name of the databases to manipulate--%><%@ property category="Database"Name="SourceDatabase"Type="Schemaexplorer.databaseschema"Optional="False"description="Database The table enums'll come from."%><%--introduces the following class libraries to operate the database prerequisites. Don't get tangled up in the line. --%><%@ Assembly name="Schemaexplorer"%><%@ Import namespace="Schemaexplorer"%><%--sourcedatabase, is you choose the database attribute class, covers the database name, creation time, string link, description and so on, you can point to see--%> Public enum<%=sourcedatabase.name%>tables{<%--iterating through the collection of tables in the database--%><% for(intx =0; x < SourceDatabase.Tables.Count; X + +) {Tableschema table=Sourcedatabase.tables[x]; if(X < SourceDatabase.Tables.Count-1)        //The output table name, which is a C # comment, is not written into the generated code. \ t is a newline character. Response.writeline ("\t{0},", table.    Name); ElseResponse.writeline ("\t{0}", table. Name);}%>    }

3. Iterate through the fields in the database table, declare and use the Custom function

<%@ codetemplate language="C #"Targetlanguage="C #"debug="False"description="Create A list of properties from database table."%><%--declare the parameters of the database table, in the table properties in the lower-left corner, select the database table that you want to manipulate--%><%@ property name="SourceTable"Type="Schemaexplorer.tableschema"category="Context"description="Table , the object is based on."%><%--A mapping dictionary that introduces the system type to C # data type--%><%@ map name="Csharpalias"Src="System-csharpalias"description="System to C # Type Map"%><%--introduces the following class libraries to operate the database prerequisites. --%><%@ Assembly name="Schemaexplorer"%><%@ Import namespace="Schemaexplorer"%><%--traversing a database table field properties--%><%foreach(Columnschema columninch  This. Sourcetable.columns) {%><%--stitching strings, outputting properties of entities in C #--%> Public<%= ControlType (Csharpalias[column. Systemtype.fullname])%> <%= stringutil.topascalcase (column. Name)%>{Get;Set; }<%}%><script runat="Template">//nullable type if type is int, or datetime type output  Public stringControlType (Objectval) {     varty=val.     ToString (); if(ty=="int")     {         return "int?"; }     if(ty=="System.DateTime")     {         return "System.DateTime?"; }     returnTy;}</script>

4. Batch generate files and specify the location of the makefile

The code is as follows

<%@ Template language="C #"Targetlanguage="Text"%><%--register the template to be generated--%><%@ register name="tableenumtemplate"Template="TABLEENUM.CST"mergeproperties="flase"excludeproperties=""%><%@ Register name="tableclumtemplate"Template="TABLEPROPERTIES.CST"mergeproperties="flase"excludeproperties=""%><%--declare the parameters of the database, in the database attribute in the lower-left corner, select the name of the databases to manipulate--%><%@ property category="Database"Name="SourceDatabase"Type="Schemaexplorer.databaseschema"Optional="False"description="Database The table enums'll come from."The%><%--type data type is Tableschema, which indicates that the parameter table is a Table object. --%><%@ Property Name="SourceTable"Type="Tableschema"Deepload="True"Optional="False"category="Table"description="Table Name"%><%--function to execute output file--%><% This. OutPutFile (); %><script runat="Template">//Output File    Private voidOutPutFile () {//generate templates that enumerate table namesCodetemplate table =Newtableenumtemplate (); //Specify the output path        stringTablefilepath = OutputDirectory +"\\"+ This. Sourcedatabase.name +". CS"; //assigning values to child template parametersTable. SetProperty ("SourceDatabase", This.        SourceDatabase); Table. Rendertofile (Tablefilepath,true); //to generate a template for a list table fieldCodetemplate Cloumn =Newtableclumtemplate (); //Specify the output path        stringCloumnfilepath = OutputDirectory +"\\"+ This. Sourcetable.name +". CS"; //assigning values to child template parametersCloumn. SetProperty ("SourceTable", This.        SourceTable); Cloumn. Rendertofile (Cloumnfilepath,true); }    //Solution Output Path    Private stringDirectory =String.Empty; [Editor (typeof(System.Windows.Forms.Design.FolderNameEditor),typeof(System.Drawing.Design.UITypeEditor)] [Optional, notchecked] [DefaultValue ("")]     Public stringOutputDirectory {Get        {            returnDirectory; }        Set        {            if(value.) EndsWith ("\\")) value = value. Substring (0, value. Length-1); Directory=value; }     }</script>

All right, that's all, it's enough to meet my needs.

Summary

If you have any questions after reading this article, please join the top left corner of the blog to Exchange learning.

Codesmith Template code Generation practical explanation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.