码迷,mamicode.com
首页 > Windows程序 > 详细

小白C#窗体系列-12.逆天代码生成器

时间:2014-11-14 12:08:25      阅读:531      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   ar   os   sp   for   文件   数据   

有些代码重复劳动,用网上的代码生成器太烦了,很多代码都存在明显的注入漏洞,很多代码风格都不适合自己。。。于是就花了一个上午写了个代码生成器,源码共享一下,其实功能点很简单,就是逆天又想偷点懒而已。。。     本来是准备昨天晚上编的,后来喝的有点高了。。。好了,不屁话了直接入正轨:
 就重点讲一下model类的生成吧:
先调用model窗体 
 
            ModelForm f1 = ModelForm.GetModelForm(); //单例(不清楚的上网搜搜吧)
            
            this.Hide();
            
            f1.ShowDialog();//它会自动阻塞线程
            
            this.Show();
   ModelForm加载时执行: 
        private void ModelForm_Load(object sender, EventArgs e)
        {
            this.Hide();
            
            MainForm main = MainForm.GetMainForm();
            
            if (DialogResult.OK == main.ShowDialog())//返回则主窗体显示出来
            {
                this.Show();
 
                txtConnStr.Text = main.connStr;//获取连接字符串
 
                #region 查询表并加载到combox里面
                using (SqlConnection conn = new SqlConnection(main.connStr))
                {
                    using (SqlCommand cmd = new SqlCommand("select table_name from INFORMATION_SCHEMA.TABLES", conn))
                    {
                        try
                        {
                            conn.Open();
                            
                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                if (reader.HasRows)
                                {
                                    while (reader.Read())
                                    {
                                        comBoxTables.Items.Add(reader.GetString(0));
                                    }
                                }
                            }
                        }
                        catch
                        {
                            MessageBox.Show("莫名异常,数据库估计出问题了~");
                        }
                    }
                }
                try
                {
                    comBoxTables.SelectedIndex = 0;
                }
                catch
                {
                    MessageBox.Show("数据库木有表啊~");
                }
 
                #endregion
            }
            else//当跳出的窗体关闭时,主窗体也会随之关闭
            {
                this.Close();
            }
        }
 
 这个是生成代码: 
        private void btnGetCode_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtNamespace.Text.Trim()))
            {
                MessageBox.Show("命名空间不能为空!", "逆天友情提醒");
            }
 
            if (comBoxTables.SelectedIndex == -1)
            {
                MessageBox.Show("你确定你选择了Table?", "逆天友情提醒");
            }
 
            //准备生成代码
            string table = comBoxTables.SelectedItem.ToString();
 
            List<TableInfo> list = new List<TableInfo>();
 
            #region 选中表列的信息~name,null,type
            
            using (SqlConnection conn = new SqlConnection(txtConnStr.Text.Trim()))
            {
                using (SqlCommand cmd = new SqlCommand("select column_name,is_nullable,data_type from INFORMATION_SCHEMA.COLUMNS where table_name=@tbName", conn))
                {
                    cmd.Parameters.AddWithValue("@tbName", table);//add已经过时了
                    
                    conn.Open();
                    
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                TableInfo info = new TableInfo();
                                
                                info.T_Name = FormatName(reader.GetString(0));//规范化一下命名规范
                                
                                info.T_Null = reader.GetString(1);
                                
                                info.T_Type = FormatType(reader.GetString(2), reader.GetString(1).ToLower());//把数据库里面类型转换成C#里面的类型+可空类型
                                
                                list.Add(info);
                            }
                        }
                    }
                }
            }
            #endregion
 
            #region 生成Model类
            
            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("");
            
            sb.AppendLine("namespace " + FormatName(txtNamespace.Text.Trim()) + ".Model");
            
            sb.AppendLine("{");
            
            sb.AppendLine("\tpublic class " + FormatName(table));
            
            sb.AppendLine("\t{");
            
            foreach (TableInfo item in list)
            {
                sb.AppendLine("\t\tpublic " + item.T_Type + " " + item.T_Name + " { get; set; }");
            }
            
            sb.AppendLine("\t}");
            
            sb.AppendLine("}");
 
            rtxtMain.Text = sb.ToString();
 
            //生成cs文件
            try
            {
                File.WriteAllText(FormatName(table) + ".cs", sb.ToString());
                
                MessageBox.Show("Model类生成完毕!","来自根目录的消息");
            }
            catch
            {
                MessageBox.Show("写入文件失败。。。");
            }
            
            #endregion
        }
 
 这个是格式化:
 
        #region 规范化操作 
        /// <summary>
        /// 规范化一下命名规范
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        private string FormatName(string p)
        {
            return char.ToUpper(p[0]) + p.Substring(1);//首字母大写
        }
 
        /// <summary>
        
        /// 把数据库里面类型转换成C#里面的类型~注意可空类型(值类型才有可空类型)
        
        /// </summary>
        
        /// <param name="p"></param>
        
        /// <returns></returns>
        
        private string FormatType(string p, string isNull)
        {
            Type pType;
            
            #region 数据库类型转换成C#类型
            
            switch (p)
            {
                case "int":
                
                    p = "int";
                    
                    pType = typeof(int);
                    
                    break;
                    
                case "nvarchar":
                
                case "varchar":
                
                case "nchar":
                
                case "char":
                
                case "ntext":
                
                    p = "string";
                    
                    pType = typeof(string);
                    
                    break;
                    
                case "bit":
                
                    p = "bool";
                    
                    pType = typeof(bool);
                    
                    break;
                    
                case "datetime":
                
                    p = "DateTime";
                    
                    pType = typeof(DateTime);
                    
                    break;
                    
                case "uniqueidentifier":
                
                    p = "Guid";
                    
                    pType = typeof(Guid);
                    
                    break;                    
                    
                case "money":
                
                    p = "decimal";
                    
                    pType = typeof(decimal);
                    
                    break;
                    
                default:
                
                    p = "object";
                    
                    pType = typeof(object);
                    
                    break;
            }
            #endregion
            
            //判断是否为可空类型~首先数据库里面为空,然后为值类型
            
            if (pType.IsValueType && isNull == "yes")
            {
                return p + "?";
            }
            else
            {
                return p;
            }
        }
        #endregion
 下面的代码也就那么回事,没什么技术含量,看看就行,1.1会支持批量转并且加上自定义代码模板设计
  
  本期推荐:ASPX脚本通用防护1.0                                                                     下一期:看逆天需要什么吧,应该是文件分割合并器

小白C#窗体系列-12.逆天代码生成器

标签:blog   http   io   ar   os   sp   for   文件   数据   

原文地址:http://www.cnblogs.com/dunitian/p/4096747.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!