代码生成工具

开发了个简单的代码生成工具,生成Model层的实体类,并生成Insert和Update的SQL语句。

程序结构:

IGenerator:生成器接口

BaseGenerator:生成器基类,实现了一些生成器必须调用的方法和定义了一些必须的属性

ModelGenerator:Model层的实体类生成器,核心类

IVisitor:访问数据库的接口

OracleVisitor:Oracle数据库访问

SqlServerVisitor:SQLServer数据库访问

下面是具体的实现:

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace CodeGenerator
 7 {
 8     public interface IGenerator
 9     {
10         /// <summary>
11         /// Generate
12         /// </summary>
13         void Generator();
14     }
15 }
16 

 

  

 

BaseGenerator
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Data;
 6 using System.IO;
 7 
 8 namespace CodeGenerator
 9 {
10     public class BaseGenerator
11     {
12         /// <summary>
13         /// The scheme of database or table
14         /// </summary>
15         public DataSet DBScheme { getset; }
16         /// <summary>
17         /// The target table to generate
18         /// </summary>
19         public string TableName { getset; }
20         /// <summary>
21         /// The db connection string
22         /// </summary>
23         public string DBConnectionString { getset; }
24         /// <summary>
25         /// Filter some special chars,avoid excute sql text error.
26         /// </summary>
27         /// <param name="str"></param>
28         /// <returns></returns>
29         public string FilterSQLSpecialChar(string str)
30         {
31             str = str.Replace("'""''");
32             return str;
33         }
34         /// <summary>
35         /// Write string to file
36         /// </summary>
37         /// <param name="content">the content string</param>
38         /// <param name="fileName">the file to be writed,will convert the old content in the file</param>
39         public void WriteToFile(string content, string fileName)
40         {
41             string path = "Result";
42             if (!Directory.Exists(path))
43             {
44                 Directory.CreateDirectory(path);
45             }
46             fileName = Path.Combine(path, fileName);
47             using (StreamWriter sw = new StreamWriter(fileName, false, Encoding.Default))
48             {
49                 sw.Write(content);
50             }
51         }
52         /// <summary>
53         /// Get C# type from DataSet type
54         /// </summary>
55         /// <param name="typeName">the type of DataSet column</param>
56         /// <returns></returns>
57         public string GetColumnType(string typeName)
58         {
59             string result = string.Empty;
60             switch (typeName)
61             {
62                 case "Decimal":
63                     result = "int";
64                     break;
65                 default:
66                     result = "string";
67                     break;
68             }
69             return result;
70         }
71     }
72 }
73 

 

 

ModelGenerator
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 
  6 namespace CodeGenerator
  7 {
  8     public class ModelGenerator : BaseGenerator, IGenerator
  9     {
 10         /// <summary>
 11         /// Property
 12         /// </summary>
 13         /// <param name="name">from table column</param>
 14         /// <param name="type">from table column</param>
 15         /// <returns></returns>
 16         private string PropertyGenerator(string name, string type)
 17         {
 18             return string.Format("public {0} {1} {{ get; set; }}\r\n\r\n", type, name);
 19         }
 20         /// <summary>
 21         /// Add method,method name:GetAddSQL
 22         /// </summary>
 23         /// <param name="columnsList">All columns in table</param>
 24         /// <returns></returns>
 25         private string AddMethodGennerator(List<string> columnsList)
 26         {
 27             StringBuilder sbText = new StringBuilder();
 28             sbText.Append("public string GetAddSQL()\r\n");
 29             sbText.Append("{\r\n");
 30             sbText.Append("StringBuilder sbSql = new StringBuilder();\r\n");
 31             sbText.AppendFormat("sbSql.Append(\"insert into {0} values (\");\r\n", TableName);
 32             foreach (var item in columnsList)
 33             {
 34                 sbText.AppendFormat("sbSql.Append(\"'\" + {0}.ToString().Replace(\"'\",\"''\") +\"',\");\r\n", item);
 35             }
 36             sbText.Append("string result = sbSql.ToString();\r\n");
 37             sbText.Append("result = result.Substring(0, result.Length - 1); //last ',' should be deleted\r\n");
 38             sbText.Append("result += \")\";\r\n");
 39             sbText.Append("return result;\r\n");
 40             sbText = sbText.Append("}\r\n");
 41             return sbText.ToString();
 42         }
 43         /// <summary>
 44         /// Update method,method name:GetUpdateSQL
 45         /// </summary>
 46         /// <param name="columnsList">All columns in table</param>
 47         /// <returns></returns>
 48         private string UpdateMethodGennerator(List<string> columnsList)
 49         {
 50             StringBuilder sbText = new StringBuilder();
 51             sbText.Append("public string GetUpdateSQL()\r\n");
 52             sbText.Append("{\r\n");
 53             sbText.Append("StringBuilder sbSql = new StringBuilder();\r\n");
 54             sbText.AppendFormat("sbSql.Append(\"update {0set \");\r\n", TableName);
 55             foreach (var item in columnsList)
 56             {
 57                 sbText.AppendFormat("sbSql.Append(\"{0= '\" + {0}.ToString().Replace(\"'\",\"''\") + \"',\");\r\n", item);
 58             }
 59             sbText.AppendFormat("sbSql.Append(\" where {0}={0}\");\r\n", columnsList[0]);
 60             sbText.Append("return sbSql.ToString();\r\n");
 61             sbText.Append("}\r\n");
 62             return sbText.ToString();
 63         }
 64 
 65         #region IGenerator Members
 66 
 67         public void Generator()
 68         {
 69             string fileName = string.Format("{0}.cs", TableName);
 70             string strContent = string.Empty;
 71             string name = string.Empty;
 72             string type = string.Empty;
 73             IVisitor dbVisitor = new OracleVisitor();
 74             dbVisitor.Init(DBConnectionString);
 75             DBScheme = dbVisitor.Get(TableName);
 76             if (DBScheme == null || DBScheme.Tables.Count == 0)
 77             {
 78                 throw new Exception("No table in the database");
 79             }
 80             //Namespace
 81             strContent += "using System;\r\n";
 82             strContent += "using System.Text;\r\n";
 83             //Class
 84             strContent += string.Format("public class {0} \r\n",TableName);
 85             strContent += "{\r\n";
 86             int columnCount = DBScheme.Tables[0].Columns.Count;
 87             List<string> columnsList = new List<string>();
 88             //Property
 89             for (int i = 0; i < columnCount; i++)
 90             {
 91                 name = DBScheme.Tables[0].Columns[i].ColumnName;
 92                 type = GetColumnType(DBScheme.Tables[0].Columns[i].DataType.Name);
 93                 strContent += PropertyGenerator(name, type);
 94                 columnsList.Add(name);
 95             }
 96             //Add method
 97             strContent += AddMethodGennerator(columnsList);
 98             //Update method
 99             strContent += UpdateMethodGennerator(columnsList);
100             strContent += "}\r\n";
101             WriteToFile(strContent, fileName);
102         }
103 
104         #endregion
105     }
106 }
 

 

 

 

