CodeSmith template code generation practice Details, codesmith practice

Source: Internet
Author: User

CodeSmith template code generation practice Details, codesmith practice
Preface

Company projects are developed based on soa-oriented architecture ideas. It is inevitable to break down many sub-projects. However, if there are too many shelf structures for the subitem, it will produce a pot of porridge for later development and maintenance. To avoid such confusion at the structural layer as much as possible, we made a decision to use a unified shelf structure to simplify project management.

In this way, there will be a lot of repeated code or logic at each layer in the structure. To improve development efficiency and save development time, we adopt codesmith based on custom templates, generate code. Allows the addition, deletion, modification, and query functions of a single table to be generated in one click from the data access layer to the ui display layer. Next we will start to review the coding process of my codeSmith template.

CodeSmith installation and download

Address: http://www.codesmithtools.com

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

The codesmith link that I used with the cracking registration tool: http://pan.baidu.com/s/1dddndsd.

Installation Without introduction. You only need a lot of codes after installation. So annoying, I am using Baidu cloud. Register the software. Do not rush to open codesmith after installation. register the software first.

The installation is complete and the attack is successful.

Open the main interface of codesmith as follows.

 

Note: Open the new Csharp template, and the file suffixed with cst is the template file. You can write your own template code in this suffix format. Place the cursor in the template file, and F5 will generate the file for your code.

Write your own codesmith template code.

1. Custom parameter templates

Note: here we can see the parameter declaration, and the Use Rules of the basic syntax, with <%>. After getting familiar with it, assign a value to the parameter in the lower right corner, place the cursor in the template, click f5 to generate the code, read it, and click it.

2. traverse the template of the table in the database

 

Note: The image shows how to configure the database.

The template code is as follows:

<% -- Introduce c # template -- %> <% @ CodeTemplate Language = "C #" TargetLanguage = "C #" Debug = "False" Description = "Create an enum of tables. "%> <% -- declare Database parameters, in the Database attribute in the lower left corner, select the Database Name -- %> <% @ Property Category = "Database" Name = "SourceDatabase" Type = "SchemaExplorer. databaseSchema "Optional =" False "Description =" Database the table enums will come from. "%> <% -- Introduce the following class library to operate databases. Don't join us. -- %> <% @ Assembly Name = "SchemaExplorer" %> <% @ Import Namespace = "SchemaExplorer" %> <% -- SourceDatabase is the attribute class of the database you choose, it covers the database name, creation time, string link, description, and so on. you can click here to see -- %> public enum <% = SourceDatabase. name %> Tables {<% -- traverse the table set in the database -- %> <% for (int x = 0; x <SourceDatabase. tables. count; x ++) {TableSchema table = SourceDatabase. tables [x]; if (x <SourceDatabase. tables. count-1) // name of the output table, which is a c # comment and is not written into the generated code. \ T is a line break. Response. WriteLine ("\ t {0},", table. Name); else Response. WriteLine ("\ t {0}", table. Name) ;}%>}

3. Traverse fields in the database table, declare and use custom functions

<% @ CodeTemplate Language = "C #" TargetLanguage = "C #" Debug = "False" Description = "Create a list of properties from database table. "%> <% -- declare the database table parameters, in the table attribute in the lower left corner, select the database table to operate -- %> <% @ Property Name = "SourceTable" Type = "SchemaExplorer. tableSchema "Category =" Context "Description =" Table that the object is based on. "%> <% -- Introduce the ing dictionary for converting the system type to the c # data type -- %> <% @ Map Name =" CSharpAlias "Src =" System-CSharpAlias "Description = "System to C # Type Map" %> <% -- Introduce the following class library, which is essential for database operations. -- %> <% @ Assembly Name = "SchemaExplorer" %> <% @ Import Namespace = "SchemaExplorer" %> <% -- traverse the field attributes of the database table -- %> <% foreach (ColumnSchema column in this. sourceTable. columns) {%> <% -- concatenate a string and output the properties of the c # entity -- %> public <% = ControlType (CSharpAlias [column. systemType. fullName]) %> <% = StringUtil. toPascalCase (column. name) %> {get; set ;}<%}%> <script runat = "template"> // if the type is int, or datetime type output can be empty type public string ControlType (o Bject val) {var ty = val. ToString (); if (ty = "int") {return "int? ";} If (ty =" System. DateTime ") {return" System. DateTime? ";}Return ty ;}</script>

4. Generate files in batches and specify the file location

 

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 Database parameters. In the Database attribute in the lower left corner, select the Database Name -- %> <% @ Property Category = "Database" Name = "SourceDatabase" Type = "SC HemaExplorer. DatabaseSchema "Optional =" False "Description =" Database the table enums will come from. "%> <% -- the Type data Type is TableSchema, indicating that the parameter Table is a table object. -- %> <% @ Property Name = "SourceTable" Type = "TableSchema" DeepLoad = "True" Optional = "False" Category = "Table" Description = "Table Name" %> <% -- execute the function -- %> <% this. outPutFile (); %> <script runat = "template"> // output file private void OutPutFile () {// generate the template CodeTemplate table = new TableEnumTemplate () for listing table names (); // specify the output path string tableFilePath = OutputDirectory + "\" + this. sourceDatabase. name + ". cs "; // assign table to the sub-template parameters. setProperty ("SourceDatabase", this. sourceDatabase); table. renderToFile (tableFilePath, true); // generate the template CodeTemplate cloumn = new TableClumTemplate (); // specify the output path string cloumnFilePath = OutputDirectory + "\" + this. sourceTable. name + ". cs "; // assign cloumn to the subtemplate parameter. setProperty ("SourceTable", this. sourceTable); cloumn. renderToFile (cloumnFilePath, true);} // solution output path private string Directory = String. empty; [Editor (typeof (System. windows. forms. design. folderNameEditor), typeof (System. drawing. design. UITypeEditor)] [Optional, NotChecked] [DefaultValue ("")] public string OutputDirectory {get {return Directory;} set {if (value. endsWith ("\") value = value. substring (0, value. length-1); Directory = value ;}</script>

Well, that's enough to meet my needs.

Summary

If you have any questions after reading this article, join the group in the upper-left corner of the blog to exchange and learn.

Related Article

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.