using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Text; using System.Data; using System.Web; using Newtonsoft.Json.Linq; using WaterCloud.Code; using WaterCloud.Domain.SystemManage; using System.Threading.Tasks; using Chloe; using WaterCloud.DataBase; namespace WaterCloud.CodeGenerator { public class SingleTableTemplate { private string buttoncacheKey = "watercloud_modulebuttondata_"; private string fieldscacheKey = "watercloud_modulefieldsdata_"; private string cacheKey = "watercloud_moduleldata_"; private string quickcacheKey = "watercloud_quickmoduledata_"; private string initcacheKey = "watercloud_init_"; private string authorizecacheKey = "watercloud_authorizeurldata_";// +权限 private IRepositoryBase uniwork; public SingleTableTemplate(IDbContext context) { uniwork = new RepositoryBase(context); } #region GetBaseConfig public BaseConfigModel GetBaseConfig(string path, string username, string tableName, string tableDescription, List tableFieldList) { path = GetProjectRootPath(path); BaseConfigModel baseConfigModel = new BaseConfigModel(); baseConfigModel.TableName = tableName; baseConfigModel.TableNameUpper = TableMappingHelper.ConvertTo_Uppercase(tableName); #region FileConfigModel baseConfigModel.FileConfig = new FileConfigModel(); baseConfigModel.FileConfig.ClassPrefix = TableMappingHelper.GetClassNamePrefix(tableName); baseConfigModel.FileConfig.ClassDescription = tableDescription; baseConfigModel.FileConfig.CreateUserName = username; baseConfigModel.FileConfig.CreateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm"); baseConfigModel.FileConfig.EntityName = string.Format("{0}Entity", baseConfigModel.FileConfig.ClassPrefix); baseConfigModel.FileConfig.ServiceName = string.Format("{0}Service", baseConfigModel.FileConfig.ClassPrefix); baseConfigModel.FileConfig.ControllerName = string.Format("{0}Controller", baseConfigModel.FileConfig.ClassPrefix); baseConfigModel.FileConfig.PageIndexName = "Index"; baseConfigModel.FileConfig.PageFormName = "Form"; baseConfigModel.FileConfig.PageDetailsName = "Details"; #endregion #region OutputConfigModel baseConfigModel.OutputConfig = new OutputConfigModel(); baseConfigModel.OutputConfig.OutputModule = string.Empty; baseConfigModel.OutputConfig.OutputEntity = Path.Combine(path, "WaterCloud.Domain\\Entity"); baseConfigModel.OutputConfig.OutputService = Path.Combine(path, "WaterCloud.Service"); baseConfigModel.OutputConfig.OutputWeb = Path.Combine(path, "WaterCloud.Web"); #endregion #region PageIndexModel baseConfigModel.PageIndex = new PageIndexModel(); baseConfigModel.PageIndex.IsMunu = true; baseConfigModel.PageIndex.IsTree = false; baseConfigModel.PageIndex.IsSearch = true; baseConfigModel.PageIndex.IsFields = false; baseConfigModel.PageIndex.IsPagination = true; baseConfigModel.PageIndex.IsFields = false; baseConfigModel.PageIndex.IsPublic = false; baseConfigModel.PageIndex.IsCache = false; baseConfigModel.PageIndex.IsAsc = false; baseConfigModel.PageIndex.SortColumn = "F_CreatorTime"; baseConfigModel.PageIndex.ButtonList = new List(); baseConfigModel.PageIndex.ColumnList = tableFieldList; baseConfigModel.PageIndex.KeywordColum = new List(); baseConfigModel.PageIndex.KeywordColum.Add("F_EnCode"); baseConfigModel.PageIndex.KeywordColum.Add("F_FullName"); baseConfigModel.PageIndex.ParentColum = "F_ParentId"; baseConfigModel.PageIndex.TreeColum = "F_FullName"; baseConfigModel.PageIndex.DeleteColum = "F_DeleteMark"; baseConfigModel.PageIndex.CreateColum = "F_CreatorTime"; #endregion #region PageFormModel baseConfigModel.PageForm = new PageFormModel(); baseConfigModel.PageForm.ShowMode = 1; baseConfigModel.PageForm.FieldList = new Dictionary(); #endregion return baseConfigModel; } #endregion #region BuildEntity public string BuildEntity(BaseConfigModel baseConfigModel, DataTable dt, string idColumn = "F_Id") { StringBuilder sb = new StringBuilder(); sb.AppendLine("using System;"); //sb.AppendLine("using Newtonsoft.Json;"); //sb.AppendLine("using WaterCloud.Code;"); sb.AppendLine("using System.ComponentModel.DataAnnotations;"); sb.AppendLine("using Chloe.Annotations;"); sb.AppendLine(); sb.AppendLine("namespace WaterCloud.Domain." + baseConfigModel.OutputConfig.OutputModule); sb.AppendLine("{"); SetClassDescription("实体类", baseConfigModel, sb); baseConfigModel.TableNameUpper = TableMappingHelper.ConvertTo_Uppercase(baseConfigModel.TableName); sb.AppendLine(" [TableAttribute(\"" + baseConfigModel.TableName + "\")]"); var baseEntity = GetBaseEntity(baseConfigModel.FileConfig.EntityName, dt, idColumn); if (string.IsNullOrEmpty(baseEntity)) { sb.AppendLine(" public class " + baseConfigModel.FileConfig.EntityName); } else { sb.AppendLine(" public class " + baseConfigModel.FileConfig.EntityName + " : " + baseEntity); } sb.AppendLine(" {"); string column = string.Empty; string remark = string.Empty; string datatype = string.Empty; foreach (DataRow dr in dt.Rows) { column = dr["TableColumn"].ToString(); //基础字段一样生成 //if (BaseField.BaseFieldList.Where(p => p == column.ToLower()).Any()) //{ // // 基础字段不需要生成,继承合适的BaseEntity即可。 // continue; //} remark = dr["Remark"].ToString(); datatype = dr["Datatype"].ToString(); //column = TableMappingHelper.ConvertToUppercase(column); datatype = TableMappingHelper.GetPropertyDatatype(datatype); sb.AppendLine(" /// "); sb.AppendLine(" /// " + remark); sb.AppendLine(" /// "); if (idColumn == column) { if (datatype == "int?") { sb.AppendLine(" [AutoIncrement]"); sb.AppendLine(" [Column(\"" + column + "\", IsPrimaryKey = true)]"); sb.AppendLine(" public int " + column + " { get; set; }"); } else if (datatype == "long?") { sb.AppendLine(" [Column(\"" + column + "\", IsPrimaryKey = true)]"); sb.AppendLine(" public long " + column + " { get; set; }"); } else { sb.AppendLine(" [Column(\"" + column + "\", IsPrimaryKey = true)]"); sb.AppendLine(" public " + datatype + " " + column + " { get; set; }"); } } else { sb.AppendLine(" public " + datatype + " " + column + " { get; set; }"); } //switch (datatype) //{ // case "long?": // sb.AppendLine(" [JsonConverter(typeof(StringJsonConverter))]"); // break; // case "DateTime?": // sb.AppendLine(" [JsonConverter(typeof(DateTimeJsonConverter))]"); // break; //} } sb.AppendLine(" }"); sb.AppendLine("}"); return sb.ToString(); } #endregion #region BuildService public string BuildService(BaseConfigModel baseConfigModel, DataTable dt, string idColumn = "F_Id", string idType = "int") { var baseEntity = GetBaseEntity(baseConfigModel.FileConfig.EntityName, dt, idColumn); StringBuilder sb = new StringBuilder(); string method = string.Empty; sb.AppendLine("using System;"); sb.AppendLine("using System.Linq;"); sb.AppendLine("using System.Threading.Tasks;"); sb.AppendLine("using System.Collections.Generic;"); sb.AppendLine("using WaterCloud.Code;"); sb.AppendLine("using Chloe;"); sb.AppendLine("using WaterCloud.Domain." + baseConfigModel.OutputConfig.OutputModule + ";"); sb.AppendLine(); sb.AppendLine("namespace WaterCloud.Service." + baseConfigModel.OutputConfig.OutputModule); sb.AppendLine("{"); SetClassDescription("服务类", baseConfigModel, sb); sb.AppendLine(" public class " + baseConfigModel.FileConfig.ServiceName + " : DataFilterService<" + baseConfigModel.FileConfig.EntityName + ">, IDenpendency"); sb.AppendLine(" {"); if (baseConfigModel.PageIndex.IsCache == true) { sb.AppendLine(" private string cacheKey = \"watercloud_" + baseConfigModel.FileConfig.ClassPrefix.ToLower() + "data_\";"); } sb.AppendLine(" public " + baseConfigModel.FileConfig.ServiceName + "(IDbContext context) : base(context)"); sb.AppendLine(" {"); sb.AppendLine(" }"); sb.AppendLine(" #region 获取数据"); sb.AppendLine(" public async Task> GetList(string keyword = \"\")"); sb.AppendLine(" {"); if (baseConfigModel.PageIndex.IsCache == false) { sb.AppendLine(" var data = repository.IQueryable();"); sb.AppendLine(" if (!string.IsNullOrEmpty(keyword))"); sb.AppendLine(" {"); for (int i = 0; i < baseConfigModel.PageIndex.KeywordColum.Count; i++) { if (i == 0) { sb.AppendLine($" data = data.Where(t => t.{baseConfigModel.PageIndex.KeywordColum[i]}.Contains(keyword)" + (i == baseConfigModel.PageIndex.KeywordColum.Count - 1 ? ");" : "")); } else { sb.AppendLine($" || t.{baseConfigModel.PageIndex.KeywordColum[i]}.Contains(keyword)" + (i == baseConfigModel.PageIndex.KeywordColum.Count - 1 ? ");" : "")); } } sb.AppendLine(" }"); sb.AppendLine(" return data." + (string.IsNullOrEmpty(baseConfigModel.PageIndex.DeleteColum) ? "" : $"Where(t => t.{baseConfigModel.PageIndex.DeleteColum} == false).") + (baseConfigModel.PageIndex.IsAsc == true ? "OrderBy" : "OrderByDesc") + $"(t => t.{baseConfigModel.PageIndex.SortColumn}).ToList();"); } else { sb.AppendLine(" var data = await repository.CheckCacheList(cacheKey + \"list\");"); sb.AppendLine(" if (!string.IsNullOrEmpty(keyword))"); sb.AppendLine(" {"); for (int i = 0; i < baseConfigModel.PageIndex.KeywordColum.Count; i++) { if (i == 0) { sb.AppendLine($" data = data.Where(t => t.{baseConfigModel.PageIndex.KeywordColum[i]}.Contains(keyword)" + (i == baseConfigModel.PageIndex.KeywordColum.Count - 1 ? ").ToList();" : "")); } else { sb.AppendLine($" || t.{baseConfigModel.PageIndex.KeywordColum[i]}.Contains(keyword)" + (i == baseConfigModel.PageIndex.KeywordColum.Count - 1 ? ").ToList();" : "")); } } sb.AppendLine(" }"); sb.AppendLine(" return data." + (string.IsNullOrEmpty(baseConfigModel.PageIndex.DeleteColum) ? "" : $"Where(t => t.{baseConfigModel.PageIndex.DeleteColum} == false).") + (baseConfigModel.PageIndex.IsAsc == true ? "OrderBy" : "OrderByDesc") + $"(t => t.{baseConfigModel.PageIndex.SortColumn}).ToList();"); } sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" public async Task> GetLookList(string keyword = \"\")"); sb.AppendLine(" {"); sb.AppendLine($" var query = repository.IQueryable()" + (string.IsNullOrEmpty(baseConfigModel.PageIndex.DeleteColum) ? ";" : $".Where(t => t.{baseConfigModel.PageIndex.DeleteColum} == false);")); sb.AppendLine(" if (!string.IsNullOrEmpty(keyword))"); sb.AppendLine(" {"); sb.AppendLine(" //此处需修改"); for (int i = 0; i < baseConfigModel.PageIndex.KeywordColum.Count; i++) { if (i == 0) { sb.AppendLine($" query = query.Where(t => t.{baseConfigModel.PageIndex.KeywordColum[i]}.Contains(keyword)" + (i == baseConfigModel.PageIndex.KeywordColum.Count - 1 ? ");" : "")); } else { sb.AppendLine($" || t.{baseConfigModel.PageIndex.KeywordColum[i]}.Contains(keyword)" + (i == baseConfigModel.PageIndex.KeywordColum.Count - 1 ? ");" : "")); } } sb.AppendLine(" }"); sb.AppendLine(" //权限过滤"); sb.AppendLine(" query = GetDataPrivilege(\"u\", \"\", query);"); sb.AppendLine($" return query." + (baseConfigModel.PageIndex.IsAsc == true ? "OrderBy" : "OrderByDesc") + $"(t => t.{baseConfigModel.PageIndex.SortColumn}).ToList();"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" public async Task> GetLookList(SoulPage<" + baseConfigModel.FileConfig.EntityName + "> pagination,string keyword = \"\"," + idType + " id=\"\")"); sb.AppendLine(" {"); sb.AppendLine($" var query = repository.IQueryable()" + (string.IsNullOrEmpty(baseConfigModel.PageIndex.DeleteColum) ? ";" : $".Where(t => t.{baseConfigModel.PageIndex.DeleteColum} == false);")); sb.AppendLine(" if (!string.IsNullOrEmpty(keyword))"); sb.AppendLine(" {"); for (int i = 0; i < baseConfigModel.PageIndex.KeywordColum.Count; i++) { if (i == 0) { sb.AppendLine($" query = query.Where(t => t.{baseConfigModel.PageIndex.KeywordColum[i]}.Contains(keyword)" + (i == baseConfigModel.PageIndex.KeywordColum.Count - 1 ? ");" : "")); } else { sb.AppendLine($" || t.{baseConfigModel.PageIndex.KeywordColum[i]}.Contains(keyword)" + (i == baseConfigModel.PageIndex.KeywordColum.Count - 1 ? ");" : "")); } } sb.AppendLine(" }"); if (idType == "int" || idType == "long") { sb.AppendLine(" if(id == 0)"); } else { sb.AppendLine(" if(!string.IsNullOrEmpty(id))"); } sb.AppendLine(" {"); sb.AppendLine(" query= query.Where(u=>u." + idColumn + "==id);"); sb.AppendLine(" }"); sb.AppendLine(" //权限过滤"); sb.AppendLine(" query = GetDataPrivilege(\"u\",\"\",query);"); sb.AppendLine(" return await repository.OrderList(query, pagination);"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" public async Task<" + baseConfigModel.FileConfig.EntityName + $"> GetForm({idType} keyValue)"); sb.AppendLine(" {"); if (baseConfigModel.PageIndex.IsCache == false) { sb.AppendLine(" var data = await repository.FindEntity(keyValue);"); sb.AppendLine($" return data;"); } else { sb.AppendLine(" var cachedata = await repository.CheckCache(cacheKey, keyValue);"); sb.AppendLine(" return cachedata;"); } sb.AppendLine(" }"); sb.AppendLine(" #endregion"); sb.AppendLine(); sb.AppendLine(" public async Task<" + baseConfigModel.FileConfig.EntityName + $"> GetLookForm({idType} keyValue)"); sb.AppendLine(" {"); if (baseConfigModel.PageIndex.IsCache == true) { sb.AppendLine(" var cachedata = await repository.CheckCache(cacheKey, keyValue);"); sb.AppendLine(" return GetFieldsFilterData(cachedata);"); } else { sb.AppendLine(" var data = await repository.FindEntity(keyValue);"); sb.AppendLine(" return GetFieldsFilterData(data);"); } sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #region 提交数据"); sb.AppendLine(" public async Task SubmitForm(" + baseConfigModel.FileConfig.EntityName + $" entity, {idType} keyValue)"); sb.AppendLine(" {"); if (idType == "int" || idType == "long") { sb.AppendLine(" if(keyValue == 0)"); } else { sb.AppendLine(" if(string.IsNullOrEmpty(keyValue))"); } sb.AppendLine(" {"); sb.AppendLine(" //初始值添加"); if (!string.IsNullOrEmpty(baseConfigModel.PageIndex.DeleteColum)) { sb.AppendLine($" entity.{baseConfigModel.PageIndex.DeleteColum} = false;"); } foreach (var item in baseConfigModel.PageIndex.ColumnList) { if (item.field != idColumn && item.field != baseConfigModel.PageIndex.DeleteColum && item.field != baseConfigModel.PageIndex.CreateColum && !string.IsNullOrEmpty(item.value)) { sb.AppendLine($" entity.{item.field} = {item.value};"); } } if (string.IsNullOrEmpty(baseEntity)) { if (idType == "int") { sb.AppendLine(" entity." + idColumn + " = 0;"); } else if (idType == "long") { sb.AppendLine(" entity." + idColumn + " = 0;"); } else { sb.AppendLine(" entity." + idColumn + " = Utils.GuId();"); } if (!string.IsNullOrEmpty(baseConfigModel.PageIndex.CreateColum)) { sb.AppendLine($" entity.{baseConfigModel.PageIndex.CreateColum} = DateTime.Now;"); } } else { sb.AppendLine(" entity.Create();"); } sb.AppendLine(" await repository.Insert(entity);"); if (baseConfigModel.PageIndex.IsCache == true) { sb.AppendLine(" await CacheHelper.Remove(cacheKey + \"list\");"); } sb.AppendLine(" }"); sb.AppendLine(" else"); sb.AppendLine(" {"); sb.AppendLine(" //此处需修改"); if (string.IsNullOrEmpty(baseEntity)) { if (idType == "int") { sb.AppendLine(" entity." + idColumn + " = Convert.ToInt32(keyValue);"); } else if (idType == "long") { sb.AppendLine(" entity." + idColumn + " = Convert.ToInt64(keyValue);"); } else { sb.AppendLine(" entity." + idColumn + " = keyValue;"); } } else { sb.AppendLine(" entity.Modify(keyValue); "); } sb.AppendLine(" await repository.Update(entity);"); if (baseConfigModel.PageIndex.IsCache == true) { sb.AppendLine(" await CacheHelper.Remove(cacheKey + keyValue);"); sb.AppendLine(" await CacheHelper.Remove(cacheKey + \"list\");"); } sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" public async Task DeleteForm(string keyValue)"); sb.AppendLine(" {"); sb.AppendLine(" var ids = keyValue.Split(',');"); sb.AppendLine(" await repository.Delete(t => ids.Contains(t." + idColumn + ".ToString()));"); if (baseConfigModel.PageIndex.IsCache == true) { sb.AppendLine(" foreach (var item in ids)"); sb.AppendLine(" {"); sb.AppendLine(" await CacheHelper.Remove(cacheKey + item);"); sb.AppendLine(" }"); sb.AppendLine(" await CacheHelper.Remove(cacheKey + \"list\");"); } sb.AppendLine(" }"); sb.AppendLine(" #endregion"); sb.AppendLine(); sb.AppendLine(" }"); sb.AppendLine("}"); return sb.ToString(); } #endregion #region BuildController public string BuildController(BaseConfigModel baseConfigModel, string idColumn = "F_Id", string idType = "string") { StringBuilder sb = new StringBuilder(); sb.AppendLine("using System;"); sb.AppendLine("using System.Linq;"); sb.AppendLine("using System.Threading.Tasks;"); sb.AppendLine("using System.Collections.Generic;"); sb.AppendLine("using Microsoft.AspNetCore.Mvc;"); sb.AppendLine("using WaterCloud.Code;"); sb.AppendLine("using WaterCloud.Domain." + baseConfigModel.OutputConfig.OutputModule + ";"); sb.AppendLine("using WaterCloud.Service;"); sb.AppendLine("using Microsoft.AspNetCore.Authorization;"); sb.AppendLine("using WaterCloud.Service." + baseConfigModel.OutputConfig.OutputModule + ";"); sb.AppendLine(); sb.AppendLine("namespace WaterCloud.Web.Areas." + baseConfigModel.OutputConfig.OutputModule + ".Controllers"); sb.AppendLine("{"); SetClassDescription("控制器类", baseConfigModel, sb); sb.AppendLine(" [Area(\"" + baseConfigModel.OutputConfig.OutputModule + "\")]"); sb.AppendLine(" public class " + baseConfigModel.FileConfig.ControllerName + " : ControllerBase"); sb.AppendLine(" {"); sb.AppendLine(" public " + baseConfigModel.FileConfig.ServiceName + " _service {get;set;}"); sb.AppendLine(); sb.AppendLine(" #region 获取数据"); if (baseConfigModel.PageIndex.IsTree == true) { sb.AppendLine(" [HttpGet]"); sb.AppendLine(" [HandlerAjaxOnly]"); sb.AppendLine(" public async Task GetTreeGridJson(string keyword)"); sb.AppendLine(" {"); sb.AppendLine(" var data = await _service.GetLookList(keyword);"); sb.AppendLine(" if (!string.IsNullOrEmpty(keyword))"); sb.AppendLine(" {"); sb.AppendLine(" //此处需修改"); sb.AppendLine(" data = data.TreeWhere(t => t." + baseConfigModel.PageIndex.TreeColum + ".Contains(keyword));"); sb.AppendLine(" }"); sb.AppendLine(" return Success(data.Count, data);"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" [HttpGet]"); sb.AppendLine(" [HandlerAjaxOnly]"); sb.AppendLine(" public async Task GetTreeSelectJson()"); sb.AppendLine(" {"); sb.AppendLine(" var data = await _service.GetList();"); sb.AppendLine(" var treeList = new List();"); sb.AppendLine(" foreach (var item in data)"); sb.AppendLine(" {"); sb.AppendLine(" //此处需修改"); sb.AppendLine(" TreeSelectModel treeModel = new TreeSelectModel();"); sb.AppendLine(" treeModel.id = item." + idColumn + ";"); sb.AppendLine(" treeModel.text = item." + baseConfigModel.PageIndex.TreeColum + ";"); sb.AppendLine(" treeModel.parentId = item." + baseConfigModel.PageIndex.ParentColum + ";"); sb.AppendLine(" treeList.Add(treeModel);"); sb.AppendLine(" }"); sb.AppendLine(" return Content(treeList.TreeSelectJson());"); sb.AppendLine(" }"); } else { sb.AppendLine(" [HandlerAjaxOnly]"); sb.AppendLine(" [IgnoreAntiforgeryToken]"); sb.AppendLine(" public async Task GetGridJson(SoulPage<" + baseConfigModel.FileConfig.EntityName + "> pagination, string keyword)"); sb.AppendLine(" {"); sb.AppendLine(" if (string.IsNullOrEmpty(pagination.field))"); sb.AppendLine(" {"); sb.AppendLine($" pagination.field = \"{baseConfigModel.PageIndex.SortColumn}\";"); sb.AppendLine(" pagination.order = \"" + (baseConfigModel.PageIndex.IsAsc == true ? "asc" : "desc") + "\";"); sb.AppendLine(" }"); sb.AppendLine(" var data = await _service.GetLookList(pagination,keyword);"); sb.AppendLine(" return Content(pagination.setData(data).ToJson());"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" [HttpGet]"); sb.AppendLine(" [HandlerAjaxOnly]"); sb.AppendLine(" public async Task GetListJson(string keyword)"); sb.AppendLine(" {"); sb.AppendLine(" var data = await _service.GetList(keyword);"); sb.AppendLine(" return Content(data.ToJson());"); sb.AppendLine(" }"); } sb.AppendLine(); sb.AppendLine(" [HttpGet]"); sb.AppendLine(" [HandlerAjaxOnly]"); sb.AppendLine($" public async Task GetFormJson({idType} keyValue)"); sb.AppendLine(" {"); sb.AppendLine(" var data = await _service.GetLookForm(keyValue);"); sb.AppendLine(" return Content(data.ToJson());"); sb.AppendLine(" }"); sb.AppendLine(" #endregion"); sb.AppendLine(); sb.AppendLine(" #region 提交数据"); sb.AppendLine(" [HttpPost]"); sb.AppendLine(" [HandlerAjaxOnly]"); sb.AppendLine(" public async Task SubmitForm(" + baseConfigModel.FileConfig.EntityName + $" entity, {idType} keyValue)"); sb.AppendLine(" {"); sb.AppendLine(" try"); sb.AppendLine(" {"); sb.AppendLine(" await _service.SubmitForm(entity, keyValue);"); sb.AppendLine(" return await Success(\"操作成功。\", \"\", keyValue);"); sb.AppendLine(" }"); sb.AppendLine(" catch (Exception ex)"); sb.AppendLine(" {"); sb.AppendLine(" return await Error(ex.Message, \"\", keyValue);"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" [HttpPost]"); sb.AppendLine(" [HandlerAjaxOnly]"); sb.AppendLine(" [ServiceFilter(typeof(HandlerAuthorizeAttribute))]"); sb.AppendLine(" public async Task DeleteForm(string keyValue)"); sb.AppendLine(" {"); sb.AppendLine(" try"); sb.AppendLine(" {"); sb.AppendLine(" await _service.DeleteForm(keyValue);"); sb.AppendLine(" return await Success(\"操作成功。\", \"\", keyValue, DbLogType.Delete);"); sb.AppendLine(" }"); sb.AppendLine(" catch (Exception ex)"); sb.AppendLine(" {"); sb.AppendLine(" return await Error(ex.Message, \"\", keyValue, DbLogType.Delete);"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(" #endregion"); sb.AppendLine(" }"); sb.AppendLine("}"); return sb.ToString(); } #endregion #region BuildIndex public string BuildIndex(BaseConfigModel baseConfigModel, string idColumn = "F_Id") { #region 初始化集合 if (baseConfigModel.PageIndex.ButtonList == null) { baseConfigModel.PageIndex.ButtonList = new List(); } if (baseConfigModel.PageIndex.ColumnList == null) { baseConfigModel.PageIndex.ColumnList = new List(); } #endregion List list = GetButtonAuthorizeList(); StringBuilder sb = new StringBuilder(); int buttonCount = baseConfigModel.PageIndex.ButtonList.Where(a => a != "add").Count(); sb.AppendLine("@{"); sb.AppendLine(" ViewBag.Title = \"Index\";"); sb.AppendLine(" Layout = \"~/Views/Shared/_Index.cshtml\";"); sb.AppendLine(" }"); sb.AppendLine("
"); sb.AppendLine("
"); #region 搜索栏 if (baseConfigModel.PageIndex.IsSearch == true) { sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); } #endregion #region 工具栏 sb.AppendLine(" "); #endregion sb.AppendLine("
"); if (buttonCount > 0) { sb.AppendLine(" "); } sb.AppendLine(" "); sb.AppendLine(" "); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine("
"); #region js layui方法 sb.AppendLine(" "); #endregion return sb.ToString(); } #endregion #region BuildForm public string BuildForm(BaseConfigModel baseConfigModel) { #region 初始化集合 if (baseConfigModel.PageForm.FieldList == null) { baseConfigModel.PageForm.FieldList = new Dictionary(); } #endregion StringBuilder sb = new StringBuilder(); sb.AppendLine("@{"); sb.AppendLine(" ViewBag.Title = \"Form\"; "); sb.AppendLine(" Layout = \"~/Views/Shared/_Form.cshtml\";"); sb.AppendLine("}"); sb.AppendLine(""); sb.AppendLine(""); sb.AppendLine(""); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); #region 表单控件 if (baseConfigModel.PageForm.FieldList.Count > 0) { switch (baseConfigModel.PageForm.ShowMode) { case 1: foreach (var item in baseConfigModel.PageForm.FieldList) { sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine("
"); } break; case 2: int i = 1; foreach (var item in baseConfigModel.PageForm.FieldList) { if (i % 2 != 0) { sb.AppendLine("
"); } sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine("
"); if (i % 2 == 0) { sb.AppendLine("
"); } else if (i == baseConfigModel.PageForm.FieldList.Count) { sb.AppendLine("
"); } i++; } break; } } #endregion sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine(""); sb.AppendLine(""); return sb.ToString(); } #endregion #region BuildDetails public string BuildDetails(BaseConfigModel baseConfigModel) { #region 初始化集合 if (baseConfigModel.PageForm.FieldList == null) { baseConfigModel.PageForm.FieldList = new Dictionary(); } #endregion StringBuilder sb = new StringBuilder(); sb.AppendLine("@{"); sb.AppendLine(" ViewBag.Title = \"Details\"; "); sb.AppendLine(" Layout = \"~/Views/Shared/_Form.cshtml\";"); sb.AppendLine("}"); sb.AppendLine(""); sb.AppendLine(""); sb.AppendLine(""); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); #region 表单控件 if (baseConfigModel.PageForm.FieldList.Count > 0) { switch (baseConfigModel.PageForm.ShowMode) { case 1: foreach (var item in baseConfigModel.PageForm.FieldList) { sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine("
"); } break; case 2: int i = 1; foreach (var item in baseConfigModel.PageForm.FieldList) { if (i % 2 != 0) { sb.AppendLine("
"); } sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine("
"); if (i % 2 == 0) { sb.AppendLine("
"); } else if (i == baseConfigModel.PageForm.FieldList.Count) { sb.AppendLine("
"); } i++; } break; } } #endregion sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine(""); sb.AppendLine(""); return sb.ToString(); } #endregion #region BuildMenu public string BuildMenu(BaseConfigModel baseConfigModel, string idColumn = "F_Id") { StringBuilder sb = new StringBuilder(); sb.AppendLine(); sb.AppendLine(" 菜单路径:/" + baseConfigModel.OutputConfig.OutputModule + "/" + baseConfigModel.FileConfig.ClassPrefix + "/" + baseConfigModel.FileConfig.PageIndexName); sb.AppendLine(); sb.AppendLine(" 主键:" + idColumn); List list = GetButtonAuthorizeList(); foreach (string btn in baseConfigModel.PageIndex.ButtonList) { KeyValue button = list.Where(p => p.Key == btn).FirstOrDefault(); string form = ""; switch (btn) { case "delete": form = "DeleteForm"; break; case "details": form = "Details"; break; default: form = "Form"; break; } string url = "/" + baseConfigModel.OutputConfig.OutputModule + "/" + baseConfigModel.FileConfig.ClassPrefix + "/" + form; sb.AppendLine(" 按钮名称:" + button.Description + ";编号:" + button.Value + ";事件:" + button.Key + ";连接:" + url); } sb.AppendLine(); return sb.ToString(); } #endregion #region CreateCode public async Task> CreateCode(BaseConfigModel baseConfigModel, string code) { List result = new List(); JObject param = code.ToJObject(); #region 集中判断 string codeIndex = ""; string indexPath = ""; if (!param["CodeIndex"].IsEmpty()) { codeIndex = HttpUtility.HtmlDecode(param["CodeIndex"].ToString()); indexPath = Path.Combine(baseConfigModel.OutputConfig.OutputWeb, "Areas", baseConfigModel.OutputConfig.OutputModule, "Views", baseConfigModel.FileConfig.ClassPrefix, baseConfigModel.FileConfig.PageIndexName + ".cshtml"); if (File.Exists(indexPath)) { throw new Exception("列表页已存在,列表页生成失败!"); } } string codeForm = ""; string formPath = ""; if (!param["CodeForm"].IsEmpty()) { codeForm = HttpUtility.HtmlDecode(param["CodeForm"].ToString()); formPath = Path.Combine(baseConfigModel.OutputConfig.OutputWeb, "Areas", baseConfigModel.OutputConfig.OutputModule, "Views", baseConfigModel.FileConfig.ClassPrefix, baseConfigModel.FileConfig.PageFormName + ".cshtml"); if (File.Exists(formPath)) { throw new Exception("表单页存在,表单页生成失败!"); } } string codeDetails = ""; string detailsPath = ""; if (!param["CodeDetails"].IsEmpty()) { codeDetails = HttpUtility.HtmlDecode(param["CodeDetails"].ToString()); detailsPath = Path.Combine(baseConfigModel.OutputConfig.OutputWeb, "Areas", baseConfigModel.OutputConfig.OutputModule, "Views", baseConfigModel.FileConfig.ClassPrefix, baseConfigModel.FileConfig.PageDetailsName + ".cshtml"); if (File.Exists(detailsPath)) { throw new Exception("详情页存在,详情页生成失败!"); } } string codeEntity = ""; string entityPath = ""; if (!string.IsNullOrEmpty(param["CodeEntity"].ParseToString())) { codeEntity = HttpUtility.HtmlDecode(param["CodeEntity"].ToString()); entityPath = Path.Combine(baseConfigModel.OutputConfig.OutputEntity, baseConfigModel.OutputConfig.OutputModule, baseConfigModel.FileConfig.EntityName + ".cs"); if (File.Exists(entityPath)) { throw new Exception("实体类已存在,实体类生成失败!"); } } string codeService = ""; string servicePath = ""; if (!param["CodeService"].IsEmpty()) { codeService = HttpUtility.HtmlDecode(param["CodeService"].ToString()); servicePath = Path.Combine(baseConfigModel.OutputConfig.OutputService, baseConfigModel.OutputConfig.OutputModule, baseConfigModel.FileConfig.ServiceName + ".cs"); if (File.Exists(servicePath)) { throw new Exception("服务类已存在,服务类生成失败!"); } } string codeController = ""; string controllerPath = ""; if (!param["CodeController"].IsEmpty()) { codeController = HttpUtility.HtmlDecode(param["CodeController"].ToString()); controllerPath = Path.Combine(baseConfigModel.OutputConfig.OutputWeb, "Areas", baseConfigModel.OutputConfig.OutputModule, "Controllers", baseConfigModel.FileConfig.ControllerName + ".cs"); if (File.Exists(controllerPath)) { throw new Exception("控制器已存在,控制器生成失败!"); } } #endregion #region 列表页 if (!param["CodeIndex"].IsEmpty()) { // 生成菜单,按钮 List buttonAuthorizeList = GetButtonAuthorizeList(); string menuUrl = "/" + baseConfigModel.OutputConfig.OutputModule + "/" + baseConfigModel.FileConfig.ClassPrefix + "/" + baseConfigModel.FileConfig.PageIndexName; ModuleEntity moduleEntity = new ModuleEntity(); moduleEntity.Create(); moduleEntity.F_Layers = (await uniwork.FindEntity(a => a.F_EnCode == baseConfigModel.OutputConfig.OutputModule)).F_Layers + 1; ; moduleEntity.F_FullName = baseConfigModel.FileConfig.ClassDescription; moduleEntity.F_UrlAddress = menuUrl; moduleEntity.F_EnCode = baseConfigModel.FileConfig.ClassPrefix; moduleEntity.F_IsExpand = false; moduleEntity.F_IsMenu = baseConfigModel.PageIndex.IsMunu == true ? true : false; moduleEntity.F_IsFields = baseConfigModel.PageIndex.IsFields == true ? true : false; moduleEntity.F_IsPublic = baseConfigModel.PageIndex.IsPublic == true ? true : false; moduleEntity.F_Target = "iframe"; moduleEntity.F_AllowEdit = false; moduleEntity.F_AllowDelete = false; moduleEntity.F_EnabledMark = true; moduleEntity.F_DeleteMark = false; moduleEntity.F_ParentId = (await uniwork.FindEntity(a => a.F_EnCode == baseConfigModel.OutputConfig.OutputModule)).F_Id; var parentModule = await uniwork.FindEntity(a => a.F_EnCode == baseConfigModel.OutputConfig.OutputModule); moduleEntity.F_SortCode = (uniwork.IQueryable(a => a.F_ParentId == parentModule.F_Id).Max(a => a.F_SortCode) ?? 0) + 1; List moduleButtonList = new List(); int sort = 0; foreach (var item in baseConfigModel.PageIndex.ButtonList) { KeyValue button = buttonAuthorizeList.Where(p => p.Key == item).FirstOrDefault(); string form = ""; switch (item) { case "delete": form = "DeleteForm"; break; case "details": form = "Details"; break; default: form = "Form"; break; } string url = "/" + baseConfigModel.OutputConfig.OutputModule + "/" + baseConfigModel.FileConfig.ClassPrefix + "/" + form; ModuleButtonEntity modulebutton = new ModuleButtonEntity(); modulebutton.Create(); modulebutton.F_ModuleId = moduleEntity.F_Id; modulebutton.F_ParentId = "0"; modulebutton.F_Layers = 1; modulebutton.F_EnCode = button.Value; modulebutton.F_JsEvent = button.Key; modulebutton.F_FullName = button.Description; modulebutton.F_Location = button.Key == "add" ? 1 : 2; modulebutton.F_SortCode = sort; sort++; modulebutton.F_EnabledMark = true; modulebutton.F_DeleteMark = false; modulebutton.F_Split = false; modulebutton.F_AllowDelete = false; modulebutton.F_AllowEdit = false; modulebutton.F_IsPublic = false; modulebutton.F_UrlAddress = url; moduleButtonList.Add(modulebutton); } List moduleFieldsList = new List(); foreach (var item in baseConfigModel.PageIndex.ColumnList) { ModuleFieldsEntity moduleFields = new ModuleFieldsEntity(); moduleFields.Create(); moduleFields.F_ModuleId = moduleEntity.F_Id; moduleFields.F_EnCode = item.field; moduleFields.F_FullName = item.title; moduleFields.F_IsPublic = true; moduleFields.F_EnabledMark = true; moduleFields.F_DeleteMark = false; moduleFieldsList.Add(moduleFields); } uniwork.BeginTrans(); await uniwork.Insert(moduleEntity); await uniwork.Insert(moduleButtonList); if (moduleFieldsList.Count > 0) { await uniwork.Insert(moduleFieldsList); } uniwork.Commit(); await CacheHelper.Remove(fieldscacheKey + "list"); await CacheHelper.Remove(buttoncacheKey + "list"); await CacheHelper.Remove(cacheKey + "list"); await CacheHelper.Remove(quickcacheKey + "list"); await CacheHelper.Remove(initcacheKey + "list"); await CacheHelper.Remove(initcacheKey + "modulebutton_list"); await CacheHelper.Remove(initcacheKey + "modulefields_list"); await CacheHelper.Remove(authorizecacheKey + "list"); FileHelper.CreateFile(indexPath, codeIndex); result.Add(new KeyValue { Key = "列表页", Value = indexPath, Description = "生成成功!" }); } #endregion #region 表单页 if (!param["CodeForm"].IsEmpty()) { FileHelper.CreateFile(formPath, codeForm); result.Add(new KeyValue { Key = "表单页", Value = formPath, Description = "生成成功!" }); } #endregion #region 查看页 if (!param["CodeDetails"].IsEmpty()) { FileHelper.CreateFile(detailsPath, codeDetails); result.Add(new KeyValue { Key = "详情页", Value = detailsPath, Description = "生成成功!" }); } #endregion #region 实体类 if (!string.IsNullOrEmpty(param["CodeEntity"].ParseToString())) { FileHelper.CreateFile(entityPath, codeEntity); result.Add(new KeyValue { Key = "实体类", Value = entityPath, Description = "生成成功!" }); } #endregion #region 服务类 if (!param["CodeService"].IsEmpty()) { FileHelper.CreateFile(servicePath, codeService); result.Add(new KeyValue { Key = "服务类", Value = servicePath, Description = "生成成功!" }); } #endregion #region 控制器 if (!param["CodeController"].IsEmpty()) { FileHelper.CreateFile(controllerPath, codeController); result.Add(new KeyValue { Key = "控制器", Value = controllerPath, Description = "生成成功!" }); } #endregion return result; } #endregion #region EntityCreateCode public async Task EntityCreateCode(BaseConfigModel baseConfigModel, string code) { string codeEntity = ""; string entityPath = ""; if (!string.IsNullOrEmpty(code)) { codeEntity = code; entityPath = Path.Combine(baseConfigModel.OutputConfig.OutputEntity, baseConfigModel.OutputConfig.OutputModule, baseConfigModel.FileConfig.EntityName + ".cs"); if (File.Exists(entityPath)) { throw new Exception("实体类已存在,实体类生成失败!"); } FileHelper.CreateFile(entityPath, codeEntity); } } #endregion #region 私有方法 #region GetProjectRootPath private string GetProjectRootPath(string path) { path = path.ParseToString(); path = path.Trim('\\'); if (GlobalContext.SystemConfig.Debug) { // 向上找一级 path = Directory.GetParent(path).FullName; //path = Directory.GetParent(path).FullName; } return path; } #endregion #region SetClassDescription private void SetClassDescription(string type, BaseConfigModel baseConfigModel, StringBuilder sb) { sb.AppendLine(" /// "); sb.AppendLine(" /// 创 建:" + baseConfigModel.FileConfig.CreateUserName); sb.AppendLine(" /// 日 期:" + baseConfigModel.FileConfig.CreateDate); sb.AppendLine(" /// 描 述:" + baseConfigModel.FileConfig.ClassDescription + type); sb.AppendLine(" /// "); } #endregion #region GetButtonAuthorizeList private List GetButtonAuthorizeList() { var list = new List(); list.Add(new KeyValue { Key = "add", Value = "NF-add", Description = "新增" }); list.Add(new KeyValue { Key = "edit", Value = "NF-edit", Description = "修改" }); list.Add(new KeyValue { Key = "delete", Value = "NF-delete", Description = "删除" }); list.Add(new KeyValue { Key = "details", Value = "NF-details", Description = "查看" }); return list; } #endregion private string GetBaseEntity(string EntityName, DataTable dt, string idColumn = "F_Id") { string entity = string.Empty; var columnList = dt.AsEnumerable().Select(p => p["TableColumn"].ParseToString()).ToList(); bool id = columnList.Where(p => p == idColumn).Any(); bool baseIsDelete = columnList.Where(p => p == "F_DeleteUserId").Any() && columnList.Where(p => p == "F_DeleteTime").Any() && columnList.Where(p => p == "F_DeleteMark").Any(); bool baseIsCreate = columnList.Where(p => p == "F_Id").Any() && columnList.Where(p => p == "F_CreatorUserId").Any() && columnList.Where(p => p == "F_CreatorTime").Any(); bool baseIsModifie = columnList.Where(p => p == "F_Id").Any() && columnList.Where(p => p == "F_LastModifyUserId").Any() && columnList.Where(p => p == "F_LastModifyTime").Any(); if (!id) { throw new Exception("数据库表必须有主键id字段"); } if (idColumn != "F_Id") { return null; } entity = "IEntity<" + EntityName + ">"; if (baseIsCreate) { entity += ",ICreationAudited"; } if (baseIsModifie) { entity += ",IModificationAudited"; } if (baseIsDelete) { entity += ",IDeleteAudited"; } return entity; } #endregion } }