IVisitor
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Data;
 6 
 7 namespace CodeGenerator
 8 {
 9     /// <summary>
10     /// db access interface
11     /// </summary>
12     public interface IVisitor
13     {
14         /// <summary>
15         /// Initialize the db connection string
16         /// </summary>
17         /// <param name="connStr">DBConnectionString</param>
18         void Init(string connStr);
19         /// <summary>
20         /// Get table scheme
21         /// </summary>
22         /// <param name="tableName">table name</param>
23         /// <returns></returns>
24         DataSet Get(string tableName);
25     }
26 }
27 

 

 

 

OracleVisitor
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Data;
 6 using System.Data.OracleClient;
 7 
 8 namespace CodeGenerator
 9 {
10     /// <summary>
11     /// Access oracle db
12     /// </summary>
13     public class OracleVisitor : IVisitor
14     {
15         /// <summary>
16         /// The connection string
17         /// </summary>
18         public string DBConnectionString { getset; }
19 
20         /// <summary>
21         /// Implement IVisitor,initialize the db connection string
22         /// </summary>
23         /// <param name="connStr">DBConnectionString</param>
24         public void Init(string connStr)
25         {
26             DBConnectionString = connStr;
27         }
28         /// <summary>
29         /// Implement IVisitor, get table scheme,use sql:select * from tableNamhe where rownum < 2
30         /// </summary>
31         /// <param name="tableName">the name of table</param>
32         /// <returns></returns>
33         public DataSet Get(string tableName)
34         {
35             if (string.IsNullOrEmpty(DBConnectionString))
36             {
37                 throw new Exception("Database connection string is null or empty,please call method Init to initialize connection string.");
38             }
39             DataSet ds = new DataSet();
40             string sqlText = string.Format("select * from {0} where rownum < 2", tableName);
41             using (OracleConnection conn = new OracleConnection(DBConnectionString))
42             {
43                 OracleDataAdapter da = new OracleDataAdapter(sqlText, conn);
44                 da.Fill(ds);
45             }
46             return ds;
47         }
48     }
49 }
50 
SqlServerVisitor
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Data;
 6 using System.Data.SqlClient;
 7 
 8 namespace CodeGenerator
 9 {
10     /// <summary>
11     /// Access oracle db
12     /// </summary>
13     public class SqlServerVisitor : IVisitor
14     {
15         /// <summary>
16         /// The connection string
17         /// </summary>
18         public string DBConnectionString { getset; }
19 
20         /// <summary>
21         /// Implement IVisitor,initialize the db connection string
22         /// </summary>
23         /// <param name="connStr">DBConnectionString</param>
24         public void Init(string connStr)
25         {
26             DBConnectionString = connStr;
27         }
28         /// <summary>
29         /// Implement IVisitor, get table scheme,use sql:select * from tableNamhe where rownum < 2
30         /// </summary>
31         /// <param name="tableName">the name of table</param>
32         /// <returns></returns>
33         public DataSet Get(string tableName)
34         {
35             if (string.IsNullOrEmpty(DBConnectionString))
36             {
37                 throw new Exception("Database connection string is null or empty,please call method Init to initialize connection string.");
38             }
39             DataSet ds = new DataSet();
40             string sqlText = string.Format("select * from {0} where rownum < 2", tableName);
41             using (SqlConnection conn = new SqlConnection(DBConnectionString))
42             {
43                 SqlDataAdapter da = new SqlDataAdapter(sqlText, conn);
44                 da.Fill(ds);
45             }
46             return ds;
47         }
48     }
49 }
50 

 

 

 

 

Caller
 1             try
 2             {
 3                 ModelGenerator gen = new ModelGenerator();
 4                 gen.DBConnectionString = txtConnStr.Text;
 5                 gen.TableName = txtTableName.Text;
 6                 gen.Generator();
 7                 MessageBox.Show("Succefully!");
 8             }
 9             catch (Exception ex)
10             {
11                 MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
12             }

 

 

 

posted @ 2009-12-03 09:43 消失的风 阅读(...) 评论(...) 编辑 收藏