Simple code generator principle analysis

The article ( in simple terms three-tier architecture ) analysis of the simple three-tier architecture. Including Model, DAL (Data Access Layer), BLL (business logic) implementation.

The actual development, due to the operation code repetition, will spend a lot of time, if the code generator to automatically generate code for three-tier architecture, which saves energy, but also save a lot of time to do other business logic code, increase development efficiency.

Code generators used are: soft -, CodeSmith like.

Simple code generator described basic functions:

A key generation Model, the DAL, the BLL, Model, comprising automatically generating a corresponding database table, including generating properties, add, modify, delete, query.

Interface display:

Builder development techniques:

  1. Query system view: INFORMATION_SCHEMA.TABLES, INFORMATION_SCHEMA.COLUMNS available database tables, columns of information.
  2. String concatenation: using the StringBuilder which AppendLine () will wrap.
  3. Writes a string to a text file: File.WriteAllText ()
  4. To reduce the development effort and assume some more conditions, such as the table's primary key are Id, and automatically grow, and then gradually improve after

Key Code:

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;

namespace CodeGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 执行ExecuteDataTable(),得到DataTable
/// </summary>
/// <param name="cmdText"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public DataTable ExecuteDataTable(string cmdText,
params SqlParameter[] parameters)
{
using (SqlConnection conn=new SqlConnection(txtConnStr.Text))
{
conn.Open();
using(SqlCommand cmd=conn.CreateCommand())
{
cmd.CommandText = cmdText;
cmd.Parameters.AddRange(parameters);
using (SqlDataAdapter adapter=new SqlDataAdapter (cmd))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
}
}

}

private void Form1_Load(object sender, EventArgs e)
{
txtConnStr.Text = @"Data Source=EYES\SQLEXPRESS;Initial Catalog=SanCeng;Integrated Security=True";
}

private void btnConnStr_Click(objectSENDER, EventArgs E)
{

// Clear
clbTables.Items.Clear ();
// query system attempts String SQL = " SELECT * from the INFORMATION_SCHEMA.TABLES " ; the DataTable dt = ExecuteDataTable (SQL); // acquisition system according TABLE_NAME view foreach (the DataRow Row in dt.Rows) { String TableName = Convert.ToString (Row [ " TABLE_NAME " ]); clbTables.Items.Add (TableName); } } Private void btnGo_Click ( Object











SENDER, EventArgs E)
{
// connection string
// Method AppendLine () appending the string and automatically performs a line the foreach ( String tableName in clbTables.CheckedItems) { String SQL = " SELECT * WHERE TABLE_NAME from INFORMATION_SCHEMA.COLUMNS TABLE_NAME = @ " ; the DataTable dt = ExecuteDataTable (SQL, new new the SqlParameter ( " TABLE_NAME " , tableName)); #region generating the Model CreatModel (tableName, dt); #endregion #region generating the DAL CreatDAL (tableName, dt);














#endregion
#region 生成BLL
CreatBLL(tableName, dt);
#endregion
}
}

private static void CreatDAL(string tableName, DataTable dt)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("using System;");
sb.AppendLine("using System.Collections.Generic;");
sb.AppendLine("using System.Linq;");
sb.AppendLine("using System.Text;");
sb.AppendLine("using 三层架构Demo.Model;");
sb.AppendLine("using System.Data.SqlClient;");
sb.AppendLine("using System.Data;");
sb.AppendLine("namespace 三层架构Demo.DAL");
sb.AppendLine("{");
sb.AppendLine("class " + tableName + "DAL");
sb.AppendLine("{");
//去掉Id
sb.AppendLine(" public int Addnew(" + tableName + " model)");
sb.AppendLine("{");
List<String> cols = new List<string>();
List<String> parameters = new List<string>();
foreach (DataRow row in dt.Rows)
{
string col = Convert.ToString(row["COLUMN_NAME"]);
string= Parameter "" ;
IF (! col.ToLower () = " ID " )
{
Parameter = " @ " + Convert.ToString (Row [ " COLUMN_NAME " ]);
cols.Add (COL);
Parameters.Add (Parameter) ;
}
// Parameters.Add (Parameter) placed outside plus a NULL, it will be more of a comma
// Parameters.Add (Parameter); } sb.AppendLine ( " String SQL = \" INSERT INTO " + + tableName "("



+ String.Join(",", cols) + ") output inserted.Id values(" + String.Join(",", parameters) + ")\";");
sb.AppendLine("object obj= SQLHelper.ExecuteScalar(sql");

