写代码生成工具

昨晚,突发想写 一个代码生成工具,

经过昨晚加班到 两点,今天加班到7点,

大体都弄出个模 样来了,在这里简作介绍下方法好了:

 

主要思想:1.自定义模板;2. 通过IO读写;

个人就不知道别 人是怎么实现的,不过相信通过IO写一个生成简单的实体层,应该还是没问题D。

今晚特地去了解 下 微软,原来它还是有一可以生成工程和代码的类的,真是错过场面了。

 

但是发现我的代 码还是比它们的少了;

灵活性还好很 多;

可以自定义模 板;

通过两个接口取 代了烦锁的抽象工场模式;

并支持操作 Access、SQL、ODBC、Oracle ;

很好地解决分页 问题;

一个存储过程实现一张表的增删改;

 

不过有一很大的 缺点就是:眼前还没解决生成工程的问题,现在就来晒一下先:

 

可生成 BLL、DAL、Model、存储过程、插件层(尚未集合入,稍候完善)

 

/*
 * 这是一个代码生成器的说明文档 *
 *
 * 实现思路步骤:*
 *
 * 1.设置项目命名
 * 2.创建存放文件夹
 * 3.读取模板信息
 * 4.生成目标文件
 * 5.存放目标文件
 * 6.结束提示
 *
 */

