寫代碼產生工具

來源:互聯網
上載者:User

昨晚,突發想寫 一個代碼產生工具,

經過昨晚加班到 兩點,今天加班到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
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.