优化代码生成功能、新增加打包zip文件

This commit is contained in:
izory
2021-09-22 20:25:43 +08:00
parent 44ab0f2141
commit 62407707a5
28 changed files with 528 additions and 593 deletions
+31 -20
View File
@@ -1,4 +1,5 @@
using System.Linq;
using System;
using System.Linq;
using ZR.CodeGenerator.CodeGenerator;
using ZR.Model.System.Generate;
@@ -14,17 +15,28 @@ namespace ZR.CodeGenerator
/// </summary>
/// <param name="dbColumnInfo"></param>
/// <returns></returns>
public static string GetVueJsMethod(GenTableColumn dbColumnInfo)
public static string GetVueJsMethod(GenTableColumn dbFieldInfo)
{
string columnName = dbColumnInfo.ColumnName;
string columnName = dbFieldInfo.ColumnName;
string js = "";
if (dbColumnInfo.HtmlType.Equals(GenConstants.HTML_IMAGE_UPLOAD))
if (dbFieldInfo.HtmlType.Equals(GenConstants.HTML_IMAGE_UPLOAD))
{
js += $"handleUpload{columnName}Success(res, file) {{\r\n";
js += " //文件上传成功方法\r\n";
js += $" handleUpload{columnName}Success(res, file) {{\r\n";
js += $" this.form.{columnName} = URL.createObjectURL(file.raw);\r\n";
js += " // this.$refs.upload.clearFiles();\r\n";
js += " },\r";
}
//有下拉框选项初列表查询数据
if (dbFieldInfo.HtmlType == GenConstants.HTML_SELECT && !string.IsNullOrEmpty(dbFieldInfo.DictType))
{
var sb = new System.Text.StringBuilder(500);
sb.AppendLine(@$" // {dbFieldInfo.ColumnComment}字典翻译");
sb.AppendLine($" {columnName}Format(row, column) {{");
sb.AppendLine(@$" return this.selectDictLabel(this.{columnName}Options, row.{columnName});");
sb.AppendLine(@" },");
js += sb.ToString();
}
return js;
}
@@ -78,7 +90,7 @@ namespace ZR.CodeGenerator
public static string GetDtoProperty(GenTableColumn dbFieldInfo)
{
string InputDtoContent = "";
if (CodeGeneratorTool.inputDtoNoField.Any(f => f.Replace("_", "").ToLower().Contains(dbFieldInfo.CsharpField.ToLower().Replace("_", ""))))
if (GenConstants.inputDtoNoField.Any(f => f.Replace("_", "").ToLower().Contains(dbFieldInfo.CsharpField.ToLower().Replace("_", ""))))
{
return InputDtoContent;
}
@@ -97,7 +109,7 @@ namespace ZR.CodeGenerator
public static string GetQueryDtoProperty(GenTableColumn dbFieldInfo)
{
string QueryDtoContent = "";
if (dbFieldInfo.IsQuery && !CodeGeneratorTool.inputDtoNoField.Any(f => f.Replace("_", "").ToLower().Contains(dbFieldInfo.CsharpField.ToLower().Replace("_", ""))))
if (dbFieldInfo.IsQuery && !GenConstants.inputDtoNoField.Any(f => f.Replace("_", "").ToLower().Contains(dbFieldInfo.CsharpField.ToLower().Replace("_", ""))))
{
QueryDtoContent += $" public {dbFieldInfo.CsharpType} {dbFieldInfo.CsharpField} {{ get; set; }}\r\n";
}
@@ -113,7 +125,7 @@ namespace ZR.CodeGenerator
string vueViewFromContent = "";
string labelDisabled = dbFieldInfo.IsPk ? ":disabled=\"true\"" : "";
string placeHolder = dbFieldInfo.IsIncrement ? "" : $"请输入{labelName}";
if (CodeGeneratorTool.inputDtoNoField.Any(f => f.Replace("_", "").ToLower().Contains(dbFieldInfo.CsharpField.ToLower().Replace("_", ""))))
if (GenConstants.inputDtoNoField.Any(f => f.Replace("_", "").ToLower().Contains(dbFieldInfo.CsharpField.ToLower().Replace("_", ""))))
{
return vueViewFromContent;
}
@@ -156,16 +168,17 @@ namespace ZR.CodeGenerator
}
else if (dbFieldInfo.HtmlType == GenConstants.HTML_SELECT && !string.IsNullOrEmpty(dbFieldInfo.DictType))
{
string value = TableMappingHelper.IsNumber(dbFieldInfo.CsharpType) ? "parseInt(item.dictValue)" : "item.dictValue";
vueViewFromContent += $" <el-form-item label=\"{ labelName}\" :label-width=\"labelWidth\" prop=\"{columnName}\">\r\n";
vueViewFromContent += $" <el-select v-model=\"form.{columnName}\" > ";
vueViewFromContent += $" <el-option v-for=\"item in {columnName}Options\" :key=\"item.dictValue\" :label=\"item.dictLabel\" :value=\"item.dictValue\"></el-option>\r\n";
vueViewFromContent += " </el-select>\r\n";
vueViewFromContent += $" <el-select v-model=\"form.{columnName}\">\r\n";
vueViewFromContent += $" <el-option v-for=\"item in {columnName}Options\" :key=\"item.dictValue\" :label=\"item.dictLabel\" :value=\"{value}\"></el-option>\r\n";
vueViewFromContent += " </el-select>\r\n";
vueViewFromContent += " </el-form-item>\r\n";
}
else
{
string inputNumTxt = TableMappingHelper.IsNumber(dbFieldInfo.CsharpType) ? ".number" : "";
vueViewFromContent += $" <el-form-item label=\"{ labelName}\" :label-width=\"labelWidth\" prop=\"{CodeGeneratorTool.FirstLowerCase(columnName)}\">\r\n";
vueViewFromContent += $" <el-form-item label=\"{labelName}\" :label-width=\"labelWidth\" prop=\"{CodeGeneratorTool.FirstLowerCase(columnName)}\">\r\n";
vueViewFromContent += $" <el-input v-model{inputNumTxt}=\"form.{CodeGeneratorTool.FirstLowerCase(columnName)}\" placeholder=\"{placeHolder}\" {labelDisabled}/>\r\n";
vueViewFromContent += " </el-form-item>\r\n";
}
@@ -208,13 +221,11 @@ namespace ZR.CodeGenerator
string label = CodeGeneratorTool.GetLabelName(dbFieldInfo.ColumnComment, columnName);
string vueViewListContent = "";
string showToolTip = dbFieldInfo.ColumnType.Contains("varchar") ? ":show-overflow-tooltip=\"true\"" : "";
if (!dbFieldInfo.IsList)
string formatter = !string.IsNullOrEmpty(dbFieldInfo.DictType) ? $" :formatter=\"{columnName}Format\"" : "";
if (dbFieldInfo.IsList && dbFieldInfo.HtmlType.Equals(GenConstants.HTML_IMAGE_UPLOAD))
{
}
else if (dbFieldInfo.HtmlType.Equals(GenConstants.HTML_IMAGE_UPLOAD))
{
vueViewListContent += $" <el-table-column prop=\"{ columnName}\" label=\"图片\">\r\n";
vueViewListContent += $" <el-table-column prop=\"{columnName}\" label=\"图片\">\r\n";
vueViewListContent += " <template slot-scope=\"scope\">\r\n";
vueViewListContent += $" <el-image class=\"table-td-thumb\" :src=\"scope.row.{columnName}\" :preview-src-list=\"[scope.row.{columnName}]\"></el-image>\r\n";
vueViewListContent += " </template>\r\n";
@@ -229,9 +240,9 @@ namespace ZR.CodeGenerator
// vueViewListContent += " </template>\r\n";
// vueViewListContent += " </el-table-column>\r\n";
//}
else
else if(dbFieldInfo.IsList)
{
vueViewListContent += $" <el-table-column prop=\"{columnName}\" label=\"{label}\" align=\"center\" width=\"100\" {showToolTip} />\r\n";
vueViewListContent += $" <el-table-column prop=\"{columnName}\" label=\"{label}\" align=\"center\" {showToolTip}{formatter}/>\r\n";
}
return vueViewListContent;
}
+158 -41
View File
@@ -1,8 +1,10 @@
using Infrastructure;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ZR.CodeGenerator.CodeGenerator;
using ZR.CodeGenerator.Model;
using ZR.Model.System.Generate;
@@ -20,24 +22,15 @@ namespace ZR.CodeGenerator
/// 代码生成器配置
/// </summary>
private static CodeGenerateOption _option = new CodeGenerateOption();
/// <summary>
/// InputDto输入实体是不包含字段
/// </summary>
public static readonly string[] inputDtoNoField = new string[] { "createTime", "updateTime", "addtime" };
public static readonly string[] imageFiled = new string[] { "icon", "img", "image", "url", "pic", "photo" };
public static readonly string[] selectFiled = new string[] { "status", "type", "state", "sex", "gender" };
public static readonly string[] radioFiled = new string[] { "status", "state", "isShow", "isHidden", "ishide" };
/// <summary>
/// 代码生成器入口方法
/// </summary>
/// <param name="dbTableInfo"></param>
/// <param name="dto"></param>
public static void Generate(GenTable dbTableInfo, GenerateDto dto)
public static List<string> Generate(GenTable dbTableInfo, GenerateDto dto)
{
_option.BaseNamespace = "ZR.";
//_option.TableList = listTable;
_option.ReplaceTableNameStr = dto.replaceTableNameStr;
_option.BaseNamespace = dbTableInfo.BaseNameSpace;
_option.DtosNamespace = _option.BaseNamespace + "Model";
_option.ModelsNamespace = _option.BaseNamespace + "Model";
_option.RepositoriesNamespace = _option.BaseNamespace + "Repository";
@@ -46,7 +39,43 @@ namespace ZR.CodeGenerator
_option.ServicesNamespace = _option.BaseNamespace + "Service";
_option.ApiControllerNamespace = _option.BaseNamespace + "Admin.WebApi";
GenerateSingle(dbTableInfo?.Columns, dbTableInfo, dto);
List<string> list = GenerateSingle(dbTableInfo?.Columns, dbTableInfo, dto);
return list;
}
/// <summary>
/// 打包压缩代码
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
public static string ZipGenCode(GenerateDto dto)
{
try
{
string zipPath = Environment.CurrentDirectory + "\\wwwroot\\Generatecode\\";
//生成压缩包
string zipReturnFileName = dto.baseSpace + DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip";
if (!Directory.Exists(zipPath))
{
Directory.CreateDirectory(zipPath);
}
string zipFileName = zipPath + "\\" + zipReturnFileName;
if (File.Exists(zipFileName))
{
File.Delete(zipFileName);
}
Console.WriteLine(zipFileName);
FileHelper.ZipFileDirectory(dto.ParentPath, zipFileName, 7, "", "", "*.*");
FileHelper.DeleteDirectory(dto.ParentPath);
return zipFileName;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "";
}
}
/// <summary>
@@ -55,10 +84,11 @@ namespace ZR.CodeGenerator
/// <param name="listField">表字段集合</param>
/// <param name="tableInfo">表信息</param>
/// <param name="dto"></param>
public static void GenerateSingle(List<GenTableColumn> listField, GenTable tableInfo, GenerateDto dto)
public static List<string> GenerateSingle(List<GenTableColumn> listField, GenTable tableInfo, GenerateDto dto)
{
string PKName = "id";
string PKType = "int";
List<string> genPathList = new();
ReplaceDto replaceDto = new();
replaceDto.ModelTypeName = tableInfo.ClassName;//表名对应C# 实体类名
replaceDto.TableName = tableInfo.TableName;
@@ -88,15 +118,19 @@ namespace ZR.CodeGenerator
{
replaceDto.InsertColumn += $"it.{dbFieldInfo.CsharpField}, ";
}
//查询
//TODO 查询
//if (dbFieldInfo.IsQuery)
//{
// replaceDto.Querycondition += $"predicate = predicate.And(m => m.{dbFieldInfo.CsharpField}.Contains(parm.Name));";
//}
if (dbFieldInfo.HtmlType == GenConstants.HTML_SELECT && !string.IsNullOrEmpty(dbFieldInfo.DictType))
if ((dbFieldInfo.HtmlType == GenConstants.HTML_SELECT || dbFieldInfo.HtmlType == GenConstants.HTML_RADIO) && !string.IsNullOrEmpty(dbFieldInfo.DictType))
{
replaceDto.VueDataContent += $"// {dbFieldInfo.ColumnComment}选项列表\n";
replaceDto.VueDataContent += $"{FirstLowerCase(dbFieldInfo.CsharpField)}Options: [],";
replaceDto.MountedMethod += $" this.getDicts(\"{dbFieldInfo.DictType}\").then((response) => {{\n";
replaceDto.MountedMethod += $" this.{FirstLowerCase(dbFieldInfo.CsharpField)}Options = response.data;\n";
replaceDto.MountedMethod += " })\n";
}
replaceDto.QueryProperty += CodeGenerateTemplate.GetQueryDtoProperty(dbFieldInfo);
@@ -113,29 +147,44 @@ namespace ZR.CodeGenerator
if (dto.genFiles.Contains(1))
{
GenerateModels(replaceDto, dto);
Tuple<string, string> tuple = GenerateModels(replaceDto, dto);
genPathList.Add(tuple.Item1);
//WriteAndSave(tuple.Item1, tuple.Item2);
}
if (dto.genFiles.Contains(2))
{
GenerateInputDto(replaceDto, dto);
Tuple<string, string> tuple = GenerateInputDto(replaceDto, dto);
genPathList.Add(tuple.Item1);
//WriteAndSave(tuple.Item1, tuple.Item2);
}
if (dto.genFiles.Contains(3))
{
GenerateRepository(replaceDto, dto);
Tuple<string, string> tuple = GenerateRepository(replaceDto, dto);
genPathList.Add(tuple.Item1);
//WriteAndSave(tuple.Item1, tuple.Item2);
}
if (dto.genFiles.Contains(4))
{
GenerateIService(replaceDto, dto);
GenerateService(replaceDto, dto);
Tuple<string, string> tuple = GenerateIService(replaceDto, dto);
Tuple<string, string> tuple_1 = GenerateService(replaceDto, dto);
genPathList.Add(tuple.Item1);
genPathList.Add(tuple_1.Item1);
//WriteAndSave(tuple.Item1, tuple.Item2);
//WriteAndSave(tuple_1.Item1, tuple_1.Item2);
}
if (dto.genFiles.Contains(5))
{
GenerateControllers(replaceDto, dto);
Tuple<string, string> tuple = GenerateControllers(replaceDto, dto);
genPathList.Add(tuple.Item1);
//WriteAndSave(tuple.Item1, tuple.Item2);
}
if (dto.genFiles.Contains(6))
{
GenerateVueViews(replaceDto, dto);
Tuple<string, string> tuple = GenerateVueViews(replaceDto, dto);
genPathList.Add(tuple.Item1);
//WriteAndSave(tuple.Item1, tuple.Item2);
}
return genPathList;
//GenerateIRepository(modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered);
//GenerateOutputDto(modelTypeName, modelTypeDesc, outputDtocontent, ifExsitedCovered);
}
@@ -150,7 +199,7 @@ namespace ZR.CodeGenerator
/// <param name="replaceDto">替换实体</param>
private static Tuple<string, string> GenerateModels(ReplaceDto replaceDto, GenerateDto generateDto)
{
var parentPath = "..";
var parentPath = generateDto.ParentPath;
//../ZR.Model
var servicesPath = parentPath + "\\" + _option.ModelsNamespace + "\\Models\\";
if (!Directory.Exists(servicesPath))
@@ -159,7 +208,7 @@ namespace ZR.CodeGenerator
}
// ../ZR.Model/Models/User.cs
var fullPath = servicesPath + replaceDto.ModelTypeName + ".cs";
Console.WriteLine(fullPath);
if (File.Exists(fullPath) && !generateDto.coverd)
return Tuple.Create(fullPath, "");
var content = ReadTemplate("ModelTemplate.txt");
@@ -174,7 +223,6 @@ namespace ZR.CodeGenerator
return Tuple.Create(fullPath, content);
}
/// <summary>
/// 生成InputDto文件
/// </summary>
@@ -182,7 +230,7 @@ namespace ZR.CodeGenerator
/// <param name="replaceDto">替换实体</param>
private static Tuple<string, string> GenerateInputDto(ReplaceDto replaceDto, GenerateDto generateDto)
{
var parentPath = "..";
var parentPath = generateDto.ParentPath;
var servicesPath = parentPath + "\\" + _option.ModelsNamespace + "\\Dto\\";
if (!Directory.Exists(servicesPath))
{
@@ -190,7 +238,7 @@ namespace ZR.CodeGenerator
}
// ../ZR.Model/Dto/User.cs
var fullPath = servicesPath + replaceDto.ModelTypeName + "Dto.cs";
Console.WriteLine(fullPath);
if (File.Exists(fullPath) && !generateDto.coverd)
return Tuple.Create(fullPath, ""); ;
var content = ReadTemplate("InputDtoTemplate.txt");
@@ -215,14 +263,14 @@ namespace ZR.CodeGenerator
/// <param name="replaceDto">替换实体</param>
private static Tuple<string, string> GenerateRepository(ReplaceDto replaceDto, GenerateDto generateDto)
{
var parentPath = "..";
var parentPath = generateDto.ParentPath;
var repositoryPath = parentPath + "\\" + _option.RepositoriesNamespace + "\\Repositories\\";
if (!Directory.Exists(repositoryPath))
{
Directory.CreateDirectory(repositoryPath);
}
var fullPath = repositoryPath + "\\" + replaceDto.ModelTypeName + "Repository.cs";
Console.WriteLine(fullPath);
if (File.Exists(fullPath) && !generateDto.coverd)
return Tuple.Create(fullPath, "");
var content = ReadTemplate("RepositoryTemplate.txt");
@@ -247,7 +295,7 @@ namespace ZR.CodeGenerator
/// <param name="replaceDto">替换实体</param>
private static Tuple<string, string> GenerateIService(ReplaceDto replaceDto, GenerateDto generateDto)
{
var parentPath = "..";
var parentPath = generateDto.ParentPath;
var iServicesPath = parentPath + "\\" + _option.IServicsNamespace + "\\Business\\IBusService\\";
if (!Directory.Exists(iServicesPath))
{
@@ -274,7 +322,7 @@ namespace ZR.CodeGenerator
/// </summary>
private static Tuple<string, string> GenerateService(ReplaceDto replaceDto, GenerateDto generateDto)
{
var parentPath = "..";
var parentPath = generateDto.ParentPath;
var servicesPath = parentPath + "\\" + _option.ServicesNamespace + "\\Business\\";
if (!Directory.Exists(servicesPath))
{
@@ -306,14 +354,13 @@ namespace ZR.CodeGenerator
/// </summary>
private static Tuple<string, string> GenerateControllers(ReplaceDto replaceDto, GenerateDto generateDto)
{
var parentPath = "..";
var parentPath = generateDto.ParentPath;
var servicesPath = parentPath + "\\" + _option.ApiControllerNamespace + "\\Controllers\\business\\";
if (!Directory.Exists(servicesPath))
{
Directory.CreateDirectory(servicesPath);
}
var fullPath = servicesPath + replaceDto.ModelTypeName + "Controller.cs";
Console.WriteLine(fullPath);
if (File.Exists(fullPath) && !generateDto.coverd)
return Tuple.Create(fullPath, "");
var content = ReadTemplate("ControllersTemplate.txt");
@@ -327,7 +374,7 @@ namespace ZR.CodeGenerator
.Replace("{PrimaryKey}", replaceDto.PKName)
.Replace("{UpdateColumn}", replaceDto.UpdateColumn)
.Replace("{InsertColumn}", replaceDto.InsertColumn)
.Replace("{KeyTypeName}", replaceDto.PKType);
.Replace("{PKCsharpType}", replaceDto.PKType);
WriteAndSave(fullPath, content);
return Tuple.Create(fullPath, content);
}
@@ -339,14 +386,14 @@ namespace ZR.CodeGenerator
private static Tuple<string, string> GenerateVueViews(ReplaceDto replaceDto, GenerateDto generateDto)
{
//var parentPath = "..\\CodeGenerate";//若要生成到项目中将路径改成 “..\\ZR.Vue\\src”
var parentPath = "..\\ZR.Vue\\src";
var parentPath = $"{generateDto.ParentPath}\\ZR.Vue\\src";
var servicesPath = parentPath + "\\views\\" + FirstLowerCase(replaceDto.ModelTypeName);
if (!Directory.Exists(servicesPath))
{
Directory.CreateDirectory(servicesPath);
}
var fullPath = servicesPath + "\\" + "index.vue";
Console.WriteLine(fullPath);
if (File.Exists(fullPath) && !generateDto.coverd)
return Tuple.Create(fullPath, ""); ;
var content = ReadTemplate("VueTemplate.txt");
@@ -360,8 +407,8 @@ namespace ZR.CodeGenerator
.Replace("{vueJsMethod}", replaceDto.VueJsMethod)
.Replace("{vueQueryFormHtml}", replaceDto.VueQueryFormHtml)
.Replace("{VueDataContent}", replaceDto.VueDataContent)
//.Replace("{VueViewSaveBindContent}", vueViewSaveBindContent)
.Replace("{primaryKey}", FirstLowerCase(replaceDto.PKName))
.Replace("{MountedMethod}", replaceDto.MountedMethod)
.Replace("{VueViewEditFormRuleContent}", replaceDto.VueViewEditFormRuleContent);//添加、修改表单验证规则
WriteAndSave(fullPath, content);
@@ -369,14 +416,14 @@ namespace ZR.CodeGenerator
servicesPath = parentPath + "\\api\\";
Directory.CreateDirectory(servicesPath);
fullPath = servicesPath + "\\" + FirstLowerCase(replaceDto.ModelTypeName) + ".js";
Console.WriteLine(fullPath);
if (File.Exists(fullPath) && !generateDto.coverd)
return Tuple.Create(fullPath, "");
content = ReadTemplate("VueJsTemplate.txt");
content = content
.Replace("{ModelTypeName}", replaceDto.ModelTypeName)
.Replace("{ModelTypeDesc}", replaceDto.TableDesc);
//.Replace("{fileClassName}", fileClassName)
WriteAndSave(fullPath, content);
return Tuple.Create(fullPath, content);
}
@@ -437,8 +484,9 @@ namespace ZR.CodeGenerator
/// <returns></returns>
private static string ReadTemplate(string templateName)
{
var path = AppDomain.CurrentDomain.BaseDirectory;
string fullName = $"{path}\\Template\\{templateName}";
string path = Environment.CurrentDirectory;
//var path = AppDomain.CurrentDomain.BaseDirectory;
string fullName = $"{path}\\wwwroot\\CodeGenTemplate\\{templateName}";
string temp = fullName;
string str = "";
if (!File.Exists(temp))
@@ -485,5 +533,74 @@ namespace ZR.CodeGenerator
}
#endregion
/// <summary>
/// 初始化列属性字段数据
/// </summary>
/// <param name="genTable"></param>
/// <param name="dbColumnInfos"></param>
public static List<GenTableColumn> InitGenTableColumn(GenTable genTable, List<DbColumnInfo> dbColumnInfos)
{
List<GenTableColumn> genTableColumns = new();
foreach (var column in dbColumnInfos)
{
GenTableColumn genTableColumn = new()
{
ColumnName = FirstLowerCase(column.DbColumnName),
ColumnComment = column.ColumnDescription,
IsPk = column.IsPrimarykey,
ColumnType = column.DataType,
TableId = genTable.TableId,
TableName = genTable.TableName,
CsharpType = TableMappingHelper.GetCSharpDatatype(column.DataType),
CsharpField = column.DbColumnName.Substring(0, 1).ToUpper() + column.DbColumnName[1..],
IsRequired = !column.IsNullable,
IsIncrement = column.IsIdentity,
Create_by = genTable.Create_by,
Create_time = DateTime.Now,
IsInsert = !column.IsIdentity,//非自增字段都需要插入
IsQuery = false,
HtmlType = GenConstants.HTML_INPUT
};
if (GenConstants.imageFiled.Any(f => column.DbColumnName.ToLower().Contains(f.ToLower())))
{
genTableColumn.HtmlType = GenConstants.HTML_IMAGE_UPLOAD;
}
else if (GenConstants.COLUMNTYPE_TIME.Any(f => genTableColumn.CsharpType.ToLower().Contains(f.ToLower())))
{
genTableColumn.HtmlType = GenConstants.HTML_DATETIME;
}
else if (GenConstants.radioFiled.Any(f => column.DbColumnName.EndsWith(f, StringComparison.OrdinalIgnoreCase)) ||
GenConstants.radioFiled.Any(f => column.DbColumnName.StartsWith(f, StringComparison.OrdinalIgnoreCase)))
{
genTableColumn.HtmlType = GenConstants.HTML_RADIO;
}
else if (GenConstants.selectFiled.Any(f => column.DbColumnName == f) ||
GenConstants.selectFiled.Any(f => column.DbColumnName.EndsWith(f, StringComparison.OrdinalIgnoreCase)))
{
genTableColumn.HtmlType = GenConstants.HTML_SELECT;
}
else if (column.Length > 500)
{
genTableColumn.HtmlType = GenConstants.HTML_TEXTAREA;
}
//编辑字段
if (GenConstants.COLUMNNAME_NOT_EDIT.Any(f => column.DbColumnName.Contains(f)) && !column.IsIdentity && !column.IsPrimarykey)
{
genTableColumn.IsEdit = true;
}
//列表字段
if (GenConstants.COLUMNNAME_NOT_LIST.Any(f => column.DbColumnName.Contains(f) && !column.IsPrimarykey))
{
genTableColumn.IsList = true;
}
genTableColumns.Add(genTableColumn);
}
return genTableColumns;
}
}
}
+1 -1
View File
@@ -28,7 +28,7 @@ namespace ZR.CodeGenerator
if (string.IsNullOrEmpty(dbName))
{
connStr = ConfigUtils.Instance.GetConnectionStrings(OptionsSetting.ConnAdmin);
dbType = ConfigUtils.Instance.GetAppConfig<int>(OptionsSetting.DbType);
dbType = ConfigUtils.Instance.GetAppConfig<int>(OptionsSetting.ConnDbType);
}
var db = new SqlSugarScope(new List<ConnectionConfig>()
{
+182
View File
@@ -0,0 +1,182 @@
using ICSharpCode.SharpZipLib.Checksum;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZR.CodeGenerator
{
public class FileHelper
{
/// <summary>
/// 制作压缩包(多个文件压缩到一个压缩包,支持加密、注释)
/// </summary>
/// <param name="fileNames">要压缩的文件</param>
/// <param name="topDirectoryName">压缩文件目录</param>
/// <param name="zipedFileName">压缩包文件名</param>
/// <param name="compresssionLevel">压缩级别 1-9</param>
/// <param name="password">密码</param>
/// <param name="comment">注释</param>
public static void ZipFiles(string[] fileNames, string topDirectoryName, string zipedFileName, int? compresssionLevel, string password = "", string comment = "")
{
using (ZipOutputStream zos = new ZipOutputStream(File.Open(zipedFileName, FileMode.OpenOrCreate)))
{
if (compresssionLevel.HasValue)
{
zos.SetLevel(compresssionLevel.Value);//设置压缩级别
}
if (!string.IsNullOrEmpty(password))
{
zos.Password = password;//设置zip包加密密码
}
if (!string.IsNullOrEmpty(comment))
{
zos.SetComment(comment);//设置zip包的注释
}
foreach (string file in fileNames)
{
//string fileName = string.Format("{0}/{1}", topDirectoryName, file);
string fileName = file;
if (File.Exists(fileName))
{
FileInfo item = new FileInfo(fileName);
FileStream fs = File.OpenRead(item.FullName);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
ZipEntry entry = new ZipEntry(item.Name);
zos.PutNextEntry(entry);
zos.Write(buffer, 0, buffer.Length);
}
}
}
}
/// <summary>
/// 压缩多层目录
/// </summary>
/// <param name="topDirectoryName">压缩文件目录</param>
/// <param name="zipedFileName">压缩包文件名</param>
/// <param name="compresssionLevel">压缩级别 1-9 </param>
/// <param name="password">密码</param>
/// <param name="comment">注释</param>
/// <param name="filetype">文件类型</param>
public static void ZipFileDirectory(string topDirectoryName, string zipedFileName, int compresssionLevel, string password, string comment, string filetype)
{
using (System.IO.FileStream ZipFile = File.Open(zipedFileName, FileMode.OpenOrCreate))
{
using (ZipOutputStream zos = new ZipOutputStream(ZipFile))
{
if (compresssionLevel != 0)
{
zos.SetLevel(compresssionLevel);//设置压缩级别
}
if (!string.IsNullOrEmpty(password))
{
zos.Password = password;//设置zip包加密密码
}
if (!string.IsNullOrEmpty(comment))
{
zos.SetComment(comment);//设置zip包的注释
}
ZipSetp(topDirectoryName, zos, "", filetype);
}
}
}
/// <summary>
/// 递归遍历目录
/// </summary>
/// <param name="strDirectory">The directory.</param>
/// <param name="s">The ZipOutputStream Object.</param>
/// <param name="parentPath">The parent path.</param>
private static void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath, string filetype)
{
if (strDirectory[^1] != Path.DirectorySeparatorChar)
{
strDirectory += Path.DirectorySeparatorChar;
}
Crc32 crc = new Crc32();
string[] filenames = Directory.GetFileSystemEntries(strDirectory, filetype);
foreach (string file in filenames)// 遍历所有的文件和目录
{
if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
{
string pPath = parentPath;
pPath += file.Substring(file.LastIndexOf("\\") + 1);
pPath += "\\";
ZipSetp(file, s, pPath, filetype);
}
else // 否则直接压缩文件
{
//打开压缩文件
using (FileStream fs = File.OpenRead(file))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string fileName = parentPath + file[(file.LastIndexOf("\\") + 1)..];
ZipEntry entry = new ZipEntry(fileName);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
}
}
}
}
/// <summary>
/// 删除指定目录下的所有文件及文件夹(保留目录)
/// </summary>
/// <param name="file">文件目录</param>
public static void DeleteDirectory(string file)
{
try
{
//判断文件夹是否还存在
if (Directory.Exists(file))
{
DirectoryInfo fileInfo = new DirectoryInfo(file);
//去除文件夹的只读属性
fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
foreach (string f in Directory.GetFileSystemEntries(file))
{
if (File.Exists(f))
{
//去除文件的只读属性
File.SetAttributes(file, FileAttributes.Normal);
//如果有子文件删除文件
File.Delete(f);
}
else
{
//循环递归删除子文件夹
DeleteDirectory(f);
}
}
//删除空文件夹
Directory.Delete(file);
}
}
catch (Exception ex) // 异常处理
{
//Log4NetHelper.Error("代码生成异常", ex);
}
}
}
}
+25 -14
View File
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZR.CodeGenerator
{
@@ -17,6 +13,24 @@ namespace ZR.CodeGenerator
public static string Gen_autoPre = "gen:autoPre";
public static string Gen_tablePrefix = "gen:tablePrefix";
/// <summary>
/// InputDto输入实体是不包含字段
/// </summary>
public static readonly string[] inputDtoNoField = new string[] { "createTime", "updateTime", "addtime" };
/// <summary>
/// 图片字段
/// </summary>
public static readonly string[] imageFiled = new string[] { "icon", "img", "image", "url", "pic", "photo", "avatar" };
/// <summary>
/// 下拉框字段
/// </summary>
public static readonly string[] selectFiled = new string[] { "status", "type", "state", "sex", "gender" };
/// <summary>
/// 单选按钮字段
/// </summary>
public static readonly string[] radioFiled = new string[] { "status", "state", "is"};
/** 单表(增删改查) */
public static string TPL_CRUD = "crud";
@@ -55,14 +69,14 @@ namespace ZR.CodeGenerator
"bit", "bigint", "float", "double", "decimal" };
/** 页面不需要编辑字段 */
public static string[] COLUMNNAME_NOT_EDIT = { "id", "create_by", "create_time", "del_flag" };
public static string[] COLUMNNAME_NOT_EDIT = { "id", "create_by", "create_time", "delFlag" };
/** 页面不需要显示的列表字段 */
public static string[] COLUMNNAME_NOT_LIST = { "id", "create_by", "create_time", "del_flag", "update_by",
"update_time" };
public static string[] COLUMNNAME_NOT_LIST = { "id", "create_by", "create_time", "delFlag", "update_by",
"update_time" , "password"};
/** 页面不需要查询字段 */
public static string[] COLUMNNAME_NOT_QUERY = { "id", "create_by", "create_time", "del_flag", "update_by",
public static string[] COLUMNNAME_NOT_QUERY = { "id", "create_by", "create_time", "delFlag", "update_by",
"update_time", "remark" };
/** Entity基类字段 */
@@ -102,17 +116,14 @@ namespace ZR.CodeGenerator
public static string TYPE_STRING = "string";
/** 整型 */
public static string TYPE_INTEGER = "Integer";
public static string TYPE_INT = "int";
/** 长整型 */
public static string TYPE_LONG = "Long";
public static string TYPE_LONG = "long";
/** 浮点型 */
public static string TYPE_DOUBLE = "Double";
/** 高精度计算类型 */
public static string TYPE_BIGDECIMAL = "BigDecimal";
/** 时间类型 */
public static string TYPE_DATE = "Date";
+12 -1
View File
@@ -25,7 +25,7 @@ namespace ZR.CodeGenerator.Model
/// <summary>
/// 要删除表名的字符串用
/// </summary>
public string replaceTableNameStr { get; set; }
//public string replaceTableNameStr { get; set; }
/// <summary>
/// 要生成的文件
/// </summary>
@@ -34,5 +34,16 @@ namespace ZR.CodeGenerator.Model
/// 如果目标文件存在,是否覆盖。默认为false
/// </summary>
public bool coverd { get; set; } = true;
#region 存储路径
//public string ModelPath { get; set; }
//public string ServicePath { get; set; }
//public string RepositoryPath { get; set; }
//public string ApiPath { get; set; }
//public string VuePath { get; set; }
//public string VueApiPath { get; set; }
public string ParentPath { get; set; } = "..";
#endregion
}
}
+4
View File
@@ -92,5 +92,9 @@ namespace ZR.CodeGenerator.Model
/// vue data内容
/// </summary>
public string VueDataContent { get; set; }
/// <summary>
/// vue mounted 方法
/// </summary>
public string MountedMethod { get; set; }
}
}
+18 -60
View File
@@ -45,75 +45,33 @@ namespace ZR.CodeGenerator.CodeGenerator
return sb.ToString();
}
public static string GetPropertyDatatype(string sDatatype)
/// <summary>
/// 获取C# 类型
/// </summary>
/// <param name="sDatatype"></param>
/// <returns></returns>
public static string GetCSharpDatatype(string sDatatype)
{
string sTempDatatype = string.Empty;
sDatatype = sDatatype.ToLower();
switch (sDatatype)
string sTempDatatype = sDatatype switch
{
case "int":
case "number":
case "integer":
case "smallint":
sTempDatatype = "int";
break;
case "bigint":
sTempDatatype = "long";
break;
case "tinyint":
sTempDatatype = "byte";
break;
case "numeric":
case "real":
sTempDatatype = "Single";
break;
case "float":
sTempDatatype = "float";
break;
case "decimal":
case "numer(8,2)":
sTempDatatype = "decimal";
break;
case "bit":
sTempDatatype = "bool";
break;
case "date":
case "datetime":
case "datetime2":
case "smalldatetime":
sTempDatatype = "DateTime";
break;
case "money":
case "smallmoney":
sTempDatatype = "double";
break;
case "char":
case "varchar":
case "nvarchar2":
case "text":
case "nchar":
case "nvarchar":
case "ntext":
default:
sTempDatatype = "string";
break;
}
"int" or "number" or "integer" or "smallint" => "int",
"bigint" => "long",
"tinyint" => "byte",
"numeric" or "real" or "float" => "float",
"decimal" or "numer(8,2)" => "decimal",
"bit" => "bool",
"date" or "datetime" or "datetime2" or "smalldatetime" => "DateTime",
"money" or "smallmoney" => "double",
_ => "string",
};
return sTempDatatype;
}
public static bool IsNumber(string tableDataType)
{
string[] arr = new string[] { "int", "long" };
return arr.Any(f => f.Contains(GetPropertyDatatype(tableDataType)));
return arr.Any(f => f.Contains(GetCSharpDatatype(tableDataType)));
}
}
}