namespace CodeDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public ProjectModel projModel = new ProjectModel();
        public string place=" ";

        private void btnCrModel_Click(object sender, EventArgs e)
        {
            /*
             * set Project Namings :设置项目命名
             */
            projModel.Project = "CodeDemo";
            projModel.Bll = "CodelBLL";
            projModel.Dal = "CodeDAL";
            projModel.Entity = "CodeModel";
            projModel.Plugin = "CodePlugin";

            projModel.Bllspace = "Codel.BLL";
            projModel.Dalspace = "Code.DAL";
            projModel.Entityspace = "Code.Model";
            projModel.Pluginspace = "Code.Plugin";


            /*
             * Create folders from this project:创建文件夹
             * General folders BasePath: C:/Project Name:项目文件夹存放位置 C:盘根目录下
             */

            this.Text = "正在创建文件.....";
            Thread.Sleep(2000);
            GeneralFolders();
            DataTable tb = SqlHelper.GetDataSet(" select name from sys.objects where type='u' ");
            int i = 1;
            foreach (DataRow row in tb.Rows)
            {
                string tmpString = row["name"].ToString();
                string tableName = tmpString.Substring(0, 1).ToUpper() + tmpString.Substring(1, tmpString.Length - 1);
                Thread.Sleep(2000);
                this.Text = "正在生成第"+i+"个实体类.....";
                GeneralEntity(tableName);
                this.Text = "正在生成第" + i + "个业务逻辑类.....";
                Thread.Sleep(2000);
                GeneralBLL(tableName);
                this.Text = "正在生成第" + i + "个数据存储类.....";
                Thread.Sleep(2000);
                GeneralDAL(tableName);
                this.Text = "正在生成第" + i + "个存储过程.....";
                Thread.Sleep(2000);
                GeneralProcedure(tableName);
                this.Text = "正在生成第" + i + "个常用文件.....";
                Thread.Sleep(2000);
                GeneralUsualFile();
                i++;
            }
            this.Text = "Marksion代码生成器v1.0";
            MessageBox.Show("生成成功啦!!");
        }

        /// <summary>
        /// Crteate Folders 创建文件夹
        /// </summary>
        public void GeneralFolders()
        {
            Directory.CreateDirectory("C:/" + projModel.Project);
            Directory.CreateDirectory("C:/" + projModel.Project + "/" + projModel.Bll);
            Directory.CreateDirectory("C:/" + projModel.Project + "/" + projModel.Dal);
            Directory.CreateDirectory("C:/" + projModel.Project + "/" + projModel.Entity);
            Directory.CreateDirectory("C:/" + projModel.Project + "/" + projModel.Plugin);

        }

        /// <summary>
        /// General Entity Layer:生成实体层
        /// </summary>
        /// <param name="tableName">tableNane:表名</param>
        public void GeneralEntity(string tableName)
        {

            DataTable fdTb = SqlHelper.GetDataSet(" select name from syscolumns where id= object_id('" + tableName + "') ");

            StreamReader read = new StreamReader("http://www.cnblogs.com/template/EntityModel.txt", System.Text.Encoding.GetEncoding("gbk"));

            string fileString = read.ReadToEnd();
            read.ReadToEnd();
            read.Close();
            read.Dispose();
            StreamWriter write = new StreamWriter("C:/" + projModel.Project + "/" + projModel.Entity + "/" + tableName + ".cs", false, System.Text.Encoding.UTF8);

            try
            {
                string modelString = "";
                foreach (DataRow row in fdTb.Rows)
                {
                    string field = row["name"].ToString();
                    string _field = "_" + field;
                    string method = field.Substring(0, 1).ToUpper() + field.Substring(1, field.Length - 1);
                    modelString += "\t private string " + _field + "= string.Empty; \r\n";
                    modelString += "\t public string " + method + " {get { return " + _field + "; } set { " + _field + " = value; }} \r\n\r\n";

                }
                fileString = fileString.Replace("<@namespace@>", projModel.Entityspace);
                fileString = fileString.Replace("<@time@>", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss "));
                fileString = fileString.Replace("<@table@>", tableName);
                fileString = fileString.Replace("<@model@>", tableName);
                fileString = fileString.Replace("<@fields@>", modelString);
                write.Write(fileString);
                write.Close();
                write.Dispose();
            }
            catch (IOException ex)
            {
                read.Close();
                read.Dispose();
                write.Close();
                write.Dispose();
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// General Business Logic Layer:生成业务逻辑层
        /// </summary>
        /// <param name="tableName">tableNane:表名</param>
        public void GeneralBLL(string tableName)
        {
            string fileString = ReadFileString(@"http://www.cnblogs.com/template/BllModel.txt");
            fileString = fileString.Replace("<@entitySpace@>", projModel.Entityspace);
            fileString = fileString.Replace("<@dalSpace@>", projModel.Dalspace);
            fileString = fileString.Replace("<@namespace@>", projModel.Bllspace);
            fileString = fileString.Replace("<@entity@>", tableName);
            WriteFileString(fileString, @"C:/" + projModel.Project + "/" + projModel.Bll + "/"+tableName+"BLL.cs");
        }

        /// <summary>
        /// General DataAccess Layer:生成数据存储层
        /// </summary>
        /// <param name="tableName">tableNane:表名</param>
        public void GeneralDAL(string tableName)
        {
            //生成数据存储层

            //DataTable fdTb = SqlHelper.GetDataSet("select name from syscolumns where id=object_id('"+tableName+"')");

            string fileString = ReadFileString(@"http://www.cnblogs.com/template/DalModel.txt");

            /*
            string fieldString = "";
            foreach(DataRow row in fdTb.Rows)
            {
                fieldString += "";
            }
           */

            fileString = fileString.Replace("<@entitySpace@>",projModel.Entityspace);
            fileString = fileString.Replace("<@namespace@>",projModel.Dalspace);
            fileString = fileString.Replace("<@entity@>",tableName);

            WriteFileString(fileString, @"C:/" + projModel.Project + "/" + projModel.Dal + "/"+tableName+"DAL.cs");
        }

        /// <summary>
        /// General Procedure Files:生成存储过程文件
        /// </summary>
        /// <param name="tableName">tableNane:表名</param>
        public void GeneralProcedure(string tableName)
        {
           
            string safeSql =
                "SELECT a.name AS 'columnName', b.name AS 'columnType', a.length AS 'length'"+
                "FROM sys.syscolumns AS a INNER JOIN "+"sys.systypes AS b ON a.xtype = b.xusertype INNER JOIN "+
                "sys.sysobjects AS d ON a.id = d.id  WHERE (d.id = OBJECT_ID('"+tableName+"')) ";
            DataTable fdTb = SqlHelper.GetDataSet(safeSql);

            string fieldString = ReadFileString(@"http://www.cnblogs.com/template/ProcedureModel.txt");

            OperateModel op = new OperateModel();

            string  a="";
            string  b="";
            string  c=fdTb.Rows[0][0].ToString();
            string  d="";
            string  e="";

            foreach(DataRow row in fdTb.Rows)
            {
                op.Param += "@" + row["columnName"].ToString() + place + row["columnType"].ToString() + "(" + row["length"].ToString() + ") ,\r\n";
                a+=row["columnName"].ToString()+", ";
                b+="@"+row["columnName"].ToString()+", ";
                d+=row["columnName"].ToString()+"="+"@"+row["columnName"].ToString()+", ";
            }
           
            a=a.Substring(0,a.LastIndexOf(","));
            b=b.Substring(0,b.LastIndexOf(","));
            d=d.Substring(0,d.LastIndexOf(",")-1);

            d = d.Substring(d.IndexOf(",")+1);
            e = "("+a.Substring(a.IndexOf(",")+1)+") values ("+b.Substring(b.IndexOf(",")+1)+")";

            op.Param = op.Param.Substring(0,op.Param.LastIndexOf(","));
            op.Add=tableName+place+e;
            op.Update=tableName+place+"set "+d+" where "+c+"=@"+c;
            op.Delete=tableName+place+" where "+c+"=@"+c;

            fieldString=fieldString.Replace("<@tableName@>",tableName);
            fieldString=fieldString.Replace("<@inparams@>",op.Param);
            fieldString=fieldString.Replace("<@add@>",op.Add);
            fieldString=fieldString.Replace("<@update@>",op.Update);
            fieldString=fieldString.Replace("<@delete@>",op.Delete);

            WriteFileString(fieldString,@"C:/" + projModel.Project + "/proc_" +tableName+".sql");
        }

        /// <summary>
        /// General Plugin Files:生成插件层
        /// </summary>
        public void GeneralPlugin()
        { }
        //生成通用的数据库 操作类
        public void GeneralUsualFile()
        {
            GeneralAFile(@"http://www.cnblogs.com/template/DataBase.txt", @"C:/" + projModel.Project + "/" + projModel.Dal + "/DataBase.cs");
            GeneralAFile(@"http://www.cnblogs.com/template/DataBaseManager.txt", @"C:/" + projModel.Project + "/" + projModel.Dal + "/DataBaseManager.cs");
        }

        #region
        /// <summary>
        /// File Read And Write, but with less change, rather than copy a file:
        /// 文件读写,相当于复制一个文件,但有少量内容更改
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="targetPath"></param>
        public void GeneralAFile(string sourcePath, string targetPath)
        {
            String fileString = ReadFileString(sourcePath);
            fileString = fileString.Replace("<@namespace@>", projModel.Dalspace);
            WriteFileString(fileString,targetPath);
        }

        // 读取文件流
        public string ReadFileString(string sourcePath)
        {
            StreamReader reader = new StreamReader(sourcePath, System.Text.Encoding.GetEncoding("gbk"));
            string fileString = "";
            try
            {
                fileString= reader.ReadToEnd();
                reader.Close();
                reader.Dispose();
                return fileString;
            }
            catch (IOException ex)
            {
                reader.Close();
                reader.Dispose();
                MessageBox.Show("无法读取文件! \n 原因可能是=" + ex.StackTrace);
                return null;
            }
        }

        //写入文件流
        public void WriteFileString(string fileString, string targetPath)
        {
            StreamWriter writer = new StreamWriter(targetPath, false, System.Text.Encoding.UTF8);
            try
            {
                writer.Write(fileString);
                writer.Close();
                writer.Dispose();
            }
            catch(IOException ex)
            {
                writer.Close();
                writer.Dispose();
                MessageBox.Show("无法写入文件! \n 原因可能是=" + ex.StackTrace);
            }
        }

        #endregion
    }
}

你可能感兴趣的:(代码生成)