Build a practical. net Architecture (4) [CodeBuilder-RazorEngine], razorengine

Source: Internet
Author: User

Build a practical. net Architecture (4) [CodeBuilder-RazorEngine], razorengine
To do this, you must first sharpen the tool. The following describes the code generator.

There are a wide variety of code generators, such as codesmith, T4, and dynamic software. Each code generator has its own template parsing engine.

Currently popularNVelocity(I used this before, but I encountered many keyword conflicts in the actual process. Not just $), but changedRazorEngine.

 

Source code: Razorengine http://razorengine.codeplex.com/

If you are in the mvc project, the original project conflicts with the antl3.runtime. dll version of mvc, you can download it here

RazorEngineNET4.0: https://github.com/sanxia/RazorEngineNET4.0

 

Here I use NET 4.0. After compilationRazorEngine. NET4.0.dll System. Web. Razor. Net4.0.dll

Syntax: You should use the razor Syntax of mvc.

Here is a brief introduction to the usage method. It should be enough. Study the advanced usage.

 

Below is a simple unit test:

[TestClass] public class UnitTest1 {public class TestUser {public int ID {get; set;} public string Name {get; set ;}} [TestMethod] public void TestMethod1 () {string strTest = "test @ Model. ID @ Model. name "; TestUser testUser = new TestUser () {ID = 1, Name =" 2 "}; var result = RazorEngine. razor. parse <TestUser> (strTest, testUser );}}

@ Model in the variable strTest is the TestUser object passed into the code. Now you should know how to use it.

 

Let's talk about the implementation method of HY. CodeBuilder:

HY. CodeBuilder is written in C # Of. net4.0. It realizes the data dictionary function and the code generation function. After all, it is something you can play with yourself. How can it be compared with other products,

It would be nice to do it. Here, I learned from the famous saying of Mr. Benshan:What kind of bicycle do you want?

Let's take a look at the following figures.

 

 

Main functions:

1. view database fields and other information

2. You can modify the description of tables and fields.

3. Export excel

4. Code Generation

 

 

The code generator can be downloaded at the end. There are just a few files. Currently, only MsSql, oracle, and mysql are supported. (The remarks about modifying the mysql field have not been implemented. Here we will talk about the problem)

 

HY.CodeBuilder.exe. config can modify the default namespace and template folder (Templates by default)

 

 

The Templates in Templates are defined here. You can modify and expand them. They are all in the Razor syntax, you know.

 

The @ Model in the template is described below.

@ Model: A BuildCodeService object is passed.