foreach (DataRow row in dt.Rows)
{
string col = Convert.ToString(row["COLUMN_NAME"]);
if (col.ToLower() != "id")
{
sb.AppendLine(",new SqlParameter(\"" + col + "\",model." + col + ")");
}

}
sb.AppendLine(");");
sb.AppendLine("return Convert.ToInt32(obj);");
sb.AppendLine("}");
//Delete方法

sb.AppendLine(" public int Delete(int id)");
sb.AppendLine("{");
sb.AppendLine(" string sql = \"delete from " + tableName + " where Id=@Id\";");
sb.AppendLine("return SQLHelper.ExecuteNonQuery(sql,new SqlParameter(\"Id\",id));");
sb.AppendLine("}");

//Update方法
sb.AppendLine("public int Update("+tableName+" model)");
sb.AppendLine("{");, [] = uParams1, (
string is thefrom col in cols select col+"=@"+col).ToArray();

sb.AppendLine(" string sql = \"update "+tableName+" set "+String.Join(",",uParams1)+" where Id=@Id\";");

string[] uParams2 = (from col in cols select "new SqlParameter(\"" + col + "\",model." + col + ")").ToArray();
sb.AppendLine(" return SQLHelper.ExecuteNonQuery(sql, " + String.Join(",", uParams2) + " ,new SqlParameter(\"Id\",model.Id));");
sb.AppendLine("}");

//GetId方法
sb.AppendLine(" public "+tableName+" Get(int id)");
sb.AppendLine("{");
sb.AppendLine("string sql=\"select * from "+tableName+" where Id=@Id\";");
sb.AppendLine(" DataTable dt=SQLHelper.ExecuteDataTable(sql,new SqlParameter(\"Id\",id));");
sb.AppendLine("if (dt.Rows.Count<=0)");
sb.AppendLine("{");
sb.AppendLine(" return null;");
sb.AppendLine("}");
sb.AppendLine(" else if (dt.Rows.Count==1)");
sb.AppendLine("{");
sb.AppendLine(""+tableName+" model1 = new "+tableName+"();");
foreach (DataRow row in dt.Rows)
{
string col = Convert.ToString(row["COLUMN_NAME"]);
string dataType = Convert.ToString(row["data_TYPe"]);
sb.AppendLine("model1." + col + " = Convert." + Get(GetType(dataType).ToString()) + " (Dt.Rows [0] [\" " + COL + " \ "]); " );

}
sb.AppendLine ( " return MODEL1; " );
sb.AppendLine ( " } " );
sb.AppendLine ( " the else " );
sb.AppendLine ( " { " );
sb.AppendLine ( " the throw new new Exception (\ "database has two or more duplicate data \"); " );
sb.AppendLine ( " } " );
sb.AppendLine("}");

//IEnumerable()方法
sb.AppendLine(" public IEnumerable<"+tableName+"> GetAll()");
sb.AppendLine("{");
sb.AppendLine(" string sql = \"select * from "+tableName+"\";");
sb.AppendLine("DataTable dt = SQLHelper.ExecuteDataTable(sql);");
sb.AppendLine(" List<"+tableName+"> list = new List<"+tableName+">();");
sb.AppendLine(" foreach (DataRow row in dt.Rows)");
sb.AppendLine("{");
sb.AppendLine("" + tableName + " model = new " + tableName + "();");
foreach (DataRow row in dt.Rows)
{
string col = Convert.ToString(row["COLUMN_NAME"]);
string dataType = Convert.ToString(row["data_TYPE"]);
sb.AppendLine("model." + col + " = Convert." + Get(GetType(dataType).ToString()) + "(row[\"" + col + "\"]);");

}
sb.AppendLine(" list.Add(model);");
sb.AppendLine("}");
sb.AppendLine("return list;");
sb.AppendLine("} " );
Sb.AppendLine ( " } " );
sb.AppendLine ( " } " );
File.WriteAllText ( @" D: \ " + tableName + " DAL.cs " , sb.ToString ());


}
// / <Summary> /// converted to type C # type database /// </ Summary> /// <param name = "dataType"> </ param> /// <Returns> </ Returns>privatestatic Type GetType(string dataType) {switch (dataType.ToLower())







