public JObject update(HttpRequest commentForm) { bool result = false; string msg = ""; if (commentForm != null) { string id_str = commentForm["ID"]; string Username = commentForm["Username"]; try { int id = UtilNumber.Parse(id_str); Comment comment = db.Comment.Single(e => e.ID.Equals(id)); base.CopyProperties(comment, commentForm); comment.Comment1 = comment.Content; comment.UpdateTime = DateTime.Now; db.SaveChanges(); msg = "保存成功!"; result = true; } catch (Exception error) { msg = "操作失败:" + error.Message + ",请重试!"; } } return(new JObject( new JProperty("success", result), new JProperty("msg", msg) )); }
/// <summary> /// 1.后台普通的显示cshtml文件【多个文件】 /// 如果是大文本列,需生成@Html.Raw(ViewBag.OnlineEditorHtml),默认不生成 /// [模板文件]:view/view.txt /// [生成文件名称]:ClassName /// [生成文件后缀名]:.cshtml /// </summary> private void CreateNormalView() { string ClassName = "Admin"; string InstanceName = "admin"; string Table_Comment = "系统管理员"; string Template_Name, Content, Content_New, OnlineEditorHtml = "", ComboTreeInitHtml = ""; string Relation_Table_Name; string Column_Name, Column_Type, Column_Length; foreach (string Table_Name in TableList) { //读取原文件内容到内存 Template_Name = @"AutoCode/Model/view/view.txt"; Content = UtilFile.ReadFile2String(Template_Name); ClassName = Table_Name; ComboTreeInitHtml = ""; OnlineEditorHtml = ""; if (TableInfoList.ContainsKey(Table_Name)) { Table_Comment = TableInfoList[Table_Name]["Comment"]; string[] t_c = Table_Comment.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); if (t_c.Length > 1) { Table_Comment = t_c[0]; } InstanceName = UtilString.LcFirst(ClassName); Content_New = Content.Replace("{$ClassName}", ClassName); Content_New = Content_New.Replace("{$Table_Comment}", Table_Comment); Content_New = Content_New.Replace("{$InstanceName}", InstanceName); Dictionary <string, Dictionary <string, string> > FieldInfo = FieldInfos[Table_Name]; foreach (KeyValuePair <String, Dictionary <string, string> > entry in FieldInfo) { Column_Name = entry.Key; Column_Type = entry.Value["Type"]; Column_Length = entry.Value["Length"]; Relation_Table_Name = Column_Name.Replace("_ID", ""); if (Relation_Table_Name.ToUpper().Equals("PARENT")) { ComboTreeInitHtml = @" <script type=""text/javascript"" src=""@Url.Content(""~/Content/common/js/ajax/ext/shared/components/ComboBoxTree.js"")""></script>"; } int iLength = UtilNumber.Parse(Column_Length); if (ColumnIsTextArea(Column_Name, Column_Type, iLength)) { OnlineEditorHtml = " @Html.Raw(ViewBag.OnlineEditorHtml)"; } } Content_New = Content_New.Replace("{$OnlineEditorHtml}", OnlineEditorHtml); Content_New = Content_New.Replace("{$ComboTreeInitHtml}", ComboTreeInitHtml); //存入目标文件内容 UtilFile.WriteString2FileEncodingGbk(Save_Dir + ClassName + ".cshtml", Content_New); } } }
/// <summary> /// 用户名称是否使用 /// </summary> /// <param name="Username">用户名</param> /// <param name="admin_id">用户ID</param> /// <returns>true:已使用 ;false:未使用</returns> private bool IsUsernameExist(string Username, string admin_id) { bool Used = true; var adminToUpdate = db.Admin.FirstOrDefault(person => person.Username == Username); if (adminToUpdate == null) { Used = false; } else { if (!String.IsNullOrEmpty(admin_id)) { int id = UtilNumber.Parse(admin_id); Admin admin = db.Admin.Single(e => e.ID.Equals(id)); if (admin != null && admin.Username == Username) { Used = false; } } else { Used = false; } } return(Used); }
/// <summary> /// 1.生成核心业务控制器 /// [如果是在线编辑器需生成:this.ViewBag.OnlineEditorHtml],默认不生成[1个文件] /// [模板文件]:action/homecontroller.txt /// 生成文件名称:HomeController.cs /// </summary> private void CreateHomeController() { string ClassName = "Admin"; string Table_Comment = "系统管理员"; string Template_Name, Unit_Template, Content, MainContent, Textarea_Text; string Column_Name, Column_Type, Column_Length; //读取原文件内容到内存 Template_Name = @"AutoCode/Model/action/homecontroller.txt"; Content = UtilFile.ReadFile2String(Template_Name); MainContent = ""; foreach (string Table_Name in TableList) { ClassName = Table_Name; if (TableInfoList.ContainsKey(Table_Name)) { Table_Comment = TableInfoList[Table_Name]["Comment"]; string[] t_c = Table_Comment.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); if (t_c.Length > 1) { Table_Comment = t_c[0]; } Unit_Template = @" // 控制器:{$Table_Comment} // GET: /Home/{$ClassName} public ActionResult {$ClassName}() {{$Textarea_Text} return View(); } "; Dictionary <string, Dictionary <string, string> > FieldInfo = FieldInfos[Table_Name]; Textarea_Text = ""; foreach (KeyValuePair <String, Dictionary <string, string> > entry in FieldInfo) { Column_Name = entry.Key; Column_Type = entry.Value["Type"]; Column_Length = entry.Value["Length"]; int iLength = UtilNumber.Parse(Column_Length); if (ColumnIsTextArea(Column_Name, Column_Type, iLength)) { Textarea_Text += "\"" + Column_Name + "\","; } } if (!string.IsNullOrEmpty(Textarea_Text)) { Textarea_Text = Textarea_Text.Substring(0, Textarea_Text.Length - 1); Textarea_Text = @" this.ViewBag.OnlineEditorHtml = this.Load_Onlineditor(" + Textarea_Text + ");"; } Unit_Template = Unit_Template.Replace("{$ClassName}", ClassName); Unit_Template = Unit_Template.Replace("{$Textarea_Text}", Textarea_Text); MainContent += Unit_Template.Replace("{$Table_Comment}", Table_Comment); } } Content = Content.Replace("{$MainContent}", MainContent); //存入目标文件内容 UtilFile.WriteString2File(Save_Dir + "HomeController.cs", Content); }
/// <summary> /// 电子邮件地址是否使用 /// </summary> /// <param name="Email">电子邮件地址</param> /// <param name="User_ID">用户ID</param> /// <returns>true:已使用 ;false:未使用</returns> public bool IsEmailExist(string Email, string User_ID) { Init_Db(); bool Used = true; var userToUpdate = db.User.FirstOrDefault(person => person.Email == Email); if (userToUpdate != null) { Used = false; } else { if (!String.IsNullOrEmpty(User_ID)) { int id = UtilNumber.Parse(User_ID); User user = db.User.Find(id); if (user != null && user.Email == Email) { Used = false; } } else { Used = false; } } return(Used); }
public object Create(object parent, object context, XmlNode section) { //获取配置文件中ViewUIColumns节点的defaultNodeName所有子节点 XmlNodeList nodes = section.SelectNodes(defaultNodeName); viewColumns = new Dictionary <string, ViewColumnsSection>(); ViewColumnsSection column = null; foreach (XmlNode n in nodes) { column = new ViewColumnsSection(); column.isMust = false; foreach (XmlAttribute att in n.Attributes) { if (att.Name == "name") { column.name = att.Value; continue; } if (att.Name == "header") { column.header = att.Value; continue; } if (att.Name == "visibility") { column.visibility = (Visibility)UtilNumber.Parse(att.Value); continue; } if (att.Name == "defaultHeader") { column.defaultHeader = att.Value; continue; } if (att.Name == "isMust") { bool isMust = false; bool.TryParse(att.Value, out isMust); column.isMust = isMust; continue; } } if (column.name != String.Empty && column.header != String.Empty) { viewColumns.Add(column.name, column); } else { Console.WriteLine(String.Format("配置文件{0}节点出错。\r\n{1}:{2}", section.Name, column.name, column.header)); } } if (viewColumns.Count == 0) { return(null); } return(viewColumns); }
/// <summary> /// 在所有的Controller执行Action方法前执行【before action】 /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.Controller.ViewBag.Title = Gc.SiteName; filterContext.Controller.ViewBag.SiteName = Gc.SiteName; //设置在线编辑器的类型:UEditor|CKEditor HttpCookie OnlineEditorCookie = filterContext.RequestContext.HttpContext.Request.Cookies["OnlineEditor"]; if (OnlineEditorCookie != null) { BasicController.Online_Editor = (EnumOnlineEditor)UtilNumber.Parse(OnlineEditorCookie.Value, (int)EnumOnlineEditor.UEDITOR); } //在Action执行前执行 //filterContext.HttpContext.Response.Write(@"<br />Before Action execute" + "\t " + Message); base.OnActionExecuting(filterContext); }
public void DeleteAdmin() { //测试 2 获取第77,88条数据的GUID string IDs = "77,88"; int Count = db.Admin.Count(); string[] ID_Arr = IDs.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var ID in ID_Arr) { int iID = UtilNumber.Parse(ID); Admin toDelete = db.Admin.Find(iID); Console.WriteLine(toDelete.ID + toDelete.Username + ":" + toDelete.Realname); db.Admin.Remove(toDelete); } db.SaveChanges(); Assert.IsTrue(Count == db.Admin.Count() + 2); }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; List <string> showResult = new List <string>(); showResult.Add("Javascript"); showResult.Add("C#"); showResult.Add("VB"); showResult.Add("C++"); showResult.Add("F"); showResult.Add("JAVA"); showResult.Add("PHP"); showResult.Add("Object-C"); showResult.Add("CSS"); showResult.Add("HTML"); int index = UtilNumber.Parse(UtilNumber.RandomNumber(1)); string result = showResult.ElementAt(index); context.Response.Write(result); }
public JObject deleteByIds(string condition) { string[] pids = condition.Split(','); for (int i = 0; i < pids.Length; i++) { if (!String.IsNullOrEmpty(pids[i])) { string id_str = pids[i]; int ID = UtilNumber.Parse(id_str); var toDeletes = db.Comment.Where(comment => comment.ID.Equals(ID)); foreach (var toDelete in toDeletes) { db.Comment.Remove(toDelete); } } } db.SaveChanges(); return(new JObject( new JProperty("success", true) )); }
public void DeleteByIDs() { string IDs = "131,132,133,134"; string[] ID_Arr = IDs.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries); string Condition = ""; //测试 1 if ((ID_Arr != null) && (ID_Arr.Length > 0)) { Condition = " ID=" + ID_Arr[0] + " "; for (int i = 1; i < ID_Arr.Length; i++) { Condition += " OR ID=" + ID_Arr[i] + " "; } } int Count = db.Database.ExecuteSqlCommand("DELETE FROM Admin WHERE " + Condition); Assert.IsTrue(Count > 0); //测试 2 IDs = "105,106,107,108"; Count = db.Admin.Count(); ID_Arr = IDs.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var ID in ID_Arr) { int iID = UtilNumber.Parse(ID); Admin toDelete = db.Admin.Find(iID); Console.WriteLine(toDelete.ID + toDelete.Username + ":" + toDelete.UpdateTime); db.Admin.Remove(toDelete); } db.SaveChanges(); Assert.IsTrue(Count == db.Admin.Count() + 4); }
public JObject update(HttpRequest adminForm) { bool result = false; string msg = ""; if (adminForm != null) { string admin_id = adminForm["ID"]; string Username = adminForm["Username"]; bool Flag = this.IsUsernameExist(Username, admin_id); if (Flag) { msg = "该用户名已存在,请重新输入!"; } else { try { int id = UtilNumber.Parse(admin_id); Admin admin = db.Admin.Single(e => e.ID.Equals(id)); base.CopyProperties(admin, adminForm); admin.UpdateTime = DateTime.Now; db.SaveChanges(); msg = "保存成功!"; result = true; } catch (Exception error) { msg = "操作失败:" + error.Message + ",请重试!"; } } } return(new JObject( new JProperty("success", result), new JProperty("msg", msg) )); }
/// <summary> /// 1a.生成实体类分部类(显示属性) /// </summary> private void CreateDomainPartial() { string ClassName = "Admin"; string InstanceName = "admin"; string Table_Comment = "系统管理员"; string Template_Name, UnitTemplate, Content, Content_New; string Column_Name, Column_Comment, Column_Type, Column_Length; string Relation_ClassName, Relation_Column_Comment, Relation_Table_Name, Relation_Column_Name; string UnitColumnDefine; foreach (string Table_Name in TableList) { //读取原文件内容到内存 Template_Name = @"AutoCode/Model/domain/domain.txt"; Content = UtilFile.ReadFile2String(Template_Name); ClassName = Table_Name; if (TableInfoList.ContainsKey(Table_Name)) { Dictionary <string, Dictionary <string, string> > FieldInfo = FieldInfos[Table_Name]; UnitColumnDefine = ""; foreach (KeyValuePair <String, Dictionary <string, string> > entry in FieldInfo) { Column_Name = entry.Key; Column_Comment = entry.Value["Comment"]; Column_Type = entry.Value["Type"]; Column_Length = entry.Value["Length"]; string[] c_c = Column_Comment.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); if (c_c.Length >= 1) { Column_Comment = c_c[0]; } int iLength = UtilNumber.Parse(Column_Length); if (Column_Type.Equals("tinyint")) { Column_Comment = entry.Value["Comment"]; c_c = Column_Comment.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); if (c_c.Length > 1) { Column_Comment = ""; foreach (string Comment_Single_Line in c_c) { Column_Comment += " /// " + Comment_Single_Line + "\r\n"; } Column_Comment = Column_Comment.Substring(0, Column_Comment.Length - 2); UnitTemplate = @" /// <summary> {$Column_Comment} /// </summary> public String {$Column_Name}Show { get; set; }"; UnitTemplate = UnitTemplate.Replace("{$Column_Comment}", Column_Comment); UnitTemplate = UnitTemplate.Replace("{$Column_Name}", Column_Name); UnitColumnDefine += UnitTemplate; } } else if (Column_Name.Contains("_ID")) { Relation_ClassName = Column_Name.Replace("_ID", ""); if (TableList.Contains(Relation_ClassName) || (Relation_ClassName.ToUpper().Equals("PARENT"))) { if (Relation_ClassName.ToUpper().Equals("PARENT")) { Relation_Table_Name = Relation_ClassName; Relation_Column_Name = ""; Dictionary <string, Dictionary <string, string> > Relation_FieldInfo = FieldInfos[ClassName]; foreach (KeyValuePair <String, Dictionary <string, string> > relation_entry in Relation_FieldInfo) { Relation_Column_Name = relation_entry.Key; if (UtilString.Contains(relation_entry.Key.ToUpper(), "NAME", "TITLE", "URL")) { break; } } Column_Comment = Column_Comment.Replace("标识", ""); UnitTemplate = @" /// <summary> /// 显示{$Column_Comment} /// </summary> public String {$Relation_Column_Name}_Parent { get; set; } /// <summary> /// 显示{$Column_Comment}[全] /// </summary> public String {$ClassName}ShowAll { get; set; } "; UnitTemplate = UnitTemplate.Replace("{$Column_Comment}", Column_Comment); UnitTemplate = UnitTemplate.Replace("{$ClassName}", ClassName); UnitTemplate = UnitTemplate.Replace("{$Relation_Column_Name}", Relation_Column_Name); UnitColumnDefine += UnitTemplate; } else if (TableInfoList.ContainsKey(Relation_ClassName)) { Relation_Table_Name = Relation_ClassName; Dictionary <string, Dictionary <string, string> > Relation_FieldInfo = FieldInfos[Relation_Table_Name]; Relation_Column_Name = Column_Name; Relation_Column_Comment = Relation_Column_Name; foreach (KeyValuePair <String, Dictionary <string, string> > relation_entry in Relation_FieldInfo) { Relation_Column_Name = relation_entry.Key; if (UtilString.Contains(relation_entry.Key.ToUpper(), "NAME", "TITLE", "URL")) { Relation_Column_Comment = relation_entry.Value["Comment"]; break; } } UnitTemplate = @" /// <summary> /// {$Relation_Column_Comment} /// </summary> public String {$Relation_Column_Name} { get; set; }"; UnitTemplate = UnitTemplate.Replace("{$Relation_Column_Comment}", Relation_Column_Comment); UnitTemplate = UnitTemplate.Replace("{$Relation_Column_Name}", Relation_Column_Name); UnitColumnDefine += UnitTemplate; } } } else if (ColumnIsTextArea(Column_Name, Column_Type, iLength)) { UnitTemplate = @" /// <summary> /// {$Column_Comment} /// </summary> public String {$Column_Name}Show { get; set; }"; Column_Comment = entry.Value["Comment"]; c_c = Column_Comment.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); if (c_c.Length > 1) { Column_Comment = ""; foreach (string Comment_Single_Line in c_c) { Column_Comment += " /// " + Comment_Single_Line + "\r\n"; } Column_Comment = Column_Comment.Substring(0, Column_Comment.Length - 2); } UnitTemplate = UnitTemplate.Replace("{$Column_Comment}", Column_Comment); UnitTemplate = UnitTemplate.Replace("{$Column_Name}", Column_Name); UnitColumnDefine += UnitTemplate; } } if (OneHasManyDefine.ContainsKey(Table_Name)) { UnitTemplate = @" /// <summary> /// 辅助主键 ///【用于ExtJs Combo主键下拉框显示ID以和主表ID名称区别开来】 /// </summary> public String {$Table_Name}_ID { get; set; }"; UnitTemplate = UnitTemplate.Replace("{$Table_Name}", Table_Name); UnitColumnDefine += UnitTemplate; } if (!string.IsNullOrEmpty(UnitColumnDefine)) { Table_Comment = TableInfoList[Table_Name]["Comment"]; string[] t_c = Table_Comment.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); if (t_c.Length > 1) { Table_Comment = ""; foreach (string Comment_Single_Line in t_c) { Table_Comment += " /// " + Comment_Single_Line + "\r\n"; } } else { Table_Comment = " /// " + Table_Comment; } Content_New = Content.Replace("{$ClassName}", ClassName); Content_New = Content_New.Replace("{$Table_Comment}", Table_Comment); Content_New = Content_New.Replace("{$InstanceName}", InstanceName); Content_New = Content_New.Replace("{$ColumnDefines}", UnitColumnDefine); //存入目标文件内容 UtilFile.WriteString2File(Save_Dir + ClassName + ".cs", Content_New); } } } }
/// <summary> /// 生成数据库主体部分 /// </summary> private static string CreateDbDefine() { string result = "/****** 创建数据库所有表 Script Date:" + DateTime.Now + " ******/\r\n"; string database_name = UtilMysql.Database_Name; if (IsSqlserverDefault) { database_name = UtilString.UcFirst(database_name); } result += "USE " + database_name + "\r\n"; string tablename, refer_tablename, tableComment, columnDefine; string sqlTemplate, column_name, column_type, column_null, column_default, resetSeed; string defaultValue, id_column; Dictionary <string, Dictionary <string, string> > columnInfos; foreach (Dictionary <string, string> tableInfo in tableInfos.Values) { //获取表名 tablename = tableInfo["Name"]; if (IsSqlserverDefault) { tablename = UtilString.UcFirst(tablename); } tableComment = tableInfo["Comment"]; columnInfos = UtilMysql.FieldInfoList(tablename); columnDefine = ""; defaultValue = ""; id_column = "ID"; resetSeed = ""; //获取主键名称 foreach (Dictionary <string, string> columnInfo in columnInfos.Values) { column_name = columnInfo["Field"]; bool IsKeyColumn = false; if (IsSqlserverDefault) { column_name = UtilString.UcFirst(column_name); if (column_name.ToUpper().Equals("ID")) { IsKeyColumn = true; } } else { string[] tbl = tablename.Split('_'); if (tbl.Length > 1) { if (column_name.ToUpper().Contains("ID") && column_name.ToUpper().Contains(tbl[tbl.Length - 1].ToUpper())) { id_column = column_name; IsKeyColumn = true; } } } if (IsKeyColumn) { if (tablesIDTypeGuid.Contains(tablename)) { columnDefine += "[" + id_column + "] [uniqueidentifier] NOT NULL,"; defaultValue += string.Format("ALTER TABLE [dbo].[{0}] ADD CONSTRAINT [DF_{0}_ID] DEFAULT (newid()) FOR " + id_column + "]\r\nGO\r\n", tablename); } else { columnDefine += "[" + id_column + "][int] IDENTITY(1,1) NOT NULL,"; resetSeed += "DBCC CHECKIDENT ('" + tablename + "', RESEED, 1)\r\n"; } } else { //获取列名|列类型|是否Null column_type = columnInfo["Type"]; column_type = ConvertType(column_type); column_null = (columnInfo["Null"].Equals("YES")) ? "NULL" : "NOT NULL"; column_default = columnInfo["Default"]; if (column_name.ToUpper().Contains("_ID")) { refer_tablename = column_name.Replace("_ID", ""); refer_tablename = refer_tablename.Replace("_id", ""); if (refer_tablename.ToUpper().Equals("PARENT")) { refer_tablename = tablename; } if (tablesIDTypeGuid.Contains(refer_tablename)) { column_type = "[uniqueidentifier]"; } else { column_type = "[int]"; } column_null = "NOT NULL"; } if (UtilString.Contains(column_name.ToUpper(), "TIME", "DATE")) { if (UtilString.Contains(column_name.ToUpper(), "TIMES")) { column_type = "[int]"; } else { if (IsSqlserverDefault) { column_type = "[datetime]"; } } } if (!string.IsNullOrEmpty(column_default) && (!column_name.ToUpper().Equals("UPDATETIME"))) { if (IsSqlserverDefault) { if (!column_name.ToUpper().Contains("_ID")) { defaultValue += string.Format("ALTER TABLE [dbo].[{0}] ADD CONSTRAINT [DF_{0}_{1}] DEFAULT ({2}) FOR [{1}]\r\nGO\r\n", tablename, column_name, column_default); } } } if ((column_name.ToUpper().Equals("COMMITTIME")) || (column_name.ToUpper().Equals("UPDATETIME"))) { if (IsSqlserverDefault) { defaultValue += string.Format("ALTER TABLE [dbo].[{0}] ADD CONSTRAINT [DF_{0}_{1}] DEFAULT (getdate()) FOR [{1}]\r\nGO\r\n", tablename, column_name); } } string[] type_length = column_type.Split(new char[4] { '[', ']', '(', ')' }, StringSplitOptions.RemoveEmptyEntries); if (type_length.Length == 2) { string length = type_length[1]; int i_len = UtilNumber.Parse(length); if (i_len > 4000) { i_len = 4000; column_type = "[" + type_length[0] + "]" + "(" + i_len + ")"; } } columnDefine += string.Format(" [{0}] {1} {2},", column_name, column_type, column_null); } columnDefine += "\r\n"; } columnDefine = columnDefine.Substring(0, columnDefine.Length - 2); //生成表脚本 sqlTemplate = @" SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[{0}] ( {1} CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED ([{2}] ASC) WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)ON [PRIMARY] ) ON [PRIMARY] GO "; result += string.Format(sqlTemplate, tablename, columnDefine, id_column); //生成列默认值 result += defaultValue; //自增长重置为0 result += resetSeed; } return(result); }
/// <summary> /// 生成数据库主体部分 /// </summary> private static string CreateDbDefine() { string now = DateTime.Now.ToString(); string result = @" /* Betterlife.Net Sqlserver Convert to Mysql Source Server : localhost_3306 Source Server Version : 50520 Source Host : localhost:3306 Source Database : {0} Target Server Type : MYSQL Target Server Version : 50520 File Encoding : 65001 Date: {1} */ SET FOREIGN_KEY_CHECKS=0; "; result = string.Format(result, UtilSqlserver.Database_Name, now); string tablename, tableComment, columnDefine; string sqlTemplate, column_name, column_comment, column_type, column_default, column_pkeys; List <string> primary_keys; Dictionary <string, Dictionary <string, string> > columnInfos; string[] type_length, p_keys, enum_comments; foreach (Dictionary <string, string> tableInfo in tableInfos.Values) { //获取表名 tablename = tableInfo["Name"]; tablename = UtilString.UcFirst(tablename); tableComment = tableInfo["Comment"]; tableComment = tableComment.Replace("\r", "\\r"); tableComment = tableComment.Replace("\n", "\\n"); columnInfos = UtilSqlserver.FieldInfoList(tablename); columnDefine = ""; column_default = ""; primary_keys = new List <string>(); //获取主键名称 foreach (Dictionary <string, string> columnInfo in columnInfos.Values) { column_name = columnInfo["Field"]; column_name = UtilString.UcFirst(column_name); if (columnInfo.Keys.Contains("Comment")) { column_comment = columnInfo["Comment"]; } else { column_comment = column_name; } if (column_name.ToUpper().Equals("ID")) { columnDefine += " `ID` int(11) NOT NULL AUTO_INCREMENT COMMENT '" + column_comment + "',"; primary_keys.Add("`ID`"); } else { //获取列名|列类型|是否Null column_type = columnInfo["Type"]; //column_default = columnInfo["Default"]; if (column_name.ToUpper().Contains("_ID")) { column_type = "int(11) NOT NULL "; primary_keys.Add("`" + column_name + "`"); column_default = "DEFAULT '0'"; } else { if (columnInfo["Null"].Equals("YES") || columnInfo["Null"].Equals("是")) { column_default = "DEFAULT NULL"; } else { column_default = "NOT NULL"; } if (UtilString.Contains(column_name.ToUpper(), "TIME", "DATE")) { if (UtilString.Contains(column_name.ToUpper(), "TIMES")) { column_type = "int"; column_default = "DEFAULT '0'"; } else { column_type = "datetime"; } } } type_length = column_type.Split(new char[4] { '[', ']', '(', ')' }, StringSplitOptions.RemoveEmptyEntries); if (type_length.Length == 1) { column_type = type_length[0]; if (column_type.Equals("nvarchar")) { column_type = "varchar"; } if (column_type.Equals("tinyint")) { enum_comments = Enum_ColumnDefine(column_comment); if ((enum_comments != null) && (enum_comments.Length > 1)) { column_type = "enum(" + string.Join(",", enum_comments) + ")"; } } else { if (!column_type.Equals("datetime") && !type_length.Contains("date")) { string length = columnInfo["Length"]; int i_len = UtilNumber.Parse(length); column_type += "(" + i_len + ")"; } } } column_comment = column_comment.Replace("'", "\""); column_comment = column_comment.Replace("\r", "\\r"); column_comment = column_comment.Replace("\n", "\\n"); column_comment = "COMMENT '" + column_comment + "'"; columnDefine += string.Format(" `{0}` {1} {2} {3},", column_name, column_type, column_default, column_comment); } columnDefine += "\r\n"; } if (columnDefine.Length > 2) { columnDefine = columnDefine.Substring(0, columnDefine.Length - 2); } //生成表脚本 sqlTemplate = @" -- ---------------------------- -- Table structure for `{0}` -- ---------------------------- DROP TABLE IF EXISTS `{0}`; CREATE TABLE `{0}` ( {1} ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='{2}'; "; p_keys = primary_keys.ToArray(); column_pkeys = "\r\n PRIMARY KEY (" + string.Join(",", p_keys) + ")"; columnDefine += column_pkeys; result += string.Format(sqlTemplate, tablename, columnDefine, tableComment); } return(result); }
/// <summary> /// 2.Business/Admin后台所有ExtService服务类【多个文件】 /// [模板文件]:service/extservice.txt|service/extservicedefine.txt /// [生成文件名称]:"ExtService"+ClassName|"ExtService"+ClassName /// [生成文件后缀名]:.ashx.cs|.ashx /// </summary> private void CreateExtService() { string ClassName = "Admin"; string InstanceName = "admin"; string Table_Comment = "系统管理员"; string Service_NameSpace = "AdminManage"; string Template_Name, UnitTemplate, Content, Content_New; string ColumnNameComment, ColumnCommentName, EnumColumnName; string Column_Name, Column_Table_Name, Column_Comment, Column_Type, Column_Length; string ImportConvertDataToShow, ExportConvertShowToData; string SpecialResult = ""; string Relation_ClassName, Relation_InstanceName; string Relation_Table_Name, Relation_Column_Name, TreeInstanceDefine, Relation_Column_Level, RelationFieldTreeRecursive; string ImgUploadSrc = "", Relation_Parent_Init = ""; bool IsImage; foreach (string Table_Name in TableList) { //读取原文件内容到内存 Template_Name = @"AutoCode/Model/service/extservice.txt"; Content = UtilFile.ReadFile2String(Template_Name); ClassName = Table_Name; RelationFieldTreeRecursive = ""; TreeInstanceDefine = ""; if (TableInfoList.ContainsKey(Table_Name)) { Table_Comment = TableInfoList[Table_Name]["Comment"]; string[] t_c = Table_Comment.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); if (t_c.Length > 1) { Table_Comment = t_c[0]; } InstanceName = UtilString.LcFirst(ClassName); Content_New = Content.Replace("{$ClassName}", ClassName); Content_New = Content_New.Replace("{$Table_Comment}", Table_Comment); Content_New = Content_New.Replace("{$InstanceName}", InstanceName); Dictionary <string, Dictionary <string, string> > FieldInfo = FieldInfos[Table_Name]; ColumnNameComment = ""; ColumnCommentName = ""; EnumColumnName = ""; SpecialResult = ""; ImportConvertDataToShow = ""; ExportConvertShowToData = ""; ImgUploadSrc = ""; Relation_Parent_Init = ""; foreach (KeyValuePair <String, Dictionary <string, string> > entry in FieldInfo) { IsImage = false; Column_Name = entry.Key; Column_Comment = entry.Value["Comment"]; Column_Type = entry.Value["Type"]; Column_Length = entry.Value["Length"]; string[] c_c = Column_Comment.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); if (c_c.Length >= 1) { Column_Comment = c_c[0]; } if (!((Column_Name.ToUpper().Equals(CommitTime_Str.ToUpper())) || (Column_Name.ToUpper().Equals(UpdateTime_Str.ToUpper())))) { if (!Column_Type.Equals("tinyint")) { ColumnNameComment += " {\"" + Column_Name + "\",\"" + Column_Comment + "\"},\r\n"; ColumnCommentName += " {\"" + Column_Comment + "\",\"" + Column_Name + "\"},\r\n"; } } int iLength = UtilNumber.Parse(Column_Length); IsImage = ColumnIsImage(Column_Name, Column_Comment); if (IsImage) { UnitTemplate = @" Dictionary<string,object> uploadResult=this.UploadImage({$InstanceName}Form.Files,""{$Column_Name}Upload"",""{$Column_Name}"",""{$InstanceName}""); if ((uploadResult!=null)&&((bool)uploadResult[""success""]==true)&&(uploadResult.Keys.Contains(""file_name""))){ {$InstanceName}.{$Column_Name}=(string)uploadResult[""file_name""]; }"; UnitTemplate = UnitTemplate.Replace("{$InstanceName}", InstanceName); UnitTemplate = UnitTemplate.Replace("{$Column_Name}", Column_Name); ImgUploadSrc += UnitTemplate; } else if (Column_Type.Equals("tinyint")) { Column_Comment = entry.Value["Comment"]; c_c = Column_Comment.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); if (c_c.Length > 1) { UnitTemplate = @" {$InstanceName}.{$Column_Name}Show = Enum{$Column_Table_Name}.{$Column_Name}Show(Convert.ToChar({$InstanceName}.{$Column_Name}));"; UnitTemplate = UnitTemplate.Replace("{$InstanceName}", InstanceName); UnitTemplate = UnitTemplate.Replace("{$Column_Name}", Column_Name); Column_Table_Name = Column_Name; if (Array.IndexOf(Same_Column_Names, Column_Name) > -1) { Column_Table_Name = ClassName + "_" + Column_Name; } UnitTemplate = UnitTemplate.Replace("{$Column_Table_Name}", Column_Table_Name); SpecialResult += UnitTemplate; Column_Comment = c_c[0].Trim(); EnumColumnName += "\"" + Column_Name + "\","; ColumnNameComment += " {\"" + Column_Name + "Show\",\"" + Column_Comment + "\"},\r\n"; ColumnCommentName += " {\"" + Column_Comment + "\",\"" + Column_Name + "Show\"},\r\n"; ExportConvertShowToData += " " + InstanceName + "." + Column_Name + "Show = Enum" + Column_Name + "." + Column_Name + "Show(" + InstanceName + "." + Column_Name + ");\r\n"; ImportConvertDataToShow += " " + InstanceName + "." + Column_Name + " = Enum" + Column_Name + "." + Column_Name + "ByShow(" + InstanceName + "." + Column_Name + "Show);\r\n"; } } else if (Column_Name.Contains("_ID")) { Relation_Table_Name = Column_Name.Replace("_ID", ""); Relation_ClassName = Relation_Table_Name; if (TableList.Contains(Relation_ClassName) || (Relation_ClassName.ToUpper().Equals("PARENT"))) { if (Relation_Table_Name.ToUpper().Equals("PARENT")) { Relation_Table_Name = Table_Name; Relation_ClassName = ClassName; Relation_Column_Name = ""; Relation_Column_Level = ""; Relation_InstanceName = UtilString.LcFirst(Relation_ClassName); Dictionary <string, Dictionary <string, string> > Relation_FieldInfo = FieldInfos[Table_Name]; foreach (KeyValuePair <String, Dictionary <string, string> > relation_entry in Relation_FieldInfo) { if (UtilString.Contains(relation_entry.Key.ToUpper(), "NAME", "TITLE", "URL")) { Relation_Column_Name = relation_entry.Key; break; } } bool IsPermitNull = true; foreach (KeyValuePair <String, Dictionary <string, string> > relation_entry in Relation_FieldInfo) { if (UtilString.Contains(relation_entry.Key.ToUpper(), "LEVEL")) { Relation_Column_Level = relation_entry.Key; if (relation_entry.Value["Null"].Equals("否")) { IsPermitNull = false; } break; } } TreeInstanceDefine = @" {$Relation_ClassName} {$Relation_InstanceName}_instance;"; if (string.IsNullOrEmpty(Relation_Column_Level)) { foreach (KeyValuePair <String, Dictionary <string, string> > relation_entry in Relation_FieldInfo) { if (UtilString.Contains(relation_entry.Key.ToUpper(), "TYPE")) { Relation_Column_Level = relation_entry.Key; break; } } UnitTemplate = @" {$Relation_InstanceName}_instance=null; if ({$Relation_InstanceName}.Parent_ID!=null){ {$Relation_InstanceName}_instance=db.{$Relation_ClassName}.Find({$Relation_InstanceName}.Parent_ID); {$Relation_InstanceName}.{$Relation_Column_Name}_Parent={$Relation_InstanceName}_instance.{$Relation_Column_Name}; } if ({$Relation_InstanceName}_instance!=null){ int level = (int){$Relation_InstanceName}_instance.{$Relation_Column_Level}; {$Relation_InstanceName}.{$Relation_ClassName}ShowAll=this.{$Relation_ClassName}ShowAll({$Relation_InstanceName}.Parent_ID,level); }"; RelationFieldTreeRecursive = @" /// <summary> /// 显示{$Column_Comment}[全] /// 注:采用了递归写法 /// </summary> /// <param name=""Parent_ID"">{$Column_Comment}标识</param> /// <param name=""level"">目录层级</param> /// <returns></returns> private string {$Relation_ClassName}ShowAll(int? Parent_ID,int level) { string {$Relation_ClassName}ShowAll=""""; {$Relation_ClassName} {$Relation_InstanceName}_p=db.{$Relation_ClassName}.Find(Parent_ID); if (level<=0){ {$Relation_ClassName}ShowAll={$Relation_InstanceName}_p.{$Relation_Column_Name}; }else{ Parent_ID={$Relation_InstanceName}_p.Parent_ID; {$Relation_ClassName}ShowAll=this.{$Relation_ClassName}ShowAll(Parent_ID,level-1)+""->""+{$Relation_InstanceName}_p.{$Relation_Column_Name}; } return {$Relation_ClassName}ShowAll; } "; } else { string ColumnTypeNull = "int"; if (IsPermitNull) { ColumnTypeNull += "?"; } UnitTemplate = @" {$Relation_InstanceName}_instance=null; if ({$Relation_InstanceName}.Parent_ID!=null){ {$Relation_InstanceName}_instance=db.{$Relation_ClassName}.Find({$Relation_InstanceName}.Parent_ID); {$Relation_InstanceName}.{$Relation_Column_Name}_Parent={$Relation_InstanceName}_instance.{$Relation_Column_Name}; } if ({$Relation_InstanceName}_instance!=null){ {$ColumnTypeNull} level = {$Relation_InstanceName}_instance.{$Relation_Column_Level}; {$Relation_InstanceName}.{$Relation_ClassName}ShowAll=this.{$Relation_ClassName}ShowAll({$Relation_InstanceName}.Parent_ID,level); }"; UnitTemplate = UnitTemplate.Replace("{$ColumnTypeNull}", ColumnTypeNull); RelationFieldTreeRecursive = @" /// <summary> /// 显示{$Column_Comment}[全] /// 注:采用了递归写法 /// </summary> /// <param name=""Parent_ID"">{$Column_Comment}标识</param> /// <param name=""level"">目录层级</param> /// <returns></returns> private string {$Relation_ClassName}ShowAll(int? Parent_ID,int level) { string {$Relation_ClassName}ShowAll=""""; {$Relation_ClassName} {$Relation_InstanceName}_p=db.{$Relation_ClassName}.Find(Parent_ID); if (level<=1){ {$Relation_ClassName}ShowAll={$Relation_InstanceName}_p.{$Relation_Column_Name}; }else{ Parent_ID={$Relation_InstanceName}_p.Parent_ID; {$Relation_ClassName}ShowAll=this.{$Relation_ClassName}ShowAll(Parent_ID,level-1)+""->""+{$Relation_InstanceName}_p.{$Relation_Column_Name}; } return {$Relation_ClassName}ShowAll; } "; } UnitTemplate = UnitTemplate.Replace("{$Relation_InstanceName}", Relation_InstanceName); UnitTemplate = UnitTemplate.Replace("{$Relation_ClassName}", Relation_ClassName); UnitTemplate = UnitTemplate.Replace("{$Relation_Column_Name}", Relation_Column_Name); UnitTemplate = UnitTemplate.Replace("{$Relation_Column_Level}", Relation_Column_Level); TreeInstanceDefine = TreeInstanceDefine.Replace("{$Relation_InstanceName}", Relation_InstanceName); TreeInstanceDefine = TreeInstanceDefine.Replace("{$Relation_ClassName}", Relation_ClassName); SpecialResult += UnitTemplate; Column_Comment = entry.Value["Comment"]; c_c = Column_Comment.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); if (c_c.Length >= 1) { Column_Comment = c_c[0]; } Column_Comment = Column_Comment.Replace("标识", ""); RelationFieldTreeRecursive = RelationFieldTreeRecursive.Replace("{$Column_Comment}", Column_Comment); RelationFieldTreeRecursive = RelationFieldTreeRecursive.Replace("{$Relation_InstanceName}", Relation_InstanceName); RelationFieldTreeRecursive = RelationFieldTreeRecursive.Replace("{$Relation_ClassName}", Relation_ClassName); RelationFieldTreeRecursive = RelationFieldTreeRecursive.Replace("{$Relation_Column_Name}", Relation_Column_Name); UnitTemplate = @" if ({$InstanceName}.{$Column_Name} == 0) {$InstanceName}.{$Column_Name} = null;"; UnitTemplate = UnitTemplate.Replace("{$InstanceName}", InstanceName); UnitTemplate = UnitTemplate.Replace("{$Column_Name}", Column_Name); Relation_Parent_Init += UnitTemplate; } else if (TableInfoList.ContainsKey(Relation_Table_Name)) { //读取原文件内容到内存 Template_Name = @"AutoCode/Model/domain/httpdata.txt"; Content = UtilFile.ReadFile2String(Template_Name); Relation_InstanceName = UtilString.LcFirst(Relation_ClassName); Relation_Table_Name = Relation_ClassName; Dictionary <string, Dictionary <string, string> > Relation_FieldInfo = FieldInfos[Relation_Table_Name]; Relation_Column_Name = Column_Name; foreach (KeyValuePair <String, Dictionary <string, string> > relation_entry in Relation_FieldInfo) { Relation_Column_Name = relation_entry.Key; if (UtilString.Contains(relation_entry.Key.ToUpper(), "NAME", "TITLE", "URL")) { break; } } UnitTemplate = @" {$InstanceName}.{$Relation_Column_Name} = {$InstanceName}.{$Relation_ClassName}.{$Relation_Column_Name};"; UnitTemplate = UnitTemplate.Replace("{$InstanceName}", InstanceName); UnitTemplate = UnitTemplate.Replace("{$Relation_ClassName}", Relation_ClassName); UnitTemplate = UnitTemplate.Replace("{$Relation_Column_Name}", Relation_Column_Name); SpecialResult += UnitTemplate; UnitTemplate = @" {$Relation_ClassName} {$Relation_InstanceName} = db.{$Relation_ClassName}.Where(e => e.{$Relation_Column_Name}.Equals({$InstanceName}.{$Relation_Column_Name})).SingleOrDefault(); {$InstanceName}.{$Column_Name} = {$Relation_InstanceName}.ID; "; UnitTemplate = UnitTemplate.Replace("{$InstanceName}", InstanceName); UnitTemplate = UnitTemplate.Replace("{$Relation_InstanceName}", Relation_InstanceName); UnitTemplate = UnitTemplate.Replace("{$Column_Name}", Column_Name); UnitTemplate = UnitTemplate.Replace("{$Relation_ClassName}", Relation_ClassName); UnitTemplate = UnitTemplate.Replace("{$Relation_Column_Name}", Relation_Column_Name); ImportConvertDataToShow += UnitTemplate; } } } else if (ColumnIsTextArea(Column_Name, Column_Type, iLength)) { UnitTemplate = @" if (!string.IsNullOrEmpty({$InstanceName}.{$Column_Name})) { {$InstanceName}.{$Column_Name}Show = Regex.Replace({$InstanceName}.{$Column_Name}, ""<\\s*img\\s+[^>]*?src\\s*=\\s*(\'|\"")(.*?)\\1[^>]*?\\/?\\s*>"", ""<a href='${2}' target='_blank'>${0}</a>""); {$InstanceName}.{$Column_Name}Show = {$InstanceName}.{$Column_Name}Show.Replace(""\\\"""", """"); }"; UnitTemplate = UnitTemplate.Replace("{$InstanceName}", InstanceName); UnitTemplate = UnitTemplate.Replace("{$Column_Name}", Column_Name); SpecialResult += UnitTemplate; } } ColumnNameComment = ColumnNameComment.Substring(0, ColumnNameComment.Length - 3); ColumnCommentName = ColumnCommentName.Substring(0, ColumnCommentName.Length - 3); Content_New = Content_New.Replace("{$ColumnNameComment}", ColumnNameComment); Content_New = Content_New.Replace("{$ColumnCommentName}", ColumnCommentName); SpecialResult += @" this.Stores.Add((" + ClassName + ")ClearInclude(" + InstanceName + "));"; SpecialResult = SpecialResult.Substring(1, SpecialResult.Length - 1); Content_New = Content_New.Replace("{$SpecialResult}", SpecialResult); Content_New = Content_New.Replace("{$Service_NameSpace}", Service_NameSpace); Content_New = Content_New.Replace("{$CommitTime_Str}", CommitTime_Str); Content_New = Content_New.Replace("{$UpdateTime_Str}", UpdateTime_Str); Content_New = Content_New.Replace("{$EnumColumnName}", EnumColumnName); Content_New = Content_New.Replace("{$ImportConvertDataToShow}", ImportConvertDataToShow); Content_New = Content_New.Replace("{$ExportConvertShowToData}", ExportConvertShowToData); Content_New = Content_New.Replace("{$RelationFieldTreeRecursive}", RelationFieldTreeRecursive); Content_New = Content_New.Replace("{$TreeInstanceDefine}", TreeInstanceDefine); Content_New = Content_New.Replace("{$ImgUploadSrc}", ImgUploadSrc); Content_New = Content_New.Replace("{$Relation_Parent_Init}", Relation_Parent_Init); //存入目标文件内容 UtilFile.WriteString2File(Save_Dir + "ExtService" + ClassName + ".ashx.cs", Content_New); //读取原文件内容到内存 Template_Name = @"AutoCode/Model/service/extservicedefine.txt"; Content = UtilFile.ReadFile2String(Template_Name); Content_New = Content.Replace("{$ClassName}", ClassName); Content_New = Content_New.Replace("{$Service_NameSpace}", Service_NameSpace); //存入目标文件内容 UtilFile.WriteString2File(Save_Dir + "ExtService" + ClassName + ".ashx", Content_New); } } }