Using HY. codeBuilder. model. code; using HY. codeBuilder. model. dataBase; using System. collections. generic; using System. data; using System. linq; using System. runtime. caching; using System. text; namespace HY. codeBuilder. buildCode. core {public class BuildCodeService {public CodeKeywords Keywords {get; private set;} public CodeOptions CodeModel {get; private set;} private DataTable ColumnDataT Able {get; set;} private DataBaseObject DBObject {get; set;} public BuildCodeService (DataBaseObject dbObject, string nameSpace, string tableName, DataTable columnDataTable) {Keywords = new CodeKeywords (); DBObject = dbObject; CodeModel = new CodeOptions (); CodeModel. tableName = tableName; CodeModel. nameSpace = nameSpace; ColumnDataTable = columnDataTable. copy () ;}/// <summary> /// obtain /// </s Ummary> // <returns> </returns> public List <Column> TableColumns () {string cacheKey = DBObject. DBType + "_" + DBObject. baseName + "_" + DBObject. serverIP + CodeModel. tableName; if (Common. cache. get (cacheKey )! = Null) {return (List <Column>) Common. cache. get (cacheKey) ;}list <Column> List = new list <Column> (); foreach (DataRow dr in ColumnDataTable. rows) {Column colum = new Column (); colum. columnsName = dr ["ColumnsName"]. toString (). trim (); colum. description = dr ["description"]. toString (). trim (). replace ("\ r \ n", ""); if (string. isNullOrEmpty (colum. description) {colum. description = colum. columnsName;} co Lum. DBDataType = dr ["DateType"]. toString (). trim (). toLower (); colum. default = dr ["Default"]. toString (). trim (); colum. isNullable = (dr ["allow null"]. toString (). trim () = "√ "? True: false); colum. columnsLength = dr ["Byte Count"]. toString (). trim (); colum. isPK = (dr ["primary key"]. toString (). trim () = "√ "? True: false); colum. IsIdentity = (dr [""]. ToString (). Trim () = "√ "? True: false); colum. dataType = GetDataTypeByColumn (colum); list. add (colum);} Common. cache. insert (cacheKey, list, DateTime. now. addMinutes (5); return list;} public Column PKColumn () {Column column = new Column (); foreach (Column entity in TableColumns () {if (entity. isPK) {column = entity; break;} return column;} public string GetDataTypeByColumn (Column column) {string VariableType = ""; String isNullStr = ""; switch (column. DBDataType. toLower () {case "int": VariableType = "int"; break; case "tinyint": VariableType = "int"; break; case "bigint ": variableType = "Int64"; break; case "decimal": VariableType = "decimal"; break; case "number": VariableType = "decimal"; break; case "clob ": variableType = "string"; break; case "char": VariableType = "string"; break; case "nchar": Vari AbleType = "string"; break; case "nvarchar": VariableType = "string"; break; case "varchar2": VariableType = "string"; break; case "nvarchar2 ": variableType = "string"; break; case "varchar": VariableType = "string"; break; case "text": VariableType = "string"; break; case "smalldatetime ": variableType = "DateTime"; break; case "datetime": VariableType = "DateTime"; break; case "date": VariableTyp E = "DateTime"; break; case "uniqueidentifier": VariableType = "Guid"; break; case "bit": VariableType = "bool"; break; case "image ": variableType = "byte []"; break; default: VariableType = "[" + column + "] not identified. Change it by yourself."; break;} if (column. isNullable) {isNullStr = "? "; If (VariableType =" byte [] "| VariableType =" string ") {isNullStr =" ";}} return VariableType + isNullStr ;}}}

 

The CodeKeywords object stores keywords and is used to support strings that conflict with the template engine. Of course, the Razor syntax is very powerful and I cannot use this class.

CodeOptions: some variables generated by the Code.

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace HY.CodeBuilder.Model.Code{    public class CodeOptions    {        public string NameSpace { get; set; }        public string TableName { get; set; }        public string CreateTime { get { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } }    }}

 

Column class: Field Information

Using System; using System. collections. generic; using System. linq; using System. text; namespace HY. codeBuilder. model. code {public class Column {// <summary> // field name // </summary> public string ColumnsName {get; set ;} /// <summary> /// Description /// </summary> public string Description {get; set ;} /// <summary> /// database Field Type /// </summary> public string DBDataType {get; set ;} /// <summary> /// field type // </summary> public string DataType {get; set ;} /// <summary> /// Default // </summary> public string Default {get; set ;} /// <summary> /// whether it is null /// </summary> public bool IsNullable {get; set ;} /// <summary> /// check whether the primary key is used. /// </summary> public bool IsPK {get; set ;} /// <summary> /// sequence/// </summary> public bool IsIdentity {get; set ;} /// <summary >/// length /// </summary> public string ColumnsLength {get; set ;}}}

 

 

After understanding this, you can define your own template.

 

Download:

HY.CodeBuilder.rar

 

 

Related Articles:

Build a practical. net Architecture (1) [Overview]

Build a practical. net Architecture (2) [Log Module-log4net]

Build a practical. net Architecture (3) [ORM-Dapper + DapperExtensions]

Build a practical. net Architecture (4) [CodeBuilder-RazorEngine]

 

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.