{
case "nvarchar":
case "varchar":
case "nchar":
case "char":
return typeof(string);
case "int" :
return typeof(int);
case "bigint":
return typeof(long);
case "bit":
return typeof(bool);
case "datetime":
return typeof(DateTime);
default:
return typeof(object);
}

}

private static string Get(string dataType)
{

switch (dataType.ToLower())
{
case "system.string":
return "ToString";
case "system.int32":
return "ToInt32 " ;
Case " System.Int64 " :
return " ToInt64 " ;
Case " System.DateTime " :
return " ToDateTime " ;
Case " System.Boolean " :
return " ToBoolean " ;

default :
the throw new new Exception ( " no match is found data type " );

}
}
private static void CreatModel(string tableName, DataTable dt)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("using System;");
sb.AppendLine("using System.Collections.Generic;");
sb.AppendLine("using System.Linq;");
sb.AppendLine("using System.Text;");
sb.AppendLine("namespace 三层架构Demo.Model");
sb.AppendLine("{");
sb.AppendLine("");
sb.AppendLine("class " + tableName);
sb.AppendLine("{");

foreach (DataRow row in dt.Rows)
{
string dataType = Convert.ToString(row["DATA_TYPE"]);

string columnName = Convert.ToString(row["COLUMN_NAME"]);

sb.AppendLine("public " + GetType(dataType) + " " + columnName + " { get;set;}");
}
sb.AppendLine("}");
sb.AppendLine("}");
File.WriteAllText(@"d:\" + tableName + ".cs", sb.ToString());
//MessageBox.Show(sb.ToString());

}

private static void CreatBLL(string tableName, DataTable dt)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("using System;");
sb.AppendLine("using System.Collections.Generic;");
sb.AppendLine("using System.Linq;");
sb.AppendLine("using System.Text;");
sb.AppendLine("using 三层架构Demo.Model;");
sb.AppendLine("using 三层架构Demo.DAL;");
sb.AppendLine("using System.Data.SqlClient;");
sb.AppendLine("using System.Data;");
sb.AppendLine("namespace 三层架构Demo.BLL");
sb.AppendLine("{");
sb.AppendLine("class " + tableName+"BLL");
sb.AppendLine("{");
sb.AppendLine("public int Addnew("+tableName+" model)");
sb.AppendLine("{");
sb.AppendLine(" return new "+tableName+"DAL().Addnew(model);");
sb.AppendLine("}");
sb.AppendLine(" public int Delete(int id)");
sb.AppendLine("{");
sb.AppendLine(" return new "+tableName+"DAL().Delete(id);");
sb.AppendLine("}");
sb.AppendLine(" public int Update("+tableName+" model)");
sb.AppendLine("{");
sb.AppendLine(" return new " + tableName + "DAL().Update(model);");
sb.AppendLine("}");
sb.AppendLine(" public "+tableName+" Get(int id)");
sb.AppendLine("{");
sb.AppendLine(" return new "+tableName+"DAL().Get(id);");
sb.AppendLine("}");
sb.AppendLine(" public IEnumerable<"+tableName+"> GetAll()");
sb.AppendLine("{");
sb.AppendLine(" return new "+tableName+"DAL().GetAll();");
sb.AppendLine("}");
sb.AppendLine("}");
sb.AppendLine("}");
File.WriteAllText(@"d:\" + tableName + "BLL.cs", sb.ToString());
}
}
}



Summary:
ignore a lot of limitations, so the code generator function is not perfect. With the increase of the condition to be considered, a code generator increasingly complex. But always changing them, with patience, continue AppendLine () to add a new statement, I believe that the function will be more perfect. "
工欲善其事必先利其器", the programmer will not only use code generator, and know that it is the principle of good programmers. Do not "knowing but not the why."

Quote from: http://www.cnblogs.com/OceanEyes/archive/2012/02/16/CodeGenerator.html

Reproduced in: https: //www.cnblogs.com/zhangchenliang/archive/2012/02/26/2369027.html

Guess you like

Origin blog.csdn.net/weixin_34360651/article/details/93494886