diff --git a/.vs/IoTGateway/DesignTimeBuild/.dtbcache.v2 b/.vs/IoTGateway/DesignTimeBuild/.dtbcache.v2 index ef23d53..9c0d627 100644 Binary files a/.vs/IoTGateway/DesignTimeBuild/.dtbcache.v2 and b/.vs/IoTGateway/DesignTimeBuild/.dtbcache.v2 differ diff --git a/.vs/IoTGateway/project-colors.json b/.vs/IoTGateway/project-colors.json index a1e0660..a8450a7 100644 --- a/.vs/IoTGateway/project-colors.json +++ b/.vs/IoTGateway/project-colors.json @@ -45,7 +45,27 @@ "ProjectGuid": "e5f79995-ab61-41f4-820d-ba39967b406b", "DisplayName": "PluginInterface", "ColorIndex": 7 + }, + "c2672620-8e65-486c-b967-c4c673f8da0f": { + "ProjectGuid": "c2672620-8e65-486c-b967-c4c673f8da0f", + "DisplayName": "WalkingTec.Mvvm.Core", + "ColorIndex": 8 + }, + "b370f699-965b-4d86-93b1-0f022c95b5c9": { + "ProjectGuid": "b370f699-965b-4d86-93b1-0f022c95b5c9", + "DisplayName": "WalkingTec.Mvvm.Mvc", + "ColorIndex": 9 + }, + "81cbfd0e-1d89-440a-8cc3-e32672504ff4": { + "ProjectGuid": "81cbfd0e-1d89-440a-8cc3-e32672504ff4", + "DisplayName": "WalkingTec.Mvvm.TagHelpers.LayUI", + "ColorIndex": 10 + }, + "402e5b3a-ad95-4b6a-a4b0-c8ffcbf494c3": { + "ProjectGuid": "402e5b3a-ad95-4b6a-a4b0-c8ffcbf494c3", + "DisplayName": "test", + "ColorIndex": 11 } }, - "NextColorIndex": 8 + "NextColorIndex": 12 } \ No newline at end of file diff --git a/.vs/IoTGateway/v17/.futdcache.v1 b/.vs/IoTGateway/v17/.futdcache.v1 index 1b42db8..51ef064 100644 Binary files a/.vs/IoTGateway/v17/.futdcache.v1 and b/.vs/IoTGateway/v17/.futdcache.v1 differ diff --git a/.vs/IoTGateway/v17/.suo b/.vs/IoTGateway/v17/.suo index 12fa31f..28a75b3 100644 Binary files a/.vs/IoTGateway/v17/.suo and b/.vs/IoTGateway/v17/.suo differ diff --git a/.vs/IoTGateway/v17/fileList.bin b/.vs/IoTGateway/v17/fileList.bin index ec5d33e..621eee2 100644 Binary files a/.vs/IoTGateway/v17/fileList.bin and b/.vs/IoTGateway/v17/fileList.bin differ diff --git a/IoTGateway.Model/IoTGateway.Model.csproj b/IoTGateway.Model/IoTGateway.Model.csproj index 1221e71..0623834 100644 --- a/IoTGateway.Model/IoTGateway.Model.csproj +++ b/IoTGateway.Model/IoTGateway.Model.csproj @@ -6,13 +6,9 @@ - - - - - + diff --git a/IoTGateway.sln b/IoTGateway.sln index fdd9b7c..9f03442 100644 --- a/IoTGateway.sln +++ b/IoTGateway.sln @@ -21,6 +21,14 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Drivers", "Drivers", "{52D9 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DriverModbusTCP", "Plugins\Drivers\DriverModbusTCP\DriverModbusTCP.csproj", "{7B432FC9-57E6-44BF-B8A7-2A1FB31D6ADD}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "WalkingTec.Mvvm", "WalkingTec.Mvvm", "{98B1C9F0-028C-48D8-8148-54B69CCA4590}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WalkingTec.Mvvm.Core", "WalkingTec.Mvvm\WalkingTec.Mvvm.Core\WalkingTec.Mvvm.Core.csproj", "{C2672620-8E65-486C-B967-C4C673F8DA0F}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WalkingTec.Mvvm.Mvc", "WalkingTec.Mvvm\WalkingTec.Mvvm.Mvc\WalkingTec.Mvvm.Mvc.csproj", "{B370F699-965B-4D86-93B1-0F022C95B5C9}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WalkingTec.Mvvm.TagHelpers.LayUI", "WalkingTec.Mvvm\WalkingTec.Mvvm.TagHelpers.LayUI\WalkingTec.Mvvm.TagHelpers.LayUI.csproj", "{81CBFD0E-1D89-440A-8CC3-E32672504FF4}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -55,6 +63,18 @@ Global {7B432FC9-57E6-44BF-B8A7-2A1FB31D6ADD}.Debug|Any CPU.Build.0 = Debug|Any CPU {7B432FC9-57E6-44BF-B8A7-2A1FB31D6ADD}.Release|Any CPU.ActiveCfg = Release|Any CPU {7B432FC9-57E6-44BF-B8A7-2A1FB31D6ADD}.Release|Any CPU.Build.0 = Release|Any CPU + {C2672620-8E65-486C-B967-C4C673F8DA0F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C2672620-8E65-486C-B967-C4C673F8DA0F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C2672620-8E65-486C-B967-C4C673F8DA0F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C2672620-8E65-486C-B967-C4C673F8DA0F}.Release|Any CPU.Build.0 = Release|Any CPU + {B370F699-965B-4D86-93B1-0F022C95B5C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B370F699-965B-4D86-93B1-0F022C95B5C9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B370F699-965B-4D86-93B1-0F022C95B5C9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B370F699-965B-4D86-93B1-0F022C95B5C9}.Release|Any CPU.Build.0 = Release|Any CPU + {81CBFD0E-1D89-440A-8CC3-E32672504FF4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {81CBFD0E-1D89-440A-8CC3-E32672504FF4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {81CBFD0E-1D89-440A-8CC3-E32672504FF4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {81CBFD0E-1D89-440A-8CC3-E32672504FF4}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -64,6 +84,9 @@ Global {E5F79995-AB61-41F4-820D-BA39967B406B} = {FBED048F-7AB9-4348-AD56-F9BF4D9E3A55} {52D96C24-2F2F-49B5-9F29-00414DEA41D8} = {FBED048F-7AB9-4348-AD56-F9BF4D9E3A55} {7B432FC9-57E6-44BF-B8A7-2A1FB31D6ADD} = {52D96C24-2F2F-49B5-9F29-00414DEA41D8} + {C2672620-8E65-486C-B967-C4C673F8DA0F} = {98B1C9F0-028C-48D8-8148-54B69CCA4590} + {B370F699-965B-4D86-93B1-0F022C95B5C9} = {98B1C9F0-028C-48D8-8148-54B69CCA4590} + {81CBFD0E-1D89-440A-8CC3-E32672504FF4} = {98B1C9F0-028C-48D8-8148-54B69CCA4590} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {1F219808-E6E8-4C1D-B846-41F2F7CF20FA} diff --git a/IoTGateway/IoTGateway.csproj b/IoTGateway/IoTGateway.csproj index 4a8eca7..740db28 100644 --- a/IoTGateway/IoTGateway.csproj +++ b/IoTGateway/IoTGateway.csproj @@ -16,8 +16,6 @@ - - @@ -25,6 +23,8 @@ + + diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/ActionDescriptionAttribute.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/ActionDescriptionAttribute.cs new file mode 100644 index 0000000..ee3a209 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/ActionDescriptionAttribute.cs @@ -0,0 +1,46 @@ +using System; +using System.Linq; +using Microsoft.Extensions.Localization; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// 标记Controller和Action的描述 + /// + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] + public class ActionDescriptionAttribute : Attribute + { + /// + /// 描述 + /// + public string Description { get; set; } + public string ClassFullName { get; set; } + public bool IsPage { get; set; } + public IStringLocalizer _localizer { get; set; } + /// + /// 新建一个描述 + /// + public ActionDescriptionAttribute(string desc) + { + this.Description = desc; + } + + public ActionDescriptionAttribute(string desc, string classFullName) + { + this.Description = desc; + this.ClassFullName = classFullName; + } + + public ActionDescriptionAttribute(string desc, string classFullName, bool ispage) + { + this.Description = desc; + this.ClassFullName = classFullName; + this.IsPage = ispage; + } + + public void SetLoccalizer(Type controllertype) + { + _localizer = Core.CoreProgram._localizer; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/AllRightsAttribute.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/AllRightsAttribute.cs new file mode 100644 index 0000000..52d5a9a --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/AllRightsAttribute.cs @@ -0,0 +1,12 @@ +using System; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// 标记Controller或Action不受权限控制,只要登录任何人都可访问 + /// + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] + public class AllRightsAttribute : Attribute + { + } +} \ No newline at end of file diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/DebugOnlyAttribute.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/DebugOnlyAttribute.cs new file mode 100644 index 0000000..21083f8 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/DebugOnlyAttribute.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WalkingTec.Mvvm.Core +{ + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] + public class DebugOnlyAttribute : Attribute + { + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/FixConnectionAttribute.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/FixConnectionAttribute.cs new file mode 100644 index 0000000..25c13c5 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/FixConnectionAttribute.cs @@ -0,0 +1,50 @@ +using System; + +namespace WalkingTec.Mvvm.Core +{ + public enum DBOperationEnum { Default, Read, Write } + /// + /// 标记Controller或Action使用固定的连接字符串,不受其他设定控制 + /// + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] + public class FixConnectionAttribute : Attribute + { + /// + /// 连接字符串名称 + /// + public string CsName { get; set; } + + public DBTypeEnum? DbType { get; set; } + + /// + /// 操作类型,读或写 + /// + public DBOperationEnum Operation { get; set; } + + /// + /// 新建固定连接字符串标记 + /// + /// Operation + /// the key of the ConnectionString in appsettings + public FixConnectionAttribute(DBOperationEnum Operation = DBOperationEnum.Default, string CsName = "") + { + this.CsName = CsName; + this.Operation = Operation; + this.DbType = null; + } + + /// + /// 操作类型,读或写 + /// + /// the database type, if t is Default, the value in appsettings will be used + /// Operation + /// the key of the ConnectionString in appsettings + public FixConnectionAttribute(DBTypeEnum DbType, DBOperationEnum Operation = DBOperationEnum.Default, string CsName = "") + { + this.CsName = CsName; + this.Operation = Operation; + this.DbType = DbType; + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/MiddleTableAttribute.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/MiddleTableAttribute.cs new file mode 100644 index 0000000..71ec40b --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/MiddleTableAttribute.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WalkingTec.Mvvm.Core.Attributes +{ + + /// + /// 标记某个Model是一个多对多的中间表 + /// + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] + public class MiddleTableAttribute : Attribute + { + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/NoLogAttribute.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/NoLogAttribute.cs new file mode 100644 index 0000000..8e9aa17 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/NoLogAttribute.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WalkingTec.Mvvm.Core +{ + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] + public class NoLogAttribute : Attribute + { + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/PublicAttribute.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/PublicAttribute.cs new file mode 100644 index 0000000..fecda75 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/PublicAttribute.cs @@ -0,0 +1,14 @@ +using System; +using Microsoft.AspNetCore.Authorization; + +namespace WalkingTec.Mvvm.Core +{ + //[Obsolete("已废弃,预计v3.0版本及v2.10版本开始将删除")] + /// + /// 标记Action返回的为公共页面,跳过权限验证,不需要登录即可访问 + /// + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] + public class PublicAttribute : Attribute, IAllowAnonymous + { + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/ReInitAttribute.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/ReInitAttribute.cs new file mode 100644 index 0000000..16f1a1c --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/ReInitAttribute.cs @@ -0,0 +1,27 @@ +using System; + +namespace WalkingTec.Mvvm.Core +{ + public enum ReInitModes { FAILEDONLY, SUCCESSONLY, ALWAYS } + + /// + /// 标记VM中的ReInit方法是在提交错误时触发,提交成功时触发,或是都触发。这是为了一些特殊逻辑的VM设计的 + /// + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] + public class ReInitAttribute : Attribute + { + /// + /// 触发模式 + /// + public ReInitModes ReInitMode { get; set; } + + /// + /// 新建触发标记 + /// + /// 触发模式 + public ReInitAttribute(ReInitModes mode) + { + this.ReInitMode = mode; + } + } +} \ No newline at end of file diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/ValidateFormItemOnlyAttribute.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/ValidateFormItemOnlyAttribute.cs new file mode 100644 index 0000000..ef48eec --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Attributes/ValidateFormItemOnlyAttribute.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WalkingTec.Mvvm.Core +{ + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] + public class ValidateFormItemOnlyAttribute : Attribute + { + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseBatchVM.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseBatchVM.cs new file mode 100644 index 0000000..66c2fc5 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseBatchVM.cs @@ -0,0 +1,419 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Primitives; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Reflection; +using System.Text.Json.Serialization; +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Core.Support.FileHandlers; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// 批量操作VM接口 + /// + /// 批量修改的VM + public interface IBaseBatchVM + where TEditModel : BaseVM + { + /// + /// 批量修改的VM + /// + TEditModel LinkedVM { get; } + + /// + /// 批量列表VM + /// + IBasePagedListVM ListVM { get; } + + /// + /// 列表数据的Id数组 + /// + //IEnumerable Ids { get; set; } + string[] Ids { get; set; } + + /// + /// 批量操作的错误 + /// + Dictionary ErrorMessage { get; set; } + } + + /// + /// 批量操作的基础VM,所有批量操作的VM应继承本类 + /// + /// 批量修改的VM + /// 批量列表VM + public class BaseBatchVM : BaseVM, IBaseBatchVM where TModel : TopBasePoco,new() where TLinkModel : BaseVM + { + /// + /// 批量修改的VM + /// + + public TLinkModel LinkedVM { get; set; } + + /// + /// 批量列表VM + /// + [JsonIgnore] + public IBasePagedListVM ListVM { get; set; } + + /// + /// 批量操作的错误 + /// + [JsonIgnore] + public Dictionary ErrorMessage { get; set; } + + /// + /// 列表数据的Id数组 + /// + public string[] Ids { get; set; } + + /// + /// 构造函数 + /// + public BaseBatchVM() + { + //this.Ids = new List(); + ErrorMessage = new Dictionary(); + } + + /// + /// 添加错误信息 + /// + /// 错误 + /// 数据Id + protected void SetExceptionMessage(Exception e, string id) + { + if (id != null) + { + ErrorMessage.Add(id, e.Message); + } + } + + /// + /// 检查是否可以删除,当进行批量删除操作时会调用本函数。子类如果有特殊判断应重载本函数 + /// + /// 数据Id + /// 错误信息 + /// true代表可以删除,false代表不能删除 + protected virtual bool CheckIfCanDelete(object id, out string errorMessage) + { + errorMessage = null; + return true; + } + + /// + /// 批量删除,默认对Ids中包含的主键的数据进行删除。子类如果有特殊判断应重载本函数 + /// + /// true代表成功,false代表失败 + public virtual bool DoBatchDelete() + { + bool rv = true; + //循环所有数据Id + List idsData = Ids.ToList(); + var modelType = typeof(TModel); + var pros = modelType.GetAllProperties(); + //如果包含附件,则先删除附件 + List fileids = new List(); + var fa = pros.Where(x => x.PropertyType == typeof(FileAttachment) || typeof(TopBasePoco).IsAssignableFrom(x.PropertyType)).ToList(); + var isPersist =typeof(IPersistPoco).IsAssignableFrom(modelType); + var isBasePoco = typeof(IBasePoco).IsAssignableFrom(modelType); + var query = DC.Set().AsQueryable(); + var fas = pros.Where(x => typeof(IEnumerable).IsAssignableFrom(x.PropertyType)).ToList(); + foreach (var f in fas) + { + query = query.Include(f.Name); + } + query = query.AsNoTracking().CheckIDs(idsData); + var entityList = query.ToList(); + for (int i = 0; i < entityList.Count; i++) + { + string checkErro = null; + //检查是否可以删除,如不能删除则直接跳过 + if (CheckIfCanDelete(idsData[i], out checkErro) == false) + { + ErrorMessage.Add(idsData[i], checkErro); + rv = false; + break; + } + //进行删除 + try + { + var Entity = entityList[i]; + if (isPersist) + { + (Entity as IPersistPoco).IsValid = false; + DC.UpdateProperty(Entity, "IsValid"); + if (isBasePoco) + { + (Entity as IBasePoco).UpdateTime = DateTime.Now; + (Entity as IBasePoco).UpdateBy = LoginUserInfo.ITCode; + DC.UpdateProperty(Entity, "UpdateTime"); + DC.UpdateProperty(Entity, "UpdateBy"); + } + } + else + { + + foreach (var f in fa) + { + if (f.PropertyType == typeof(FileAttachment)) + { + string fidfield = DC.GetFKName2(modelType, f.Name); + var fidpro = pros.Where(x => x.Name == fidfield).FirstOrDefault(); + var idresult = fidpro.GetValue(Entity); + if(idresult != null) + { + Guid fid = Guid.Empty; + if(Guid.TryParse(idresult.ToString(), out fid) == true) + { + fileids.Add(fid); + } + } + } + f.SetValue(Entity, null); + } + + foreach (var f in fas) + { + var subs = f.GetValue(Entity) as IEnumerable; + if (subs != null) + { + foreach (var sub in subs) + { + fileids.Add(sub.FileId); + } + f.SetValue(Entity, null); + } + else + { + + } + } + if (typeof(TModel) != typeof(FileAttachment)) + { + foreach (var pro in pros) + { + if (pro.PropertyType.GetTypeInfo().IsSubclassOf(typeof(TopBasePoco))) + { + pro.SetValue(Entity, null); + } + } + } + DC.DeleteEntity(Entity); + } + } + catch (Exception e) + { + SetExceptionMessage(e, idsData[i]); + rv = false; + } + } + //进行数据库的删除操作 + if (rv == true) + { + try + { + DC.SaveChanges(); + var fp = Wtm.ServiceProvider.GetRequiredService(); + foreach (var item in fileids) + { + fp.DeleteFile(item.ToString(), DC.ReCreate()); + } + } + catch (Exception e) + { + SetExceptionMessage(e, null); + rv = false; + } + } + //如果失败,添加错误信息 + if (rv == false) + { + if (ErrorMessage.Count > 0) + { + foreach (var id in idsData) + { + if (!ErrorMessage.ContainsKey(id)) + { + ErrorMessage.Add(id, CoreProgram._localizer?["Sys.Rollback"]); + } + } + } + ListVM?.DoSearch(); + if (ListVM != null) + { + foreach (var item in ListVM?.GetEntityList()) + { + item.BatchError = ErrorMessage.Where(x => x.Key == item.GetID().ToString()).Select(x => x.Value).FirstOrDefault(); + } + } + MSD.AddModelError("", CoreProgram._localizer?["Sys.DataCannotDelete"]); + } + return rv; + } + + + /// + /// 批量修改,默认对Ids中包含的数据进行修改,子类如果有特殊判断应重载本函数 + /// + /// true代表成功,false代表失败 + public virtual bool DoBatchEdit() + { + //获取批量修改VM的所有属性 + var pros = LinkedVM.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly); + bool rv = true; + List idsData = Ids.ToList(); + string currentvmname = this.GetType().Name; + Type vmtype = null; + //找到对应的BaseCRUDVM,并初始化 + if (currentvmname.ToLower().Contains("apibatchvm")) + { + vmtype = this.GetType().Assembly.GetExportedTypes().Where(x => x.IsSubclassOf(typeof(BaseCRUDVM)) && x.Name.ToLower().Contains("apivm") == true).FirstOrDefault(); + } + else + { + vmtype = this.GetType().Assembly.GetExportedTypes().Where(x => x.IsSubclassOf(typeof(BaseCRUDVM)) && x.Name.ToLower().Contains("apivm") == false).FirstOrDefault(); + } + IBaseCRUDVM vm = null; + if (vmtype != null) + { + vm = vmtype.GetConstructor(System.Type.EmptyTypes).Invoke(null) as IBaseCRUDVM; + vm.CopyContext(this); + } + var entityList = DC.Set().CheckIDs(idsData).ToList(); + //循环所有数据 + for (int i = 0; i < entityList.Count; i++) + { + try + { + //如果找不到对应数据,则输出错误 + TModel entity = entityList[i]; + if (vm != null) + { + vm.SetEntity(entity); + } + if (entity == null) + { + ErrorMessage.Add(idsData[i], CoreProgram._localizer?["Sys.DataNotExist"]); + rv = false; + break; + } + //如果能找到,则循环LinkedVM中的属性,给entity中同名属性赋值 + foreach (var pro in pros) + { + var proToSet = entity.GetType().GetSingleProperty(pro.Name); + var val = FC.ContainsKey("LinkedVM." + pro.Name) ? FC["LinkedVM." + pro.Name] : null; + if(val == null && FC.ContainsKey("LinkedVM." + pro.Name + "[]")) + { + val = FC["LinkedVM." + pro.Name + "[]"]; + } + if (proToSet != null && val != null) + { + var hasvalue = true; + if ( val is StringValues sv && StringValues.IsNullOrEmpty(sv) == true) + { + hasvalue = false; + } + if (hasvalue) + { + proToSet.SetValue(entity, pro.GetValue(LinkedVM)); + } + } + } + + //调用controller方法验证model + //try + //{ + // Controller.GetType().GetMethod("RedoValidation").Invoke(Controller, new object[] { entity }); + //} + //catch { } + //如果有对应的BaseCRUDVM则使用其进行数据验证 + if (vm != null) + { + vm.Validate(); + var errors = vm.MSD; + if (errors != null && errors.Count > 0) + { + var error = ""; + foreach (var key in errors.Keys) + { + if (errors[key].Count > 0) + { + error += errors[key].Select(x => x.ErrorMessage).ToSepratedString(); + } + } + if (error != "") + { + ErrorMessage.Add(idsData[i], error); + rv = false; + break; + } + } + } + if (typeof(IBasePoco).IsAssignableFrom( typeof(TModel))) + { + IBasePoco ent = entity as IBasePoco; + if (ent.UpdateTime == null) + { + ent.UpdateTime = DateTime.Now; + } + if (string.IsNullOrEmpty(ent.UpdateBy)) + { + ent.UpdateBy = LoginUserInfo?.ITCode; + } + } + DC.UpdateEntity(entity); + } + catch (Exception e) + { + SetExceptionMessage(e, idsData[i]); + rv = false; + } + } + //进行数据库的修改操作 + if (rv == true) + { + try + { + DC.SaveChanges(); + } + catch (Exception e) + { + SetExceptionMessage(e, null); + rv = false; + } + } + + //如果有错误,输出错误信息 + if (rv == false) + { + if (ErrorMessage.Count > 0) + { + foreach (var id in idsData) + { + if (!ErrorMessage.ContainsKey(id)) + { + ErrorMessage.Add(id, CoreProgram._localizer?["Sys.Rollback"]); + } + } + } + RefreshErrorList(); + } + return rv; + } + + protected void RefreshErrorList() + { + ListVM.DoSearch(); + foreach (var item in ListVM.GetEntityList()) + { + item.BatchError = ErrorMessage.Where(x => x.Key == item.GetID().ToString()).Select(x => x.Value).FirstOrDefault(); + } + + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseCRUDVM.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseCRUDVM.cs new file mode 100644 index 0000000..d74eb23 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseCRUDVM.cs @@ -0,0 +1,1054 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Core.Support.FileHandlers; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// 单表增删改查VM的接口 + /// + /// 继承TopBasePoco的类 + public interface IBaseCRUDVM where T : TopBasePoco, new() + { + T Entity { get; } + /// + /// 根据主键Id获取Entity + /// + /// 主键Id + void SetEntityById(object id); + + /// + /// 设置Entity + /// + /// 要设定的TopBasePoco + void SetEntity(object entity); + + /// + /// 添加 + /// + void DoAdd(); + + Task DoAddAsync(); + + /// + /// 修改 + /// + void DoEdit(bool updateAllFields); + Task DoEditAsync(bool updateAllFields); + + /// + /// 删除,对于TopBasePoco进行物理删除,对于PersistPoco把IsValid修改为false + /// + void DoDelete(); + Task DoDeleteAsync(); + + /// + /// 彻底删除,对PersistPoco进行物理删除 + /// + void DoRealDelete(); + Task DoRealDeleteAsync(); + + /// + /// 将源VM的上数据库上下文,Session,登录用户信息,模型状态信息,缓存信息等内容复制到本VM中 + /// + /// 复制的源 + void CopyContext(BaseVM vm); + + /// + /// 是否跳过基类的唯一性验证,批量导入的时候唯一性验证会由存储过程完成,不需要单独调用本类的验证方法 + /// + bool ByPassBaseValidation { get; set; } + + void Validate(); + IModelStateService MSD { get; } + } + + /// + /// 单表增删改查基类,所有单表操作的VM应该继承这个基类 + /// + /// 继承TopBasePoco的类 + public class BaseCRUDVM : BaseVM, IBaseCRUDVM where TModel : TopBasePoco, new() + { + public TModel Entity { get; set; } + [JsonIgnore] + public bool ByPassBaseValidation { get; set; } + + //保存读取时Include的内容 + private List>> _toInclude { get; set; } + + /// + /// 构造函数 + /// + public BaseCRUDVM() + { + //初始化Entity + var ctor = typeof(TModel).GetConstructor(Type.EmptyTypes); + Entity = ctor.Invoke(null) as TModel; + //初始化VM中所有List<>的类 + //var lists = typeof(TModel).GetAllProperties().Where(x => x.PropertyType.IsGeneric(typeof(List<>))); + //foreach (var li in lists) + //{ + // var gs = li.PropertyType.GetGenericArguments(); + // var newObj = Activator.CreateInstance(typeof(List<>).MakeGenericType(gs[0])); + // li.SetValue(Entity, newObj, null); + //} + } + + public IQueryable GetBaseQuery() + { + return DC.Set(); + } + /// + /// 设定添加和修改时对于重复数据的判断,子类进行相关操作时应重载这个函数 + /// + /// 唯一性属性 + public virtual DuplicatedInfo SetDuplicatedCheck() + { + return null; + } + + /// + /// 设定读取是Include的内容 + /// + /// 需要关联的类 + public void SetInclude(params Expression>[] exps) + { + _toInclude = _toInclude ?? new List>>(); + _toInclude.AddRange(exps); + } + + /// + /// 根据主键Id设定Entity + /// + /// 主键Id + public void SetEntityById(object id) + { + this.Entity = GetById(id); + } + + /// + /// 设置Entity + /// + /// 要设定的TopBasePoco + public void SetEntity(object entity) + { + this.Entity = entity as TModel; + } + + /// + /// 根据主键获取Entity + /// + /// 主键Id + /// Entity + protected virtual TModel GetById(object Id) + { + TModel rv = null; + //建立基础查询 + var query = DC.Set().AsQueryable(); + //循环添加其他设定的Include + if (_toInclude != null) + { + foreach (var item in _toInclude) + { + query = query.Include(item); + } + } + if (typeof(IPersistPoco).IsAssignableFrom(typeof(TModel))) + { + var mod = new IsValidModifier(); + var newExp = mod.Modify(query.Expression); + query = query.Provider.CreateQuery(newExp) as IOrderedQueryable; + } + + //获取数据 + rv = query.CheckID(Id).AsNoTracking().SingleOrDefault(); + if (rv == null) + { + throw new Exception("数据不存在"); + } + //如果TopBasePoco有关联的附件,则自动Include 附件名称 + var pros = typeof(TModel).GetAllProperties(); + var fa = pros.Where(x => x.PropertyType == typeof(FileAttachment)).ToList(); + foreach (var f in fa) + { + var fname = DC.GetFKName2(f.Name); + var fid = typeof(TModel).GetSingleProperty(fname).GetValue(rv); + if (fid != null && Wtm.ServiceProvider != null) + { + var fp = Wtm.ServiceProvider.GetRequiredService(); + var file = fp.GetFile(fid?.ToString(), false, DC); + rv.SetPropertyValue(f.Name, file); + } + } + return rv; + } + + /// + /// 添加,进行默认的添加操作。子类如有自定义操作应重载本函数 + /// + public virtual void DoAdd() + { + DoAddPrepare(); + //删除不需要的附件 + if (DeletedFileIds != null && DeletedFileIds.Count > 0 && Wtm.ServiceProvider != null) + { + var fp = Wtm.ServiceProvider.GetRequiredService(); + + foreach (var item in DeletedFileIds) + { + fp.DeleteFile(item.ToString(), DC); + } + } + DC.SaveChanges(); + } + + public virtual async Task DoAddAsync() + { + DoAddPrepare(); + //删除不需要的附件 + if (DeletedFileIds != null && DeletedFileIds.Count > 0 && Wtm.ServiceProvider != null) + { + var fp = Wtm.ServiceProvider.GetRequiredService(); + + foreach (var item in DeletedFileIds) + { + fp.DeleteFile(item.ToString(), DC.ReCreate()); + } + } + await DC.SaveChangesAsync(); + } + + private void DoAddPrepare() + { + var pros = typeof(TModel).GetAllProperties(); + //将所有TopBasePoco的属性赋空值,防止添加关联的重复内容 + if (typeof(TModel) != typeof(FileAttachment)) + { + foreach (var pro in pros) + { + if (pro.PropertyType.GetTypeInfo().IsSubclassOf(typeof(TopBasePoco))) + { + pro.SetValue(Entity, null); + } + } + } + //自动设定添加日期和添加人 + if (typeof(IBasePoco).IsAssignableFrom(typeof(TModel))) + { + IBasePoco ent = Entity as IBasePoco; + if (ent.CreateTime == null) + { + ent.CreateTime = DateTime.Now; + } + if (string.IsNullOrEmpty(ent.CreateBy)) + { + ent.CreateBy = LoginUserInfo?.ITCode; + } + } + + if (typeof(IPersistPoco).IsAssignableFrom(typeof(TModel))) + { + (Entity as IPersistPoco).IsValid = true; + } + + #region 更新子表 + foreach (var pro in pros) + { + //找到类型为List的字段 + if (pro.PropertyType.GenericTypeArguments.Count() > 0) + { + //获取xxx的类型 + var ftype = pro.PropertyType.GenericTypeArguments.First(); + //如果xxx继承自TopBasePoco + if (ftype.IsSubclassOf(typeof(TopBasePoco))) + { + //界面传过来的子表数据 + IEnumerable list = pro.GetValue(Entity) as IEnumerable; + if (list != null && list.Count() > 0) + { + string fkname = DC.GetFKName(pro.Name); + var itemPros = ftype.GetAllProperties(); + + bool found = false; + foreach (var newitem in list) + { + foreach (var itempro in itemPros) + { + if (itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco))) + { + itempro.SetValue(newitem, null); + } + if (!string.IsNullOrEmpty(fkname)) + { + if (itempro.Name.ToLower() == fkname.ToLower()) + { + try + { + itempro.SetValue(newitem, Entity.GetID()); + found = true; + } + catch { } + } + } + } + } + //如果没有找到相应的外建字段,则可能是多对多的关系,或者做了特殊的设定,这种情况框架无法支持,直接退出本次循环 + if (found == false) + { + continue; + } + //循环页面传过来的子表数据,自动设定添加日期和添加人 + foreach (var newitem in list) + { + var subtype = newitem.GetType(); + if (typeof(IBasePoco).IsAssignableFrom(subtype)) + { + IBasePoco ent = newitem as IBasePoco; + if (ent.CreateTime == null) + { + ent.CreateTime = DateTime.Now; + } + if (string.IsNullOrEmpty(ent.CreateBy)) + { + ent.CreateBy = LoginUserInfo?.ITCode; + } + } + } + } + } + } + } + #endregion + + + //添加数据 + DC.Set().Add(Entity); + + } + + /// + /// 修改,进行默认的修改操作。子类如有自定义操作应重载本函数 + /// + /// 为true时,框架会更新当前Entity的全部值,为false时,框架会检查Request.Form里的key,只更新表单提交的字段 + public virtual void DoEdit(bool updateAllFields = false) + { + DoEditPrepare(updateAllFields); + + try + { + DC.SaveChanges(); + } + catch + { + MSD.AddModelError(" ", Localizer["Sys.EditFailed"]); + } + //删除不需要的附件 + if (DeletedFileIds != null && DeletedFileIds.Count > 0 && Wtm.ServiceProvider != null) + { + var fp = Wtm.ServiceProvider.GetRequiredService(); + + foreach (var item in DeletedFileIds) + { + fp.DeleteFile(item.ToString(), DC.ReCreate()); + } + } + + } + + public virtual async Task DoEditAsync(bool updateAllFields = false) + { + DoEditPrepare(updateAllFields); + + await DC.SaveChangesAsync(); + //删除不需要的附件 + if (DeletedFileIds != null && DeletedFileIds.Count > 0 && Wtm.ServiceProvider != null) + { + var fp = Wtm.ServiceProvider.GetRequiredService(); + + foreach (var item in DeletedFileIds) + { + fp.DeleteFile(item.ToString(), DC); + } + } + } + + private void DoEditPrepare(bool updateAllFields) + { + if (typeof(IBasePoco).IsAssignableFrom(typeof(TModel))) + { + IBasePoco ent = Entity as IBasePoco; + //if (ent.UpdateTime == null) + //{ + ent.UpdateTime = DateTime.Now; + //} + //if (string.IsNullOrEmpty(ent.UpdateBy)) + //{ + ent.UpdateBy = LoginUserInfo?.ITCode; + //} + } + var pros = typeof(TModel).GetAllProperties(); + pros = pros.Where(x => x.CustomAttributes.Any(y => y.AttributeType == typeof(NotMappedAttribute)) == false).ToList(); + if (typeof(TModel) != typeof(FileAttachment)) + { + foreach (var pro in pros) + { + if (pro.PropertyType.GetTypeInfo().IsSubclassOf(typeof(TopBasePoco))) + { + pro.SetValue(Entity, null); + } + } + } + #region 更新子表 + foreach (var pro in pros) + { + //找到类型为List的字段 + if (pro.PropertyType.GenericTypeArguments.Count() > 0) + { + //获取xxx的类型 + var ftype = pro.PropertyType.GenericTypeArguments.First(); + //如果xxx继承自TopBasePoco + if (ftype.IsSubclassOf(typeof(TopBasePoco))) + { + //界面传过来的子表数据 + + if (pro.GetValue(Entity) is IEnumerable list && list.Count() > 0) + { + //获取外键字段名称 + string fkname = DC.GetFKName(pro.Name); + var itemPros = ftype.GetAllProperties(); + + bool found = false; + foreach (var newitem in list) + { + var subtype = newitem.GetType(); + if (typeof(IBasePoco).IsAssignableFrom(subtype)) + { + IBasePoco ent = newitem as IBasePoco; + if (ent.UpdateTime == null) + { + ent.UpdateTime = DateTime.Now; + } + if (string.IsNullOrEmpty(ent.UpdateBy)) + { + ent.UpdateBy = LoginUserInfo?.ITCode; + } + } + //循环页面传过来的子表数据,将关联到TopBasePoco的字段设为null,并且把外键字段的值设定为主表ID + foreach (var itempro in itemPros) + { + if (itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco))) + { + itempro.SetValue(newitem, null); + } + if (!string.IsNullOrEmpty(fkname)) + { + if (itempro.Name.ToLower() == fkname.ToLower()) + { + itempro.SetValue(newitem, Entity.GetID()); + found = true; + } + } + } + } + //如果没有找到相应的外建字段,则可能是多对多的关系,或者做了特殊的设定,这种情况框架无法支持,直接退出本次循环 + if (found == false) + { + continue; + } + + + TModel _entity = null; + //打开新的数据库联接,获取数据库中的主表和子表数据 + //using (var ndc = DC.CreateNew()) + //{ + _entity = DC.Set().Include(pro.Name).AsNoTracking().CheckID(Entity.GetID()).FirstOrDefault(); + //} + if (_entity == null) + { + MSD.AddModelError(" ", Localizer["Sys.EditFailed"]); + return; + } + //比较子表原数据和新数据的区别 + IEnumerable toadd = null; + IEnumerable toremove = null; + IEnumerable data = _entity.GetType().GetSingleProperty(pro.Name).GetValue(_entity) as IEnumerable; + Utils.CheckDifference(data, list, out toremove, out toadd); + //设定子表应该更新的字段 + List setnames = new List(); + foreach (var field in FC.Keys) + { + var f = field.ToLower(); + if (f.StartsWith("entity." + pro.Name.ToLower() + "[0].")) + { + string name = f.Replace("entity." + pro.Name.ToLower() + "[0].", ""); + setnames.Add(name); + } + } + + //前台传过来的数据 + foreach (var newitem in list) + { + //数据库中的数据 + foreach (var item in data) + { + //需要更新的数据 + if (newitem.GetID().ToString() == item.GetID().ToString()) + { + dynamic i = newitem; + var newitemType = item.GetType(); + foreach (var itempro in itemPros) + { + if (!itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco)) && (updateAllFields == true || setnames.Contains(itempro.Name.ToLower()))) + { + var notmapped = itempro.GetCustomAttribute(); + if (itempro.Name != "ID" && notmapped == null && itempro.PropertyType.IsList() == false) + { + DC.UpdateProperty(i, itempro.Name); + } + } + } + if (typeof(IBasePoco).IsAssignableFrom(item.GetType())) + { + DC.UpdateProperty(i, "UpdateTime"); + DC.UpdateProperty(i, "UpdateBy"); + } + } + } + } + //需要删除的数据 + foreach (var item in toremove) + { + //如果是PersistPoco,则把IsValid设为false,并不进行物理删除 + if (typeof(IPersistPoco).IsAssignableFrom(ftype)) + { + (item as IPersistPoco).IsValid = false; + if (typeof(IBasePoco).IsAssignableFrom(ftype)) + { + (item as IBasePoco).UpdateTime = DateTime.Now; + (item as IBasePoco).UpdateBy = LoginUserInfo?.ITCode; + } + dynamic i = item; + DC.UpdateEntity(i); + } + else + { + foreach (var itempro in itemPros) + { + if (itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco))) + { + itempro.SetValue(item, null); + } + } + dynamic i = item; + DC.DeleteEntity(i); + } + } + //需要添加的数据 + foreach (var item in toadd) + { + if (typeof(IBasePoco).IsAssignableFrom(item.GetType())) + { + IBasePoco ent = item as IBasePoco; + if (ent.CreateTime == null) + { + ent.CreateTime = DateTime.Now; + } + if (string.IsNullOrEmpty(ent.CreateBy)) + { + ent.CreateBy = LoginUserInfo?.ITCode; + } + } + DC.AddEntity(item); + } + } + else if ((pro.GetValue(Entity) is IEnumerable list2 && list2?.Count() == 0)) + { + var itemPros = ftype.GetAllProperties(); + var _entity = DC.Set().Include(pro.Name).AsNoTracking().CheckID(Entity.GetID()).FirstOrDefault(); + if (_entity != null) + { + IEnumerable removeData = _entity.GetType().GetSingleProperty(pro.Name).GetValue(_entity) as IEnumerable; + //如果是PersistPoco,则把IsValid设为false,并不进行物理删除 + if (removeData is IEnumerable removePersistPocoData) + { + foreach (var item in removePersistPocoData) + { + (item as IPersistPoco).IsValid = false; + if (typeof(IBasePoco).IsAssignableFrom(item.GetType())) + { + (item as IBasePoco).UpdateTime = DateTime.Now; + (item as IBasePoco).UpdateBy = LoginUserInfo?.ITCode; + } + dynamic i = item; + DC.UpdateEntity(i); + } + } + else + { + foreach (var item in removeData) + { + foreach (var itempro in itemPros) + { + if (itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco))) + { + itempro.SetValue(item, null); + } + } + dynamic i = item; + DC.DeleteEntity(i); + } + } + + } + } + } + } + } + #endregion + + + if (updateAllFields == false) + { + foreach (var field in FC.Keys) + { + var f = field.ToLower(); + if (f.StartsWith("entity.") && !f.Contains("[")) + { + string name = f.Replace("entity.", ""); + try + { + DC.UpdateProperty(Entity, pros.Where(x => x.Name.ToLower() == name).Select(x => x.Name).FirstOrDefault()); + } + catch (Exception) + { + } + } + } + if (typeof(IBasePoco).IsAssignableFrom(typeof(TModel))) + { + try + { + DC.UpdateProperty(Entity, "UpdateTime"); + DC.UpdateProperty(Entity, "UpdateBy"); + } + catch (Exception) + { + } + } + } + else + { + DC.UpdateEntity(Entity); + } + } + + /// + /// 删除,进行默认的删除操作。子类如有自定义操作应重载本函数 + /// + public virtual void DoDelete() + { + //如果是PersistPoco,则把IsValid设为false,并不进行物理删除 + if (typeof(IPersistPoco).IsAssignableFrom(typeof(TModel))) + { + FC.Add("Entity.IsValid", 0); + (Entity as IPersistPoco).IsValid = false; + + var pros = typeof(TModel).GetAllProperties(); + //如果包含List,将子表IsValid也设置为false + var fas = pros.Where(x => typeof(IEnumerable).IsAssignableFrom(x.PropertyType)).ToList(); + foreach (var f in fas) + { + f.SetValue(Entity, f.PropertyType.GetConstructor(Type.EmptyTypes).Invoke(null)); + } + + DoEditPrepare(false); + DC.SaveChanges(); + } + //如果是普通的TopBasePoco,则进行物理删除 + else if (typeof(TModel).GetTypeInfo().IsSubclassOf(typeof(TopBasePoco))) + { + DoRealDelete(); + } + } + + public virtual async Task DoDeleteAsync() + { + //如果是PersistPoco,则把IsValid设为false,并不进行物理删除 + if (typeof(IPersistPoco).IsAssignableFrom(typeof(TModel))) + { + FC.Add("Entity.IsValid", 0); + (Entity as IPersistPoco).IsValid = false; + var pros = typeof(TModel).GetAllProperties(); + //如果包含List,将子表IsValid也设置为false + var fas = pros.Where(x => typeof(IEnumerable).IsAssignableFrom(x.PropertyType)).ToList(); + foreach (var f in fas) + { + f.SetValue(Entity, f.PropertyType.GetConstructor(Type.EmptyTypes).Invoke(null)); + } + fas = pros.Where(x => typeof(TopBasePoco).IsAssignableFrom(x.PropertyType)).ToList(); + foreach (var f in fas) + { + f.SetValue(Entity, null); + } + DoEditPrepare(false); + try + { + await DC.SaveChangesAsync(); + } + catch (DbUpdateException) + { + MSD.AddModelError("", CoreProgram._localizer?["Sys.DeleteFailed"]); + } + } + //如果是普通的TopBasePoco,则进行物理删除 + else if (typeof(TModel).GetTypeInfo().IsSubclassOf(typeof(TopBasePoco))) + { + DoRealDelete(); + } + } + + /// + /// 物理删除,对于普通的TopBasePoco和Delete操作相同,对于PersistPoco则进行真正的删除。子类如有自定义操作应重载本函数 + /// + public virtual void DoRealDelete() + { + try + { + List fileids = new List(); + var pros = typeof(TModel).GetAllProperties(); + + //如果包含附件,则先删除附件 + var fa = pros.Where(x => x.PropertyType == typeof(FileAttachment) || typeof(TopBasePoco).IsAssignableFrom(x.PropertyType)).ToList(); + foreach (var f in fa) + { + if (f.GetValue(Entity) is FileAttachment file) + { + fileids.Add(file.ID); + } + f.SetValue(Entity, null); + } + + var fas = pros.Where(x => typeof(IEnumerable).IsAssignableFrom(x.PropertyType)).ToList(); + foreach (var f in fas) + { + var subs = f.GetValue(Entity) as IEnumerable; + if (subs == null) + { + var fullEntity = DC.Set().AsQueryable().Include(f.Name).AsNoTracking().CheckID(Entity.ID).FirstOrDefault(); + subs = f.GetValue(fullEntity) as IEnumerable; + } + if (subs != null) + { + foreach (var sub in subs) + { + fileids.Add(sub.FileId); + } + f.SetValue(Entity, null); + } + } + if (typeof(TModel) != typeof(FileAttachment)) + { + foreach (var pro in pros) + { + if (pro.PropertyType.GetTypeInfo().IsSubclassOf(typeof(TopBasePoco))) + { + pro.SetValue(Entity, null); + } + } + } + DC.DeleteEntity(Entity); + DC.SaveChanges(); + if (Wtm.ServiceProvider != null) + { + var fp = Wtm.ServiceProvider.GetRequiredService(); + foreach (var item in fileids) + { + fp.DeleteFile(item.ToString(), DC.ReCreate()); + } + } + } + catch (Exception) + { + MSD.AddModelError("", CoreProgram._localizer?["Sys.DeleteFailed"]); + } + } + + + public virtual async Task DoRealDeleteAsync() + { + try + { + List fileids = new List(); + var pros = typeof(TModel).GetAllProperties(); + + //如果包含附件,则先删除附件 + var fa = pros.Where(x => x.PropertyType == typeof(FileAttachment) || typeof(TopBasePoco).IsAssignableFrom(x.PropertyType)).ToList(); + foreach (var f in fa) + { + if (f.GetValue(Entity) is FileAttachment file) + { + fileids.Add(file.ID); + } + f.SetValue(Entity, null); + } + + var fas = pros.Where(x => typeof(IEnumerable).IsAssignableFrom(x.PropertyType)).ToList(); + foreach (var f in fas) + { + var subs = f.GetValue(Entity) as IEnumerable; + foreach (var sub in subs) + { + fileids.Add(sub.FileId); + } + f.SetValue(Entity, null); + } + if (typeof(TModel) != typeof(FileAttachment)) + { + foreach (var pro in pros) + { + if (pro.PropertyType.GetTypeInfo().IsSubclassOf(typeof(TopBasePoco))) + { + pro.SetValue(Entity, null); + } + } + } + DC.DeleteEntity(Entity); + await DC.SaveChangesAsync(); + if (Wtm.ServiceProvider != null) + { + var fp = Wtm.ServiceProvider.GetRequiredService(); + foreach (var item in fileids) + { + fp.DeleteFile(item.ToString(), DC.ReCreate()); + } + } + } + catch (Exception) + { + MSD.AddModelError("", CoreProgram._localizer?["Sys.DeleteFailed"]); + } + } + + /// + /// 创建重复数据信息 + /// + /// 重复数据信息 + /// 重复数据信息 + protected DuplicatedInfo CreateFieldsInfo(params DuplicatedField[] FieldExps) + { + DuplicatedInfo d = new DuplicatedInfo(); + d.AddGroup(FieldExps); + return d; + } + + /// + /// 创建一个简单重复数据信息 + /// + /// 重复数据的字段 + /// 重复数据信息 + public static DuplicatedField SimpleField(Expression> FieldExp) + { + return new DuplicatedField(FieldExp); + } + + /// + /// 创建一个关联到其他表数组中数据的重复信息 + /// + /// 关联表类 + /// 指向关联表类数组的Lambda + /// 指向最终字段的Lambda + /// 重复数据信息 + public static DuplicatedField SubField(Expression>> MiddleExp, params Expression>[] FieldExps) + { + return new ComplexDuplicatedField(MiddleExp, FieldExps); + } + + /// + /// 验证数据,默认验证重复数据。子类如需要其他自定义验证,则重载这个函数 + /// + /// 验证结果 + public override void Validate() + { + if (ByPassBaseValidation == false) + { + base.Validate(); + ////如果msd是BasicMSD,则认为他是手动创建的,也就是说并没有走asp.net core默认的模型验证 + ////那么手动验证模型 + //if (Wtm?.MSD is BasicMSD) + //{ + // var valContext = new ValidationContext(this.Entity); + // List error = new List(); + // if (!Validator.TryValidateObject(Entity, valContext, error, true)) + // { + // foreach (var item in error) + // { + // string key = item.MemberNames.FirstOrDefault(); + // if (MSD.Keys.Contains(key) == false) + // { + // MSD.AddModelError($"Entity.{key}", item.ErrorMessage); + // } + // } + // } + // var list = typeof(TModel).GetAllProperties().Where(x => x.PropertyType.IsListOf()); + // foreach (var item in list) + // { + // var it = item.GetValue(Entity) as IEnumerable; + // if(it == null) + // { + // continue; + // } + // var contextset = false; + // foreach (var e in it) + // { + // if(contextset == false) + // { + // valContext = new ValidationContext(e); + // contextset = true; + // } + + // if (!Validator.TryValidateObject(e, valContext, error, true)) + // { + // foreach (var err in error) + // { + // string key = err.MemberNames.FirstOrDefault(); + // if (MSD.Keys.Contains(key) == false) + // { + // MSD.AddModelError($"Entity.{item.Name}.{key}", err.ErrorMessage); + // } + // } + // } + + // } + // } + //} + + //验证重复数据 + ValidateDuplicateData(); + } + } + + /// + /// 验证重复数据 + /// 如果存在重复的数据,则返回已存在数据的id列表 + /// 如果不存在重复数据,则返回一个空列表 + /// + protected List ValidateDuplicateData() + { + //定义一个对象列表用于存放重复数据的id + var count = new List(); + //获取设定的重复字段信息 + var checkCondition = SetDuplicatedCheck(); + if (checkCondition != null && checkCondition.Groups.Count > 0) + { + //生成基础Query + var baseExp = DC.Set().AsQueryable(); + var modelType = typeof(TModel); + ParameterExpression para = Expression.Parameter(modelType, "tm"); + //循环所有重复字段组 + foreach (var group in checkCondition.Groups) + { + var innercount = new List(); + List conditions = new List(); + //生成一个表达式,类似于 x=>x.Id != id,这是为了当修改数据时验证重复性的时候,排除当前正在修改的数据 + var idproperty = typeof(TModel).GetSingleProperty("ID"); + MemberExpression idLeft = Expression.Property(para, idproperty); + ConstantExpression idRight = Expression.Constant(Entity.GetID()); + BinaryExpression idNotEqual = Expression.NotEqual(idLeft, idRight); + conditions.Add(idNotEqual); + List props = new List(); + //在每个组中循环所有字段 + foreach (var field in group.Fields) + { + Expression exp = field.GetExpression(Entity, para); + if (exp != null) + { + conditions.Add(exp); + } + //将字段名保存,为后面生成错误信息作准备 + props.AddRange(field.GetProperties()); + } + //如果要求判断id不重复,则去掉id不相等的判断,加入id相等的判断 + if (props.Any(x => x.Name.ToLower() == "id")) + { + conditions.RemoveAt(0); + BinaryExpression idEqual = Expression.Equal(idLeft, idRight); + conditions.Insert(0, idEqual); + } + //int count = 0; + if (conditions.Count > 1) + { + //循环添加条件并生成Where语句 + //Expression conExp = conditions[0]; + Expression whereCallExpression = baseExp.Expression; + for (int i = 0; i < conditions.Count; i++) + { + whereCallExpression = Expression.Call( + typeof(Queryable), + "Where", + new Type[] { modelType }, + whereCallExpression, + Expression.Lambda>(conditions[i], new ParameterExpression[] { para })); + } + var result = baseExp.Provider.CreateQuery(whereCallExpression); + + foreach (TopBasePoco res in result) + { + var id = res.GetID(); + count.Add(id); + innercount.Add(id); + } + } + if (innercount.Count > 0) + { + //循环拼接所有字段名 + string AllName = ""; + foreach (var prop in props) + { + string name = PropertyHelper.GetPropertyDisplayName(prop); + AllName += name + ","; + } + if (AllName.EndsWith(",")) + { + AllName = AllName.Remove(AllName.Length - 1); + } + //如果只有一个字段重复,则拼接形成 xxx字段重复 这种提示 + if (props.Count == 1) + { + MSD.AddModelError(GetValidationFieldName(props[0])[0], CoreProgram._localizer?["Sys.DuplicateError", AllName]); + } + //如果多个字段重复,则拼接形成 xx,yy,zz组合字段重复 这种提示 + else if (props.Count > 1) + { + MSD.AddModelError(GetValidationFieldName(props.First())[0], CoreProgram._localizer?["Sys.DuplicateGroupError", AllName]); + } + } + } + } + return count; + } + + + /// + /// 根据属性信息获取验证字段名 + /// + /// 属性信息 + /// 验证字段名称数组,用于ValidationResult + private string[] GetValidationFieldName(PropertyInfo pi) + { + return new[] { "Entity." + pi.Name }; + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseImportVM.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseImportVM.cs new file mode 100644 index 0000000..580e54c --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseImportVM.cs @@ -0,0 +1,1443 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Data; +using System.Data.SqlClient; +using System.IO; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Text.Json.Serialization; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using NPOI.HSSF.Util; +using NPOI.SS.UserModel; +using NPOI.XSSF.UserModel; +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Core.Support.FileHandlers; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// 导入接口 + /// + /// 导入模版类 + public interface IBaseImport where T : BaseTemplateVM + { + T Template { get; } + byte[] GenerateTemplate(out string displayName); + void SetParms(Dictionary parms); + TemplateErrorListVM ErrorListVM { get; set; } + } + + /// + /// 导入基类,Excel导入的类应继承本类 + /// + /// 导入模版类 + /// 导入的Model类 + public class BaseImportVM : BaseVM, IBaseImport + where T : BaseTemplateVM, new() + where P : TopBasePoco, new() + { + #region 字段、属性 + /// + /// 上传文件的Id,方便导入等操作中进行绑定,这类操作需要上传文件但不需要记录在数据库中,所以Model层中没有文件Id的字段 + /// + [Display(Name = "UploadFile")] + public string UploadFileId { get; set; } + + /// + /// 下载模板显示名称 + /// + [JsonIgnore] + public string FileDisplayName { get; set; } + + /// + /// 错误列表 + /// + [JsonIgnore] + public TemplateErrorListVM ErrorListVM { get; set; } + + /// + /// 是否验证模板类型(当其他系统模板导入到某模块时可设置为False) + /// + [JsonIgnore] + public bool ValidityTemplateType { get; set; } + + /// + /// 下载模版页面的参数 + /// + [JsonIgnore] + public Dictionary Parms { get; set; } + + protected List TemplateData; + + /// + /// 要导入的Model列表 + /// + [JsonIgnore] + public List

EntityList { get; set; } + + ///

+ /// 模版 + /// + [JsonIgnore] + public T Template { get; set; } + + /// + /// Model数据是否已被赋值 + /// + protected bool isEntityListSet = false; + + /// + /// 声明XSSF + /// + protected XSSFWorkbook xssfworkbook; + + /// + /// 唯一性验证 + /// + protected DuplicatedInfo

finalInfo; + + ///

+ /// 是否存在主子表 + /// + protected bool HasSubTable { get; set; } + + /// + /// 是否在sqlserver时使用bulk导入 + /// + public bool UseBulkSave { get; set; } + + /// + /// 是否覆盖已有数据 + /// + public bool IsOverWriteExistData { get; set; } = true; + #endregion + + #region 构造函数 + public BaseImportVM() + { + ErrorListVM = new TemplateErrorListVM(); + ValidityTemplateType = true; + Template = new T(); + } + #endregion + + #region 生成excel + /// + /// 生成模版 + /// + /// 模版文件名 + /// 生成的模版 + public virtual byte[] GenerateTemplate(out string displayName) + { + return Template.GenerateTemplate(out displayName); + } + #endregion + + #region 设置参数值 + /// + /// 设置模版参数 + /// + /// 参数 + public void SetParms(Dictionary parms) + { + Template.Parms = parms; + } + #endregion + + #region 可重写方法 + + /// + /// 设置数据唯一性验证,子类中如果需要数据唯一性验证,应重写此方法 + /// + /// 唯一性属性 + public virtual DuplicatedInfo

SetDuplicatedCheck() + { + return null; + } + + ///

+ /// 获取上传的结果值 + /// + public virtual void SetEntityList() + { + if (!isEntityListSet) + { + EntityList = new List

(); + + //初始化上传的模板数据 + SetTemplateData(); + + //如果模板中有错误,直接返回 + if (ErrorListVM.EntityList.Count > 0) + { + return; + } + + //对EntityList赋值 + SetEntityData(); + + //设置标识为初始化 + isEntityListSet = true; + } + } + + ///

+ /// 获取上传模板中填写的数据,包含了对模板正确性的验证 + /// + public virtual void SetTemplateData() + { + if (TemplateData != null && TemplateData.Count > 0) + { + return; + } + + try + { + TemplateData = new List(); + xssfworkbook = new XSSFWorkbook(); + + //【CHECK】上传附件的ID为空 + if (UploadFileId == null) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Message = CoreProgram._localizer?["Sys.PleaseUploadTemplate"] }); + return; + } + Models.IWtmFile file = null; + if (Wtm.ServiceProvider != null) + { + var fp = Wtm.ServiceProvider.GetRequiredService(); + file = fp.GetFile(UploadFileId, true, DC); + } + if (file == null) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Message = CoreProgram._localizer?["Sys.WrongTemplate"] }); + return; + } + xssfworkbook = new XSSFWorkbook(file.DataStream); + file.DataStream.Dispose(); + Template.InitExcelData(); + Template.InitCustomFormat(); + + //【CHECK】判断是否上传的是正确的模板数据 + string TemplateHiddenName = xssfworkbook.GetSheetAt(1).GetRow(0).Cells[2].ToString(); + if (ValidityTemplateType && !TemplateHiddenName.Equals(typeof(T).Name)) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Message = CoreProgram._localizer?["Sys.WrongTemplate"] }); + return; + } + + //获取数据的Sheet页信息 + ISheet sheet = xssfworkbook.GetSheetAt(0); + sheet.ForceFormulaRecalculation = true; + XSSFFormulaEvaluator XE = new XSSFFormulaEvaluator(xssfworkbook); + IEnumerator rows = sheet.GetRowEnumerator(); + var cells = sheet.GetRow(0).Cells; + + //获取模板中所有字段的属性 + List ListTemplateProptetys = new List(); + var ListPropetys = Template.GetType().GetFields().Where(x => x.FieldType == typeof(ExcelPropety)).ToList(); + for (int i = 0; i < ListPropetys.Count(); i++) + { + ExcelPropety ep = (ExcelPropety)ListPropetys[i].GetValue(Template); + ListTemplateProptetys.Add(ep); + } + + //【CHECK】验证模板的列数是否正确 + var dynamicColumn = ListTemplateProptetys.Where(x => x.DataType == ColumnDataType.Dynamic).FirstOrDefault(); + int columnCount = dynamicColumn == null ? ListTemplateProptetys.Count : (ListTemplateProptetys.Count + dynamicColumn.DynamicColumns.Count - 1); + if (columnCount != cells.Count) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Message = CoreProgram._localizer?["Sys.WrongTemplate"] }); + return; + } + + //【CHECK】判断字段是否根据顺序能一对一相对应。 //是否可以去除? + int pIndex = 0; + HasSubTable = false; + for (int i = 0; i < cells.Count; i++) + { + //是否有子表 + HasSubTable = ListTemplateProptetys[pIndex].SubTableType != null ? true : HasSubTable; + //if (ListTemplateProptetys[pIndex].DataType != ColumnDataType.Dynamic) + //{ + // if (cells[i].ToString().Trim('*') != ListTemplateProptetys[pIndex].ColumnName) + // { + // ErrorListVM.EntityList.Add(new ErrorMessage { Message = CoreProgram._localizer?["Sys.WrongTemplate"] }); + // return; + // } + // pIndex++; + //} + //else + //{ + // var listDynamicColumns = ListTemplateProptetys[i].DynamicColumns; + // int dcCount = listDynamicColumns.Count; + // for (int dclIndex = 0; dclIndex < dcCount; dclIndex++) + // { + // if (cells[i].ToString().Trim('*') != listDynamicColumns[dclIndex].ColumnName) + // { + // ErrorListVM.EntityList.Add(new ErrorMessage { Message = CoreProgram._localizer?["Sys.WrongTemplate"] }); + // break; + // } + // i = i + 1; + // } + // i = i - 1; + pIndex++; + //} + } + + //如果有子表,则设置主表字段非必填 + if (HasSubTable) + { + for (int i = 0; i < cells.Count; i++) + { + ListTemplateProptetys[i].IsNullAble = ListTemplateProptetys[i].SubTableType == null ? true : ListTemplateProptetys[i].IsNullAble; + } + } + + //向TemplateData中赋值 + int rowIndex = 2; + rows.MoveNext(); + while (rows.MoveNext()) + { + XSSFRow row = (XSSFRow)rows.Current; + if (IsEmptyRow(row, columnCount)) + { + return; + } + + T result = new T(); + pIndex = 0; + for (int i = 0; i < columnCount; i++) + { + //获取列的值 + string value = row.GetCell(i, MissingCellPolicy.CREATE_NULL_AS_BLANK).ToString(); + ExcelPropety excelPropety = CopyExcelPropety(ListTemplateProptetys[pIndex]); + + if (excelPropety.DataType == ColumnDataType.Text) + { + ICell cell = row.GetCell(i); + value = GetCellFormulaValue(XE, cell, value); + } + + if (excelPropety.DataType == ColumnDataType.Dynamic) + { + int dynamicColCount = excelPropety.DynamicColumns.Count(); + for (int dynamicColIndex = 0; dynamicColIndex < dynamicColCount; dynamicColIndex++) + { + excelPropety.DynamicColumns[dynamicColIndex].ValueValidity(row.GetCell(i + dynamicColIndex, MissingCellPolicy.CREATE_NULL_AS_BLANK).ToString(), ErrorListVM.EntityList, rowIndex); + } + i = i + dynamicColCount - 1; + } + else + { + excelPropety.ValueValidity(value, ErrorListVM.EntityList, rowIndex); + } + + //如果没有错误,进行赋值 + if (ErrorListVM.EntityList.Count == 0) + { + var pts = ListPropetys[pIndex]; + pts.SetValue(result, excelPropety); + } + + pIndex++; + } + result.ExcelIndex = rowIndex; + TemplateData.Add(result); + rowIndex++; + } + + return; + } + catch + { + ErrorListVM.EntityList.Add(new ErrorMessage { Message = CoreProgram._localizer?["Sys.WrongTemplate"] }); + } + } + + #region 进行公式计算 + public string GetCellFormulaValue(XSSFFormulaEvaluator XE, ICell cell, string Value) + { + if (!string.IsNullOrEmpty(Value) && Value.IndexOf("=") == 0) + { + try + { + string Formula = Value.Substring(1); + cell.SetCellFormula(Formula); + XE.EvaluateFormulaCell(cell); + Value = cell.NumericCellValue.ToString(); + } + catch (Exception) + { + } + } + return Value; + } + #endregion + + /// + /// 根据模板中的数据,填写导入类的集合中 + /// + public virtual void SetEntityData() + { + //反射出类中所有属性字段 P是Model层定义的类 + var pros = typeof(P).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); + + //反射出模板类中的所有属性字段 T是模板类,ExcelProperty 是自定义的Excel属性类 + List ListExcelFields = typeof(T).GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).Where(x => x.FieldType == typeof(ExcelPropety)).ToList(); + + //循环Excel中的数据 + foreach (var item in TemplateData) + { + int rowIndex = 2; + bool isMainData = false; + + //主表信息 + Dictionary ParentEntity = new Dictionary(); + string ParentEntityValues = string.Empty; + + //子表信息 + Dictionary> ChildrenEntity = new Dictionary>(); + Dictionary ChildrenEntityDic = new Dictionary(); + + //循环TemplateVM中定义的所有的列,区分出主子表 + foreach (var ExcelField in ListExcelFields) + { + //获取本列的ExcelProperty的值 + if (typeof(T).GetField(ExcelField.Name).GetValue(item) is ExcelPropety ep) + { + //如果是子表的字段 + if (ep.SubTableType != null) + { + //保存子表字段信息稍后处理 + if (!ChildrenEntity.ContainsKey(ep.SubTableType)) + { + ChildrenEntity[ep.SubTableType] = new List(); + } + ChildrenEntity[ep.SubTableType].Add(ExcelField); + } + else + { + //保存子表字段信息稍后处理 + ParentEntity.Add(ep.FieldName, ep); + ParentEntityValues += ep.Value; + } + } + } + + //子表信息是否为空 + foreach (var sub in ChildrenEntity) + { + string subVal = string.Empty; + foreach (var field in sub.Value) + { + ExcelPropety ep = typeof(T).GetField(field.Name).GetValue(item) as ExcelPropety; + subVal += ep.Value; + } + ChildrenEntityDic.Add(sub.Key, subVal); + } + + P entity = null; + + //说明主表信息为空 + if (string.IsNullOrEmpty(ParentEntityValues)) + { + entity = EntityList.LastOrDefault(); + } + else + { + //初始化一个新的Entity + entity = new P(); + isMainData = true; + + //给主表赋值 + foreach (var mep in ParentEntity) + { + SetEntityFieldValue(entity, mep.Value, rowIndex, mep.Key, item); + } + } + + //给子表赋值 + foreach (var sub in ChildrenEntity) + { + //循环Entity的所有属性,找到List类型的字段 + foreach (var pro in pros) + { + if (pro.PropertyType.IsGenericType) + { + var gtype = pro.PropertyType.GetGenericArguments()[0]; + if (gtype == sub.Key) + { + //子表 + var subList = entity.GetType().GetSingleProperty(pro.Name).GetValue(entity); + string fk = DC.GetFKName

(pro.Name); + + //如果子表不为空 + if (!string.IsNullOrEmpty(ChildrenEntityDic.Where(x => x.Key == sub.Key).FirstOrDefault().Value)) + { + IList list = null; + if (subList == null) + { + //初始化List + list = typeof(List<>).MakeGenericType(gtype).GetConstructor(Type.EmptyTypes).Invoke(null) as IList; + } + else + { + list = subList as IList; + } + + //初始化一个SubTableType + var SubTypeEntity = gtype.GetConstructor(System.Type.EmptyTypes).Invoke(null); + + //给SubTableType中和本ExcelProperty同名的字段赋值 + foreach (var field in sub.Value) + { + ExcelPropety ep = typeof(T).GetField(field.Name).GetValue(item) as ExcelPropety; + SetEntityFieldValue(SubTypeEntity, ep, rowIndex, ep.FieldName, item); + } + + if (string.IsNullOrEmpty(fk) == false) + { + PropertyHelper.SetPropertyValue(SubTypeEntity, fk, entity.GetID()); + } + + if (typeof(IBasePoco).IsAssignableFrom(SubTypeEntity.GetType())) + { + (SubTypeEntity as IBasePoco).CreateTime = DateTime.Now; + (SubTypeEntity as IBasePoco).CreateBy = LoginUserInfo?.ITCode; + } + //var context = new ValidationContext(SubTypeEntity); + //var validationResults = new List(); + //TryValidateObject(SubTypeEntity, context, validationResults); + //if (validationResults.Count == 0) + //{ + //将付好值得SubTableType实例添加到List中 + list.Add(SubTypeEntity); + + PropertyHelper.SetPropertyValue(entity, pro.Name, list); + //} + //else + //{ + // ErrorListVM.EntityList.Add(new ErrorMessage { Message = validationResults.FirstOrDefault()?.ErrorMessage ?? "Error", ExcelIndex = item.ExcelIndex }); + // break; + //} + + } + break; + } + } + } + + } + entity.ExcelIndex = item.ExcelIndex; + if (isMainData) + { + EntityList.Add(entity); + } + } + } + + ///

+ /// 进行上传中的错误验证 + /// + public virtual void SetValidateCheck() + { + //找到对应的BaseCRUDVM,并初始化 + var vms = this.GetType().Assembly.GetExportedTypes().Where(x => x.IsSubclassOf(typeof(BaseCRUDVM

))).ToList(); + var vmtype = vms.Where(x => x.Name.ToLower() == typeof(P).Name.ToLower() + "vm").FirstOrDefault(); + if (vmtype == null) + { + vmtype = vms.FirstOrDefault(); + } + + IBaseCRUDVM

vm = null; + DuplicatedInfo

dinfo = null; + if (vmtype != null) + { + vm = vmtype.GetConstructor(System.Type.EmptyTypes).Invoke(null) as IBaseCRUDVM

; + vm.CopyContext(this); + dinfo = (vm as dynamic).SetDuplicatedCheck(); + } + var cinfo = this.SetDuplicatedCheck(); + finalInfo = new DuplicatedInfo

+ { + Groups = new List>() + }; + if (cinfo != null) + { + foreach (var item in cinfo?.Groups) + { + finalInfo.Groups.Add(item); + } + } + else if (dinfo != null) + { + foreach (var item in dinfo?.Groups) + { + finalInfo.Groups.Add(item); + } + } + //调用controller方法验证model + //var vmethod = Controller?.GetType().GetMethod("RedoValidation"); + foreach (var entity in EntityList) + { + //try + //{ + // vmethod.Invoke(Controller, new object[] { entity }); + //} + //catch { } + + if (vm != null) + { + vm.SetEntity(entity); + vm.ByPassBaseValidation = true; + vm.Validate(); + var basevm = vm as BaseVM; + if (basevm?.MSD?.Count > 0) + { + foreach (var key in basevm.MSD.Keys) + { + foreach (var error in basevm.MSD[key]) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Message = error.ErrorMessage, Index = entity.ExcelIndex }); + } + } + } + } + (vm as BaseVM)?.MSD.Clear(); + + //在本地EntityList中验证是否有重复 + ValidateDuplicateData(finalInfo, entity); + } + } + + protected void SetEntityFieldValue(object entity, ExcelPropety ep, int rowIndex, string fieldName, T templateVM) + { + if (ep.FormatData != null) + { + ProcessResult processResult = ep.FormatData(ep.Value, templateVM); + if (processResult != null) + { + //未添加任何处理结果 + if (processResult.EntityValues.Count == 0) + { + PropertyHelper.SetPropertyValue(entity, fieldName, ep.Value, stringBasedValue: true); + } + //字段为一对一 + if (processResult.EntityValues.Count == 1) + { + ep.Value = processResult.EntityValues[0].FieldValue; + if (!string.IsNullOrEmpty(processResult.EntityValues[0].ErrorMsg)) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Message = processResult.EntityValues[0].ErrorMsg, ExcelIndex = rowIndex, Index = rowIndex }); + } + PropertyHelper.SetPropertyValue(entity, fieldName, ep.Value, stringBasedValue: true); + } + //字段为一对多 + if (processResult.EntityValues.Count > 1) + { + foreach (var entityValue in processResult.EntityValues) + { + if (!string.IsNullOrEmpty(entityValue.ErrorMsg)) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Message = entityValue.ErrorMsg, ExcelIndex = rowIndex, Index = rowIndex }); + } + PropertyHelper.SetPropertyValue(entity, entityValue.FieldName, entityValue.FieldValue, stringBasedValue: true); + } + } + } + } + else if (ep.FormatSingleData != null) + { + ep.FormatSingleData(ep.Value, templateVM, out string singleEntityValue, out string errorMsg); + if (!string.IsNullOrEmpty(errorMsg)) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Message = errorMsg, ExcelIndex = rowIndex, Index = rowIndex }); + } + PropertyHelper.SetPropertyValue(entity, fieldName, singleEntityValue, stringBasedValue: true); + } + else + { + PropertyHelper.SetPropertyValue(entity, fieldName, ep.Value, stringBasedValue: true); + } + } + + protected bool IsUpdateRecordDuplicated(DuplicatedInfo

checkCondition, P entity) + { + if (checkCondition != null && checkCondition.Groups.Count > 0) + { + //生成基础Query + var baseExp = EntityList.AsQueryable(); + var modelType = typeof(P); + ParameterExpression para = Expression.Parameter(modelType, "tm"); + //循环所有重复字段组 + foreach (var group in checkCondition.Groups) + { + List conditions = new List(); + //生成一个表达式,类似于 x=>x.Id != id,这是为了当修改数据时验证重复性的时候,排除当前正在修改的数据 + var idproperty = modelType.GetSingleProperty("ID"); + MemberExpression idLeft = Expression.Property(para, idproperty); + ConstantExpression idRight = Expression.Constant(entity.GetID()); + BinaryExpression idNotEqual = Expression.NotEqual(idLeft, idRight); + conditions.Add(idNotEqual); + List props = new List(); + //在每个组中循环所有字段 + foreach (var field in group.Fields) + { + Expression exp = field.GetExpression(entity, para); + if (exp != null) + { + conditions.Add(exp); + } + //将字段名保存,为后面生成错误信息作准备 + props.AddRange(field.GetProperties()); + } + int count = 0; + if (conditions.Count > 1) + { + //循环添加条件并生成Where语句 + Expression conExp = conditions[0]; + for (int i = 1; i < conditions.Count; i++) + { + conExp = Expression.And(conExp, conditions[i]); + } + + MethodCallExpression whereCallExpression = Expression.Call( + typeof(Queryable), + "Where", + new Type[] { modelType }, + baseExp.Expression, + Expression.Lambda>(conExp, new ParameterExpression[] { para })); + var result = baseExp.Provider.CreateQuery(whereCallExpression); + + foreach (var res in result) + { + count++; + } + } + if (count > 0) + { + return true; + } + } + } + return false; + } + + protected void ValidateDuplicateData(DuplicatedInfo

checkCondition, P entity) + { + if (checkCondition != null && checkCondition.Groups.Count > 0) + { + //生成基础Query + var baseExp = EntityList.AsQueryable(); + var modelType = typeof(P); + ParameterExpression para = Expression.Parameter(modelType, "tm"); + //循环所有重复字段组 + foreach (var group in checkCondition.Groups) + { + List conditions = new List(); + //生成一个表达式,类似于 x=>x.Id != id,这是为了当修改数据时验证重复性的时候,排除当前正在修改的数据 + var idproperty = modelType.GetSingleProperty("ExcelIndex"); + MemberExpression idLeft = Expression.Property(para, idproperty); + ConstantExpression idRight = Expression.Constant(entity.ExcelIndex); + BinaryExpression idNotEqual = Expression.NotEqual(idLeft, idRight); + conditions.Add(idNotEqual); + List props = new List(); + //在每个组中循环所有字段 + foreach (var field in group.Fields) + { + Expression exp = field.GetExpression(entity, para); + if (exp != null) + { + conditions.Add(exp); + } + //将字段名保存,为后面生成错误信息作准备 + props.AddRange(field.GetProperties()); + } + int count = 0; + if (conditions.Count > 1) + { + //循环添加条件并生成Where语句 + Expression whereCallExpression = baseExp.Expression; + for (int i = 0; i < conditions.Count; i++) + { + whereCallExpression = Expression.Call( + typeof(Queryable), + "Where", + new Type[] { modelType }, + whereCallExpression, + Expression.Lambda>(conditions[i], new ParameterExpression[] { para })); + } + var result = baseExp.Provider.CreateQuery(whereCallExpression); + + foreach (var res in result) + { + count++; + } + } + if (count > 0) + { + //循环拼接所有字段名 + string AllName = ""; + foreach (var prop in props) + { + string name = PropertyHelper.GetPropertyDisplayName(prop); + AllName += name + ","; + } + if (AllName.EndsWith(",")) + { + AllName = AllName.Remove(AllName.Length - 1); + } + //如果只有一个字段重复,则拼接形成 xxx字段重复 这种提示 + if (props.Count == 1) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Message = CoreProgram._localizer?["Sys.DuplicateError", AllName], Index = entity.ExcelIndex }); + } + //如果多个字段重复,则拼接形成 xx,yy,zz组合字段重复 这种提示 + else if (props.Count > 1) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Message = CoreProgram._localizer?["Sys.DuplicateGroupError", AllName], Index = entity.ExcelIndex }); + } + } + } + } + } + + + private void TryValidateObject(object model, ValidationContext context, ICollection results) + { + var modelType = model.GetType(); + foreach (var p in modelType.GetProperties()) + { + var propertyValue = p.GetValue(model); + TryValidateProperty(propertyValue, context, results, p); + } + } + + private void TryValidateProperty(object value, ValidationContext context, ICollection results, PropertyInfo propertyInfo = null) + { + var modelType = context.ObjectType; + if (propertyInfo == null) + { + propertyInfo = modelType.GetProperty(context.MemberName!); + } + + if (propertyInfo != null) + { + var rules = propertyInfo.GetCustomAttributes(true).Where(i => i.GetType().BaseType == typeof(ValidationAttribute)).Cast(); + var displayName = propertyInfo.GetPropertyDisplayName(); + var memberName = propertyInfo.Name; + foreach (var rule in rules) + { + if (!rule.IsValid(value)) + { + string errorMessage = "Error"; + if (!string.IsNullOrEmpty(rule.ErrorMessage)) + { + if (rule is RangeAttribute range) + { + if (range.Minimum != null && range.Maximum != null) + { + errorMessage = Wtm.Localizer[rule.ErrorMessage, displayName, range.Minimum, range.Maximum]; + } + else if (range.Minimum != null) + { + errorMessage = Wtm.Localizer[rule.ErrorMessage, displayName, range.Minimum]; + } + else if (range.Maximum != null) + { + errorMessage = Wtm.Localizer[rule.ErrorMessage, displayName, range.Maximum]; + } + } + else if (rule is StringLengthAttribute sl) + { + if (sl.MaximumLength > 0 && sl.MinimumLength > 0) + { + errorMessage = Wtm.Localizer[rule.ErrorMessage, displayName, sl.MinimumLength, sl.MaximumLength]; + } + else if (sl.MinimumLength > 0) + { + errorMessage = Wtm.Localizer[rule.ErrorMessage, displayName, sl.MinimumLength]; + } + else if (sl.MaximumLength > 0) + { + errorMessage = Wtm.Localizer[rule.ErrorMessage, displayName, sl.MaximumLength]; + } + } + else + { + errorMessage = Wtm.Localizer[rule.ErrorMessage, displayName]; + } + } + results.Add(new ValidationResult(errorMessage, new string[] { memberName })); + } + } + } + } + + + ///

+ /// 保存指定表中的数据 + /// + /// 成功返回True,失败返回False + public virtual bool BatchSaveData() + { + //删除不必要的附件 + if (DeletedFileIds != null && DeletedFileIds.Count > 0 && Wtm.ServiceProvider != null) + { + var fp = Wtm.ServiceProvider.GetRequiredService(); + + foreach (var item in DeletedFileIds) + { + fp.DeleteFile(item.ToString(), DC.ReCreate()); + } + } + + //进行赋值 + SetEntityList(); + foreach (var entity in EntityList) + { + var context = new ValidationContext(entity); + var validationResults = new List(); + TryValidateObject(entity, context, validationResults); + if (validationResults.Count > 0) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Message = validationResults.FirstOrDefault()?.ErrorMessage ?? "Error", ExcelIndex = entity.ExcelIndex, Index = entity.ExcelIndex }); + } + } + if (ErrorListVM.EntityList.Count > 0) + { + DoReInit(); + return false; + } + + //执行验证 + SetValidateCheck(); + if (ErrorListVM.EntityList.Count > 0) + { + DoReInit(); + return false; + } + + //循环数据列表 + List

ListAdd = new List

(); + foreach (var item in EntityList) + { + //根据唯一性的设定查找数据库中是否有同样的数据 + P exist = IsDuplicateData(item, finalInfo); + //如果设置了覆盖功能 + if (IsOverWriteExistData) + { + if (exist != null) + { + //如果有重复数据,则进行修改 + var tempPros = typeof(T).GetFields(); + foreach (var pro in tempPros) + { + var excelProp = Template.GetType().GetField(pro.Name).GetValue(Template) as ExcelPropety; + var proToSet = typeof(P).GetSingleProperty(excelProp.FieldName); + if (proToSet != null) + { + var val = proToSet.GetValue(item); + PropertyHelper.SetPropertyValue(exist, excelProp.FieldName, val, stringBasedValue: true); + try + { + DC.UpdateProperty(exist, proToSet.Name); + } + catch { } + } + } + + if (tempPros.Where(x => x.Name == "UpdateTime").SingleOrDefault() == null) + { + if (typeof(IBasePoco).IsAssignableFrom(exist.GetType())) + { + (exist as IBasePoco).UpdateTime = DateTime.Now; + DC.UpdateProperty(exist, "UpdateTime"); + } + } + + if (tempPros.Where(x => x.Name == "UpdateBy").SingleOrDefault() == null) + { + if (typeof(IBasePoco).IsAssignableFrom(exist.GetType())) + { + (exist as IBasePoco).UpdateBy = LoginUserInfo.ITCode; + DC.UpdateProperty(exist, "UpdateBy"); + } + } + exist.ExcelIndex = item.ExcelIndex; + //DC.UpdateEntity(exist); + + continue; + } + else + { + if (typeof(IPersistPoco).IsAssignableFrom(item.GetType())) + { + (item as IPersistPoco).IsValid = true; + } + } + } + else + { + if (exist == null) + { + if (typeof(IPersistPoco).IsAssignableFrom(item.GetType())) + { + (item as IPersistPoco).IsValid = true; + } + } + } + //进行添加操作 + if (typeof(IBasePoco).IsAssignableFrom(item.GetType())) + { + (item as IBasePoco).CreateTime = DateTime.Now; + (item as IBasePoco).CreateBy = LoginUserInfo?.ITCode; + } + //如果是SqlServer数据库,而且没有主子表功能,进行Bulk插入 + if (ConfigInfo.Connections.Where(x => x.Key == (CurrentCS ?? "default")).FirstOrDefault().DbType == DBTypeEnum.SqlServer && !HasSubTable && UseBulkSave == true) + { + ListAdd.Add(item); + } + else + { + DC.Set

().Add(item); + } + } + + if (ErrorListVM.EntityList.Count > 0) + { + DoReInit(); + return false; + } + + //如果没有错误,更新数据库 + if (EntityList.Count > 0) + { + try + { + DC.SaveChanges(); + + if (ListAdd.Count > 0) + { + BulkInsert

(DC, DC.GetTableName

(), ListAdd); + } + } + catch (Exception e) + { + SetExceptionMessage(e, null); + DoReInit(); + return false; + } + } + if (string.IsNullOrEmpty(UploadFileId) == false && Wtm.ServiceProvider != null) + { + var fp = Wtm.ServiceProvider.GetRequiredService(); + fp.DeleteFile(UploadFileId, DC.ReCreate()); + } + + return true; + } + + ///

+ /// 批量插入数据库操作,支持SqlServer + /// + /// + /// data context + /// + /// + protected static void BulkInsert(IDataContext dc, string tableName, IList list) + { + using (var bulkCopy = new SqlBulkCopy(dc.CSName)) + { + bulkCopy.BatchSize = list.Count; + bulkCopy.DestinationTableName = tableName; + + var table = new DataTable(); + var props = typeof(K).GetAllProperties().Distinct(x => x.Name); + + //生成Table的列 + foreach (var propertyInfo in props) + { + var notmapped = propertyInfo.GetCustomAttribute(); + var notobject = propertyInfo.PropertyType.Namespace.Equals("System") || propertyInfo.PropertyType.IsEnumOrNullableEnum(); + if (notmapped == null && notobject) + { + string Name = dc.GetFieldName(propertyInfo.Name); + bulkCopy.ColumnMappings.Add(Name, Name); + table.Columns.Add(Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType); + } + } + + //给Table赋值 + var values = new object[table.Columns.Count]; + foreach (var item in list) + { + var Index = 0; + foreach (var propertyInfo in props) + { + var notmapped = propertyInfo.GetCustomAttribute(); + var notobject = propertyInfo.PropertyType.Namespace.Equals("System") || propertyInfo.PropertyType.IsEnumOrNullableEnum(); + if (notmapped == null && notobject) + { + values[Index] = propertyInfo.GetValue(item); + Index++; + } + } + table.Rows.Add(values); + } + //检测是否有继承字段,如果存在,进行赋值 + string Discriminator = dc.GetFieldName("Discriminator"); + if (!string.IsNullOrEmpty(Discriminator)) + { + bulkCopy.ColumnMappings.Add("Discriminator", "Discriminator"); + table.Columns.Add("Discriminator", typeof(string)); + for (int i = 0; i < table.Rows.Count; i++) + { + table.Rows[i]["Discriminator"] = typeof(K).Name; + } + } + bulkCopy.WriteToServer(table); + } + } + #endregion + + #region 验证是否空行 + /// + /// 验证Excel中某行是否为空行 + /// + /// 行数 + /// 列数 + /// True代表空行,False代表非空行 + private bool IsEmptyRow(XSSFRow row, int colCount) + { + bool result = true; + for (int i = 0; i < colCount; i++) + { + string value = row.GetCell(i, MissingCellPolicy.CREATE_NULL_AS_BLANK).ToString(); + if (!string.IsNullOrEmpty(value)) + { + result = false; + break; + } + } + return result; + } + #endregion + + #region 复制Excel属性 + /// + /// 复制Excel属性 + /// + /// 单元格属性 + /// 复制后的单元格 + private ExcelPropety CopyExcelPropety(ExcelPropety excelPropety) + { + ExcelPropety ep = new ExcelPropety + { + BackgroudColor = excelPropety.BackgroudColor, + ColumnName = excelPropety.ColumnName, + DataType = excelPropety.DataType, + ResourceType = excelPropety.ResourceType, + IsNullAble = excelPropety.IsNullAble, + ListItems = excelPropety.ListItems, + MaxValuseOrLength = excelPropety.MaxValuseOrLength, + MinValueOrLength = excelPropety.MinValueOrLength, + Value = excelPropety.Value, + SubTableType = excelPropety.SubTableType, + CharCount = excelPropety.CharCount, + ReadOnly = excelPropety.ReadOnly, + FormatData = excelPropety.FormatData, + FormatSingleData = excelPropety.FormatSingleData, + FieldName = excelPropety.FieldName + }; + List li = new List(); + foreach (var item in excelPropety.DynamicColumns) + { + li.Add(CopyExcelPropety(item)); + } + ep.DynamicColumns = li; + return ep; + } + #endregion + + #region 设置异常信息 + /// + /// 设置错误信息 + /// + /// 异常 + /// 数据Id + protected void SetExceptionMessage(Exception e, long? id) + { + //检查是否为数据库操作错误 + if (e is DbUpdateException) + { + var de = e as DbUpdateException; + if (de.Entries != null) + { + if (de.Entries.Count == 0) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Index = 0, Message = e.Message + e.InnerException?.Message }); + } + //循环此错误相关的数据 + foreach (var ent in de.Entries) + { + //获取错误数据Id + var errorId = (long)((ent.Entity as TopBasePoco).ExcelIndex); + //根据State判断修改或删除操作,输出不同的错误信息 + if (ent.State == EntityState.Deleted) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Index = errorId, Message = CoreProgram._localizer?["Sys.DataCannotDelete"] }); + } + else if (ent.State == EntityState.Modified) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Index = errorId, Message = CoreProgram._localizer?["Sys.EditFailed"] }); + } + else + { + ErrorListVM.EntityList.Add(new ErrorMessage { Index = errorId, Message = de.Message }); + } + } + } + } + //对于其他类型的错误,直接添加错误信息 + else + { + if (id != null) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Index = id.Value, Message = e.Message }); + } + else + { + ErrorListVM.EntityList.Add(new ErrorMessage { Index = 0, Message = e.Message }); + } + } + } + #endregion + + #region 验证数据重复 + + /// + /// 判断数据是否在库中存在重复数据 + /// + /// 要验证的数据 + /// 验证表达式 + /// null代表没有重复 + protected P IsDuplicateData(P Entity, DuplicatedInfo

checkCondition) + { + //获取设定的重复字段信息 + if (checkCondition != null && checkCondition.Groups.Count > 0) + { + //生成基础Query + var baseExp = DC.Set

().AsQueryable(); + var modelType = typeof(P); + ParameterExpression para = Expression.Parameter(modelType, "tm"); + //循环所有重复字段组 + foreach (var group in checkCondition.Groups) + { + List conditions = new List(); + //生成一个表达式,类似于 x=>x.Id != id,这是为了当修改数据时验证重复性的时候,排除当前正在修改的数据 + //在每个组中循环所有字段 + List props = new List(); + //在每个组中循环所有字段 + foreach (var field in group.Fields) + { + Expression exp = field.GetExpression(Entity, para); + if (exp != null) + { + conditions.Add(exp); + } + //将字段名保存,为后面生成错误信息作准备 + props.AddRange(field.GetProperties()); + } + + if (conditions.Count > 0) + { + //循环添加条件并生成Where语句 + Expression whereCallExpression = baseExp.Expression; + for (int i = 0; i < conditions.Count; i++) + { + whereCallExpression = Expression.Call( + typeof(Queryable), + "Where", + new Type[] { modelType }, + whereCallExpression, + Expression.Lambda>(conditions[i], new ParameterExpression[] { para })); + } + var result = baseExp.Provider.CreateQuery(whereCallExpression); + + + foreach (var res in result) + { + if (IsOverWriteExistData == false) + { + //循环拼接所有字段名 + string AllName = ""; + foreach (var prop in props) + { + string name = PropertyHelper.GetPropertyDisplayName(prop); + AllName += name + ","; + } + if (AllName.EndsWith(",")) + { + AllName = AllName.Remove(AllName.Length - 1); + } + //如果只有一个字段重复,则拼接形成 xxx字段重复 这种提示 + if (props.Count == 1) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Message = CoreProgram._localizer?["Sys.DuplicateError", AllName], Index = Entity.ExcelIndex }); + } + //如果多个字段重复,则拼接形成 xx,yy,zz组合字段重复 这种提示 + else if (props.Count > 1) + { + ErrorListVM.EntityList.Add(new ErrorMessage { Message = CoreProgram._localizer?["Sys.DuplicateGroupError", AllName], Index = Entity.ExcelIndex }); + } + + } + return res as P; + } + } + } + } + return null; + } + #endregion + + protected DuplicatedInfo

CreateFieldsInfo(params DuplicatedField

[] FieldExps) + { + DuplicatedInfo

d = new DuplicatedInfo

(); + d.AddGroup(FieldExps); + return d; + } + + ///

+ /// 创建一个简单重复数据信息 + /// + /// 重复数据的字段 + /// 重复数据信息 + public static DuplicatedField

SimpleField(Expression> FieldExp) + { + return new DuplicatedField

(FieldExp); + } + + ///

+ /// 创建一个关联到其他表数组中数据的重复信息 + /// + /// 关联表类 + /// 指向关联表类数组的Lambda + /// 指向最终字段的Lambda + /// 重复数据信息 + public static DuplicatedField

SubField(Expression>> MiddleExp, params Expression>[] FieldExps) + { + return new ComplexDuplicatedField(MiddleExp, FieldExps); + } + + public ErrorObj GetErrorJson() + { + var mse = new ErrorObj(); + mse.Form = new Dictionary(); + var err = ErrorListVM?.EntityList?.Where(x => x.Index == 0).FirstOrDefault()?.Message; + if (string.IsNullOrEmpty(err)) + { + Models.IWtmFile fa = null; + if(Wtm.ServiceProvider == null) { + return mse; + } + var fp = Wtm.ServiceProvider.GetRequiredService(); + fa = fp.GetFile(UploadFileId, true, DC); + xssfworkbook = new XSSFWorkbook(fa.DataStream); + fa.DataStream.Dispose(); + var propetys = Template.GetType().GetFields().Where(x => x.FieldType == typeof(ExcelPropety)).ToList(); + List excelPropetys = new List(); + for (int porpetyIndex = 0; porpetyIndex < propetys.Count(); porpetyIndex++) + { + ExcelPropety ep = (ExcelPropety)propetys[porpetyIndex].GetValue(Template); + excelPropetys.Add(ep); + } + int columnCount = excelPropetys.Count; + //int excelPropetyCount = excelPropetys.Count; + var dynamicColumn = excelPropetys.Where(x => x.DataType == ColumnDataType.Dynamic).FirstOrDefault(); + if (dynamicColumn != null) + { + columnCount = columnCount + dynamicColumn.DynamicColumns.Count - 1; + } + ISheet sheet = xssfworkbook.GetSheetAt(0); + var errorStyle = xssfworkbook.CreateCellStyle(); + IFont f = xssfworkbook.CreateFont(); + f.Color = HSSFColor.Red.Index; + errorStyle.SetFont(f); + errorStyle.IsLocked = true; + foreach (var e in ErrorListVM?.EntityList) + { + if (e.Index > 0) + { + var c = sheet.GetRow((int)(e.Index - 1)).CreateCell(columnCount); + c.CellStyle = errorStyle; + c.SetCellValue(e.Message); + } + } + MemoryStream ms = new MemoryStream(); + xssfworkbook.Write(ms); + ms.Position = 0; + + var newfile = fp.Upload("Error-" + fa.FileName, ms.Length, ms); + ms.Close(); + ms.Dispose(); + err = CoreProgram._localizer?["Sys.ImportError"]; + mse.Form.Add("Entity.Import", err); + mse.Form.Add("Entity.ErrorFileId", newfile.GetID()); + } + else + { + mse.Form.Add("Entity.Import", err); + } + return mse; + } + } + + #region 辅助类 + public class ErrorMessage : TopBasePoco + { + [Display(Name = "Sys.RowIndex")] + public long Index { get; set; } + + [Display(Name = "Sys.CellIndex")] + public long Cell { get; set; } + [Display(Name = "Sys.ErrorMsg")] + public string Message { get; set; } + } + + ///

+ /// 错误数据列表 + /// + public class TemplateErrorListVM : BasePagedListVM + { + + public TemplateErrorListVM() + { + EntityList = new List(); + NeedPage = false; + } + + protected override IEnumerable> InitGridHeader() + { + return new List>{ + this.MakeGridHeader(x => x.Index, 60), + this.MakeGridHeader(x => x.Message) + }; + } + + public override IOrderedQueryable GetSearchQuery() + { + return EntityList.AsQueryable().OrderBy(x => x.Index); + } + } + + #endregion + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BasePagedListVM.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BasePagedListVM.cs new file mode 100644 index 0000000..42ef418 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BasePagedListVM.cs @@ -0,0 +1,1228 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.Data; +using System.Data.Common; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; +using Microsoft.Data.SqlClient; +using Microsoft.EntityFrameworkCore; +using MySqlConnector; +using Npgsql; +using NpgsqlTypes; +using NPOI.HSSF.Util; +using NPOI.SS.UserModel; +using NPOI.SS.Util; +using NPOI.XSSF.UserModel; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Core +{ + public delegate object ColumnFormatCallBack(T entity, object fieldValue) where T : TopBasePoco; + + /// + /// ListVM的搜索模式枚举 + /// + public enum ListVMSearchModeEnum + { + Search, //搜索 + Export, //导出 + Batch, //批量 + Selector,//选择器 + MasterDetail, // + CheckExport, + Custom1, Custom2, Custom3, Custom4, Custom5 + }; + + /// + /// ListVM的基类,所有ListVM应该继承这个类, 基类提供了搜索,导出等列表常用功能 + /// + /// ListVM中的Model类 + /// ListVM使用的Searcher类 + public class BasePagedListVM : BaseVM, IBasePagedListVM + where TModel : TopBasePoco + where TSearcher : BaseSearcher + { + + + [JsonIgnore] + public string TotalText { get; set; } = CoreProgram._localizer?["Sys.Total"]; + + public virtual DbCommand GetSearchCommand() + { + return null; + } + + private int? _childrenDepth; + + + /// + /// 多级表头深度 默认 1级 + /// + public int GetChildrenDepth() + { + if (_childrenDepth == null) + { + _childrenDepth = _getHeaderDepth(); + } + return _childrenDepth.Value; + } + + /// + /// GridHeaders + /// + [JsonIgnore] + private IEnumerable> GridHeaders { get; set; } + + /// + /// GetHeaders + /// + /// + public IEnumerable> GetHeaders() + { + if (GridHeaders == null) + { + GridHeaders = InitGridHeader(); + } + return GridHeaders; + } + + /// + /// 计算多级表头深度 + /// + /// + private int _getHeaderDepth() + { + IEnumerable> headers = GetHeaders(); + return headers.Max(x => x.MaxDepth); + } + + private List _gridActions; + + /// + /// 页面动作 + /// + public List GetGridActions() + { + if (_gridActions == null) + { + _gridActions = InitGridAction(); + } + return _gridActions; + } + + /// + /// 初始化 InitGridHeader,继承的类应该重载这个函数来设定数据的列和动作 + /// + protected virtual IEnumerable> InitGridHeader() + { + return new List>(); + } + + protected virtual List InitGridAction() + { + return new List(); + } + + #region GenerateExcel + + /// + /// 生成Excel + /// + /// 生成的Excel文件 + public virtual byte[] GenerateExcel() + { + NeedPage = false; + + //获取导出的表头 + if (GridHeaders == null) + { + GetHeaders(); + } + + //去掉ID列和Action列 + RemoveActionAndIdColumn(); + + //如果没有数据源,进行查询 + if (IsSearched == false) + { + DoSearch(); + } + + //获取分成Excel的个数 + ExportMaxCount = ExportMaxCount == 0 ? 1000000 : (ExportMaxCount > 1000000 ? 1000000 : ExportMaxCount); + ExportExcelCount = EntityList.Count < ExportMaxCount ? 1 : ((EntityList.Count % ExportMaxCount) == 0 ? (EntityList.Count / ExportMaxCount) : (EntityList.Count / ExportMaxCount + 1)); + + //如果是1,直接下载Excel,如果是多个,下载ZIP包 + if (ExportExcelCount == 1) + { + return DownLoadExcel(); + } + else + { + return DownLoadZipPackage(typeof(TModel).Name + "_" + DateTime.Now.ToString("yyyyMMddHHmmssffff")); + } + } + + /// + /// 根据集合生成单个Excel + /// + /// + /// + private IWorkbook GenerateWorkBook(List List) + { + IWorkbook book = new XSSFWorkbook(); + ISheet sheet = book.CreateSheet(); + IRow row = sheet.CreateRow(0); + + //创建表头样式 + ICellStyle headerStyle = book.CreateCellStyle(); + headerStyle.FillBackgroundColor = ExportTitleBackColor == null ? HSSFColor.LightBlue.Index : ExportTitleBackColor.Value; + headerStyle.FillPattern = FillPattern.SolidForeground; + headerStyle.FillForegroundColor = ExportTitleBackColor == null ? HSSFColor.LightBlue.Index : ExportTitleBackColor.Value; + headerStyle.BorderBottom = BorderStyle.Thin; + headerStyle.BorderTop = BorderStyle.Thin; + headerStyle.BorderLeft = BorderStyle.Thin; + headerStyle.BorderRight = BorderStyle.Thin; + IFont font = book.CreateFont(); + font.FontName = "Calibri"; + font.FontHeightInPoints = 12; + font.Color = ExportTitleFontColor == null ? HSSFColor.Black.Index : ExportTitleFontColor.Value; + headerStyle.SetFont(font); + + ICellStyle cellStyle = book.CreateCellStyle(); + cellStyle.BorderBottom = BorderStyle.Thin; + cellStyle.BorderTop = BorderStyle.Thin; + cellStyle.BorderLeft = BorderStyle.Thin; + cellStyle.BorderRight = BorderStyle.Thin; + + //生成表头 + int max = MakeExcelHeader(sheet, GridHeaders, 0, 0, headerStyle); + + //放入数据 + var ColIndex = 0; + for (int i = 0; i < List.Count; i++) + { + ColIndex = 0; + var DR = sheet.CreateRow(i + max); + foreach (var baseCol in GridHeaders) + { + foreach (var col in baseCol.BottomChildren) + { + //处理枚举变量的多语言 + bool IsEmunBoolParp = false; + var proType = col.FieldType; + if (proType.IsEnumOrNullableEnum()) + { + IsEmunBoolParp = true; + } //获取数据,并过滤特殊字符 + string text = Regex.Replace(col.GetText(List[i]).ToString(), @"<[^>]*>", String.Empty); + + //处理枚举变量的多语言 + if (IsEmunBoolParp) + { + string enumdisplay = PropertyHelper.GetEnumDisplayName(proType, text); + if (string.IsNullOrEmpty(enumdisplay) == false) + { + text = enumdisplay; + } + + else + { + if (int.TryParse(text, out int enumvalue)) + { + text = PropertyHelper.GetEnumDisplayName(proType, enumvalue); + } + } + } + + //建立excel单元格 + ICell cell; + if (col.FieldType?.IsNumber() == true) + { + cell = DR.CreateCell(ColIndex, CellType.Numeric); + try + { + cell.SetCellValue(Convert.ToDouble(text)); + } + catch { } + } + else + { + cell = DR.CreateCell(ColIndex); + cell.SetCellValue(text); + } + cell.CellStyle = cellStyle; + ColIndex++; + } + } + } + return book; + } + + private byte[] DownLoadExcel() + { + var book = GenerateWorkBook(EntityList); + byte[] rv = new byte[] { }; + using (MemoryStream ms = new MemoryStream()) + { + book.Write(ms); + rv = ms.ToArray(); + } + return rv; + } + + private byte[] DownLoadZipPackage(string FileName) + { + //文件根目录 + string RootPath = $"{Directory.GetCurrentDirectory()}\\{FileName}"; + + //文件夹目录 + string FilePath = $"{RootPath}//FileFolder"; + + //压缩包目录 + string ZipPath = $"{RootPath}//{FileName}.zip"; + + //打开文件夹 + DirectoryInfo FileFolder = new DirectoryInfo(FilePath); + if (!FileFolder.Exists) + { + //创建文件夹 + FileFolder.Create(); + } + else + { + //清空文件夹 + FileSystemInfo[] Files = FileFolder.GetFileSystemInfos(); + foreach (var item in Files) + { + if (item is DirectoryInfo) + { + DirectoryInfo Directory = new DirectoryInfo(item.FullName); + Directory.Delete(true); + } + else + { + File.Delete(item.FullName); + } + } + } + + //放入数据 + for (int i = 0; i < ExportExcelCount; i++) + { + var List = EntityList.Skip(i * ExportMaxCount).Take(ExportMaxCount).ToList(); + var WorkBook = GenerateWorkBook(List); + string SavePath = $"{FilePath}/{FileName}_{i + 1}.xlsx"; + using (FileStream FS = new FileStream(SavePath, FileMode.CreateNew)) + { + WorkBook.Write(FS); + } + } + + //生成压缩包 + ZipFile.CreateFromDirectory(FilePath, ZipPath); + + //读取压缩包 + FileStream ZipFS = new FileStream(ZipPath, FileMode.Open, FileAccess.Read); + byte[] bt = new byte[ZipFS.Length]; + ZipFS.Read(bt, 0, bt.Length); + ZipFS.Close(); + + //删除根目录文件夹 + DirectoryInfo RootFolder = new DirectoryInfo(RootPath); + if (RootFolder.Exists) + { + RootFolder.Delete(true); + } + + return bt; + } + + /// + /// 生成Excel的表头 + /// + /// + /// + /// + /// + /// + /// + private int MakeExcelHeader(ISheet sheet, IEnumerable> cols, int rowIndex, int colIndex, ICellStyle style) + { + var row = sheet.GetRow(rowIndex); + if (row == null) + { + row = sheet.CreateRow(rowIndex); + } + int maxLevel = cols.Select(x => x.MaxLevel).Max(); + //循环所有列 + foreach (var col in cols) + { + //添加新单元格 + var cell = row.CreateCell(colIndex); + cell.CellStyle = style; + cell.SetCellValue(col.Title); + var bcount = col.BottomChildren.Count(); + var rowspan = 0; + if (rowIndex >= 0) + { + rowspan = maxLevel - col.MaxLevel; + } + var cellRangeAddress = new CellRangeAddress(rowIndex, rowIndex + rowspan, colIndex, colIndex + bcount - 1); + sheet.AddMergedRegion(cellRangeAddress); + if (rowspan > 0 || bcount > 1) + { + cell.CellStyle.Alignment = HorizontalAlignment.Center; + cell.CellStyle.VerticalAlignment = VerticalAlignment.Center; + } + for (int i = cellRangeAddress.FirstRow; i <= cellRangeAddress.LastRow; i++) + { + IRow r = CellUtil.GetRow(i, sheet); + for (int j = cellRangeAddress.FirstColumn; j <= cellRangeAddress.LastColumn; j++) + { + ICell c = CellUtil.GetCell(r, (short)j); + c.CellStyle = style; + } + } + if (col.Children != null && col.Children.Count() > 0) + { + MakeExcelHeader(sheet, col.Children, rowIndex + rowspan + 1, colIndex, style); + } + colIndex += bcount; + } + return maxLevel; + } + + #endregion + + #region Old + public SortInfo CreateSortInfo(Expression> pro, SortDir dir) + { + SortInfo rv = new SortInfo + { + Property = PropertyHelper.GetPropertyName(pro), + Direction = dir + }; + return rv; + } + + /// + /// InitList后触发的事件 + /// + public event Action> OnAfterInitList; + + /// + ///记录批量操作时列表中选择的Id + /// + public List Ids { get; set; } + public string SelectorValueField { get; set; } + /// + /// 是否已经搜索过 + /// + [JsonIgnore] + public bool IsSearched { get; set; } + + [JsonIgnore] + public bool PassSearch { get; set; } + /// + /// 查询模式 + /// + [JsonIgnore] + public ListVMSearchModeEnum SearcherMode { get; set; } + + /// + /// 是否需要分页 + /// + [JsonIgnore] + public bool NeedPage { get; set; } + + /// + /// 允许导出Excel的最大行数,超过行数会分成多个文件,最多不能超过100万 + /// + [JsonIgnore] + public int ExportMaxCount { get; set; } + + /// + /// 根据允许导出的Excel最大行数,算出最终导出的Excel个数 + /// + [JsonIgnore] + public int ExportExcelCount { get; set; } + + /// + /// 导出文件第一行背景颜色,使用HSSFColor,例如:HSSFColor.Red.Index + /// + [JsonIgnore] + public short? ExportTitleBackColor { get; set; } + + /// + /// 导出文件第一行文字颜色,使用HSSFColor,例如:HSSFColor.Red.Index + /// + [JsonIgnore] + public short? ExportTitleFontColor { get; set; } + + /// + /// 数据列表 + /// + [JsonIgnore] + public List EntityList { get; set; } + + + /// + /// 搜索条件 + /// + [JsonIgnore] + public TSearcher Searcher { get; set; } + + /// + /// 使用 VM 的 Id 来生成 SearcherDiv 的 Id + /// + [JsonIgnore] + public string SearcherDivId + { + get { return this.UniqueId + "Searcher"; } + } + + + /// + /// 替换查询条件,如果被赋值,则列表会使用里面的Lambda来替换原有Query里面的Where条件 + /// + [JsonIgnore()] + public Expression ReplaceWhere { get; set; } + + /// + /// 构造函数 + /// + public BasePagedListVM() + { + //默认需要分页 + NeedPage = true; + //初始化数据列表 + EntityList = new List(); + //初始化搜索条件 + Searcher = typeof(TSearcher).GetConstructor(Type.EmptyTypes).Invoke(null) as TSearcher; + } + + /// + /// 获取数据列表 + /// + /// 数据列表 + public IEnumerable GetEntityList() + { + if (IsSearched == false && (EntityList == null || EntityList.Count == 0)) + { + DoSearch(); + } + return EntityList?.AsEnumerable(); + } + + + /// + /// 调用InitListVM并触发OnAfterInitList事件 + /// + public void DoInitListVM() + { + InitListVM(); + OnAfterInitList?.Invoke(this); + } + + + /// + /// 初始化ListVM,继承的类应该重载这个函数来设定数据的列和动作 + /// + protected virtual void InitListVM() + { + } + + public virtual bool GetIsSelected(object item) + { + return false; + } + + public override void Validate() + { + Searcher?.Validate(); + base.Validate(); + } + + /// + /// 设定行前景色,继承的类应重载这个函数来根据每行的数据显示不同的前景色 + /// + /// 数据 + /// 前景颜色 + public virtual string SetFullRowColor(object entity) + { + return ""; + } + + /// + /// 设定行背景色,继承的类应重载这个函数来根据每行的数据显示不同的背景色 + /// + /// 数据 + /// 背景颜色 + public virtual string SetFullRowBgColor(object entity) + { + return ""; + } + + /// + /// 设定搜索语句,继承的类应该重载这个函数来指定自己的搜索语句 + /// + /// 搜索语句 + public virtual IOrderedQueryable GetSearchQuery() + { + return DC.Set().OrderByDescending(x => x.ID); + } + + /// + /// 设定导出时搜索语句,继承的类应该重载这个函数来指定自己导出时的搜索语句,如不指定则默认和搜索用的搜索语句相同 + /// + /// 搜索语句 + public virtual IOrderedQueryable GetExportQuery() + { + return GetSearchQuery(); + } + + /// + /// 设定搜索语句,继承的类应该重载这个函数来指定自己导出时的搜索语句,如不指定则默认和搜索用的搜索语句相同 + /// + /// 搜索语句 + public virtual IOrderedQueryable GetSelectorQuery() + { + return GetSearchQuery(); + } + + /// + /// 设定勾选后导出的搜索语句,继承的类应该重载这个函数来指定自己导出时的搜索语句,如不指定则默认和搜索用的搜索语句相同 + /// + /// 搜索语句 + public virtual IOrderedQueryable GetCheckedExportQuery() + { + var baseQuery = GetBatchQuery(); + return baseQuery; + } + + /// + /// 设定批量模式下的搜索语句,继承的类应重载这个函数来指定自己批量模式的搜索语句,如果不指定则默认使用Ids.Contains(x.Id)来代替搜索语句中的Where条件 + /// + /// 搜索语句 + public virtual IOrderedQueryable GetBatchQuery() + { + var baseQuery = GetSearchQuery(); + if (ReplaceWhere == null) + { + var mod = new WhereReplaceModifier(Ids.GetContainIdExpression()); + var newExp = mod.Modify(baseQuery.Expression); + var newQuery = baseQuery.Provider.CreateQuery(newExp) as IOrderedQueryable; + return newQuery; + } + else + { + return baseQuery; + } + } + + /// + /// 设定主从模式的搜索语句,继承的类应该重载这个函数来指定自己主从模式的搜索语句,如不指定则默认和搜索用的搜索语句相同 + /// + /// 搜索语句 + public virtual IOrderedQueryable GetMasterDetailsQuery() + { + return GetSearchQuery(); + } + + /// + /// 进行搜索 + /// + public virtual void DoSearch() + { + var cmd = GetSearchCommand(); + if (cmd == null) + { + IOrderedQueryable query = null; + //根据搜索模式调用不同的函数 + switch (SearcherMode) + { + case ListVMSearchModeEnum.Search: + query = GetSearchQuery(); + break; + case ListVMSearchModeEnum.Export: + query = GetExportQuery(); + break; + case ListVMSearchModeEnum.Batch: + query = GetBatchQuery(); + break; + case ListVMSearchModeEnum.MasterDetail: + query = GetMasterDetailsQuery(); + break; + case ListVMSearchModeEnum.CheckExport: + query = GetCheckedExportQuery(); + break; + case ListVMSearchModeEnum.Selector: + query = GetSelectorQuery(); + break; + default: + query = GetSearchQuery(); + break; + } + + //如果设定了替换条件,则使用替换条件替换Query中的Where语句 + if (ReplaceWhere != null) + { + var mod = new WhereReplaceModifier(ReplaceWhere as Expression>); + var newExp = mod.Modify(query.Expression); + query = query.Provider.CreateQuery(newExp) as IOrderedQueryable; + } + if (Searcher.SortInfo != null) + { + var mod = new OrderReplaceModifier(Searcher.SortInfo); + var newExp = mod.Modify(query.Expression); + query = query.Provider.CreateQuery(newExp) as IOrderedQueryable; + } + if (typeof(IPersistPoco).IsAssignableFrom( typeof(TModel))) + { + var mod = new IsValidModifier(); + var newExp = mod.Modify(query.Expression); + query = query.Provider.CreateQuery(newExp) as IOrderedQueryable; + } + if (PassSearch == false) + { + //如果需要分页,则添加分页语句 + if (NeedPage && Searcher.Limit != -1) + { + //获取返回数据的数量 + var count = query.Count(); + if (count < 0) + { + count = 0; + } + if (Searcher.Limit == 0) + { + Searcher.Limit = ConfigInfo?.UIOptions.DataTable.RPP ?? 20; + } + //根据返回数据的数量,以及预先设定的每页行数来设定数据量和总页数 + Searcher.Count = count; + Searcher.PageCount = (int)Math.Ceiling((1.0 * Searcher.Count / Searcher.Limit)); + if (Searcher.Page <= 0) + { + Searcher.Page = 1; + } + if (Searcher.PageCount > 0 && Searcher.Page > Searcher.PageCount) + { + Searcher.Page = Searcher.PageCount; + } + EntityList = query.Skip((Searcher.Page - 1) * Searcher.Limit).Take(Searcher.Limit).AsNoTracking().ToList(); + } + else //如果不需要分页则直接获取数据 + { + EntityList = query.AsNoTracking().ToList(); + Searcher.Count = EntityList.Count(); + Searcher.Limit = EntityList.Count(); + Searcher.PageCount = 1; + Searcher.Page = 1; + } + } + else + { + EntityList = query.AsNoTracking().ToList(); + } + } + else + { + ProcessCommand(cmd); + } + IsSearched = true; + //调用AfterDoSearch函数来处理自定义的后续操作 + AfterDoSearcher(); + } + + + private void ProcessCommand(DbCommand cmd) + { + object total; + + if (Searcher.Page <= 0) + { + Searcher.Page = 1; + } + if (DC.Database.IsMySql()) + { + List parms = new List(); + foreach (MySqlParameter item in cmd.Parameters) + { + parms.Add(new MySqlParameter(string.Format("@{0}", item.ParameterName), item.Value)); + } + if (cmd.CommandType == CommandType.StoredProcedure) + { + parms.Add(new MySqlParameter("@SearchMode", Enum.GetName(typeof(ListVMSearchModeEnum), SearcherMode))); + parms.Add(new MySqlParameter("@NeedPage", (NeedPage && Searcher.Limit != -1))); + parms.Add(new MySqlParameter("@CurrentPage", Searcher.Page)); + parms.Add(new MySqlParameter("@RecordsPerPage", Searcher.Limit)); + parms.Add(new MySqlParameter("@Sort", Searcher.SortInfo?.Property)); + parms.Add(new MySqlParameter("@SortDir", Searcher.SortInfo?.Direction)); + parms.Add(new MySqlParameter("@IDs", Ids == null ? "" : Ids.ToSepratedString())); + + MySqlParameter outp = new MySqlParameter("@TotalRecords", MySqlDbType.Int64) + { + Value = 0, + Direction = ParameterDirection.Output + }; + parms.Add(outp); + } + var pa = parms.ToArray(); + + EntityList = DC.Run(cmd.CommandText, cmd.CommandType, pa).ToList(); + if (cmd.CommandType == CommandType.StoredProcedure) + { + total = pa.Last().Value; + } + else + { + total = EntityList.Count; + } + } + else if (DC.Database.IsNpgsql()) + { + List parms = new List(); + foreach (NpgsqlParameter item in cmd.Parameters) + { + parms.Add(new NpgsqlParameter(string.Format("@{0}", item.ParameterName), item.Value)); + } + + if (cmd.CommandType == CommandType.StoredProcedure) + { + parms.Add(new NpgsqlParameter("@SearchMode", Enum.GetName(typeof(ListVMSearchModeEnum), SearcherMode))); + parms.Add(new NpgsqlParameter("@NeedPage", (NeedPage && Searcher.Limit != -1))); + parms.Add(new NpgsqlParameter("@CurrentPage", Searcher.Page)); + parms.Add(new NpgsqlParameter("@RecordsPerPage", Searcher.Limit)); + parms.Add(new NpgsqlParameter("@Sort", Searcher.SortInfo?.Property)); + parms.Add(new NpgsqlParameter("@SortDir", Searcher.SortInfo?.Direction)); + parms.Add(new NpgsqlParameter("@IDs", Ids == null ? "" : Ids.ToSepratedString())); + + NpgsqlParameter outp = new NpgsqlParameter("@TotalRecords", NpgsqlDbType.Bigint) + { + Value = 0, + Direction = ParameterDirection.Output + }; + parms.Add(outp); + } + var pa = parms.ToArray(); + + EntityList = DC.Run(cmd.CommandText, cmd.CommandType, pa).ToList(); + if (cmd.CommandType == CommandType.StoredProcedure) + { + total = pa.Last().Value; + } + else + { + total = EntityList.Count; + } + } + else + { + List parms = new List(); + foreach (SqlParameter item in cmd.Parameters) + { + parms.Add(new SqlParameter(string.Format("@{0}", item.ParameterName), item.Value)); + } + if (cmd.CommandType == CommandType.StoredProcedure) + { + + parms.Add(new SqlParameter("@SearchMode", Enum.GetName(typeof(ListVMSearchModeEnum), SearcherMode))); + parms.Add(new SqlParameter("@NeedPage", (NeedPage && Searcher.Limit != -1))); + parms.Add(new SqlParameter("@CurrentPage", Searcher.Page)); + parms.Add(new SqlParameter("@RecordsPerPage", Searcher.Limit)); + parms.Add(new SqlParameter("@Sort", Searcher.SortInfo?.Property)); + parms.Add(new SqlParameter("@SortDir", Searcher.SortInfo?.Direction)); + parms.Add(new SqlParameter("@IDs", Ids == null ? "" : Ids.ToSepratedString())); + + SqlParameter outp = new SqlParameter("@TotalRecords", 0) + { + Direction = ParameterDirection.Output + }; + parms.Add(outp); + } + var pa = parms.ToArray(); + + EntityList = DC.Run(cmd.CommandText, cmd.CommandType, pa).ToList(); + if (cmd.CommandType == CommandType.StoredProcedure) + { + total = pa.Last().Value; + } + else + { + total = EntityList.Count; + } + + } + if (NeedPage && Searcher.Limit != -1) + { + if (total != null) + { + try + { + Searcher.Count = long.Parse(total.ToString()); + Searcher.PageCount = (int)((Searcher.Count - 1) / Searcher.Limit + 1); + } + catch { } + } + } + else + { + Searcher.PageCount = EntityList.Count; + } + + } + + public DateTime AddTime(DateTime dt, string type, int size) + { + switch (type) + { + case "year": + return dt.AddYears(size); + case "month": + return dt.AddMonths(size); + case "day": + return dt.AddDays(size); + case "hour": + return dt.AddHours(size); + case "minute": + return dt.AddMinutes(size); + case "second": + return dt.AddSeconds(size); + default: + return dt; + } + } + + /// + /// 搜索后运行的函数,继承的类如果需要在搜索结束后进行其他操作,可重载这个函数 + /// + public virtual void AfterDoSearcher() + { + if (SearcherMode == ListVMSearchModeEnum.Selector && Ids != null && Ids.Count > 0 && EntityList != null && EntityList.Count > 0) + { + foreach (var item in EntityList) + { + if (string.IsNullOrEmpty(SelectorValueField) || SelectorValueField.ToLower() == "id") + { + var id = item.GetID(); + if (Ids.Contains(id.ToString())) + { + item.Checked = true; + } + } + else + { + var v = item.GetPropertyValue(SelectorValueField); + if (Ids.Contains(v.ToString())) + { + item.Checked = true; + } + } + } + } + } + + /// + /// 删除所有ActionGridColumn的列 + /// + public void RemoveActionColumn(object root = null) + { + if (root == null) + { + if (GridHeaders == null) + { + GetHeaders(); + } + root = GridHeaders; + } + if (root != null) + { + //IEnumerable> + var aroot = root as List>; + var toRemove = aroot.Where(x => x.ColumnType == GridColumnTypeEnum.Action).FirstOrDefault(); + aroot.Remove(toRemove); + foreach (var child in aroot) + { + if (child.Children != null && child.Children.Count() > 0) + { + RemoveActionColumn(child.Children); + } + } + } + } + + public void RemoveAction() + { + _gridActions = new List(); + } + + public void RemoveActionAndIdColumn(IEnumerable> root = null) + { + if (root == null) + { + if (GridHeaders == null) + { + GetHeaders(); + } + root = GridHeaders; + } + if (root != null) + { + var aroot = root as List>; + List> remove = null; + var idpro = typeof(TModel).GetSingleProperty("ID")?.PropertyType; + if (idpro == typeof(string)) + { + remove = aroot.Where(x => x.ColumnType == GridColumnTypeEnum.Action || x.Hide == true || x.DisableExport).ToList(); + } + else + { + remove = aroot.Where(x => x.ColumnType == GridColumnTypeEnum.Action || x.Hide == true || x.DisableExport || x.FieldName?.ToLower() == "id").ToList(); + } + foreach (var item in remove) + { + aroot.Remove(item); + } + foreach (var child in root) + { + if (child.Children != null && child.Children.Count() > 0) + { + RemoveActionAndIdColumn(child.Children); + } + } + } + } + + + /// + /// 添加Error列,主要为批量模式使用 + /// + public void AddErrorColumn() + { + GetHeaders(); + //寻找所有Header为错误信息的列,如果没有则添加 + if (GridHeaders.Where(x => x.Field == "BatchError").FirstOrDefault() == null) + { + var temp = GridHeaders as List>; + if (temp.Where(x => x.ColumnType == GridColumnTypeEnum.Action).FirstOrDefault() == null) + { + temp.Add(this.MakeGridColumn(x => x.BatchError, Width: 200, Header: Core.CoreProgram._localizer?["Sys.Error"]).SetForeGroundFunc(x => "ff0000").SetFixed(GridColumnFixedEnum.Right)); + } + else + { + temp.Insert(temp.Count - 1, this.MakeGridColumn(x => x.BatchError, Width: 200, Header: Core.CoreProgram._localizer?["Sys.Error"]).SetForeGroundFunc(x => "ff0000").SetFixed(GridColumnFixedEnum.Right)); + } + } + } + + public void ProcessListError(List Entities) + { + if(Entities == null) + { + return; + } + EntityList = Entities; + IsSearched = true; + bool haserror = false; + List keys = new List(); + if (string.IsNullOrEmpty(DetailGridPrix) == false) + { + if (EntityList.Any(x => x.BatchError != null)) + { + haserror = true; + } + else + { + foreach (var item in MSD.Keys) + { + if (item.StartsWith(DetailGridPrix+"[")) + { + var errors = MSD[item]; + if (errors.Count > 0) + { + Regex r = new Regex($"{DetailGridPrix}\\[(.*?)\\]"); + try + { + if (int.TryParse(r.Match(item).Groups[1].Value, out int index)) + { + EntityList[index].BatchError = errors.Select(x => x.ErrorMessage).ToSepratedString(); + keys.Add(item); + haserror = true; + } + } + catch { } + } + } + } + foreach (var item in keys) + { + MSD.RemoveModelError(item); + } + } + if (haserror) + { + AddErrorColumn(); + } + } + } + + public TModel CreateEmptyEntity() + { + return typeof(TModel).GetConstructor(Type.EmptyTypes).Invoke(null) as TModel; + } + + public void ClearEntityList() + { + EntityList?.Clear(); + } + + public string DetailGridPrix { get; set; } + + public Type ModelType => typeof(TModel); + + #endregion + + public virtual void UpdateEntityList(bool updateAllFields = false) + { + if (EntityList != null) + { + var ftype = EntityList.GetType().GenericTypeArguments.First(); + var itemPros = ftype.GetAllProperties(); + + foreach (var newitem in EntityList) + { + var subtype = newitem.GetType(); + if (typeof(IBasePoco).IsAssignableFrom( subtype)) + { + IBasePoco ent = newitem as IBasePoco; + if (ent.UpdateTime == null) + { + ent.UpdateTime = DateTime.Now; + } + if (string.IsNullOrEmpty(ent.UpdateBy)) + { + ent.UpdateBy = LoginUserInfo?.ITCode; + } + } + //循环页面传过来的子表数据,将关联到TopBasePoco的字段设为null,并且把外键字段的值设定为主表ID + foreach (var itempro in itemPros) + { + if (itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco))) + { + itempro.SetValue(newitem, null); + } + } + } + + IEnumerable data = null; + //打开新的数据库联接,获取数据库中的主表和子表数据 + using (var ndc = DC.CreateNew()) + { + var ids = EntityList.Select(x => x.GetID().ToString()).ToList(); + data = ndc.Set().AsNoTracking().Where(ids.GetContainIdExpression()).ToList(); + } + //比较子表原数据和新数据的区别 + IEnumerable toadd = null; + IEnumerable toremove = null; + Utils.CheckDifference(data, EntityList, out toremove, out toadd); + //设定子表应该更新的字段 + List setnames = new List(); + foreach (var field in FC.Keys) + { + if (field.StartsWith("EntityList[0].")) + { + string name = field.Replace("EntityList[0].", ""); + setnames.Add(name); + } + } + + //前台传过来的数据 + foreach (var newitem in EntityList) + { + //数据库中的数据 + foreach (var item in data) + { + //需要更新的数据 + if (newitem.GetID().ToString() == item.GetID().ToString()) + { + dynamic i = newitem; + var newitemType = item.GetType(); + foreach (var itempro in itemPros) + { + if (!itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco)) && (updateAllFields == true || setnames.Contains(itempro.Name))) + { + var notmapped = itempro.GetCustomAttribute(); + if (itempro.Name != "ID" && notmapped == null && itempro.PropertyType.IsList() == false) + { + DC.UpdateProperty(i, itempro.Name); + } + } + } + if ( typeof(IBasePoco).IsAssignableFrom( item.GetType())) + { + DC.UpdateProperty(i, "UpdateTime"); + DC.UpdateProperty(i, "UpdateBy"); + } + } + } + } + //需要删除的数据 + foreach (var item in toremove) + { + //如果是PersistPoco,则把IsValid设为false,并不进行物理删除 + if (typeof(IPersistPoco).IsAssignableFrom( ftype)) + { + (item as IPersistPoco).IsValid = false; + if (typeof(IBasePoco).IsAssignableFrom(ftype)) + { + (item as IBasePoco).UpdateTime = DateTime.Now; + (item as IBasePoco).UpdateBy = LoginUserInfo?.ITCode; + } + dynamic i = item; + DC.UpdateEntity(i); + } + else + { + foreach (var itempro in itemPros) + { + if (itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco))) + { + itempro.SetValue(item, null); + } + } + dynamic i = item; + DC.DeleteEntity(i); + } + } + //需要添加的数据 + foreach (var item in toadd) + { + if (typeof(IBasePoco).IsAssignableFrom( item.GetType())) + { + IBasePoco ent = item as IBasePoco; + if (ent.CreateTime == null) + { + ent.CreateTime = DateTime.Now; + } + if (string.IsNullOrEmpty(ent.CreateBy)) + { + ent.CreateBy = LoginUserInfo?.ITCode; + } + } + DC.AddEntity(item); + + + } + + DC.SaveChanges(); + } + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseSearcher.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseSearcher.cs new file mode 100644 index 0000000..1ccc8ab --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseSearcher.cs @@ -0,0 +1,196 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Text.Json.Serialization; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// 搜索条件基类,一般和ListVM配合使用实现对ListVM的搜索功能。 + /// + public class BaseSearcher : ISearcher + { + #region Property + + #region 分页相关 + /// + /// 当前页 + /// + public int Page { get; set; } + /// + /// 每页数 + /// + public int Limit { get; set; } + /// + /// 记录数 + /// + [JsonIgnore] + public long Count { get; set; } + /// + /// 分页数 + /// + [JsonIgnore] + public int PageCount { get; set; } + #endregion + + /// + /// 记录 Controller 中的表单数据 + /// + [JsonIgnore] + public Dictionary FC { get; set; } + + [JsonIgnore] + public IModelStateService MSD { get => Wtm?.MSD; } + + /// + /// 获取VM的全名 + /// + [JsonIgnore] + public string VMFullName + { + get + { + var name = GetType().AssemblyQualifiedName; + name = name.Substring(0, name.LastIndexOf(", Version=")); + return name; + } + } + + private IDataContext _dc; + /// + /// 数据库环境 + /// + [JsonIgnore] + public IDataContext DC + { + get + { + if (_dc == null) + { + return Wtm?.DC; + } + else + { + return _dc; + } + } + set + { + _dc = value; + } + } + + /// + /// Session信息 + /// + [JsonIgnore] + public ISessionService Session { get => Wtm?.Session; } + + /// + /// 当前登录人信息 + /// + [JsonIgnore] + public LoginUserInfo LoginUserInfo { get => Wtm?.LoginUserInfo; } + + [JsonIgnore] + public string ViewDivId { get; set; } + #region 未使用 + /// + /// 排序信息 + /// + public SortInfo SortInfo { get; set; } + + /// + /// 前台搜索框是否展开 + /// + [JsonIgnore] + public bool? IsExpanded { get; set; } + + private Guid _uniqueId; + [JsonIgnore] + public string UniqueId + { + get + { + if (_uniqueId == Guid.Empty) + { + _uniqueId = Guid.NewGuid(); + } + return _uniqueId.ToNoSplitString(); + } + } + + [JsonIgnore] + public WTMContext Wtm { get; set; } + #endregion + + #endregion + + #region Event + + /// + /// InitVM 完成后触发的事件 + /// + public event Action OnAfterInit; + /// + /// ReInitVM 完成后触发的事件 + /// + public event Action OnAfterReInit; + + #endregion + + #region Method + + /// + /// 调用 InitVM 并触发 OnAfterInit 事件 + /// + public void DoInit() + { + InitVM(); + OnAfterInit?.Invoke(this); + } + + /// + /// 调用 ReInitVM 并触发 OnAfterReInit 事件 + /// + public void DoReInit() + { + ReInitVM(); + OnAfterReInit?.Invoke(this); + } + + /// + /// 初始化ViewModel,框架会在创建VM实例之后自动调用本函数 + /// + protected virtual void InitVM() + { + } + + /// + /// 从新初始化ViewModel,框架会在验证失败时自动调用本函数 + /// + protected virtual void ReInitVM() + { + InitVM(); + } + + public virtual void Validate() + { + + } + /// + /// 将源 VM 的 FC 等内容复制到本VM中 + /// + /// + public void CopyContext(IBaseVM vm) + { + FC = vm.FC; + this.Wtm = vm.Wtm; + this.ViewDivId = vm.ViewDivId; + } + + #endregion + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseTemplateVM.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseTemplateVM.cs new file mode 100644 index 0000000..539ae64 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseTemplateVM.cs @@ -0,0 +1,345 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Data; +using System.IO; +using System.Linq; +using NPOI.HSSF.UserModel; +using NPOI.HSSF.Util; +using NPOI.SS.UserModel; +using NPOI.XSSF.UserModel; + +namespace WalkingTec.Mvvm.Core +{ + public class BaseTemplateVM : BaseVM + { + #region 属性 + /// + /// 下载模板显示名称 + /// + public string FileDisplayName { get; set; } + + /// + /// 是否验证模板类型(当其他系统模板导入到某模块时可设置为False) + /// + public bool ValidityTemplateType { get; set; } + + /// + /// 需要导出的数据 + /// + public DataTable TemplateDataTable { get; set; } + + /// + /// 下载模版页面参数 + /// + public Dictionary Parms { get; set; } + + /// + /// Excel索引 + /// + public long ExcelIndex { get; set; } + #endregion + + #region 构造函数 + public BaseTemplateVM() + { + ValidityTemplateType = true; + Parms = new Dictionary(); + var propetys = this.GetType().GetFields().Where(x => x.FieldType == typeof(ExcelPropety)).ToList(); + for (int porpetyIndex = 0; porpetyIndex < propetys.Count(); porpetyIndex++) + { + ExcelPropety excelPropety = (ExcelPropety)propetys[porpetyIndex].GetValue(this); + if (propetys[porpetyIndex].GetCustomAttributes(typeof(DisplayAttribute), false).Length == 0) + { + excelPropety.ColumnName = excelPropety.FieldDisplayName; + } + else + { + excelPropety.ColumnName = propetys[porpetyIndex].GetPropertyDisplayName(); + } + } + } + #endregion + + #region 初始化Excel属性数据 + /// + /// 初始化Excel属性数据 包括动态列,列表中的下拉选项 + /// + public virtual void InitExcelData() + { + + } + + public virtual void InitCustomFormat() + { + + } + + #endregion + + #region 初始化模版数据 + /// + /// 初始化模版数据 + /// + public virtual void SetTemplateDataValus() + { + + } + #endregion + + #region 生成模板 + /// + /// 生成模板 + /// + /// 文件名 + /// 生成的模版文件 + public byte[] GenerateTemplate(out string displayName) + { + //设置导出的文件名称 + string SheetName = !string.IsNullOrEmpty(FileDisplayName) ? FileDisplayName : this.GetType().Name; + displayName = SheetName + "_" + DateTime.Now.ToString("yyyy-MM-dd") + "_" + DateTime.Now.ToString("hh^mm^ss") + ".xlsx"; + + //1.声明Excel文档 + IWorkbook workbook = new XSSFWorkbook(); + + //加载初始化数据和下拉菜单数据,可重载 + InitExcelData(); + + //设置TemplateDataTable的各列的类型 + CreateDataTable(); + + //设置初始化数据到DataTable中 + SetTemplateDataValus(); + + //2.设置workbook的sheet页 + ISheet sheet = workbook.CreateSheet(); + workbook.SetSheetName(0, SheetName); + + //3.设置Sheet页的Row + IRow row = sheet.CreateRow(0); + row.HeightInPoints = 20; + + ISheet enumSheet = workbook.CreateSheet(); + IRow enumSheetRow1 = enumSheet.CreateRow(0); + enumSheetRow1.CreateCell(0).SetCellValue(CoreProgram._localizer?["Sys.Yes"]); + enumSheetRow1.CreateCell(1).SetCellValue(CoreProgram._localizer?["Sys.No"]); + enumSheetRow1.CreateCell(2).SetCellValue(this.GetType().Name); //为模板添加标记,必要时可添加版本号 + + ISheet dataSheet = workbook.CreateSheet(); + + #region 设置excel模板列头 + //默认灰色 + var headerStyle = GetCellStyle(workbook); + headerStyle.IsLocked = true; + + //黄色 + var yellowStyle = GetCellStyle(workbook, BackgroudColorEnum.Yellow); + yellowStyle.IsLocked = true; + + //红色 + var redStyle = GetCellStyle(workbook, BackgroudColorEnum.Red); + redStyle.IsLocked = true; + + //取得所有ExcelPropety + var propetys = this.GetType().GetFields().Where(x => x.FieldType == typeof(ExcelPropety)).ToList(); + + //设置列的索引 + int _currentColunmIndex = 0; + + //设置Excel是否需要保护,默认不保护 + bool IsProtect = false; + + //循环类的属性,赋值给列 + for (int porpetyIndex = 0; porpetyIndex < propetys.Count(); porpetyIndex++) + { + //依次获取属性字段 + ExcelPropety excelPropety = (ExcelPropety)propetys[porpetyIndex].GetValue(this); + ColumnDataType dateType = (excelPropety.DataType == ColumnDataType.DateTime || excelPropety.DataType == ColumnDataType.Date) ? ColumnDataType.Text : excelPropety.DataType; //日期类型默认设置成Text类型,在赋值时会进行日期验证 + + //设置是否保护Excel + if (excelPropety.ReadOnly) + { + IsProtect = true; + } + //给必填项加星号 + string colName = excelPropety.IsNullAble ? excelPropety.ColumnName : excelPropety.ColumnName + "*"; + row.CreateCell(_currentColunmIndex).SetCellValue(colName); + + //修改列头样式 + switch (excelPropety.BackgroudColor) + { + case BackgroudColorEnum.Yellow: + row.Cells[_currentColunmIndex].CellStyle = yellowStyle; + break; + case BackgroudColorEnum.Red: + row.Cells[_currentColunmIndex].CellStyle = redStyle; + break; + default: + row.Cells[_currentColunmIndex].CellStyle = headerStyle; + break; + } + + var dataStyle = workbook.CreateCellStyle(); + var dataFormat = workbook.CreateDataFormat(); + + if (dateType == ColumnDataType.Dynamic) + { + int dynamicColCount = excelPropety.DynamicColumns.Count(); + for (int dynamicColIndex = 0; dynamicColIndex < dynamicColCount; dynamicColIndex++) + { + var dynamicCol = excelPropety.DynamicColumns.ToList()[dynamicColIndex]; + string dynamicColName = excelPropety.IsNullAble ? dynamicCol.ColumnName : dynamicCol.ColumnName + "*"; + row.CreateCell(_currentColunmIndex).SetCellValue(dynamicColName); + row.Cells[_currentColunmIndex].CellStyle = headerStyle; + if (dynamicCol.ReadOnly) + { + IsProtect = true; + } + //设定列宽 + if (excelPropety.CharCount > 0) + { + sheet.SetColumnWidth(_currentColunmIndex, excelPropety.CharCount * 256); + dataStyle.WrapText = true; + } + else + { + sheet.AutoSizeColumn(_currentColunmIndex); + } + //设置单元格样式及数据类型 + dataStyle.IsLocked = excelPropety.ReadOnly; + dynamicCol.SetColumnFormat(dynamicCol.DataType, _currentColunmIndex, sheet, dataSheet, dataStyle, dataFormat); + _currentColunmIndex++; + } + } + else + { + //设定列宽 + if (excelPropety.CharCount > 0) + { + sheet.SetColumnWidth(_currentColunmIndex, excelPropety.CharCount * 256); + dataStyle.WrapText = true; + } + else + { + sheet.AutoSizeColumn(_currentColunmIndex); + } + //设置是否锁定 + dataStyle.IsLocked = excelPropety.ReadOnly; + //设置单元格样式及数据类型 + excelPropety.SetColumnFormat(dateType, _currentColunmIndex, sheet, dataSheet, dataStyle, dataFormat); + _currentColunmIndex++; + } + } + #endregion + + #region 添加模版数据 + if (TemplateDataTable.Rows.Count > 0) + { + for (int i = 0; i < TemplateDataTable.Rows.Count; i++) + { + DataRow tableRow = TemplateDataTable.Rows[i]; + IRow dataRow = sheet.CreateRow(1 + i); + for (int porpetyIndex = 0; porpetyIndex < propetys.Count(); porpetyIndex++) + { + string colName = propetys[porpetyIndex].Name; + tableRow[colName].ToString(); + dataRow.CreateCell(porpetyIndex).SetCellValue(tableRow[colName].ToString()); + } + } + } + #endregion + + //冻结行 + sheet.CreateFreezePane(0, 1, 0, 1); + + //锁定excel + if (IsProtect) + { + sheet.ProtectSheet("password"); + } + + //隐藏前2个Sheet + workbook.SetSheetHidden(1, SheetState.Hidden); + workbook.SetSheetHidden(2, SheetState.Hidden); + + //返回byte数组 + MemoryStream ms = new MemoryStream(); + workbook.Write(ms); + return ms.ToArray(); + } + #endregion + + #region 取得表头的样式 + private static ICellStyle GetCellStyle(IWorkbook workbook, BackgroudColorEnum backgroudColor = BackgroudColorEnum.Grey) + { + var headerStyle = workbook.CreateCellStyle(); + + //设定表头样式 + headerStyle.BorderBottom = BorderStyle.Thin; + headerStyle.BorderLeft = BorderStyle.Thin; + headerStyle.BorderRight = BorderStyle.Thin; + headerStyle.BorderTop = BorderStyle.Thin; + + //用灰色填充背景 + short headerbg; + + switch (backgroudColor) + { + case BackgroudColorEnum.Grey: + headerbg = HSSFColor.LightBlue.Index; + break; + case BackgroudColorEnum.Yellow: + headerbg = HSSFColor.LightYellow.Index; + break; + case BackgroudColorEnum.Red: + headerbg = HSSFColor.Pink.Index; + break; + default: + headerbg = HSSFColor.Pink.Index; + break; + } + + headerStyle.FillForegroundColor = headerbg; + headerStyle.FillPattern = FillPattern.SolidForeground; + headerStyle.FillBackgroundColor = headerbg; + headerStyle.Alignment = HorizontalAlignment.Center; + return headerStyle; + } + #endregion + + #region 初始化DataTable(不含动态列) + private void CreateDataTable() + { + TemplateDataTable = new DataTable(); + var propetys = this.GetType().GetFields().Where(x => x.FieldType == typeof(ExcelPropety)).ToList(); + foreach (var p in propetys) + { + ExcelPropety excelPropety = (ExcelPropety)p.GetValue(this); + ColumnDataType dateType = excelPropety.DataType; + switch (dateType) + { + case ColumnDataType.Bool: + TemplateDataTable.Columns.Add(p.Name, typeof(bool)); + break; + case ColumnDataType.Date: + TemplateDataTable.Columns.Add(p.Name, typeof(string)); + break; + case ColumnDataType.Number: + TemplateDataTable.Columns.Add(p.Name, typeof(int)); + break; + case ColumnDataType.Text: + TemplateDataTable.Columns.Add(p.Name, typeof(string)); + break; + case ColumnDataType.Float: + TemplateDataTable.Columns.Add(p.Name, typeof(decimal)); + break; + default: + TemplateDataTable.Columns.Add(p.Name, typeof(string)); + break; + } + } + } + #endregion + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseVM.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseVM.cs new file mode 100644 index 0000000..fc6635b --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/BaseVM.cs @@ -0,0 +1,284 @@ + +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Reflection; +using System.Text.Json.Serialization; +using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Logging; + +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Core.Support.Json; + +namespace WalkingTec.Mvvm.Core +{ + + /// + /// 所有ViewModel的基类,提供了基本的功能 + /// + public class BaseVM : IBaseVM + { + /// + /// BaseVM + /// + public BaseVM() + { + FC = new Dictionary(); + } + + #region Property + + [JsonIgnore] + public WTMContext Wtm { get; set; } + + private Guid _uniqueId; + /// + /// VM实例的Id + /// + [JsonIgnore] + public string UniqueId + { + get + { + if (_uniqueId == Guid.Empty) + { + _uniqueId = Guid.NewGuid(); + } + return _uniqueId.ToNoSplitString(); + } + } + + + /// + /// 前台传递过来的弹出窗口ID,多层弹出窗口用逗号分隔 + /// + [JsonIgnore] + public string WindowIds { get => Wtm?.WindowIds; } + + private string _viewdivid; + /// + /// PartialView中主Div的Id + /// + [JsonIgnore] + public string ViewDivId + { + set { _viewdivid = value; } + get + { + if (string.IsNullOrEmpty(_viewdivid)) + { + _viewdivid = "ViewDiv" + UniqueId; + } + return _viewdivid; + } + } + + + private IDataContext _dc; + /// + /// 数据库环境 + /// + [JsonIgnore] + public IDataContext DC + { + get + { + if (_dc == null) + { + return Wtm?.DC; + } + else + { + return _dc; + } + } + set + { + _dc = value; + } + } + + /// + /// 获取VM的全名 + /// + [JsonIgnore] + public string VMFullName + { + get + { + var name = GetType().AssemblyQualifiedName; + name = name.Substring(0, name.LastIndexOf(", Version=")); + return name; + } + } + + /// + /// 获取VM所在Dll + /// + [JsonIgnore] + public string CreatorAssembly + { + get; set; + } + + /// + /// 获取当前使用的连接字符串 + /// + [JsonIgnore] + public string CurrentCS { get => Wtm?.CurrentCS; } + + /// + /// 记录Controller中传递过来的表单数据 + /// + [JsonIgnore] + public Dictionary FC { get; set; } + + /// + /// 获取配置文件的信息 + /// + [JsonIgnore] + public Configs ConfigInfo { get=> Wtm?.ConfigInfo; } + + + [JsonIgnore] + public IUIService UIService { get=> Wtm?.UIService; } + + /// + /// 当前弹出层ID + /// + [JsonIgnore] + public string CurrentWindowId { get => Wtm?.CurrentWindowId; } + + /// + /// 父级弹出层ID + /// + [JsonIgnore] + public string ParentWindowId { get => Wtm?.ParentWindowId; } + + [JsonIgnore] + public IDistributedCache Cache { get => Wtm?.Cache; } + + /// + /// 当前登录人信息 + /// + [JsonIgnore] + public LoginUserInfo LoginUserInfo { get=> Wtm?.LoginUserInfo;} + + /// + /// 当前Url + /// + [JsonIgnore] + public string CurrentUrl { get => Wtm?.BaseUrl; } + + /// + /// 记录原始提交页面 + /// + [JsonIgnore] + public string FromView { get; set; } + + /// + /// 记录当前页面 + /// + [JsonIgnore] + public string CurrentView { get; set; } + + /// + /// Session信息 + /// + [JsonIgnore] + public ISessionService Session { get => Wtm?.Session; } + + /// + /// Controller传递过来的ModelState信息 + /// + [JsonIgnore] + public IModelStateService MSD { get => Wtm?.MSD; } + + /// + /// 用于保存删除的附件ID + /// + public List DeletedFileIds { get; set; } = new List(); + + [JsonIgnore] + public string ControllerName { get; set; } + + [JsonIgnore] + public IStringLocalizer Localizer { get => Wtm?.Localizer; } + #endregion + + #region Event + + /// + /// InitVM完成后触发的事件 + /// + public event Action OnAfterInit; + /// + /// ReInitVM完成后触发的事件 + /// + public event Action OnAfterReInit; + + #endregion + + #region Method + + /// + /// 调用 InitVM 并触发 OnAfterInit 事件 + /// + public void DoInit() + { + InitVM(); + OnAfterInit?.Invoke(this); + } + + /// + /// 调用 ReInitVM 并触发 OnAfterReInit 事件 + /// + public void DoReInit() + { + ReInitVM(); + OnAfterReInit?.Invoke(this); + } + + + + /// + /// 初始化ViewModel,框架会在创建VM实例之后自动调用本函数 + /// + protected virtual void InitVM() + { + } + + /// + /// 从新初始化ViewModel,框架会在验证失败时自动调用本函数 + /// + protected virtual void ReInitVM() + { + InitVM(); + } + + /// + /// 验证函数,MVC会在提交数据的时候自动调用本函数 + /// + /// + public virtual void Validate() + { + return; + } + + /// + /// 将源VM的上数据库上下文,Session,登录用户信息,模型状态信息,缓存信息等内容复制到本VM中 + /// + /// 复制的源 + public void CopyContext(BaseVM vm) + { + Wtm = vm.Wtm; + FC = vm.FC; + CreatorAssembly = vm.CreatorAssembly; + } + + #endregion + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/CS.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/CS.cs new file mode 100644 index 0000000..6c33ecc --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/CS.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using Microsoft.EntityFrameworkCore; + +namespace WalkingTec.Mvvm.Core +{ + public class CS + { + public string Key { get; set; } + public string Value { get; set; } + public DBTypeEnum? DbType { get; set; } + public string Version { get; set; } + public string DbContext { get; set; } + + public ConstructorInfo DcConstructor; + + public IDataContext CreateDC() + { + if (DcConstructor == null) + { + var AllAssembly = Utils.GetAllAssembly(); + List cis = new List(); + if (AllAssembly != null) + { + foreach (var ass in AllAssembly) + { + try + { + var t = ass.GetExportedTypes().Where(x => typeof(DbContext).IsAssignableFrom(x) && x.Name != "DbContext" && x.Name != "FrameworkContext" && x.Name != "EmptyContext").ToList(); + foreach (var st in t) + { + var ci = st.GetConstructor(new Type[] { typeof(CS) }); + if (ci != null) + { + cis.Add(ci); + } + } + } + catch { } + } + string dcname = DbContext; + if (string.IsNullOrEmpty(dcname)) + { + dcname = "DataContext"; + } + DcConstructor = cis.Where(x => x.DeclaringType.Name.ToLower() == dcname.ToLower()).FirstOrDefault(); + if (DcConstructor == null) + { + DcConstructor = cis.FirstOrDefault(); + } + } + } + return (IDataContext)DcConstructor?.Invoke(new object[] { this }); + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/Configs.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/Configs.cs new file mode 100644 index 0000000..81d2349 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/Configs.cs @@ -0,0 +1,480 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using Microsoft.Extensions.Logging; +using WalkingTec.Mvvm.Core.ConfigOptions; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// Configs + /// + public class Configs + { + #region ConnectionStrings + + private List _connectStrings; + + /// + /// ConnectionStrings + /// + public List Connections + { + get + { + if (_connectStrings == null) + { + _connectStrings = new List(); + } + return _connectStrings; + } + set + { + _connectStrings = value; + } + } + + #endregion + + #region Domains + + private Dictionary _domains; + + /// + /// ConnectionStrings + /// + public Dictionary Domains + { + get + { + if (_domains == null) + { + _domains = new Dictionary(); + } + return _domains; + } + set + { + _domains = value; + foreach (var item in _domains) + { + if(item.Value != null) + { + item.Value.Name = item.Key; + } + } + } + } + + #endregion + + + #region QuickDebug + + private bool? _isQuickDebug; + + /// + /// Is debug mode + /// + public bool IsQuickDebug + { + get + { + return _isQuickDebug ?? false; + } + set + { + _isQuickDebug = value; + } + } + + #endregion + + public string ErrorHandler { get; set; } = "/_Framework/Error"; + + #region Cookie prefix + + private string _cookiePre; + + /// + /// Cookie prefix + /// + public string CookiePre + { + get + { + return _cookiePre ?? string.Empty; + } + set + { + _cookiePre = value; + } + } + + #endregion + + #region PageMode + + private PageModeEnum? _pageMode; + + /// + /// PageMode + /// + public PageModeEnum PageMode + { + get + { + if (_pageMode == null) + { + _pageMode = PageModeEnum.Single; + } + return _pageMode.Value; + } + set + { + _pageMode = value; + } + } + #endregion + + #region TabMode + + private TabModeEnum? _tabMode; + + /// + /// TabMode + /// + public TabModeEnum TabMode + { + get + { + if (_tabMode == null) + { + _tabMode = TabModeEnum.Default; + } + return _tabMode.Value; + } + set + { + _tabMode = value; + } + } + #endregion + + #region BlazorMode + + private BlazorModeEnum? _blazorMode; + + /// + /// TabMode + /// + public BlazorModeEnum BlazorMode + { + get + { + if (_blazorMode == null) + { + _blazorMode = BlazorModeEnum.Server; + } + return _blazorMode.Value; + } + set + { + _blazorMode = value; + } + } + #endregion + + + #region Custom settings + + private Dictionary _appSettings; + + /// + /// Custom settings + /// + public Dictionary AppSettings + { + get + { + if (_appSettings == null) + { + _appSettings = new Dictionary(); + } + return _appSettings; + } + set + { + _appSettings = value; + } + } + + #endregion + + #region FileOptions + + private FileUploadOptions _fileUploadOptions; + + /// + /// FileOptions + /// + public FileUploadOptions FileUploadOptions + { + get + { + if (_fileUploadOptions == null) + { + _fileUploadOptions = new FileUploadOptions() + { + UploadLimit = DefaultConfigConsts.DEFAULT_UPLOAD_LIMIT, + SaveFileMode = "database", + Settings = new Dictionary>() + }; + } + return _fileUploadOptions; + } + set + { + _fileUploadOptions = value; + } + } + + #endregion + + #region UIOptions + + private UIOptions _uiOptions; + + /// + /// UIOptions + /// + public UIOptions UIOptions + { + get + { + if (_uiOptions == null) + { + _uiOptions = new UIOptions(); + if (_uiOptions.DataTable == null) + _uiOptions.DataTable = new UIOptions.DataTableOptions + { + RPP = DefaultConfigConsts.DEFAULT_RPP + }; + + if (_uiOptions.ComboBox == null) + _uiOptions.ComboBox = new UIOptions.ComboBoxOptions + { + DefaultEnableSearch = DefaultConfigConsts.DEFAULT_COMBOBOX_DEFAULT_ENABLE_SEARCH + }; + + if (_uiOptions.DateTime == null) + _uiOptions.DateTime = new UIOptions.DateTimeOptions + { + DefaultReadonly = DefaultConfigConsts.DEFAULT_DATETIME_DEFAULT_READONLY + }; + + if (_uiOptions.SearchPanel == null) + _uiOptions.SearchPanel = new UIOptions.SearchPanelOptions + { + DefaultExpand = DefaultConfigConsts.DEFAULT_SEARCHPANEL_DEFAULT_EXPAND + }; + } + return _uiOptions; + } + set + { + _uiOptions = value; + } + } + + #endregion + + #region Is FileAttachment public + + private bool? _isFilePublic; + + /// + /// Is FileAttachment public + /// + public bool IsFilePublic + { + get + { + return _isFilePublic ?? false; + } + set + { + _isFilePublic = value; + } + } + + #endregion + + #region UEditorOptions + + private UEditorOptions _ueditorOptions; + + /// + /// UEditor配置 + /// + /// + public UEditorOptions UEditorOptions + { + get + { + if (_ueditorOptions == null) + { + _ueditorOptions = new UEditorOptions(); + } + return _ueditorOptions; + } + set + { + _ueditorOptions = value; + } + } + #endregion + + #region Cors configs + + private Cors _cors; + + /// + /// Cors configs + /// + public Cors CorsOptions + { + get + { + if (_cors == null) + { + _cors = new Cors(); + _cors.Policy = new List(); + } + return _cors; + } + set + { + _cors = value; + } + } + + #endregion + + #region Support Languages + + private string _languages; + + /// + /// Support Languages + /// + public string Languages + { + get + { + if (string.IsNullOrEmpty((_languages))) + { + _languages = "zh"; + } + return _languages; + } + set + { + _languages = value; + } + } + + private List _supportLanguages; + public List SupportLanguages + { + get + { + if(_supportLanguages == null) + { + _supportLanguages = new List(); + var lans = Languages.Split(","); + foreach (var lan in lans) + { + _supportLanguages.Add(new CultureInfo(lan)); + } + + } + return _supportLanguages; + } + } + + #endregion + + public string HostRoot { get; set; } = ""; + + + #region CookieOption configs + + private CookieOption _cookieOption; + + /// + /// Cors configs + /// + public CookieOption CookieOptions + { + get + { + if (_cookieOption == null) + { + _cookieOption = new CookieOption(); + } + return _cookieOption; + } + set + { + _cookieOption = value; + } + } + + #endregion + + #region JwtOption configs + + private JwtOption _jwtOption; + + /// + /// Cors configs + /// + public JwtOption JwtOptions + { + get + { + if (_jwtOption == null) + { + _jwtOption = new JwtOption(); + } + return _jwtOption; + } + set + { + _jwtOption = value; + if(_jwtOption.SecurityKey.Length < 18) + { + var count = 18 - _jwtOption.SecurityKey.Length; + for (int i = 0; i < count; i++){ + _jwtOption.SecurityKey += "x"; + } + } + } + } + + #endregion + + public IDataContext CreateDC(string csName = null) + { + if (string.IsNullOrEmpty(csName)) + { + csName = "default"; + } + var cs = Connections.Where(x => x.Key.ToLower() == csName.ToLower()).FirstOrDefault(); + return cs?.CreateDC(); + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/CookieOptions.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/CookieOptions.cs new file mode 100644 index 0000000..d0db150 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/CookieOptions.cs @@ -0,0 +1,17 @@ +using Microsoft.AspNetCore.Authentication.Cookies; + +namespace WalkingTec.Mvvm.Core +{ + public class CookieOption + { + public string Issuer { get; set; } = "http://localhost"; + public string Audience { get; set; } = "http://localhost"; + public int Expires { get; set; } = 3600; + public bool SlidingExpiration { get; set; } = true; + public string LoginPath { get; set; } = "/Login/Login"; + public string LogoutPath { get; set; } = "/Login/Logout"; + public string AccessDeniedPath { get; set; } = "/Login/Login"; + public string Domain { get; set; } = ""; + public string ReturnUrlParameter { get; set; } = CookieAuthenticationDefaults.ReturnUrlParameter; + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/Cors.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/Cors.cs new file mode 100644 index 0000000..c8b2c18 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/Cors.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WalkingTec.Mvvm.Core +{ + public class Cors + { + public bool EnableAll { get; set; } + public List Policy { get; set; } + } + + public class CorsPolicy + { + public string Name { get; set; } + public string Domain { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/DFS.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/DFS.cs new file mode 100644 index 0000000..c48c11d --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/DFS.cs @@ -0,0 +1,35 @@ +using System.Collections.Generic; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// DFS + /// + public class DFS + { + /// + /// StorageMaxConnection + /// + public int? StorageMaxConnection { get; set; } + + /// + /// TrackerMaxConnection + /// + public int? TrackerMaxConnection { get; set; } + + /// + /// ConnectionTimeout + /// + public int? ConnectionTimeout { get; set; } + + /// + /// ConnectionLifeTime + /// + public int? ConnectionLifeTime { get; set; } + + /// + /// Trackers + /// + public List Trackers { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/DFSTracker.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/DFSTracker.cs new file mode 100644 index 0000000..b066df2 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/DFSTracker.cs @@ -0,0 +1,18 @@ +namespace WalkingTec.Mvvm.Core +{ + /// + /// DFSTracker + /// + public class DFSTracker + { + /// + /// IP + /// + public string IP { get; set; } + + /// + /// Port + /// + public int Port { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/DefaultConfigConsts.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/DefaultConfigConsts.cs new file mode 100644 index 0000000..4846060 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/DefaultConfigConsts.cs @@ -0,0 +1,38 @@ +namespace WalkingTec.Mvvm.Core.ConfigOptions +{ + /// + /// DefaultConfigConsts + /// + public static class DefaultConfigConsts + { + /// + /// 默认上传路径 + /// + public const string DEFAULT_UPLOAD_DIR = ".\\upload"; + + /// + /// 默认列表行数 + /// + public const int DEFAULT_RPP = 20; + + /// + /// 默认上传文件限制 + /// + public const int DEFAULT_UPLOAD_LIMIT = 20 * 1024 * 1024; + + /// + /// 默认允许ComboBox搜索 + /// + public const bool DEFAULT_COMBOBOX_DEFAULT_ENABLE_SEARCH = true; + + /// + /// 默认开启DateTime只读 + /// + public const bool DEFAULT_DATETIME_DEFAULT_READONLY = true; + + /// + /// 默认展开SearchPanel内容 + /// + public const bool DEFAULT_SEARCHPANEL_DEFAULT_EXPAND = true; + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/Domain.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/Domain.cs new file mode 100644 index 0000000..0136a87 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/Domain.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WalkingTec.Mvvm.Core.ConfigOptions +{ + public class Domain + { + public string Name { get; set; } + + public string Address { get; set; } + + public string InnerAddress { get; set; } + + public string EntryUrl { get; set; } + + public string Url + { + get + { + var rv = Address; + if (string.IsNullOrEmpty(rv) == false && rv.ToLower().StartsWith("http://") == false && rv.ToLower().StartsWith("https://") == false) + { + rv = "http://" + rv; + } + return rv; + } + } + + public string InnerUrl + { + get + { + var rv = InnerAddress; + if (string.IsNullOrEmpty(rv) == false && rv.ToLower().StartsWith("http://") == false && rv.ToLower().StartsWith("https://") == false) + { + rv = "http://" + rv; + } + return rv; + } + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/FileUploadOptions.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/FileUploadOptions.cs new file mode 100644 index 0000000..552859a --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/FileUploadOptions.cs @@ -0,0 +1,34 @@ +using System.Collections.Generic; + +namespace WalkingTec.Mvvm.Core.ConfigOptions +{ + /// + /// FileOptions + /// + public class FileUploadOptions + { + /// + /// 文件保存位置 + /// + public string SaveFileMode { get; set; } + + /// + /// 上传文件限制 单位字节 默认 20 * 1024 * 1024 = 20971520 bytes + /// + public long UploadLimit { get; set; } = 20971520; + + + public Dictionary> Settings { get; set; } + + } + + public class FileHandlerOptions + { + public string GroupName { get; set; } + public string GroupLocation { get; set; } + public string ServerUrl { get; set; } + + public string Key { get; set; } + public string Secret { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/JwtOptions.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/JwtOptions.cs new file mode 100644 index 0000000..2fc8cd7 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/JwtOptions.cs @@ -0,0 +1,14 @@ +using System.Text; + +namespace WalkingTec.Mvvm.Core +{ + public class JwtOption + { + public string Issuer { get; set; } = "http://localhost"; + public string Audience { get; set; } = "http://localhost"; + public int Expires { get; set; } = 3600; + public string SecurityKey { get; set; } = "wtm"; + public string LoginPath { get; set; } + public int RefreshTokenExpires { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/KV.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/KV.cs new file mode 100644 index 0000000..a62d27c --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/KV.cs @@ -0,0 +1,19 @@ +namespace WalkingTec.Mvvm.Core +{ + /// + /// KV + /// + public class KV + { + /// + /// Key + /// + public string Key { get; set; } + + /// + /// Value + /// + public string Value { get; set; } + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/UEditorOptions.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/UEditorOptions.cs new file mode 100644 index 0000000..230815b --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/UEditorOptions.cs @@ -0,0 +1,386 @@ + +using System.Text.Json.Serialization; + +namespace WalkingTec.Mvvm.Core.ConfigOptions +{ + public class UEditorOptions + { + #region 上传图片配置项 + /// + /// 执行上传图片的action名称 + /// + /// + [JsonPropertyName("imageActionName")] + public string ImageActionName { get; set; } = "UploadForLayUIUEditor"; + + /// + /// 提交的图片表单名称 + /// + /// + [JsonPropertyName("imageFieldName")] + public string ImageFieldName { get; set; } = "FileID"; + + /// + /// 上传大小限制,单位B + /// + /// + [JsonPropertyName("imageMaxSize")] + public int ImageMaxSize { get; set; } = 2048000; + + /// + /// 上传图片格式显示 + /// + /// + [JsonPropertyName("imageAllowFiles")] + public string[] ImageAllowFiles { get; set; } = new string[] { ".png", ".jpg", ".jpeg", ".gif", ".bmp" }; + + /// + /// 是否压缩图片,默认是true + /// + /// + [JsonPropertyName("imageCompressEnable")] + public bool ImageCompressEnable { get; set; } = true; + + /// + /// 图片压缩最长边限制 + /// + /// + [JsonPropertyName("imageCompressBorder")] + public int ImageCompressBorder { get; set; } = 1600; + + /// + /// 插入的图片浮动方式 + /// + /// + [JsonPropertyName("imageInsertAlign")] + public string ImageInsertAlign { get; set; } = "none"; + + /// + /// 图片访问路径前缀 默认返回全路径 + /// + /// + [JsonPropertyName("imageUrlPrefix")] + public string ImageUrlPrefix { get; set; } = string.Empty; + + /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */ + /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */ + /* {time} 会替换成时间戳 */ + /* {yyyy} 会替换成四位年份 */ + /* {yy} 会替换成两位年份 */ + /* {mm} 会替换成两位月份 */ + /* {dd} 会替换成两位日期 */ + /* {hh} 会替换成两位小时 */ + /* {ii} 会替换成两位分钟 */ + /* {ss} 会替换成两位秒 */ + /* 非法字符 \ : * ? " < > | */ + /* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */ + + /// + /// 上传保存路径,可以自定义保存路径和文件名格式 + /// + /// + [JsonPropertyName("imagePathFormat")] + public string ImagePathFormat { get; set; } = "upload/image/{yyyy}{mm}{dd}/{time}{rand:6}"; + + #endregion + + #region 涂鸦图片上传配置项 + + /// + /// 执行上传涂鸦的action名称 + /// + /// + [JsonPropertyName("scrawlActionName")] + public string ScrawlActionName { get; set; } = "UploadForLayUIUEditor"; + + /// + /// 提交的图片表单名称 + /// + /// + [JsonPropertyName("scrawlFieldName")] + public string ScrawlFieldName { get; set; } = "FileID"; + + /// + /// 上传保存路径,可以自定义保存路径和文件名格式 + /// + /// + [JsonPropertyName("scrawlPathFormat")] + public string ScrawlPathFormat { get; set; } = "upload/image/{yyyy}{mm}{dd}/{time}{rand:6}"; + + /// + /// 上传大小限制,单位B + /// + /// + [JsonPropertyName("scrawlMaxSize")] + public int ScrawlMaxSize { get; set; } = 2048000; + + /// + /// 图片访问路径前缀 + /// + /// + [JsonPropertyName("scrawlUrlPrefix")] + public string ScrawlUrlPrefix { get; set; } = string.Empty; + + /// + /// 插入的图片浮动方式 + /// + /// + [JsonPropertyName("scrawlInsertAlign")] + public string ScrawlInsertAlign { get; set; } = "none"; + #endregion + + #region 截图工具上传 + + /// + /// 执行上传截图的action名称 + /// + /// + [JsonPropertyName("snapscreenActionName")] + public string SnapscreenActionName { get; set; } = "UploadForLayUIUEditor"; + + /// + /// 上传保存路径,可以自定义保存路径和文件名格式 + /// + /// + [JsonPropertyName("snapscreenPathFormat")] + public string SnapscreenPathFormat { get; set; } = "upload/image/{yyyy}{mm}{dd}/{time}{rand:6}"; + + /// + /// 图片访问路径前缀 + /// + /// + [JsonPropertyName("snapscreenUrlPrefix")] + public string SnapscreenUrlPrefix { get; set; } = string.Empty; + + /// + /// 插入的图片浮动方式 + /// + /// + [JsonPropertyName("snapscreenInsertAlign")] + public string SnapscreenInsertAlign { get; set; } = "none"; + #endregion + + #region 抓取远程图片配置 + + [JsonPropertyName("catcherLocalDomain")] + public string[] CatcherLocalDomain { get; set; } = new string[] { "127.0.0.1", "localhost", "img.baidu.com" }; + + /// + /// 执行抓取远程图片的action名称 + /// + /// + [JsonPropertyName("catcherActionName")] + public string CatcherActionName { get; set; } = "catchimage"; + + /// + /// 提交的图片列表表单名称 + /// + /// + [JsonPropertyName("catcherFieldName")] + public string CatcherFieldName { get; set; } = "source"; + + /// + /// 上传保存路径,可以自定义保存路径和文件名格式 + /// + /// + [JsonPropertyName("catcherPathFormat")] + public string CatcherPathFormat { get; set; } = "upload/image/{yyyy}{mm}{dd}/{time}{rand:6}"; + + /// + /// 图片访问路径前缀 + /// + /// + [JsonPropertyName("catcherUrlPrefix")] + public string CatcherUrlPrefix { get; set; } = string.Empty; + + /// + /// 上传大小限制,单位B + /// + /// + [JsonPropertyName("catcherMaxSize")] + public int CatcherMaxSize { get; set; } = 2048000; + + /// + /// 抓取图片格式显示 + /// + /// + [JsonPropertyName("catcherAllowFiles")] + public string[] CatcherAllowFiles { get; set; } = new string[] { ".png", ".jpg", ".jpeg", ".gif", ".bmp" }; + #endregion + + #region 上传视频配置 + + /// + /// 执行上传视频的action名称 + /// + /// + [JsonPropertyName("videoActionName")] + public string VideoActionName { get; set; } = "UploadForLayUIUEditor"; + + /// + /// 提交的视频表单名称 + /// + /// + [JsonPropertyName("videoFieldName")] + public string VideoFieldName { get; set; } = "FileID"; + + /// + /// 上传保存路径,可以自定义保存路径和文件名格式 + /// + /// + [JsonPropertyName("videoPathFormat")] + public string VideoPathFormat { get; set; } = "upload/video/{yyyy}{mm}{dd}/{time}{rand:6}"; + + /// + /// 视频访问路径前缀 + /// + /// + [JsonPropertyName("videoUrlPrefix")] + public string VideoUrlPrefix { get; set; } = string.Empty; + + /// + /// 上传大小限制,单位B,默认100MB + /// + /// + [JsonPropertyName("videoMaxSize")] + public int VideoMaxSize { get; set; } = 102400000; + + /// + /// 上传视频格式显示 + /// + /// + [JsonPropertyName("videoAllowFiles")] + public string[] VideoAllowFiles { get; set; } = new string[] { ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid" }; + + #endregion + + #region 上传文件配置 + + /// + /// controller里,执行上传视频的action名称 + /// + /// + [JsonPropertyName("fileActionName")] + public string FileActionName { get; set; } = "UploadForLayUIUEditor"; + + /// + /// 提交的文件表单名称 + /// + /// + [JsonPropertyName("fileFieldName")] + public string FileFieldName { get; set; } = "FileID"; + + /// + /// 上传保存路径,可以自定义保存路径和文件名格式 + /// + /// + [JsonPropertyName("filePathFormat")] + public string FilePathFormat { get; set; } = "upload/file/{yyyy}{mm}{dd}/{time}{rand:6}"; + + /// + /// 文件访问路径前缀 + /// + /// + [JsonPropertyName("fileUrlPrefix")] + public string FileUrlPrefix { get; set; } = string.Empty; + + /// + /// 上传大小限制,单位B,默认50MB + /// + /// + [JsonPropertyName("fileMaxSize")] + public int FileMaxSize { get; set; } = 51200000; + + /// + /// 上传文件格式显示 + /// + /// + [JsonPropertyName("fileAllowFiles")] + public string[] FileAllowFiles { get; set; } = new string[] { ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid", ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml" }; + + #endregion + + #region 列出指定目录下的图片 + + /// + /// 执行图片管理的action名称 + /// + /// + [JsonPropertyName("imageManagerActionName")] + public string ImageManagerActionName { get; set; } = "listimage"; + + /// + /// 指定要列出图片的目录 + /// + /// + [JsonPropertyName("imageManagerListPath")] + public string ImageManagerListPath { get; set; } = string.Empty; + + /// + /// 每次列出文件数量 + /// + /// + [JsonPropertyName("imageManagerListSize")] + public int ImageManagerListSize { get; set; } = 20; + + /// + /// 图片访问路径前缀 + /// + /// + [JsonPropertyName("imageManagerUrlPrefix")] + public string ImageManagerUrlPrefix { get; set; } = string.Empty; + + /// + /// 插入的图片浮动方式 + /// + /// + [JsonPropertyName("imageManagerInsertAlign")] + public string ImageManagerInsertAlign { get; set; } = "none"; + + /// + /// 列出的文件类型 + /// + /// + [JsonPropertyName("imageManagerAllowFiles")] + public string[] ImageManagerAllowFiles { get; set; } = new string[] { ".png", ".jpg", ".jpeg", ".gif", ".bmp" }; + #endregion + + #region 列出指定目录下的文件 + + /// + /// 执行文件管理的action名称 + /// + /// + [JsonPropertyName("fileManagerActionName")] + public string FileManagerActionName { get; set; } = "listfile"; + + /// + /// 指定要列出文件的目录 + /// + /// + [JsonPropertyName("fileManagerListPath")] + public string FileManagerListPath { get; set; } = "upload/file"; + + /// + /// 文件访问路径前缀 + /// + /// + [JsonPropertyName("fileManagerUrlPrefix")] + public string FileManagerUrlPrefix { get; set; } = "/ueditor/net/"; + + /// + /// 每次列出文件数量 + /// + /// + [JsonPropertyName("fileManagerListSize")] + public int FileManagerListSize { get; set; } = 20; + + /// + /// 列出的文件类型 + /// + /// + [JsonPropertyName("fileManagerAllowFiles")] + public string[] FileManagerAllowFiles { get; set; } = new string[] { ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid", ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml" }; + #endregion + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/UIOptions.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/UIOptions.cs new file mode 100644 index 0000000..7766e5a --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ConfigOptions/UIOptions.cs @@ -0,0 +1,49 @@ +namespace WalkingTec.Mvvm.Core.ConfigOptions +{ + public class UIOptions + { + public DataTableOptions DataTable { get; set; } + public ComboBoxOptions ComboBox { get; set; } + public DateTimeOptions DateTime { get; set; } + public SearchPanelOptions SearchPanel { get; set; } + + public class DataTableOptions + { + /// + /// 默认列表行数 + /// + public int RPP { get; set; } + + public bool ShowPrint { get; set; } + + public bool ShowFilter { get; set; } + } + + public class ComboBoxOptions + { + + /// + /// 默认允许ComboBox搜索 + /// + public bool DefaultEnableSearch { get; set; } + } + + public class DateTimeOptions + { + + /// + /// 默认开启DateTime只读 + /// + public bool DefaultReadonly { get; set; } + } + + public class SearchPanelOptions + { + + /// + /// 默认展开SearchPanel内容 + /// + public bool DefaultExpand { get; set; } + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/CoreProgram.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/CoreProgram.cs new file mode 100644 index 0000000..e46bb30 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/CoreProgram.cs @@ -0,0 +1,34 @@ +using System.Text.Json; +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Options; + +namespace WalkingTec.Mvvm.Core +{ + public class CoreProgram + { + public static IStringLocalizer _localizer { + get; + set; + } + + public static JsonSerializerOptions DefaultJsonOption + { + get;set; + } + + public static JsonSerializerOptions DefaultPostJsonOption + { + get; set; + } + + + public static string[] Buildindll = new string[] + { + "WalkingTec.Mvvm.Core", + "WalkingTec.Mvvm.Mvc", + "WalkingTec.Mvvm.Admin", + "WalkingTec.Mvvm.Taghelpers" + }; + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/DataContext.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/DataContext.cs new file mode 100644 index 0000000..3d97f2e --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/DataContext.cs @@ -0,0 +1,1269 @@ +using Microsoft.Data.SqlClient; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Console; +using Microsoft.Extensions.Logging.Debug; +using Microsoft.Extensions.Options; +using MySqlConnector; +using Npgsql; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Core.Support.Json; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// FrameworkContext + /// + public partial class FrameworkContext : EmptyContext, IDataContext + { + public DbSet BaseFrameworkMenus { get; set; } + public DbSet BaseFunctionPrivileges { get; set; } + public DbSet BaseDataPrivileges { get; set; } + public DbSet BaseFileAttachments { get; set; } + public DbSet BaseFrameworkRoles { get; set; } + public DbSet BaseFrameworkUserRoles { get; set; } + public DbSet BaseFrameworkUserGroups { get; set; } + public DbSet BaseFrameworkGroups { get; set; } + public DbSet BaseActionLogs { get; set; } + //public DbSet BaseFrameworkAreas { get; set; } + public DbSet PersistedGrants { get; set; } + + /// + /// FrameworkContext + /// + public FrameworkContext() : base() + { + } + + /// + /// FrameworkContext + /// + /// + public FrameworkContext(string cs) : base(cs) + { + } + + public FrameworkContext(string cs, DBTypeEnum dbtype, string version = null) : base(cs, dbtype, version) + { + } + + public FrameworkContext(CS cs) : base(cs) + { + } + public FrameworkContext(DbContextOptions options) : base(options) { } + + /// + /// OnModelCreating + /// + /// + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + //菜单和菜单权限的级联删除 + modelBuilder.Entity().HasOne(x => x.MenuItem).WithMany(x => x.Privileges).HasForeignKey(x => x.MenuItemId).OnDelete(DeleteBehavior.Cascade); + + var modelAsms = Utils.GetAllAssembly(); + + var allTypes = new List();// 所有 DbSet<> 的泛型类型 + + #region 获取所有 DbSet 的泛型类型 T 及其 List 类型属性对应的类型 T + + // 获取所有 DbSet 的泛型类型 T + foreach (var asm in modelAsms) + { + try + { + var dcModule = asm.GetExportedTypes().Where(x => typeof(DbContext).IsAssignableFrom(x)).ToList(); + if (dcModule != null && dcModule.Count > 0) + { + foreach (var module in dcModule) + { + foreach (var pro in module.GetProperties()) + { + if (pro.PropertyType.IsGeneric(typeof(DbSet<>))) + { + if (!allTypes.Contains(pro.PropertyType.GenericTypeArguments[0], new TypeComparer())) + { + allTypes.Add(pro.PropertyType.GenericTypeArguments[0]); + } + } + } + } + } + } + catch { } + } + + // 获取类型 T 下 List 类型的属性对应的类型 S,且S 必须是 TopBasePoco 的子类,只有这些类会生成库 + for (int i = 0; i < allTypes.Count; i++) // + { + var item = allTypes[i]; + var pros = item.GetProperties(); + foreach (var pro in pros) + { + if (typeof(TopBasePoco).IsAssignableFrom(pro.PropertyType)) + { + if (allTypes.Contains(pro.PropertyType) == false) + { + allTypes.Add(pro.PropertyType); + } + } + else + { + if (pro.PropertyType.IsGenericType && pro.PropertyType.GetGenericTypeDefinition() == typeof(List<>)) + { + var inner = pro.PropertyType.GetGenericArguments()[0]; + if (typeof(TopBasePoco).IsAssignableFrom(inner)) + { + if (allTypes.Contains(inner) == false) + { + allTypes.Add(inner); + } + } + } + } + } + } + + #endregion + foreach (var item in allTypes) + { + if (typeof(TopBasePoco).IsAssignableFrom(item) && typeof(ISubFile).IsAssignableFrom(item) == false) + { + //将所有关联附件的外键设为不可级联删除 + var pros = item.GetProperties().Where(x => x.PropertyType == typeof(FileAttachment)).ToList(); + foreach (var filepro in pros) + { + var builder = typeof(ModelBuilder).GetMethod("Entity", Type.EmptyTypes).MakeGenericMethod(item).Invoke(modelBuilder, null) as EntityTypeBuilder; + builder.HasOne(filepro.Name).WithMany().OnDelete(DeleteBehavior.Restrict); + } + } + } + } + + + /// + /// 数据初始化 + /// + /// + /// + /// 返回true表示需要进行初始化数据操作,返回false即数据库已经存在或不需要初始化数据 + public async override Task DataInit(object allModules, bool IsSpa) + { + bool rv = await Database.EnsureCreatedAsync(); + //判断是否存在初始数据 + bool emptydb = false; + try + { + emptydb = Set().Count() == 0 && Set().Count() == 0; + } + catch { } + + if (emptydb == true) + { + var AllModules = allModules as List; + var roles = new FrameworkRole[] + { + new FrameworkRole{ ID = Guid.NewGuid(), RoleCode = "001", RoleName = CoreProgram._localizer?["Sys.Admin"]} + }; + + var adminRole = roles[0]; + if (Set().Any() == false) + { + var systemManagement = GetFolderMenu("SystemManagement", new List { adminRole }); + var logList = IsSpa ? GetMenu2(AllModules, "ActionLog", "MenuKey.ActionLog", new List { adminRole }, 1) : GetMenu(AllModules, "_Admin", "ActionLog", "Index", "MenuKey.ActionLog", new List { adminRole }, 1); + var userList = IsSpa ? GetMenu2(AllModules, "FrameworkUser", "MenuKey.UserManagement", new List { adminRole }, 2) : GetMenu(AllModules, "_Admin", "FrameworkUser", "Index", "MenuKey.UserManagement", new List { adminRole }, 2); + var roleList = IsSpa ? GetMenu2(AllModules, "FrameworkRole", "MenuKey.RoleManagement", new List { adminRole }, 3) : GetMenu(AllModules, "_Admin", "FrameworkRole", "Index", "MenuKey.RoleManagement", new List { adminRole }, 3); + var groupList = IsSpa ? GetMenu2(AllModules, "FrameworkGroup", "MenuKey.GroupManagement", new List { adminRole }, 4) : GetMenu(AllModules, "_Admin", "FrameworkGroup", "Index", "MenuKey.GroupManagement", new List { adminRole }, 4); + var menuList = IsSpa ? GetMenu2(AllModules, "FrameworkMenu", "MenuKey.MenuMangement", new List { adminRole }, 5) : GetMenu(AllModules, "_Admin", "FrameworkMenu", "Index", "MenuKey.MenuMangement", new List { adminRole }, 5); + var dpList = IsSpa ? GetMenu2(AllModules, "DataPrivilege", "MenuKey.DataPrivilege", new List { adminRole }, 6) : GetMenu(AllModules, "_Admin", "DataPrivilege", "Index", "MenuKey.DataPrivilege", new List { adminRole }, 6); + if (logList != null) + { + var menus = new FrameworkMenu[] { logList, userList, roleList, groupList, menuList, dpList }; + foreach (var item in menus) + { + if (item != null) + { + systemManagement.Children.Add(item); + } + } + Set().Add(systemManagement); + + if (IsSpa == false) + { + systemManagement.Icon = "layui-icon layui-icon-set"; + logList?.SetPropertyValue("Icon", "layui-icon layui-icon-form"); + userList?.SetPropertyValue("Icon", "layui-icon layui-icon-friends"); + roleList?.SetPropertyValue("Icon", "layui-icon layui-icon-user"); + groupList?.SetPropertyValue("Icon", "layui-icon layui-icon-group"); + menuList?.SetPropertyValue("Icon", "layui-icon layui-icon-menu-fill"); + dpList?.SetPropertyValue("Icon", "layui-icon layui-icon-auz"); + + var apifolder = GetFolderMenu("Api", new List { adminRole }); + apifolder.ShowOnMenu = false; + apifolder.DisplayOrder = 100; + var logList2 = GetMenu2(AllModules, "ActionLog", "MenuKey.ActionLog", new List { adminRole }, 1); + var userList2 = GetMenu2(AllModules, "FrameworkUser", "MenuKey.UserManagement", new List { adminRole }, 2); + var roleList2 = GetMenu2(AllModules, "FrameworkRole", "MenuKey.RoleManagement", new List { adminRole }, 3); + var groupList2 = GetMenu2(AllModules, "FrameworkGroup", "MenuKey.GroupManagement", new List { adminRole }, 4); + var menuList2 = GetMenu2(AllModules, "FrameworkMenu", "MenuKey.MenuMangement", new List { adminRole }, 5); + var dpList2 = GetMenu2(AllModules, "DataPrivilege", "MenuKey.DataPrivilege", new List { adminRole }, 6); + var apis = new FrameworkMenu[] { logList2, userList2, roleList2, groupList2, menuList2, dpList2 }; + //apis.ToList().ForEach(x => { x.ShowOnMenu = false;x.PageName += $"({Program._localizer["BuildinApi"]})"; }); + foreach (var item in apis) + { + if (item != null) + { + apifolder.Children.Add(item); + + } + } + Set().Add(apifolder); + } + else + { + systemManagement.Icon = " _wtmicon _wtmicon-icon_shezhi"; + logList?.SetPropertyValue("Icon", " _wtmicon _wtmicon-chaxun"); + userList?.SetPropertyValue("Icon", " _wtmicon _wtmicon-zhanghaoquanxianguanli"); + roleList?.SetPropertyValue("Icon", " _wtmicon _wtmicon-quanxianshenpi"); + groupList?.SetPropertyValue("Icon", " _wtmicon _wtmicon-zuzhiqunzu"); + menuList?.SetPropertyValue("Icon", " _wtmicon _wtmicon--lumingpai"); + dpList?.SetPropertyValue("Icon", " _wtmicon _wtmicon-anquan"); + } + } + + } + Set().AddRange(roles); + await SaveChangesAsync(); + } + return rv; + } + + private FrameworkMenu GetFolderMenu(string FolderText, List allowedRoles, bool isShowOnMenu = true, bool isInherite = false) + { + FrameworkMenu menu = new FrameworkMenu + { + PageName = "MenuKey." + FolderText, + Children = new List(), + Privileges = new List(), + ShowOnMenu = isShowOnMenu, + IsInside = true, + FolderOnly = true, + IsPublic = false, + DisplayOrder = 1 + }; + + if (allowedRoles != null) + { + foreach (var role in allowedRoles) + { + menu.Privileges.Add(new FunctionPrivilege { RoleCode = role.RoleCode, Allowed = true }); + + } + } + return menu; + } + + private FrameworkMenu GetMenu(List allModules, string areaName, string controllerName, string actionName, string pageKey, List allowedRoles, int displayOrder) + { + var acts = allModules.Where(x => x.ClassName == controllerName && (areaName == null || x.Area?.Prefix?.ToLower() == areaName.ToLower())).SelectMany(x => x.Actions).ToList(); + var act = acts.Where(x => x.MethodName == actionName).SingleOrDefault(); + var rest = acts.Where(x => x.MethodName != actionName && x.IgnorePrivillege == false).ToList(); + FrameworkMenu menu = GetMenuFromAction(act, true, allowedRoles, displayOrder); + if (menu != null) + { + menu.PageName = pageKey; + for (int i = 0; i < rest.Count; i++) + { + if (rest[i] != null) + { + var sub = GetMenuFromAction(rest[i], false, allowedRoles, (i + 1)); + sub.PageName = pageKey; + menu.Children.Add(sub); + } + } + } + return menu; + } + + private FrameworkMenu GetMenu2(List allModules, string controllerName, string pageKey, List allowedRoles, int displayOrder) + { + var acts = allModules.Where(x => (x.FullName == $"WalkingTec.Mvvm.Admin.Api,{controllerName}")&& x.IsApi == true).SelectMany(x => x.Actions).ToList(); + var rest = acts.Where(x => x.IgnorePrivillege == false).ToList(); + SimpleAction act = null; + if (acts.Count > 0) + { + act = acts[0]; + } + FrameworkMenu menu = GetMenuFromAction(act, true, allowedRoles, displayOrder); + if (menu != null) + { + menu.PageName = pageKey; + menu.Url = "/" + acts[0].Module.ClassName.ToLower(); + menu.ActionName = "MainPage"; + menu.ClassName = acts[0].Module.FullName; + menu.MethodName = null; + for (int i = 0; i < rest.Count; i++) + { + if (rest[i] != null) + { + var sub = GetMenuFromAction(rest[i], false, allowedRoles, (i + 1)); + sub.PageName = pageKey; + menu.Children.Add(sub); + } + } + } + return menu; + } + + private FrameworkMenu GetMenuFromAction(SimpleAction act, bool isMainLink, List allowedRoles, int displayOrder = 1) + { + if (act == null) + { + return null; + } + FrameworkMenu menu = new FrameworkMenu + { + //ActionId = act.ID, + //ModuleId = act.ModuleId, + ClassName = act.Module.FullName, + MethodName = act.MethodName, + Url = act.Url, + Privileges = new List(), + ShowOnMenu = isMainLink, + FolderOnly = false, + Children = new List(), + IsPublic = false, + IsInside = true, + DisplayOrder = displayOrder, + }; + if (isMainLink) + { + menu.ModuleName = act.Module.ModuleName; + menu.ActionName = act.ActionDes?.Description ?? act.ActionName; + menu.MethodName = null; + } + else + { + menu.ModuleName = act.Module.ModuleName; + menu.ActionName = act.ActionDes?.Description ?? act.ActionName; + } + if (allowedRoles != null) + { + foreach (var role in allowedRoles) + { + menu.Privileges.Add(new FunctionPrivilege { RoleCode = role.RoleCode, Allowed = true }); + + } + } + return menu; + } + + } + + public partial class EmptyContext : DbContext, IDataContext + { + private ILoggerFactory _loggerFactory; + + /// + /// Commited + /// + public bool Commited { get; set; } + + /// + /// IsFake + /// + public bool IsFake { get; set; } + + public bool IsDebug { get; set; } + /// + /// CSName + /// + public string CSName { get; set; } + + public DBTypeEnum DBType { get; set; } + + public string Version { get; set; } + public CS ConnectionString { get; set; } + /// + /// FrameworkContext + /// + public EmptyContext() + { + CSName = "default"; + DBType = DBTypeEnum.SqlServer; + } + + /// + /// FrameworkContext + /// + /// + public EmptyContext(string cs) + { + CSName = cs; + DBType = DBTypeEnum.SqlServer; + } + + public EmptyContext(string cs, DBTypeEnum dbtype, string version = null) + { + CSName = cs; + DBType = dbtype; + Version = version; + } + + public EmptyContext(CS cs) + { + CSName = cs.Value; + DBType = cs.DbType ?? DBTypeEnum.SqlServer; + Version = cs.Version; + ConnectionString = cs; + } + + public EmptyContext(DbContextOptions options) : base(options) { } + + public IDataContext CreateNew() + { + if (ConnectionString != null) + { + return (IDataContext)this.GetType().GetConstructor(new Type[] { typeof(CS) }).Invoke(new object[] { ConnectionString }); ; + } + else + { + return (IDataContext)this.GetType().GetConstructor(new Type[] { typeof(string), typeof(DBTypeEnum), typeof(string) }).Invoke(new object[] { CSName, DBType, Version }); + } + } + + public IDataContext ReCreate() + { + if (this?.Database?.CurrentTransaction != null) + { + return this; + } + else + { + if (ConnectionString != null) + { + return (IDataContext)this.GetType().GetConstructor(new Type[] { typeof(CS) }).Invoke(new object[] { ConnectionString }); ; + } + else + { + return (IDataContext)this.GetType().GetConstructor(new Type[] { typeof(string), typeof(DBTypeEnum) }).Invoke(new object[] { CSName, DBType }); + } + } + } + /// + /// 将一个实体设为填加状态 + /// + /// 实体 + public void AddEntity(T entity) where T : TopBasePoco + { + this.Entry(entity).State = EntityState.Added; + } + + /// + /// 将一个实体设为修改状态 + /// + /// 实体 + public void UpdateEntity(T entity) where T : TopBasePoco + { + this.Entry(entity).State = EntityState.Modified; + } + + /// + /// 将一个实体的某个字段设为修改状态,用于只更新个别字段的情况 + /// + /// 实体类 + /// 实体 + /// 要设定为修改状态的字段 + public void UpdateProperty(T entity, Expression> fieldExp) + where T : TopBasePoco + { + var set = this.Set(); + if (set.Local.AsQueryable().CheckID(entity.GetID()).FirstOrDefault() == null) + { + set.Attach(entity); + } + this.Entry(entity).Property(fieldExp).IsModified = true; + } + + /// + /// UpdateProperty + /// + /// + /// + /// + public void UpdateProperty(T entity, string fieldName) + where T : TopBasePoco + { + var set = this.Set(); + if (set.Local.AsQueryable().CheckID(entity.GetID()).FirstOrDefault() == null) + { + set.Attach(entity); + } + this.Entry(entity).Property(fieldName).IsModified = true; + } + + /// + /// 将一个实体设定为删除状态 + /// + /// 实体 + public void DeleteEntity(T entity) where T : TopBasePoco + { + var set = this.Set(); + var exist = set.Local.AsQueryable().CheckID(entity.GetID()).FirstOrDefault(); + if (exist == null) + { + set.Attach(entity); + set.Remove(entity); + } + else + { + set.Remove(exist); + + } + } + + /// + /// CascadeDelete + /// + /// + /// + public void CascadeDelete(T entity) where T : TreePoco + { + if (entity != null && entity.ID != Guid.Empty) + { + var set = this.Set(); + var entities = set.Where(x => x.ParentId == entity.ID).ToList(); + if (entities.Count > 0) + { + foreach (var item in entities) + { + CascadeDelete(item); + } + } + DeleteEntity(entity); + } + } + + /// + /// GetCoreType + /// + /// + /// + public Type GetCoreType(Type t) + { + if (t != null && t.IsNullable()) + { + if (!t.GetTypeInfo().IsValueType) + { + return t; + } + else + { + if ("DateTime".Equals(t.GenericTypeArguments[0].Name)) + { + return typeof(string); + } + return Nullable.GetUnderlyingType(t); + } + } + else + { + if ("DateTime".Equals(t.Name)) + { + return typeof(string); + } + return t; + } + } + + /// + /// OnModelCreating + /// + /// + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + if (DBType == DBTypeEnum.Oracle) + { + modelBuilder.Model.SetMaxIdentifierLength(30); + } + } + + /// + /// OnConfiguring + /// + /// + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + switch (DBType) + { + case DBTypeEnum.SqlServer: + optionsBuilder.UseSqlServer(CSName); + break; + case DBTypeEnum.MySql: + ServerVersion sv = null; + if (string.IsNullOrEmpty(Version) == false) + { + ServerVersion.TryParse(Version, out sv); + } + if (sv == null) + { + sv = ServerVersion.AutoDetect(CSName); + } + optionsBuilder.UseMySql(CSName, sv); + break; + case DBTypeEnum.PgSql: + optionsBuilder.UseNpgsql(CSName); + break; + case DBTypeEnum.Memory: + optionsBuilder.UseInMemoryDatabase(CSName); + break; + case DBTypeEnum.SQLite: + optionsBuilder.UseSqlite(CSName); + break; + case DBTypeEnum.Oracle: + + optionsBuilder.UseOracle(CSName, option => + { + if (string.IsNullOrEmpty(Version) == false) + { + option.UseOracleSQLCompatibility(Version); + } + else + { + option.UseOracleSQLCompatibility("11"); + } + }); + break; + default: + break; + } + if (IsDebug == true) + { + optionsBuilder.EnableDetailedErrors(); + optionsBuilder.EnableSensitiveDataLogging(); + if (_loggerFactory != null) + { + optionsBuilder.UseLoggerFactory(_loggerFactory); + } + } + base.OnConfiguring(optionsBuilder); + } + + public void SetLoggerFactory(ILoggerFactory factory) + { + this._loggerFactory = factory; + } + + + /// + /// 数据初始化 + /// + /// + /// + /// 返回true表示需要进行初始化数据操作,返回false即数据库已经存在或不需要初始化数据 + public async virtual Task DataInit(object allModules, bool IsSpa) + { + bool rv = await Database.EnsureCreatedAsync(); + return rv; + } + + #region 执行存储过程返回datatable + /// + /// 执行存储过程,返回datatable结果集 + /// + /// 存储过程名称 + /// 存储过程参数 + /// + public DataTable RunSP(string command, params object[] paras) + { + return Run(command, CommandType.StoredProcedure, paras); + } + #endregion + + public IEnumerable RunSP(string command, params object[] paras) + { + return Run(command, CommandType.StoredProcedure, paras); + } + + #region 执行Sql语句,返回datatable + public DataTable RunSQL(string sql, params object[] paras) + { + return Run(sql, CommandType.Text, paras); + } + #endregion + + public IEnumerable RunSQL(string sql, params object[] paras) + { + return Run(sql, CommandType.Text, paras); + } + + + #region 执行存储过程或Sql语句返回DataTable + /// + /// 执行存储过程或Sql语句返回DataTable + /// + /// 存储过程名称或Sql语句 + /// 命令类型 + /// 参数 + /// + public DataTable Run(string sql, CommandType commandType, params object[] paras) + { + DataTable table = new DataTable(); + var connection = this.Database.GetDbConnection(); + var isClosed = connection.State == ConnectionState.Closed; + if (isClosed) + { + connection.Open(); + } + using (var command = connection.CreateCommand()) + { + command.CommandText = sql; + command.CommandTimeout = 2400; + command.CommandType = commandType; + if (this.Database.CurrentTransaction != null) + { + command.Transaction = this.Database.CurrentTransaction.GetDbTransaction(); + } + if (paras != null) + { + foreach (var param in paras) + command.Parameters.Add(param); + } + using (var reader = command.ExecuteReader()) + { + table.Load(reader); + } + } + if (isClosed) + { + connection.Close(); + } + return table; + } + #endregion + + + public IEnumerable Run(string sql, CommandType commandType, params object[] paras) + { + IEnumerable entityList = new List(); + DataTable dt = Run(sql, commandType, paras); + entityList = EntityHelper.GetEntityList(dt); + return entityList; + } + + + public object CreateCommandParameter(string name, object value, ParameterDirection dir) + { + object rv = null; + switch (this.DBType) + { + case DBTypeEnum.SqlServer: + rv = new SqlParameter(name, value) { Direction = dir }; + break; + case DBTypeEnum.MySql: + rv = new MySqlParameter(name, value) { Direction = dir }; + break; + case DBTypeEnum.PgSql: + rv = new NpgsqlParameter(name, value) { Direction = dir }; + break; + case DBTypeEnum.SQLite: + rv = new SqliteParameter(name, value) { Direction = dir }; + break; + case DBTypeEnum.Oracle: + //rv = new OracleParameter(name, value) { Direction = dir }; + break; + } + return rv; + } + } + + public class NullContext : IDataContext + { + + + public bool IsFake { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public IModel Model => throw new NotImplementedException(); + + public DatabaseFacade Database => throw new NotImplementedException(); + + public string CSName { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DBTypeEnum DBType { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public bool IsDebug { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public void AddEntity(T entity) where T : TopBasePoco + { + throw new NotImplementedException(); + } + + public void CascadeDelete(T entity) where T : TreePoco + { + throw new NotImplementedException(); + } + + public object CreateCommandParameter(string name, object value, ParameterDirection dir) + { + throw new NotImplementedException(); + } + + public IDataContext CreateNew() + { + throw new NotImplementedException(); + } + + public Task DataInit(object AllModel, bool IsSpa) + { + throw new NotImplementedException(); + } + + public void DeleteEntity(T entity) where T : TopBasePoco + { + throw new NotImplementedException(); + } + + public void Dispose() + { + + } + + public IDataContext ReCreate() + { + throw new NotImplementedException(); + } + + public DataTable Run(string sql, CommandType commandType, params object[] paras) + { + throw new NotImplementedException(); + } + + public IEnumerable Run(string sql, CommandType commandType, params object[] paras) + { + throw new NotImplementedException(); + } + + public DataTable RunSP(string command, params object[] paras) + { + throw new NotImplementedException(); + } + + public IEnumerable RunSP(string command, params object[] paras) + { + throw new NotImplementedException(); + } + + public DataTable RunSQL(string command, params object[] paras) + { + throw new NotImplementedException(); + } + + public IEnumerable RunSQL(string sql, params object[] paras) + { + throw new NotImplementedException(); + } + + public int SaveChanges() + { + throw new NotImplementedException(); + } + + public int SaveChanges(bool acceptAllChangesOnSuccess) + { + throw new NotImplementedException(); + } + + public Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default) + { + throw new NotImplementedException(); + } + + public Task SaveChangesAsync(CancellationToken cancellationToken = default) + { + throw new NotImplementedException(); + } + + public DbSet Set() where T : class + { + throw new NotImplementedException(); + } + + public void SetLoggerFactory(ILoggerFactory factory) + { + throw new NotImplementedException(); + } + + public void UpdateEntity(T entity) where T : TopBasePoco + { + throw new NotImplementedException(); + } + + public void UpdateProperty(T entity, Expression> fieldExp) where T : TopBasePoco + { + throw new NotImplementedException(); + } + + public void UpdateProperty(T entity, string fieldName) where T : TopBasePoco + { + throw new NotImplementedException(); + } + } + + public partial class PlusContext : EmptyContext, IDataContext + { + public DbSet BaseFrameworkMenus { get; set; } + public DbSet BaseFunctionPrivileges { get; set; } + public DbSet BaseDataPrivileges { get; set; } + public DbSet BaseFileAttachments { get; set; } + public DbSet BaseFrameworkRoles { get; set; } + public DbSet BaseFrameworkGroups { get; set; } + public DbSet BaseActionLogs { get; set; } + //public DbSet BaseFrameworkAreas { get; set; } + public DbSet PersistedGrants { get; set; } + + /// + /// FrameworkContext + /// + public PlusContext() : base() + { + } + + /// + /// FrameworkContext + /// + /// + public PlusContext(string cs) : base(cs) + { + } + + public PlusContext(string cs, DBTypeEnum dbtype, string version = null) : base(cs, dbtype, version) + { + } + + public PlusContext(CS cs) : base(cs) + { + } + public PlusContext(DbContextOptions options) : base(options) { } + + /// + /// OnModelCreating + /// + /// + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + //菜单和菜单权限的级联删除 + modelBuilder.Entity().HasOne(x => x.MenuItem).WithMany(x => x.Privileges).HasForeignKey(x => x.MenuItemId).OnDelete(DeleteBehavior.Cascade); + + var modelAsms = Utils.GetAllAssembly(); + + var allTypes = new List();// 所有 DbSet<> 的泛型类型 + + #region 获取所有 DbSet 的泛型类型 T 及其 List 类型属性对应的类型 T + + // 获取所有 DbSet 的泛型类型 T + foreach (var asm in modelAsms) + { + try + { + var dcModule = asm.GetExportedTypes().Where(x => typeof(DbContext).IsAssignableFrom(x)).ToList(); + if (dcModule != null && dcModule.Count > 0) + { + foreach (var module in dcModule) + { + foreach (var pro in module.GetProperties()) + { + if (pro.PropertyType.IsGeneric(typeof(DbSet<>))) + { + if (!allTypes.Contains(pro.PropertyType.GenericTypeArguments[0], new TypeComparer())) + { + allTypes.Add(pro.PropertyType.GenericTypeArguments[0]); + } + } + } + } + } + } + catch { } + } + + // 获取类型 T 下 List 类型的属性对应的类型 S,且S 必须是 TopBasePoco 的子类,只有这些类会生成库 + for (int i = 0; i < allTypes.Count; i++) // + { + var item = allTypes[i]; + var pros = item.GetProperties(); + foreach (var pro in pros) + { + if (typeof(TopBasePoco).IsAssignableFrom(pro.PropertyType)) + { + if (allTypes.Contains(pro.PropertyType) == false) + { + allTypes.Add(pro.PropertyType); + } + } + else + { + if (pro.PropertyType.IsGenericType && pro.PropertyType.GetGenericTypeDefinition() == typeof(List<>)) + { + var inner = pro.PropertyType.GetGenericArguments()[0]; + if (typeof(TopBasePoco).IsAssignableFrom(inner)) + { + if (allTypes.Contains(inner) == false) + { + allTypes.Add(inner); + } + } + } + } + } + } + + #endregion + foreach (var item in allTypes) + { + if (typeof(TopBasePoco).IsAssignableFrom(item) && typeof(ISubFile).IsAssignableFrom(item) == false) + { + //将所有关联附件的外键设为不可级联删除 + var pros = item.GetProperties().Where(x => x.PropertyType == typeof(FileAttachment)).ToList(); + foreach (var filepro in pros) + { + var builder = typeof(ModelBuilder).GetMethod("Entity", Type.EmptyTypes).MakeGenericMethod(item).Invoke(modelBuilder, null) as EntityTypeBuilder; + builder.HasOne(filepro.Name).WithMany().OnDelete(DeleteBehavior.Restrict); + } + } + } + } + + + /// + /// 数据初始化 + /// + /// + /// + /// 返回true表示需要进行初始化数据操作,返回false即数据库已经存在或不需要初始化数据 + public async override Task DataInit(object allModules, bool IsSpa) + { + bool rv = await Database.EnsureCreatedAsync(); + //判断是否存在初始数据 + bool emptydb = false; + try + { + emptydb = Set().Count() == 0 && Set().Count() == 0; + } + catch { } + + if (emptydb == true) + { + var AllModules = allModules as List; + var roles = new FrameworkRole[] + { + new FrameworkRole{ ID = Guid.NewGuid(), RoleCode = "001", RoleName = CoreProgram._localizer?["Sys.Admin"]} + }; + + var adminRole = roles[0]; + if (Set().Any() == false) + { + var systemManagement = GetFolderMenu("SystemManagement", new List { adminRole }); + var logList = IsSpa ? GetMenu2(AllModules, "ActionLog", "MenuKey.ActionLog", new List { adminRole }, 1) : GetMenu(AllModules, "_Admin", "ActionLog", "Index", "MenuKey.ActionLog", new List { adminRole }, 1); + var userList = IsSpa ? GetMenu2(AllModules, "FrameworkUser", "MenuKey.UserManagement", new List { adminRole }, 2) : GetMenu(AllModules, "_Admin", "FrameworkUser", "Index", "MenuKey.UserManagement", new List { adminRole }, 2); + var roleList = IsSpa ? GetMenu2(AllModules, "FrameworkRole", "MenuKey.RoleManagement", new List { adminRole }, 3) : GetMenu(AllModules, "_Admin", "FrameworkRole", "Index", "MenuKey.RoleManagement", new List { adminRole }, 3); + var groupList = IsSpa ? GetMenu2(AllModules, "FrameworkGroup", "MenuKey.GroupManagement", new List { adminRole }, 4) : GetMenu(AllModules, "_Admin", "FrameworkGroup", "Index", "MenuKey.GroupManagement", new List { adminRole }, 4); + var menuList = IsSpa ? GetMenu2(AllModules, "FrameworkMenu", "MenuKey.MenuMangement", new List { adminRole }, 5) : GetMenu(AllModules, "_Admin", "FrameworkMenu", "Index", "MenuKey.MenuMangement", new List { adminRole }, 5); + var dpList = IsSpa ? GetMenu2(AllModules, "DataPrivilege", "MenuKey.DataPrivilege", new List { adminRole }, 6) : GetMenu(AllModules, "_Admin", "DataPrivilege", "Index", "MenuKey.DataPrivilege", new List { adminRole }, 6); + if (logList != null) + { + var menus = new FrameworkMenu[] { logList, userList, roleList, groupList, menuList, dpList }; + foreach (var item in menus) + { + if (item != null) + { + systemManagement.Children.Add(item); + } + } + Set().Add(systemManagement); + + if (IsSpa == false) + { + systemManagement.Icon = "layui-icon layui-icon-set"; + logList?.SetPropertyValue("Icon", "layui-icon layui-icon-form"); + userList?.SetPropertyValue("Icon", "layui-icon layui-icon-friends"); + roleList?.SetPropertyValue("Icon", "layui-icon layui-icon-user"); + groupList?.SetPropertyValue("Icon", "layui-icon layui-icon-group"); + menuList?.SetPropertyValue("Icon", "layui-icon layui-icon-menu-fill"); + dpList?.SetPropertyValue("Icon", "layui-icon layui-icon-auz"); + + var apifolder = GetFolderMenu("Api", new List { adminRole }); + apifolder.ShowOnMenu = false; + apifolder.DisplayOrder = 100; + var logList2 = GetMenu2(AllModules, "ActionLog", "MenuKey.ActionLog", new List { adminRole }, 1); + var userList2 = GetMenu2(AllModules, "FrameworkUser", "MenuKey.UserManagement", new List { adminRole }, 2); + var roleList2 = GetMenu2(AllModules, "FrameworkRole", "MenuKey.RoleManagement", new List { adminRole }, 3); + var groupList2 = GetMenu2(AllModules, "FrameworkGroup", "MenuKey.GroupManagement", new List { adminRole }, 4); + var menuList2 = GetMenu2(AllModules, "FrameworkMenu", "MenuKey.MenuMangement", new List { adminRole }, 5); + var dpList2 = GetMenu2(AllModules, "DataPrivilege", "MenuKey.DataPrivilege", new List { adminRole }, 6); + var apis = new FrameworkMenu[] { logList2, userList2, roleList2, groupList2, menuList2, dpList2 }; + //apis.ToList().ForEach(x => { x.ShowOnMenu = false;x.PageName += $"({Program._localizer["BuildinApi"]})"; }); + foreach (var item in apis) + { + if (item != null) + { + apifolder.Children.Add(item); + + } + } + Set().Add(apifolder); + } + else + { + systemManagement.Icon = " _wtmicon _wtmicon-icon_shezhi"; + logList?.SetPropertyValue("Icon", " _wtmicon _wtmicon-chaxun"); + userList?.SetPropertyValue("Icon", " _wtmicon _wtmicon-zhanghaoquanxianguanli"); + roleList?.SetPropertyValue("Icon", " _wtmicon _wtmicon-quanxianshenpi"); + groupList?.SetPropertyValue("Icon", " _wtmicon _wtmicon-zuzhiqunzu"); + menuList?.SetPropertyValue("Icon", " _wtmicon _wtmicon--lumingpai"); + dpList?.SetPropertyValue("Icon", " _wtmicon _wtmicon-anquan"); + } + } + + } + Set().AddRange(roles); + await SaveChangesAsync(); + } + return rv; + } + + private FrameworkMenu GetFolderMenu(string FolderText, List allowedRoles, bool isShowOnMenu = true, bool isInherite = false) + { + FrameworkMenu menu = new FrameworkMenu + { + PageName = "MenuKey." + FolderText, + Children = new List(), + Privileges = new List(), + ShowOnMenu = isShowOnMenu, + IsInside = true, + FolderOnly = true, + IsPublic = false, + DisplayOrder = 1 + }; + + if (allowedRoles != null) + { + foreach (var role in allowedRoles) + { + menu.Privileges.Add(new FunctionPrivilege { RoleCode = role.RoleCode, Allowed = true }); + + } + } + return menu; + } + + private FrameworkMenu GetMenu(List allModules, string areaName, string controllerName, string actionName, string pageKey, List allowedRoles, int displayOrder) + { + var acts = allModules.Where(x => x.ClassName == controllerName && (areaName == null || x.Area?.Prefix?.ToLower() == areaName.ToLower())).SelectMany(x => x.Actions).ToList(); + var act = acts.Where(x => x.MethodName == actionName).SingleOrDefault(); + var rest = acts.Where(x => x.MethodName != actionName && x.IgnorePrivillege == false).ToList(); + FrameworkMenu menu = GetMenuFromAction(act, true, allowedRoles, displayOrder); + if (menu != null) + { + menu.PageName = pageKey; + for (int i = 0; i < rest.Count; i++) + { + if (rest[i] != null) + { + var sub = GetMenuFromAction(rest[i], false, allowedRoles, (i + 1)); + sub.PageName = pageKey; + menu.Children.Add(sub); + } + } + } + return menu; + } + + private FrameworkMenu GetMenu2(List allModules, string controllerName, string pageKey, List allowedRoles, int displayOrder) + { + var acts = allModules.Where(x => x.FullName == $"WalkingTec.Mvvm.Admin.Api,{controllerName}" && x.IsApi == true).SelectMany(x => x.Actions).ToList(); + var rest = acts.Where(x => x.IgnorePrivillege == false).ToList(); + SimpleAction act = null; + if (acts.Count > 0) + { + act = acts[0]; + } + FrameworkMenu menu = GetMenuFromAction(act, true, allowedRoles, displayOrder); + if (menu != null) + { + menu.PageName = pageKey; + menu.Url = "/" + acts[0].Module.ClassName.ToLower(); + menu.ActionName = "MainPage"; + menu.ClassName = acts[0].Module.FullName; + menu.MethodName = null; + for (int i = 0; i < rest.Count; i++) + { + if (rest[i] != null) + { + var sub = GetMenuFromAction(rest[i], false, allowedRoles, (i + 1)); + sub.PageName = pageKey; + menu.Children.Add(sub); + } + } + } + return menu; + } + + private FrameworkMenu GetMenuFromAction(SimpleAction act, bool isMainLink, List allowedRoles, int displayOrder = 1) + { + if (act == null) + { + return null; + } + FrameworkMenu menu = new FrameworkMenu + { + //ActionId = act.ID, + //ModuleId = act.ModuleId, + ClassName = act.Module.FullName, + MethodName = act.MethodName, + Url = act.Url, + Privileges = new List(), + ShowOnMenu = isMainLink, + FolderOnly = false, + Children = new List(), + IsPublic = false, + IsInside = true, + DisplayOrder = displayOrder, + }; + if (isMainLink) + { + menu.ModuleName = act.Module.ModuleName; + menu.ActionName = act.ActionDes?.Description ?? act.ActionName; + menu.MethodName = null; + } + else + { + menu.ModuleName = act.Module.ModuleName; + menu.ActionName = act.ActionDes?.Description ?? act.ActionName; + } + if (allowedRoles != null) + { + foreach (var role in allowedRoles) + { + menu.Privileges.Add(new FunctionPrivilege { RoleCode = role.RoleCode, Allowed = true }); + + } + } + return menu; + } + + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Enums.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Enums.cs new file mode 100644 index 0000000..2058b09 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Enums.cs @@ -0,0 +1,156 @@ +using System.ComponentModel.DataAnnotations; + +namespace WalkingTec.Mvvm.Core +{ + public enum HttpMethodEnum + { + GET, + POST, + PUT, + DELETE + } + + + /// + /// 列表操作列类型 + /// + public enum ColumnFormatTypeEnum + { + Dialog,//弹出窗口 + Button,//按钮 + Download,//下载 + ViewPic,//查看图片 + Script,//脚本 + Html + } + + + /// + /// 数据库类型 + /// + public enum DBTypeEnum { SqlServer, MySql, PgSql, Memory, SQLite, Oracle } + + /// + /// 页面显示方式 + /// + public enum PageModeEnum { Single, Tab } + + /// + /// Tab页的显示方式 + /// + public enum TabModeEnum { Default, Simple } + + public enum BlazorModeEnum { Server, Wasm} + + /// + /// 按钮 + /// + public enum ButtonTypesEnum + { + Button, + Link + }; + + /// + /// 按钮 + /// + public enum RedirectTypesEnum + { + Layer, + Self, + NewWindow, + NewTab, + }; + + /// + /// 日期类型 + /// + public enum DateTimeTypeEnum + { + /// + /// 日期选择器 + /// 可选择:年、月、日 + /// + Date, + /// + /// 日期时间选择器 + /// 可选择:年、月、日、时、分、秒 + /// + DateTime, + /// + /// 年选择器 + /// 只提供年列表选择 + /// + Year, + /// + /// 年月选择器 + /// 只提供年、月选择 + /// + Month, + /// + /// 时间选择器 + /// 只提供时、分、秒选择 + /// + Time + }; + + /// + /// 图形枚举 + /// + public enum ChartEnum + { + line, + pie, + column, + bubble, + barcolumn + } + + /// + /// 图形统计值类型 + /// + public enum ChartValueType + { + sum, + count, + sumpct, + countpct + } + /// + /// 图形统计分区类型 + /// + public enum PartitionType + { + year, + month, + day, + hour, + minute, + second + } + + public enum UIEnum + { LayUI, React, VUE,Blazor } + + + + public enum BoolComboTypes { YesNo, ValidInvalid, MaleFemale, HaveNotHave, Custom } + + public enum SortDir { Asc, Desc } + + public enum BackgroudColorEnum + { + Grey, + Yellow, + Red + }; + + public enum GenderEnum + { + [Display(Name = "Sys.Male")] + Male = 0, + [Display(Name = "Sys.Female")] + Female = 1 + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Exceptions/NullOrEmptyStringException.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Exceptions/NullOrEmptyStringException.cs new file mode 100644 index 0000000..a343314 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Exceptions/NullOrEmptyStringException.cs @@ -0,0 +1,17 @@ +using System; +using System.Runtime.Serialization; + +namespace WalkingTec.Mvvm.Core.Exceptions +{ + /// + /// 对象为 null 或 空字符串 异常 + /// + public class NullOrEmptyStringException : Exception + { + public const string DEFAULT_EXCEPTION_MSG = "对象为 null 或 空字符串 异常"; + public NullOrEmptyStringException() : base(DEFAULT_EXCEPTION_MSG) { } + public NullOrEmptyStringException(string message) : base(message) { } + public NullOrEmptyStringException(string message, Exception innerException) : base(message, innerException) { } + protected NullOrEmptyStringException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/ConfigExtension.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/ConfigExtension.cs new file mode 100644 index 0000000..8b0b915 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/ConfigExtension.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Text; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; + +namespace WalkingTec.Mvvm.Core.Extensions +{ + public static class ConfigExtension + { + /// + /// + /// + /// + /// + /// + /// + /// + public static IConfigurationBuilder WTMConfig(this IConfigurationBuilder configBuilder, IHostEnvironment env, string jsonFileDir=null, string jsonFileName = null) + { + IConfigurationBuilder rv = configBuilder; + if (string.IsNullOrEmpty(jsonFileDir)) + { + rv = rv.WTM_SetCurrentDictionary(); + } + else + { + rv = rv.SetBasePath(jsonFileDir); + } + if (string.IsNullOrEmpty(jsonFileName)) + { + rv = rv.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); + } + else + { + rv = rv.AddJsonFile(jsonFileName, optional: true, reloadOnChange: true); + } + rv = rv.AddEnvironmentVariables(); + if (env != null) + { + rv = rv.AddInMemoryCollection(new Dictionary { { "HostRoot", env.ContentRootPath } }); + } + else + { + rv = rv.AddInMemoryCollection(new Dictionary { { "HostRoot", Directory.GetCurrentDirectory() } }); + } + return rv; + } + + + public static IConfigurationBuilder WTM_SetCurrentDictionary(this IConfigurationBuilder cb) + { + CurrentDirectoryHelpers.SetCurrentDirectory(); + + if (!File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json"))) + { + var binLocation = Assembly.GetEntryAssembly()?.Location; + if (!string.IsNullOrEmpty(binLocation)) + { + var binPath = new FileInfo(binLocation).Directory?.FullName; + if (File.Exists(Path.Combine(binPath, "appsettings.json"))) + { + Directory.SetCurrentDirectory(binPath); + cb.SetBasePath(binPath); + //.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) + //.AddEnvironmentVariables(); + } + } + } + else + { + cb.SetBasePath(Directory.GetCurrentDirectory()); + } + return cb; + } + + } + + /// + /// 解决IIS InProgress下CurrentDirectory获取错误的问题 + /// + internal class CurrentDirectoryHelpers + + { + + internal const string AspNetCoreModuleDll = "aspnetcorev2_inprocess.dll"; + + + + [System.Runtime.InteropServices.DllImport("kernel32.dll")] + + private static extern IntPtr GetModuleHandle(string lpModuleName); + + + + [System.Runtime.InteropServices.DllImport(AspNetCoreModuleDll)] + + private static extern int http_get_application_properties(ref IISConfigurationData iiConfigData); + + + + [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] + + private struct IISConfigurationData + + { + + public IntPtr pNativeApplication; + + [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.BStr)] + + public string pwzFullApplicationPath; + + [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.BStr)] + + public string pwzVirtualApplicationPath; + + public bool fWindowsAuthEnabled; + + public bool fBasicAuthEnabled; + + public bool fAnonymousAuthEnable; + + } + + + + public static void SetCurrentDirectory() + + { + + try + + { + + // Check if physical path was provided by ANCM + + var sitePhysicalPath = Environment.GetEnvironmentVariable("ASPNETCORE_IIS_PHYSICAL_PATH"); + + if (string.IsNullOrEmpty(sitePhysicalPath)) + + { + + // Skip if not running ANCM InProcess + + if (GetModuleHandle(AspNetCoreModuleDll) == IntPtr.Zero) + + { + + return; + + } + + + + IISConfigurationData configurationData = default(IISConfigurationData); + + if (http_get_application_properties(ref configurationData) != 0) + + { + + return; + + } + + + + sitePhysicalPath = configurationData.pwzFullApplicationPath; + + } + + + + Environment.CurrentDirectory = sitePhysicalPath; + + } + + catch + + { + + // ignore + + } + + } + + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/DCExtension.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/DCExtension.cs new file mode 100644 index 0000000..41ca0e0 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/DCExtension.cs @@ -0,0 +1,1112 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data.Common; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using System.Transactions; +using Microsoft.EntityFrameworkCore; +using WalkingTec.Mvvm.Core.Support.Json; + +namespace WalkingTec.Mvvm.Core.Extensions +{ + /// + /// DC相关扩展函数 + /// + public static class DCExtension + { + #region 树形下拉 + /// + /// 查询数据源,并转化成TreeSelectListItem列表 + /// + /// 数据源类型 + /// 基础查询 + /// wtm context + /// 表达式用来获取Text字段对应的值 + /// 表达式用来获取Value字段对应的值,不指定则默认使用Id字段 + /// 表达式用来获取icon字段对应的值 + /// 表达式用来获取Url字段对应的值 + /// 表达式用来获取Tag字段对应的值 + /// 表达式用来获取Expanded字段对应的值,指示节点是否展开 + /// 忽略数据权限判断 + /// 是否根据Text字段排序,默认为是 + /// SelectListItem列表 + public static List GetTreeSelectListItems(this IQueryable baseQuery + , WTMContext wtmcontext + , Expression> textField + , Expression> valueField = null + , Expression> iconField = null + , Expression> urlField = null + , Expression> tagField = null + , Expression> expandField = null + , bool ignorDataPrivilege = false + , bool SortByName = true) + where T : TreePoco + { + var dps = wtmcontext?.LoginUserInfo?.DataPrivileges; + var query = baseQuery.AsNoTracking(); + + //如果没有指定忽略权限,则拼接权限过滤的where条件 + if (ignorDataPrivilege == false) + { + query = AppendSelfDPWhere(query, wtmcontext, dps); + } + + if (typeof(IPersistPoco).IsAssignableFrom(typeof(T))) + { + var mod = new IsValidModifier(); + var newExp = mod.Modify(query.Expression); + query = query.Provider.CreateQuery(newExp) as IOrderedQueryable; + } + + //处理后面要使用的expression + //if (valueField == null) + //{ + valueField = x => x.GetID().ToString(); + //} + Expression> parentField = x => x.GetParentID().ToString(); + + //定义PE + ParameterExpression pe = Expression.Parameter(typeof(T)); + ChangePara cp = new ChangePara(); + + //创建新类,形成类似 new SimpleTreeTextAndValue() 的表达式 + NewExpression newItem = Expression.New(typeof(TreeSelectListItem)); + + //绑定Text字段,形成类似 Text = textField 的表达式 + var textMI = typeof(TreeSelectListItem).GetMember("Text")[0]; + MemberBinding textBind = Expression.Bind(textMI, cp.Change(textField.Body, pe)); + + //绑定Value字段,形成类似 Value = valueField 的表达式 + var valueMI = typeof(TreeSelectListItem).GetMember("Value")[0]; + MemberBinding valueBind = Expression.Bind(valueMI, cp.Change(valueField.Body, pe)); + + //绑定ParentId字段,形成类似 Value = valueField 的表达式 + var parentMI = typeof(TreeSelectListItem).GetMember("ParentId")[0]; + MemberBinding parentBind = Expression.Bind(parentMI, cp.Change(parentField.Body, pe)); + + //绑定Url字段,形成类似 Value = valueField 的表达式 + MemberBinding urlBind = null; + var urlMI = typeof(TreeSelectListItem).GetMember("Url")[0]; + if (urlField != null) + { + urlBind = Expression.Bind(urlMI, cp.Change(urlField.Body, pe)); + } + else + { + urlBind = Expression.Bind(urlMI, Expression.Constant(string.Empty)); + } + + //绑定icon字段,形成类似 Icon = iconField 的表达式 + MemberBinding iconBind = null; + var iconMI = typeof(TreeSelectListItem).GetMember("Icon")[0]; + if (iconField != null) + { + iconBind = Expression.Bind(iconMI, cp.Change(iconField.Body, pe)); + } + else + { + iconBind = Expression.Bind(iconMI, Expression.Constant(string.Empty)); + } + + //绑定Tag字段,形成类似 Value = valueField 的表达式 + MemberBinding tagBind = null; + var tagMI = typeof(TreeSelectListItem).GetMember("Tag")[0]; + if (tagField != null) + { + tagBind = Expression.Bind(tagMI, cp.Change(tagField.Body, pe)); + } + else + { + tagBind = Expression.Bind(tagMI, Expression.Constant("")); + } + + //绑定Tag字段,形成类似 Value = valueField 的表达式 + MemberBinding expandBind = null; + var expandMI = typeof(TreeSelectListItem).GetMember("Expended")[0]; + if (expandField != null) + { + expandBind = Expression.Bind(expandMI, cp.Change(expandField.Body, pe)); + } + else + { + expandBind = Expression.Bind(expandMI, Expression.Constant(false)); + } + + //合并创建新类和绑定字段的表达式,形成类似 new SimpleTextAndValue{ Text = textField, Value = valueField} 的表达式 + MemberInitExpression init = Expression.MemberInit(newItem, textBind, valueBind, iconBind, parentBind, urlBind, tagBind, expandBind); + + //将最终形成的表达式转化为Lambda,形成类似 x=> new SimpleTextAndValue { Text = x.textField, Value = x.valueField} 的表达式 + var lambda = Expression.Lambda>(init, pe); + + List rv = null; + + //根据Text对下拉菜单数据排序 + if (SortByName == true) + { + rv = query.Select(lambda).ToList().OrderBy(x => x.Text).ToList(); + } + else + { + rv = query.Select(lambda).ToList(); + } + + List toDel = new List(); + + rv.ForEach(x => + { + var c = rv.Where(y => y.ParentId == x.Value.ToString()).ToList(); + x.Children = c; + toDel.AddRange(c); + }); + toDel.ForEach(x => rv.Remove(x)); + return rv.ToList(); + } + + #endregion + + #region 下拉 + /// + /// 查询数据源,并转化成SelectListItem列表 + /// + /// 数据源类型 + /// 基础查询 + /// Wtm Context + /// SelectListItem中Text字段对应的值 + /// SelectListItem中Value字段对应的值,默认为Id列 + /// 忽略数据权限判断 + /// 是否根据Text字段排序,默认为是 + /// SelectListItem列表 + public static List GetSelectListItems(this IQueryable baseQuery + , WTMContext wtmcontext + , Expression> textField + , Expression> valueField = null + , bool ignorDataPrivilege = false + , bool SortByName = true) + where T : TopBasePoco + { + var dps = wtmcontext?.LoginUserInfo?.DataPrivileges; + var query = baseQuery.AsNoTracking(); + + //如果value字段为空,则默认使用Id字段作为value值 + if (valueField == null) + { + valueField = x => x.GetID().ToString(); + } + + //如果没有指定忽略权限,则拼接权限过滤的where条件 + if (ignorDataPrivilege == false) + { + query = AppendSelfDPWhere(query,wtmcontext,dps); + } + + if (typeof(IPersistPoco).IsAssignableFrom( typeof(T))) + { + var mod = new IsValidModifier(); + var newExp = mod.Modify(query.Expression); + query = query.Provider.CreateQuery(newExp) as IOrderedQueryable; + } + + + //定义PE + ParameterExpression pe = Expression.Parameter(typeof(T)); + ChangePara cp = new ChangePara(); + //创建新类,形成类似 new SimpleTextAndValue() 的表达式 + NewExpression newItem = Expression.New(typeof(ComboSelectListItem)); + + //绑定Text字段,形成类似 Text = textField 的表达式 + var textMI = typeof(ComboSelectListItem).GetMember("Text")[0]; + MemberBinding textBind = Expression.Bind(textMI, cp.Change(textField.Body, pe)); + + + //绑定Value字段,形成类似 Value = valueField 的表达式 + var valueMI = typeof(ComboSelectListItem).GetMember("Value")[0]; + MemberBinding valueBind = Expression.Bind(valueMI, cp.Change(valueField.Body, pe)); + + //如果是树形结构,给ParentId赋值 + MemberBinding parentBind = null; + var parentMI = typeof(ComboSelectListItem).GetMember("ParentId")[0]; + if (typeof(TreePoco<>).IsAssignableFrom(typeof(T))) + { + var parentMember = Expression.MakeMemberAccess(pe, typeof(TreePoco<>).GetSingleProperty("ParentId")); + var p = Expression.Call(parentMember, "ToString", new Type[] { }); + //var p1 = Expression.Call(p, "ToLower", new Type[] { }); + parentBind = Expression.Bind(parentMI, p); + } + else + { + parentBind = Expression.Bind(parentMI, Expression.Constant(string.Empty)); + } + + //合并创建新类和绑定字段的表达式,形成类似 new SimpleTextAndValue{ Text = textField, Value = valueField} 的表达式 + MemberInitExpression init = Expression.MemberInit(newItem, textBind, valueBind, parentBind); + + //将最终形成的表达式转化为Lambda,形成类似 x=> new SimpleTextAndValue { Text = x.textField, Value = x.valueField} 的表达式 + var lambda = Expression.Lambda>(init, pe); + + + List rv = new List(); + //根据Text对下拉菜单数据排序 + if (SortByName == true) + { + rv = query.Select(lambda).ToList().OrderBy(x => x.Text).ToList(); + } + else + { + rv = query.Select(lambda).ToList(); + } + + return rv; + } + + #endregion + + /// + /// 拼接本表的数据权限过滤 + /// + /// 数据类 + /// 源query + /// Wtm context + /// 数据权限列表 + /// 拼接好where条件的query + private static IQueryable AppendSelfDPWhere(IQueryable query, WTMContext wtmcontext, List dps) where T : TopBasePoco + { + var dpsSetting = wtmcontext?.DataPrivilegeSettings; + Type modelTye = typeof(T); + bool isBasePoco = typeof(IBasePoco).IsAssignableFrom(modelTye); + ParameterExpression pe = Expression.Parameter(modelTye); + Expression peid = Expression.Property(pe, modelTye.GetSingleProperty("ID")); + //循环数据权限,加入到where条件中,达到自动过滤的效果 + + Expression selfexp = Expression.NotEqual(Expression.Constant(1), Expression.Constant(1)); + if(isBasePoco == true) + { + selfexp = Expression.Equal(Expression.Property(pe, "CreateBy"), Expression.Constant(wtmcontext.LoginUserInfo?.ITCode)); + } + if (dpsSetting?.Where(x => x.ModelName == query.ElementType.Name).SingleOrDefault() != null) + { + //如果dps参数是空,则生成 1!=1 这种错误的表达式,这样就查不到任何数据了 + if (dps == null) + { + query = query.Where(Expression.Lambda>(selfexp, pe)); + } + else + { + //在dps中找到和baseQuery源数据表名一样的关联id + var ids = dps.Where(x => x.TableName == query.ElementType.Name).Select(x => x.RelateId).ToList(); + if (ids == null || ids.Count() == 0) + { + query = query.Where(Expression.Lambda>(selfexp, pe)); + } + else + { + if (!ids.Contains(null)) + { + var exp = Expression.OrElse(selfexp, ids.GetContainIdExpression(typeof(T), pe).Body); + query = query.Where(Expression.Lambda>(exp,pe)); + } + } + } + } + return query; + } + + /// + /// 为查询语句添加关联表的权限过滤 + /// + /// 源数据类 + /// 源Query + /// + /// 关联表外键 + /// 修改后的查询语句 + public static IQueryable DPWhere(this IQueryable baseQuery, WTMContext wtmcontext, params Expression>[] IdFields) where T:TopBasePoco + { + var dps = wtmcontext?.LoginUserInfo?.DataPrivileges; + //循环所有关联外键 + List tableNameList = new List(); + foreach (var IdField in IdFields) + { + + //将外键 Id 用.分割,循环生成指向最终id的表达式,比如x=> x.a.b.Id + var fieldName = IdField.GetPropertyName(false); + //获取关联的类 + string typename = ""; + //如果外键名称不是‘id’,则根据model层的命名规则,它应该是xxxId,所以抹掉最后的 Id 应该是关联的类名 + if (fieldName.ToLower() != "id") + { + fieldName = fieldName.Remove(fieldName.Length - 2); + typename = IdField.GetPropertyInfo().DeclaringType.GetSingleProperty(fieldName).PropertyType.Name; + } + //如果是 Id,则本身就是关联的类 + else + { + typename = typeof(T).Name; + } + tableNameList.Add(typename); + + } + //var test = DPWhere(baseQuery, dps, tableNameList, IdFields); + return DPWhere(baseQuery,wtmcontext,tableNameList, IdFields); + } + + #region AddBy YOUKAI 20160310 + /// + /// 为查询语句添加关联表的权限过滤 + /// + /// 源数据类 + /// 源Query + /// wtm context + /// 关联数据权限的表名,如果关联外键为自身,则参数第一个为自身 + /// 关联表外键 + /// 修改后的查询语句 + public static IQueryable DPWhere(this IQueryable baseQuery,WTMContext wtmcontext,List tableName, params Expression>[] IdFields) where T:TopBasePoco + { + var dps = wtmcontext?.LoginUserInfo?.DataPrivileges; + Type modelTye = typeof(T); + bool isBasePoco = typeof(IBasePoco).IsAssignableFrom(modelTye); + + // var dpsSetting = BaseVM.AllDPS; + ParameterExpression pe = Expression.Parameter(modelTye); + Expression left1 = Expression.Constant(1); + Expression right1 = Expression.Constant(1); + Expression trueExp = Expression.Equal(left1, right1); + Expression falseExp = Expression.NotEqual(left1, right1); + Expression finalExp = null; + Expression selfexp = falseExp; + if (isBasePoco == true) + { + selfexp = Expression.Equal(Expression.Property(pe, "CreateBy"), Expression.Constant(wtmcontext.LoginUserInfo?.ITCode)); + } + int tindex = 0; + //循环所有关联外键 + foreach (var IdField in IdFields) + { + bool mtm = false; + Expression exp = trueExp; + //将外键Id用.分割,循环生成指向最终id的表达式,比如x=> x.a.b.Id + var fullname = IdField.GetPropertyName(); + string[] splits = fullname.Split('.'); + int leftindex = splits[0].IndexOf('['); + if (leftindex > 0) + { + mtm = true; + splits[0] = splits[0].Substring(0, leftindex); + } + Expression peid = Expression.MakeMemberAccess(pe, pe.Type.GetSingleProperty(splits[0])); + Type middletype = null; + if (mtm) + { + middletype = peid.Type.GetGenericArguments()[0]; + + } + else + { + for (int i = 1; i < splits.Length; i++) + { + peid = Expression.MakeMemberAccess(peid, peid.Type.GetSingleProperty(splits[i])); + } + middletype = (peid as MemberExpression).Member.DeclaringType; + } + //如果dps为空,则拼接一个返回假的表达式,这样就查询不出任何数据 + if (dps == null) + { + exp = selfexp; + } + else + { + var fieldName = IdField.GetPropertyName(false); + //如果外键名称不是‘id’,则根据model层的命名规则,它应该是xxxId,所以抹掉最后的 Id 应该是关联的类名 + if (fieldName.ToLower() != "id") + { + fieldName = fieldName.Remove(fieldName.Length - 2); + var typeinfo = middletype.GetSingleProperty(fieldName); + //var IsTableName = tableName?.Where(x => x == fieldName).FirstOrDefault(); + var IsTableName = tableName?.Where(x => x.ToLower() == typeinfo.PropertyType.Name.ToLower()).FirstOrDefault(); + if (string.IsNullOrEmpty(IsTableName)) + { + continue; + } + fieldName = IsTableName; + //typename = PropertyHelper.GetPropertyInfo(IdField).DeclaringType.GetProperty(fieldName).PropertyType.Name; + } + //如果是Id,则本身就是关联的类 + else + { + fieldName = tableName[tindex]; + } + var dpsSetting = wtmcontext.DataPrivilegeSettings; + + //循环系统设定的数据权限,如果没有和关联类一样的表,则跳过 + if (dpsSetting.Where(x => x.ModelName == fieldName).SingleOrDefault() == null) + { + continue; + } + //获取dps中关联到关联类的id列表 + var ids = dps.Where(x => x.TableName == fieldName).Select(x => x.RelateId).ToList(); + //如果没有关联的id,则拼接一个返回假的where,是语句查询不到任何数据 + if (ids == null || ids.Count() == 0) + { + exp = selfexp; + } + //如果有关联 Id + else + { + //如果关联 Id 不包含null,则生成类似 x=> ids.Contains(x.a.b.Id) 这种条件 + //如果关联 Id 包括null,则代表可以访问所有数据,就不需要再拼接where条件了 + if (!ids.Contains(null)) + { + if (mtm == true) + { + ParameterExpression midpe = Expression.Parameter(middletype); + Expression middleid = Expression.PropertyOrField(midpe, IdField.GetPropertyName(false)); + + var queryable = Expression.Call( + typeof(Queryable), + "AsQueryable", + new Type[] { middletype }, + peid); + + List ddd = new List(); + + exp = Expression.Call( + typeof(Queryable), + "Any", + new Type[] { middletype }, + queryable, + Expression.Lambda(typeof(Func<,>).MakeGenericType(middletype, typeof(bool)), ids.GetContainIdExpression(middletype, midpe, middleid).Body, new ParameterExpression[] { midpe })); + + } + else + { + exp = ids.GetContainIdExpression(typeof(T), pe, peid).Body; + } + exp = Expression.OrElse(selfexp, exp); + } + } + } + //把所有where里的条件用And拼接在一起 + if (finalExp == null) + { + finalExp = exp; + } + else + { + finalExp = Expression.OrElse(finalExp, exp); + } + tindex++; + } + //如果没有进行任何修改,则还返回baseQuery + if (finalExp == null) + { + return baseQuery; + } + else + { + //返回加入了where条件之后的baseQuery + var query = baseQuery.Where(Expression.Lambda>(finalExp, pe)); + return query; + } + } + #endregion + + public static IOrderedQueryable Sort(this IQueryable baseQuery, string sortInfo, params SortInfo[] defaultSorts) where T : TopBasePoco + { + List info = new List(); + IOrderedQueryable rv = null; + if (string.IsNullOrEmpty(sortInfo)) + { + if (defaultSorts == null || defaultSorts.Length == 0) + { + ParameterExpression pe = Expression.Parameter(typeof(T)); + var idproperty = typeof(T).GetSingleProperty("ID"); + Expression pro = Expression.Property(pe, idproperty); + Type proType = typeof(Guid); + Expression final = Expression.Call( + typeof(Queryable), + "OrderBy", + new Type[] { typeof(T), proType }, + baseQuery.Expression, + Expression.Lambda(pro, new ParameterExpression[] { pe })); + rv = baseQuery.Provider.CreateQuery(final) as IOrderedQueryable; + return rv; + } + else + { + info.AddRange(defaultSorts); + } + } + else + { + var temp = JsonSerializer.Deserialize>(sortInfo); + info.AddRange(temp); + } + foreach (var item in info) + { + ParameterExpression pe = Expression.Parameter(typeof(T)); + var idproperty = typeof(T).GetSingleProperty(item.Property); + Expression pro = Expression.Property(pe, idproperty); + Type proType = typeof(T).GetSingleProperty(item.Property).PropertyType; + if (item.Direction == SortDir.Asc) + { + if (rv == null) + { + Expression final = Expression.Call( + typeof(Queryable), + "OrderBy", + new Type[] { typeof(T), proType }, + baseQuery.Expression, + Expression.Lambda(pro, new ParameterExpression[] { pe })); + rv = baseQuery.Provider.CreateQuery(final) as IOrderedQueryable; + } + else + { + Expression final = Expression.Call( + typeof(Queryable), + "ThenBy", + new Type[] { typeof(T), proType }, + rv.Expression, + Expression.Lambda(pro, new ParameterExpression[] { pe })); + rv = rv.Provider.CreateQuery(final) as IOrderedQueryable; + } + } + if (item.Direction == SortDir.Desc) + { + if (rv == null) + { + Expression final = Expression.Call( + typeof(Queryable), + "OrderByDescending", + new Type[] { typeof(T), proType }, + baseQuery.Expression, + Expression.Lambda(pro, new ParameterExpression[] { pe })); + rv = baseQuery.Provider.CreateQuery(final) as IOrderedQueryable; + } + else + { + Expression final = Expression.Call( + typeof(Queryable), + "ThenByDescending", + new Type[] { typeof(T), proType }, + rv.Expression, + Expression.Lambda(pro, new ParameterExpression[] { pe })); + rv = rv.Provider.CreateQuery(final) as IOrderedQueryable; + } + } + } + return rv; + } + + public static IQueryable CheckID(this IQueryable baseQuery, object val, Expression> member=null) + { + ParameterExpression pe = Expression.Parameter(typeof(T)); + PropertyInfo idproperty = null; + if (member == null) + { + idproperty = typeof(T).GetSingleProperty("ID"); + } + else + { + idproperty = member.GetPropertyInfo(); + } + Expression peid = Expression.Property(pe, idproperty); + var convertid = PropertyHelper.ConvertValue(val, idproperty.PropertyType); + return baseQuery.Where(Expression.Lambda>(Expression.Equal(peid, Expression.Constant(convertid)), pe)); + } + + public static IQueryable CheckParentID(this IQueryable baseQuery, string val) + { + ParameterExpression pe = Expression.Parameter(typeof(T)); + PropertyInfo idproperty = null; + idproperty = typeof(T).GetSingleProperty("ParentId"); + Expression peid = Expression.Property(pe, idproperty); + var p = Expression.Call(peid, "ToString", new Type[] { }); + if(val == null) + { + return baseQuery.Where(Expression.Lambda>(Expression.Equal(peid, Expression.Constant(null)), pe)); + } + else + { + return baseQuery.Where(Expression.Lambda>(Expression.Equal(p, Expression.Constant(val)), pe)); + } + } + + + public static IQueryable CheckIDs(this IQueryable baseQuery, List val, Expression> member = null) + { + if(val == null) + { + return baseQuery; + } + ParameterExpression pe = Expression.Parameter(typeof(T)); + PropertyInfo idproperty = null; + if (member == null) + { + idproperty = typeof(T).GetSingleProperty("ID"); + } + else + { + idproperty = member.GetPropertyInfo(); + } + Expression peid = Expression.Property(pe, idproperty); + var exp = val.GetContainIdExpression(typeof(T), pe, peid).Body; + return baseQuery.Where(Expression.Lambda>(exp, pe)); + } + + + public static IQueryable CheckNotNull(this IQueryable baseQuery, Expression> member) + { + return baseQuery.CheckNotNull(member.GetPropertyName()); + } + + public static IQueryable CheckNotNull(this IQueryable baseQuery, string member) + { + ParameterExpression pe = Expression.Parameter(typeof(T)); + PropertyInfo idproperty = typeof(T).GetSingleProperty(member); + Expression peid = Expression.Property(pe, idproperty); + return baseQuery.Where(Expression.Lambda>(Expression.NotEqual(peid, Expression.Constant(null)), pe)); + } + + + public static IQueryable CheckNull(this IQueryable baseQuery, Expression> member) + { + ParameterExpression pe = Expression.Parameter(typeof(T)); + PropertyInfo idproperty = typeof(T).GetSingleProperty(member.GetPropertyName()); + Expression peid = Expression.Property(pe, idproperty); + return baseQuery.Where(Expression.Lambda>(Expression.Equal(peid, Expression.Constant(null)), pe)); + } + + /// + /// val不为空时,附加查询条件 + /// + /// + /// + /// + /// + /// + /// + public static IQueryable CheckWhere(this IQueryable baseQuery, S val, Expression> where) + { + if (val == null) + { + return baseQuery; + } + else if(val is string s && string.IsNullOrEmpty(s)) + { + return baseQuery; + } + else + { + if (typeof(IList).IsAssignableFrom(val.GetType())) + { + if (((IList)val).Count == 0) + { + return baseQuery; + } + } + return baseQuery.Where(where); + } + } + + /// + /// 条件为true时,附加查询条件 + /// + /// + /// + /// bool? + /// + /// + public static IQueryable WhereIf(this IQueryable baseQuery, bool? val, Expression> where) + { + if (val == null || val == false) + { + return baseQuery; + } + return baseQuery.Where(where); + } + + public static IQueryable CheckEqual(this IQueryable baseQuery, string val, Expression> field) + { + if (val == null || val == "") + { + return baseQuery; + } + else + { + val = val.Trim(); + var equal = Expression.Equal(field.Body, Expression.Constant(val)); + var where = Expression.Lambda>(equal, field.Parameters[0]); + return baseQuery.Where(where); + } + } + + public static IQueryable CheckEqual(this IQueryable baseQuery, S? val, Expression> field) + where S : struct + { + if (val == null) + { + return baseQuery; + } + else + { + var equal = Expression.Equal(Expression.PropertyOrField(field.Body, "Value"), Expression.Constant(val)); + var where = Expression.Lambda>(equal, field.Parameters[0]); + return baseQuery.Where(where); + } + } + + public static IQueryable CheckEqual(this IQueryable baseQuery, S val, Expression> field) + where S : struct + { + S? a = val; + return baseQuery.CheckEqual(a, field); + } + + + public static IQueryable CheckBetween(this IQueryable baseQuery, S? valMin, S? valMax, Expression> field, bool includeMin = true, bool includeMax = true) + where S : struct + { + if (valMin == null && valMax == null) + { + return baseQuery; + } + else + { + IQueryable rv = baseQuery; + if (valMin != null) + { + BinaryExpression exp1 = !includeMin ? Expression.GreaterThan(Expression.PropertyOrField(field.Body, "Value"), Expression.Constant(valMin)) : Expression.GreaterThanOrEqual(Expression.PropertyOrField(field.Body, "Value"), Expression.Constant(valMin)); + rv = rv.Where(Expression.Lambda>(exp1, field.Parameters[0])); + } + if (valMax != null) + { + BinaryExpression exp2 = !includeMax ? Expression.LessThan(Expression.PropertyOrField(field.Body, "Value"), Expression.Constant(valMax)) : Expression.LessThanOrEqual(Expression.PropertyOrField(field.Body, "Value"), Expression.Constant(valMax)); + rv = rv.Where(Expression.Lambda>(exp2, field.Parameters[0])); + } + return rv; + } + } + + public static IQueryable CheckBetween(this IQueryable baseQuery, S valMin, S valMax, Expression> field, bool includeMin = true, bool includeMax = true) +where S : struct + { + S? a = valMin; + S? b = valMax; + return CheckBetween(baseQuery, a, b, field, includeMin, includeMax); + } + + public static IQueryable CheckBetween(this IQueryable baseQuery, S? valMin, S valMax, Expression> field, bool includeMin = true, bool includeMax = true) +where S : struct + { + S? a = valMin; + S? b = valMax; + return CheckBetween(baseQuery, a, b, field, includeMin, includeMax); + } + + public static IQueryable CheckBetween(this IQueryable baseQuery, S valMin, S? valMax, Expression> field, bool includeMin = true, bool includeMax = true) +where S : struct + { + S? a = valMin; + S? b = valMax; + return CheckBetween(baseQuery, a, b, field, includeMin, includeMax); + } + + public static IQueryable CheckContain(this IQueryable baseQuery, string val, Expression> field, bool ignoreCase = true) + { + if (string.IsNullOrEmpty(val)) + { + return baseQuery; + } + else + { + val = val.Trim(); + Expression exp = null; + if (ignoreCase == true) + { + var tolower = Expression.Call(field.Body, "ToLower", null); + exp = Expression.Call(tolower, "Contains", null, Expression.Constant(val.ToLower())); + } + else + { + exp = Expression.Call(field.Body, "Contains", null, Expression.Constant(val)); + + } + var where = Expression.Lambda>(exp, field.Parameters[0]); + return baseQuery.Where(where); + } + } + + public static IQueryable CheckContain(this IQueryable baseQuery, List val, Expression> field) + { + if (val == null || val.Count == 0 || (val.Count == 1 && val[0] == null)) + { + return baseQuery; + } + else + { + Expression exp = null; + exp = Expression.Call(Expression.Constant(val), "Contains", null, field.Body); + + var where = Expression.Lambda>(exp, field.Parameters[0]); + return baseQuery.Where(where); + } + } + + public static IQueryable DynamicSelect(this IQueryable baseQuery, string fieldName) + { + ParameterExpression pe = Expression.Parameter(typeof(T)); + var idproperty = typeof(T).GetSingleProperty(fieldName); + Expression pro = Expression.Property(pe, idproperty); + Expression tostring = Expression.Call(pro, "ToString", new Type[] { }); + Type proType = typeof(string); + Expression final = Expression.Call( + typeof(Queryable), + "Select", + new Type[] { typeof(T), proType }, + baseQuery.Expression, + Expression.Lambda(tostring, new ParameterExpression[] { pe })); + var rv = baseQuery.Provider.CreateQuery(final) as IOrderedQueryable; + return rv; + } + + + public static string GetTableName(this IDataContext self) + { + return self.Model.FindEntityType(typeof(T)).GetTableName(); + } + + /// + /// 通过模型和模型的某个List属性的名称来判断List的字表中关联到主表的主键名称 + /// + /// 主表Model + /// DataContext + /// 主表中的子表List属性名称 + /// 主键名称 + public static string GetFKName(this IDataContext self, string listFieldName) where T : class + { + return GetFKName(self, typeof(T), listFieldName); + } + + /// + /// 通过模型和模型的某个List属性的名称来判断List的字表中关联到主表的主键名称 + /// + /// DataContext + /// 主表model类型 + /// 主表中的子表List属性名称 + /// 主键名称 + public static string GetFKName(this IDataContext self, Type sourceType, string listFieldName) + { + try + { + var test = self.Model.FindEntityType(sourceType).GetReferencingForeignKeys().Where(x => x.PrincipalToDependent?.Name == listFieldName).FirstOrDefault(); + if (test != null && test.Properties.Count > 0) + { + return test.Properties[0].Name; + } + else + { + return ""; + } + } + catch + { + return ""; + } + } + + + /// + /// 通过子表模型和模型关联到主表的属性名称来判断该属性对应的主键名称 + /// + /// 子表Model + /// DataContext + /// 关联主表的属性名称 + /// 主键名称 + public static string GetFKName2(this IDataContext self, string FieldName) where T : class + { + return GetFKName2(self, typeof(T), FieldName); + } + + /// + /// 通过模型和模型关联到主表的属性名称来判断该属性对应的主键名称 + /// + /// DataContext + /// 子表model类型 + /// 关联主表的属性名称 + /// 主键名称 + public static string GetFKName2(this IDataContext self, Type sourceType, string FieldName) + { + try + { + var test = self.Model.FindEntityType(sourceType).GetForeignKeys().Where(x => x.DependentToPrincipal?.Name == FieldName).FirstOrDefault(); + if (test != null && test.Properties.Count > 0) + { + return test.Properties[0].Name; + } + else + { + return ""; + } + } + catch + { + return ""; + } + } + + public static string GetFieldName(this IDataContext self, Expression> field) + { + string pname = field.GetPropertyName(); + return self.GetFieldName(pname); + } + + + public static string GetFieldName(this IDataContext self, string fieldname) + { + var rv = self.Model.FindEntityType(typeof(T)).FindProperty(fieldname); + return rv?.GetColumnName(new Microsoft.EntityFrameworkCore.Metadata.StoreObjectIdentifier()); + } + + public static string GetPropertyNameByFk(this IDataContext self, Type sourceType, string fkname) + { + try + { + var test = self.Model.FindEntityType(sourceType).GetForeignKeys().Where(x => x.DependentToPrincipal?.ForeignKey?.Properties[0]?.Name == fkname).FirstOrDefault(); + if (test != null && test.Properties.Count > 0) + { + return test.DependentToPrincipal.Name; + } + else + { + return ""; + } + } + catch + { + return ""; + } + } + + + public static Expression> GetContainIdExpression(this List Ids, Expression peid = null) + { + ParameterExpression pe = Expression.Parameter(typeof(TModel)); + var rv = Ids.GetContainIdExpression(typeof(TModel), pe, peid) as Expression>; + return rv; + } + + public static LambdaExpression GetContainIdExpression(this List Ids, Type modeltype, ParameterExpression pe, Expression peid = null) + { + if (Ids == null) + { + Ids = new List(); + } + if (peid == null) + { + peid = Expression.Property(pe, modeltype.GetSingleProperty("ID")); + } + else + { + ChangePara cp = new ChangePara(); + peid = cp.Change(peid, pe); + } + List newids = new List(); + foreach (var item in Ids) + { + object vv = PropertyHelper.ConvertValue(item, peid.Type); + if (vv != null) + { + newids.Add(vv); + } + } + Expression dpleft = Expression.Constant(newids, typeof(IEnumerable)); + Expression dpleft2 = Expression.Call(typeof(Enumerable), "Cast", new Type[] { peid.Type }, dpleft); + Expression dpleft3 = Expression.Call(typeof(Enumerable), "ToList", new Type[] { peid.Type }, dpleft2); + Expression dpcondition = Expression.Call(typeof(Enumerable), "Contains", new Type[] { peid.Type }, dpleft3, peid); + var rv = Expression.Lambda(typeof(Func<,>).MakeGenericType(modeltype, typeof(bool)), dpcondition, pe); + return rv; + } + + /// + /// 开始一个事务,当使用同一IDataContext时,嵌套的两个事务不会引起冲突,当嵌套的事务执行时引起的异常会通过回滚方法向上层抛出异常 + /// + /// DataContext + /// 可用的事务实例 + public static Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction BeginTransaction(this IDataContext self) + { + if (self == null) + throw new ArgumentNullException(nameof(self)); + if (self.Database == null) + throw new ArgumentNullException(nameof(self.Database)); + if (@"Microsoft.EntityFrameworkCore.InMemory".Equals(self.Database.ProviderName, StringComparison.OrdinalIgnoreCase)) + return FakeNestedTransaction.DefaultTransaction; + return self.Database.CurrentTransaction == null ? self.Database.BeginTransaction() : FakeNestedTransaction.DefaultTransaction; + } + + /// + /// 开始一个事务,当使用同一IDataContext时,嵌套的两个事务不会引起冲突,当嵌套的事务执行时引起的异常会通过回滚方法向上层抛出异常 + /// + /// DataContext + /// + /// 可用的事务实例 + public static Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction BeginTransaction(this IDataContext self, System.Data.IsolationLevel isolationLevel) + { + if (self == null) + throw new ArgumentNullException(nameof(self)); + if (self.Database == null) + throw new ArgumentNullException(nameof(self.Database)); + if (@"Microsoft.EntityFrameworkCore.InMemory".Equals(self.Database.ProviderName, StringComparison.OrdinalIgnoreCase)) + return FakeNestedTransaction.DefaultTransaction; + return self.Database.CurrentTransaction == null ? self.Database.BeginTransaction(isolationLevel) : FakeNestedTransaction.DefaultTransaction; + } + } + + public static class DbCommandExtension + { + public static void AddParameter(this DbCommand command) + { + + } + } + + internal class FakeNestedTransaction : Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction + { + internal static readonly FakeNestedTransaction DefaultTransaction = new FakeNestedTransaction(); + + private FakeNestedTransaction() { } + + public void Dispose() + { + } + + public void Commit() + { + } + + public void Rollback() + { + throw new TransactionInDoubtException("an exception occurs while executing the nested transaction or processing the results"); + } + + public Task CommitAsync(CancellationToken cancellationToken = default) + { + throw new NotImplementedException(); + } + + public Task RollbackAsync(CancellationToken cancellationToken = default) + { + throw new NotImplementedException(); + } + + public ValueTask DisposeAsync() + { + throw new NotImplementedException(); + } + + public Guid TransactionId => Guid.Empty; + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/DistinctExtension.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/DistinctExtension.cs new file mode 100644 index 0000000..9aba5fe --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/DistinctExtension.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Linq; + +namespace WalkingTec.Mvvm.Core.Extensions +{ + public static class DistinctExtensions + { + public static IEnumerable Distinct(this IEnumerable source, Func keySelector) + { + return source.Distinct(new CommonEqualityComparer(keySelector)); + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/ITreeDataExtension.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/ITreeDataExtension.cs new file mode 100644 index 0000000..fa1f0c5 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/ITreeDataExtension.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace WalkingTec.Mvvm.Core.Extensions +{ + /// + /// 树形结构Model的扩展函数 + /// + public static class ITreeDataExtension + { + + /// + /// 获取一个父节点下的所有子节点,包括子节点的子节点 + /// + /// 树形结构类 + /// 树形结构实例 + /// 排序字段,可为空 + /// 树形结构列表,包含所有子节点 + public static List GetAllChildren(this T self, Func order = null) + where T : TreePoco + { + List rv = new List(); + var children = self.Children; + if(order != null && children != null) + { + children = children.OrderBy(order).ToList(); + } + if (children != null && children.Count() > 0) + { + //var dictinct = children.Where(x => x.GetID().ToString() != self.GetID().ToString()).ToList(); + foreach (var item in children) + { + rv.Add(item); + //递归添加子节点的子节点 + rv.AddRange(item.GetAllChildren(order)); + } + } + return rv; + } + + public static int GetLevel(this T self) + where T : TreePoco + { + int level = 0; + while (self.Parent != null) + { + level++; + self = self.Parent; + } + return level; + } + + /// + /// 查询数据库,根据某个节点ID递归获取其下所有级别的子节点ID + /// + /// 树形结构类 + /// 树形结构实例 + /// dc + /// 子节点ID列表 + /// 所有级别子节点ID + public static List GetAllChildrenIDs(this T self + , IDataContext dc + , List subids = null) + where T : TreePoco + { + List rv = new List(); + List ids = null; + if (subids == null) + { + ids = dc.Set().Where(x => x.ParentId == self.ID).Select(x => x.ID).ToList(); + } + else + { + ids = dc.Set().Where(x => subids.Contains(x.ParentId.Value)).Select(x => x.ID).ToList(); + } + if (ids != null && ids.Count > 0) + { + rv.AddRange(ids); + rv.AddRange(self.GetAllChildrenIDs(dc, ids)); + } + return rv; + } + + /// + /// 将树形结构列表转变为标准列表 + /// + /// 树形结构类 + /// 树形结构实例 + /// 排序字段,可以为空 + /// 返回标准列表,所有节点都在同一级上 + public static List FlatTree(this List self, Func order = null) + where T :TreePoco + { + List rv = new List(); + if(order != null) + { + self = self.OrderBy(order).ToList(); + } + foreach (var item in self) + { + rv.Add(item); + rv.AddRange(item.GetAllChildren(order)); + } + return rv; + } + + /// + /// 将树形结构列表转变为标准列表 + /// + /// 树形结构实例 + /// 排序字段,可以为空 + /// 返回标准列表,所有节点都在同一级上 + public static IEnumerable FlatTreeSelectList(this IEnumerable self, Func order = null) + { + List rv = new List(); + if (order != null) + { + self = self.OrderBy(order).ToList(); + } + foreach (var item in self) + { + rv.Add(item); + if (item.Children != null) + { + rv.AddRange(item.GetTreeSelectChildren(order)); + } + } + return rv; + } + + /// + /// 获取TreeSelect节点下所有子节点 + /// + /// + /// + /// + public static List GetTreeSelectChildren(this TreeSelectListItem self, Func order = null) + { + List rv = new List(); + var children = self.Children; + if (order != null && children != null) + { + children = children.OrderBy(order).ToList(); + } + if (children != null && children.Count() > 0) + { + var dictinct = children.Where(x => x.Value != self.Value).ToList(); + foreach (var item in dictinct) + { + rv.Add(item); + //递归添加子节点的子节点 + rv.AddRange(item.GetTreeSelectChildren(order)); + } + } + return rv; + } + + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/ListExtension.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/ListExtension.cs new file mode 100644 index 0000000..51141d4 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/ListExtension.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; + +namespace WalkingTec.Mvvm.Core.Extensions +{ + public static class ListExtension + { + /// + /// 将数据的List转化为下拉菜单数据List + /// + /// 源数据类 + /// 源数据List + /// 指向text字段的表达式 + /// 指向value字段的表达式 + /// 默认被选中的条件 + /// 下拉菜单数据List + public static List ToListItems(this List self + , Expression> textField + , Expression> valueField + , Expression> selectedCondition = null) + { + var rv = new List(); + if (self != null) + { + //循环列表中的数据 + foreach (var item in self) + { + //获取textField的值作为text + string text = textField.Compile().Invoke(item).ToString(); + //获取valueField的值作为value + string value = valueField.Compile().Invoke(item).ToString(); + //添加到下拉菜单List中 + ComboSelectListItem li = new ComboSelectListItem(); + li.Text = text; + li.Value = value; + //如果有默认选择的条件,则将当前数据带入到判断表达式中,如果返回true,则将下拉数据的selected属性设为true + if (selectedCondition != null) + { + if (selectedCondition.Compile().Invoke(item)) + { + li.Selected = true; + } + } + rv.Add(li); + } + } + return rv; + } + + public static object ToChartData(this List self, int radius = 100, string seriesname = "Info") + { + //var data = string.Empty; + if (self != null && self.Count > 0) + { + var cd = self as List; + var i = 0; + for (i = 0; i < cd.Count; i++) + { + if (string.IsNullOrEmpty(cd[i].Series)) + { + cd[i].Series = "Data"; + } + } + string[] series = cd.Select(x => x.Series).Distinct().ToArray(); + + + var yCount = cd.GroupBy(x => x.Category).ToList(); + var isScatter = cd.Any(x => x.ValueX > 0); + var dataset = "{\"source\":["; + if (isScatter) + { + dataset = "[{\"source\":["; + i = 0; + foreach (var item in cd) + { + + dataset += $"[{item.ValueX},{item.Value},{item.Addition},\"{item.Category}\",\"{item.Series}\"]"; + + if (i < cd.Count - 1) + { + dataset += ","; + } + i++; + } + dataset += "]},"; + for (i = 0; i < series.Length; i++) + { + dataset += $"{{\"transform\": {{\"type\": \"filter\",\"config\": {{\"dimension\": 4,\"value\": \"{series[i]}\"}}}}}}"; + if (i < series.Length - 1) + { + dataset += ","; + } + } + dataset += "]"; + } + else + { + object[,] rtc = new object[yCount.Count + 1, series.Length + 1]; + rtc[0, 0] = $"{seriesname}"; + + for (i = 0; i < series.Length; i++) + { + rtc[0, i + 1] = series[i]; + } + i = 0; + foreach (var item in yCount) + { + rtc[i + 1, 0] = item.Key; + for (int j = 0; j < series.Length; j++) + { + var ser = item.Where(x => x.Series == series[j])?.FirstOrDefault(); + if (ser != null) + { + rtc[i + 1, j + 1] = ser.Value; + } + else + { + rtc[i + 1, j + 1] = 0; + } + } + + i++; + } + for (i = 0; i <= yCount.Count; i++) + { + dataset += "["; + for (int j = 0; j <= series.Length; j++) + { + dataset += $"\"{rtc[i, j]}\""; + if (j < series.Length) + { + dataset += ","; + } + } + dataset += "]"; + if (i < yCount.Count) + { + dataset += ","; + } + } + dataset += "]}"; + } + var seriesStr = "["; + var legend = "{\"data\":["; + var max = cd.Max(x => x.Addition); + for (i = 0; i < series.Length; i++) + { + seriesStr += $"{{\"type\":\"charttype\""; + if (isScatter) + { + seriesStr += $",\"encode\":{{\"x\":0,\"y\":1,\"tooltip\":[2,3]}},\"name\": \"{series[i]}\",\"datasetIndex\": {i + 1}"; + seriesStr += $",\"symbolSize\": \"function(data) {{return data[2] / ({max} / {radius})}}\""; + } + seriesStr += "}"; + legend += $"\"{series[i]}\""; + if (i < series.Length - 1) + { + seriesStr += ","; + legend += ","; + } + } + legend += "]}"; + seriesStr += "]"; + return new { dataset = dataset, series = seriesStr, legend = legend }; + } + else + { + var dataset = "{\"source\":[]}"; + var seriesStr = "[]"; + var legend = "{\"data\":[]}"; + return new { dataset = dataset, series = seriesStr, legend = legend }; + } + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/ListVMExtension.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/ListVMExtension.cs new file mode 100644 index 0000000..694d533 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/ListVMExtension.cs @@ -0,0 +1,377 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace WalkingTec.Mvvm.Core.Extensions +{ + public static class ListVMExtension + { + /// + /// 获取Jason格式的列表数据 + /// + /// 是否需要对数据进行Json编码 + /// 不在后台进行ColumnFormatInfo的转化,而是直接输出ColumnFormatInfo的json结构到前端,由前端处理,默认False + /// + /// Json格式的数据 + public static string GetDataJson(this IBasePagedListVM self, bool returnColumnObject = false, bool enumToString = true) where T : TopBasePoco, new() + { + var sb = new StringBuilder(); + self.GetHeaders(); + if (self.IsSearched == false) + { + self.DoSearch(); + } + var el = self.GetEntityList().ToList(); + //如果列表主键都为0,则生成自增主键,避免主键重复 + if (el.All(x => { + var id = x.GetID(); + if(id == null || (id is Guid gid && gid == Guid.Empty) || (id is int iid && iid==0) || (id is long lid && lid == 0)) + { + return true; + } + else + { + return false; + } + } )) + { + el.ForEach(x => x.ID = Guid.NewGuid()); + } + //循环生成列表数据 + for (int x = 0; x < el.Count; x++) + { + var sou = el[x]; + sb.Append(self.GetSingleDataJson(sou, returnColumnObject, x, enumToString)); + if (x < el.Count - 1) + { + sb.Append(','); + } + } + return $"[{sb}]"; + } + + private static string GetFormatResult(BaseVM vm, ColumnFormatInfo info) + { + string rv = ""; + switch (info.FormatType) + { + case ColumnFormatTypeEnum.Dialog: + rv = vm.UIService.MakeDialogButton(info.ButtonType, info.Url, info.Text, info.Width, info.Height, info.Title, info.ButtonID, info.ShowDialog, info.Resizable, info.Maxed, info.ButtonClass, info.Style).ToString(); + break; + case ColumnFormatTypeEnum.Button: + rv = vm.UIService.MakeButton(info.ButtonType, info.Url, info.Text, info.Width, info.Height, info.Title, info.ButtonID, info.Resizable, info.Maxed, vm.ViewDivId, info.ButtonClass, info.Style, info.RType).ToString(); + break; + case ColumnFormatTypeEnum.Download: + if (info.FileID == null) + { + rv = ""; + } + else + { + rv = vm.UIService.MakeDownloadButton(info.ButtonType, info.FileID.Value, info.Text, vm.CurrentCS, info.ButtonClass, info.Style).ToString(); + } + break; + case ColumnFormatTypeEnum.ViewPic: + if (info.FileID == null) + { + rv = ""; + } + else + { + rv = vm.UIService.MakeViewButton(info.ButtonType, info.FileID.Value, info.Text, info.Width, info.Height, info.Title, info.Resizable, vm.CurrentCS, info.Maxed, info.ButtonClass, info.Style).ToString(); + } + break; + case ColumnFormatTypeEnum.Script: + rv = vm.UIService.MakeScriptButton(info.ButtonType, info.Text, info.Script, info.ButtonID, info.Url, info.ButtonClass, info.Style).ToString(); + break; + case ColumnFormatTypeEnum.Html: + rv = info.Html; + break; + default: + break; + } + return rv; + } + + /// + /// 生成单条数据的Json格式 + /// + /// + /// + /// 数据 + /// 不在后台进行ColumnFormatInfo的转化,而是直接输出ColumnFormatInfo的json结构到前端,由前端处理,默认False + /// index + /// + /// Json格式的数据 + public static string GetSingleDataJson(this IBasePagedListVM self, object obj, bool returnColumnObject, int index = 0, bool enumToString = true) where T : TopBasePoco + { + bool inner = false; + var sb = new StringBuilder(); + var RowBgColor = string.Empty; + var RowColor = string.Empty; + if (obj is not T sou) + { + sou = self.CreateEmptyEntity(); + } + RowBgColor = self.SetFullRowBgColor(sou); + RowColor = self.SetFullRowColor(sou); + var isSelected = self.GetIsSelected(sou); + //循环所有列 + sb.Append('{'); + bool containsID = false; + bool addHiddenID = false; + Dictionary colorcolumns = new Dictionary(); + foreach (var baseCol in self.GetHeaders()) + { + foreach (var col in baseCol.BottomChildren) + { + inner = false; + if (col.ColumnType != GridColumnTypeEnum.Normal) + { + continue; + } + if (col.FieldName?.ToLower() == "id") + { + containsID = true; + } + var backColor = col.GetBackGroundColor(sou); + //获取ListVM中设定的单元格前景色 + var foreColor = col.GetForeGroundColor(sou); + + if (backColor == string.Empty) + { + backColor = RowBgColor; + } + if (foreColor == string.Empty) + { + foreColor = RowColor; + } + (string bgcolor, string forecolor) colors = (null, null); + if (backColor != string.Empty) + { + colors.bgcolor = backColor; + } + if (foreColor != string.Empty) + { + colors.forecolor = foreColor; + } + if (string.IsNullOrEmpty(colors.bgcolor) == false || string.IsNullOrEmpty(colors.forecolor) == false) + { + colorcolumns.Add(col.Field, colors); + } + //设定列名,如果是主键ID,则列名为id,如果不是主键列,则使用f0,f1,f2...这种方式命名,避免重复 + var ptype = col.FieldType; + if (col.Field?.ToLower() == "children" && typeof(IEnumerable).IsAssignableFrom(ptype)) + { + var children = ((IEnumerable)col.GetObject(obj))?.ToList(); + if (children == null || children.Count == 0) + { + continue; + } + } + var html = string.Empty; + + if (col.EditType == EditTypeEnum.Text || col.EditType == null) + { + if (typeof(IEnumerable).IsAssignableFrom(ptype)) + { + var children = ((IEnumerable)col.GetObject(obj))?.ToList(); + if (children != null) + { + html = "["; + for (int i = 0; i < children.Count; i++) + { + var item = children[i]; + html += self.GetSingleDataJson(item, returnColumnObject,0,enumToString); + if (i < children.Count - 1) + { + html += ","; + } + } + html += "]"; + } + else + { + //html = "[]"; + } + inner = true; + } + else + { + if (returnColumnObject == true) + { + html = col.GetText(sou, false).ToString(); + } + else + { + var info = col.GetText(sou); + + if (info is ColumnFormatInfo) + { + html = GetFormatResult(self as BaseVM, info as ColumnFormatInfo); + } + else if (info is List) + { + var temp = string.Empty; + foreach (var item in info as List) + { + temp += GetFormatResult(self as BaseVM, item); + temp += "  "; + } + html = temp; + } + else + { + html = info.ToString(); + } + } + + //如果列是布尔值,直接返回true或false,让前台生成CheckBox + if (ptype == typeof(bool) || ptype == typeof(bool?)) + { + if(enumToString == false) + { + html = html.ToLower(); + inner = true; + } + else if (returnColumnObject == false) + { + if (html.ToLower() == "true") + { + html = (self as BaseVM).UIService.MakeCheckBox(true, isReadOnly: true); + } + if (html.ToLower() == "false" || html == string.Empty) + { + html = (self as BaseVM).UIService.MakeCheckBox(false, isReadOnly: true); + } + } + else + { + if (html != null && html != string.Empty) + { + html = html.ToLower(); + } + } + } + //如果列是枚举,直接使用枚举的文本作为多语言的Key查询多语言文字 + else if (ptype.IsEnumOrNullableEnum()) + { + if (enumToString == true) + { + string enumdisplay = PropertyHelper.GetEnumDisplayName(ptype, html); + if (string.IsNullOrEmpty(enumdisplay) == false) + { + html = enumdisplay; + } + } + } + //If this column is a class or list, html will be set to a json string, sest inner to true to remove the " + if (returnColumnObject == true && ptype?.Namespace.Equals("System") == false && ptype?.IsEnumOrNullableEnum() == false) + { + inner = true; + } + } + if (enumToString == false && string.IsNullOrEmpty(html)) + { + continue; + } + + } + else + { + string val = col.GetText(sou).ToString(); + string name = $"{self.DetailGridPrix}[{index}].{col.Field}"; + switch (col.EditType) + { + case EditTypeEnum.TextBox: + html = (self as BaseVM).UIService.MakeTextBox(name, val); + break; + case EditTypeEnum.CheckBox: + _ = bool.TryParse(val, out bool nb); + html = (self as BaseVM).UIService.MakeCheckBox(nb, null, name, "true"); + break; + case EditTypeEnum.ComboBox: + html = (self as BaseVM).UIService.MakeCombo(name, col.ListItems, val); + break; + case EditTypeEnum.Datetime: + html = (self as BaseVM).UIService.MakeDateTime(name, val); + break; + default: + break; + } + } + if (string.IsNullOrEmpty(self.DetailGridPrix) == false && addHiddenID == false) + { + html += $@""; + addHiddenID = true; + } + if (inner == false) + { + html = "\"" + html.Replace(Environment.NewLine, "").Replace("\t", string.Empty).Replace("\n", string.Empty).Replace("\r", string.Empty).Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""; + } + sb.Append($"\"{col.Field}\":"); + sb.Append(html); + sb.Append(','); + } + } + sb.Append($"\"TempIsSelected\":\"{ (isSelected == true ? "1" : "0") }\""); + foreach (var cc in colorcolumns) + { + if (string.IsNullOrEmpty(cc.Value.Item1) == false) + { + string bg = cc.Value.Item1; + if (bg.StartsWith("#") == false) + { + bg = "#" + bg; + } + sb.Append($",\"{cc.Key}__bgcolor\":\"{bg}\""); + } + if (string.IsNullOrEmpty(cc.Value.Item2) == false) + { + string fore = cc.Value.Item2; + if (fore.StartsWith("#") == false) + { + fore = "#" + fore; + } + sb.Append($",\"{cc.Key}__forecolor\":\"{fore}\""); + } + } + if (containsID == false) + { + sb.Append($",\"ID\":\"{(sou as dynamic).ID}\""); + } + // 标识当前行数据是否被选中 + sb.Append($@",""LAY_CHECKED"":{sou.Checked.ToString().ToLower()}"); + sb.Append(string.Empty); + sb.Append('}'); + return sb.ToString(); + } + + /// + /// Get json format string of ListVM's search result + /// + /// Model type + /// a listvm + /// true to return plain text, false to return formated html, such as checkbox,buttons ... + /// use enum display name + /// json string + public static string GetJson(this IBasePagedListVM self, bool PlainText = true, bool enumToString = true) where T : TopBasePoco, new() + { + return $@"{{""Data"":{self.GetDataJson(PlainText,enumToString)},""Count"":{self.Searcher.Count},""Page"":{self.Searcher.Page},""PageCount"":{self.Searcher.PageCount},""Msg"":""success"",""Code"":200}}"; + } + + public static object GetJsonForApi(this IBasePagedListVM self, bool PlainText = true) where T : TopBasePoco, new() + { + return new { Data = self.GetEntityList(), Count = self.Searcher.Count, PageCount = self.Searcher.PageCount, Page = self.Searcher.Page, Msg = "success", Code = 200 }; + } + + + public static string GetError(this IBasePagedListVM self) where T : TopBasePoco, new() + { + return $@"{{""Data"":{{}},""Count"":0,""Page"":0,""PageCount"":0,""Msg"":""{(self as BaseVM).MSD.GetFirstError()}"",""Code"":400}}"; + } + + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/LoginUserInfoExtension.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/LoginUserInfoExtension.cs new file mode 100644 index 0000000..0795d61 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/LoginUserInfoExtension.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading.Tasks; + +using Microsoft.Extensions.Caching.Distributed; + +using WalkingTec.Mvvm.Core.Auth; + +namespace WalkingTec.Mvvm.Core.Extensions +{ + public static class LoginUserInfoExtension + { + public static ClaimsPrincipal CreatePrincipal(this LoginUserInfo self) + { + if (string.IsNullOrEmpty(self.ITCode)) throw new ArgumentException("Id is mandatory", nameof(self.ITCode)); + var claims = new List { new Claim(AuthConstants.JwtClaimTypes.Subject, self.ITCode) }; + + if (!string.IsNullOrEmpty(self.Name)) + { + claims.Add(new Claim(AuthConstants.JwtClaimTypes.Name, self.Name)); + } + if (!string.IsNullOrEmpty(self.TenantCode)) + { + claims.Add(new Claim(AuthConstants.JwtClaimTypes.TenantCode, self.TenantCode)); + } + + var id = new ClaimsIdentity( + claims.Distinct(new ClaimComparer()), + AuthConstants.AuthenticationType, + AuthConstants.JwtClaimTypes.Name, + AuthConstants.JwtClaimTypes.TenantCode); + return new ClaimsPrincipal(id); + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/PagedListExtension.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/PagedListExtension.cs new file mode 100644 index 0000000..28cb96a --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/PagedListExtension.cs @@ -0,0 +1,323 @@ +using System; +using System.Linq.Expressions; + +namespace WalkingTec.Mvvm.Core.Extensions +{ + public static class PagedListExtension + { + #region MakeGridColumn 生成GridColumn + /// + /// 生成GridColumn + /// + /// 继承自TopBasePoco的类 + /// 继承自ISearcher的类 + /// self + /// 指向T中字段的表达式 + /// 格式化显示内容的委托函数,函数接受两个参数,第一个是整行数据,第二个是所选列的数据 + /// 表头名称 + /// 列宽 + /// 是否填充 + /// 是否允许多行 + /// 是否需要分组 + /// 设置前景色的委托函数 + /// 设置背景色的委托函数 + /// 返回设置好的GridColumn类的实例 + public static GridColumn MakeGridColumn(this IBasePagedListVM self + , Expression> ColumnExp + , ColumnFormatCallBack Format = null + , string Header = null + , int? Width = null + , int? Flex = null + , bool AllowMultiLine = true + , bool NeedGroup = false + , Func ForeGroundFunc = null + , Func BackGroundFunc = null) + where T : TopBasePoco + where V : ISearcher + { + GridColumn rv = new GridColumn(ColumnExp, Format, Header, Width, Flex, AllowMultiLine, NeedGroup, ForeGroundFunc, BackGroundFunc); + return rv; + } + #endregion + + #region MakeActionGridColumn 生成Grid动作列(增删该查) + ///// + ///// 生成Grid动作列(增删该查) + ///// + ///// 继承自TopBasePoco的类 + ///// 继承自ISearcher的类 + ///// self + ///// 表头名称 + ///// 列宽 + ///// 返回设置好的动作列 + //public static GridColumn MakeActionGridColumn(this IBasePagedListVM self + // , string Header = null + // , int? Width = null) + // where T : TopBasePoco + // where V : ISearcher + //{ + // ActionGridColumn rv = new ActionGridColumn(Header, Width); + // rv.Sortable = false; + // return rv; + //} + #endregion + + #region MakeGridAction 创建一个新的列表动作 + ///// + ///// 创建一个新的列表动作 + ///// + ///// 继承自TopBasePoco的类 + ///// 继承自ISearcher的类 + ///// self + ///// 动作名 + ///// 弹出窗口标题 + ///// 动作的Controller + ///// 动作的Action + ///// 动作类型 + ///// 是否在每行都显示 + ///// 域名 + ///// 是否需要弹出窗口,默认为true + ///// 弹出窗口的宽度 + ///// 弹出窗口的高度 + ///// 动作图标css,默认为null,没有图标 + ///// 是否在工具栏隐藏 默认false + ///// Button的id 默认自动生成 + ///// 是否在新页面打开 + ///// 列表动作 + //public static GridAction MakeGridAction(this IBasePagedListVM self + // , string name + // , string dialogTitle + // , string controllerName + // , string actionName + // , GridActionParameterTypesEnum paraType + // , bool showInRow + // , string areaName = null + // , bool showDialog = true + // , int? dialogWidth = null + // , int? dialogHeight = null + // , string iconCls = null + // , bool hideOnToolBar = false + // , string buttonId = null + // , bool isRedirect = false + // , bool resizable = true) + // where T : TopBasePoco + // where V : ISearcher + //{ + // return new GridAction { Name = name, Area = areaName, ControllerName = controllerName, DialogTitle = dialogTitle, ActionName = actionName, DialogWidth = dialogWidth, DialogHeight = dialogHeight, ParameterType = paraType, ShowInRow = showInRow, OnClickFunc = null, ShowDialog = showDialog, IconCls = iconCls, HideOnToolBar = hideOnToolBar, ButtonId = buttonId, IsRedirect = isRedirect, Resizable = resizable }; + //} + #endregion + + #region MakeScriptGridAction 创建一个执行自定义js的列表动作 + ///// + ///// 创建一个执行自定义js的列表动作 + ///// + ///// 继承自TopBasePoco的类 + ///// 继承自ISearcher的类 + ///// self + ///// 动作的Controller + ///// 动作的Action + ///// 动作名 + ///// 点击动作按钮执行的js + ///// 是否在操作列中显示 默认true + ///// 是否在工具栏中隐藏 默认true + ///// 动作的区域 + ///// Button的id 默认自动生成 + ///// 列表动作 + ///// + ///// 框架的自动权限验证无法验证自定义的js中跳转到的链接, + ///// 所以虽然只是运行js,但如果js最终跳转到某个链接,则还是需要在这里指定Controller和Action,这样框架就可以自动判断权限 + ///// + //public static GridAction MakeScriptGridAction(this IBasePagedListVM self + // , string controllerName + // , string actionName + // , string name + // , string script + // , string areaName = null + // , string buttonId = null + // , bool showInRow = true + // , bool hideOnToolBar = true + // , bool resizable = true)//add by wuwh 2014.05.07 添加hideOnToolBar参数 + // where T : TopBasePoco + // where V : ISearcher + //{ + // return new GridAction { Area = areaName, ControllerName = controllerName, ActionName = actionName, Name = name, OnClickFunc = script, ShowInRow = showInRow, ButtonId = buttonId, HideOnToolBar = hideOnToolBar, Resizable = resizable }; + //} + #endregion + + #region MakeStandardAction 创建标准动作 + ////新增参数 whereStr + ///// + ///// 创建标准动作 + ///// + ///// 继承自TopBasePoco的类 + ///// 继承自ISearcher的类 + ///// self + ///// 动作的Controller + ///// 标准动作类型 + ///// 弹出窗口的标题 + ///// 域名 + ///// 弹出窗口的宽度 + ///// 弹出窗口的高度 + ///// 动作名,默认为‘新建’ + ///// Button的id 默认自动生成 + ///// 列表动作 + ///// + ///// 根据标准动作类型,创建默认属性的标准动作 + ///// + //public static GridAction MakeStandardAction(this IBasePagedListVM self + // , string controllerName + // , GridActionStandardTypesEnum standardType + // , string dialogTitle + // , string areaName = null + // , int? dialogWidth = null + // , int? dialogHeight = null + // , string name = null + // , string buttonId = null + // , bool resizable = true + // , params Expression>[] whereStr) + // where T : TopBasePoco + // where V : ISearcher + //{ + // string iconcls = ""; + // string action = ""; + // string gridname = ""; + // GridActionParameterTypesEnum paraType = GridActionParameterTypesEnum.NoId; + // bool showinrow = false; + // bool hideontoolbar = false; + // switch (standardType) + // { + // case GridActionStandardTypesEnum.Create: + // iconcls = "icon-add"; + // action = "Create"; + // gridname = "新建"; + // paraType = GridActionParameterTypesEnum.NoId; + // break; + // case GridActionStandardTypesEnum.Edit: + // iconcls = "icon-edit"; + // action = "Edit"; + // gridname = "修改"; + // paraType = GridActionParameterTypesEnum.SingleId; + // showinrow = true; + // hideontoolbar = true; + // break; + // case GridActionStandardTypesEnum.Delete: + // iconcls = "icon-delete"; + // action = "Delete"; + // gridname = "删除"; + // paraType = GridActionParameterTypesEnum.SingleId; + // showinrow = true; + // hideontoolbar = true; + // break; + // case GridActionStandardTypesEnum.Details: + // iconcls = "icon-details"; + // action = "Details"; + // gridname = "详细"; + // paraType = GridActionParameterTypesEnum.SingleId; + // showinrow = true; + // hideontoolbar = true; + // break; + // case GridActionStandardTypesEnum.BatchEdit: + // iconcls = "icon-edit"; + // action = "BatchEdit"; + // gridname = "批量修改"; + // paraType = GridActionParameterTypesEnum.MultiIds; + // break; + // case GridActionStandardTypesEnum.BatchDelete: + // iconcls = "icon-delete"; + // action = "BatchDelete"; + // gridname = "批量删除"; + // paraType = GridActionParameterTypesEnum.MultiIds; + // break; + // case GridActionStandardTypesEnum.Import: + // iconcls = "icon-details"; + // action = "ImportExcelData"; + // gridname = "导入"; + // paraType = GridActionParameterTypesEnum.NoId; + // break; + // default: + // break; + // } + // List list = new List(); + // foreach (var item in whereStr) + // { + // list.Add(PropertyHelper.GetPropertyName(item)); + // } + + // return new GridAction { Name = (name == null ? gridname : name), DialogTitle = dialogTitle, IconCls = iconcls, ControllerName = controllerName, ActionName = action, Area = areaName, DialogWidth = dialogWidth, DialogHeight = dialogHeight, ParameterType = paraType, ShowInRow = showinrow, ShowDialog = true, HideOnToolBar = hideontoolbar, ButtonId = buttonId, Resizable = resizable, whereStr = list.ToArray() }; + //} + #endregion + + #region MakeStandardExportAction 创建标准导出按钮 + ///// + ///// 创建标准导出按钮 + ///// + ///// 继承自TopBasePoco的类 + ///// 继承自ISearcher的类 + ///// self + ///// vmGuid + ///// + ///// 导出类型 默认null,支持所有导出 + ///// 参数 + ///// + //public static GridAction MakeStandardExportAction(this IBasePagedListVM self + // , string gridid = null + // , bool MustSelect = false + // , ExportEnum? exportType = null + // , params KeyValuePair[] param) + // where T : TopBasePoco + // where V : ISearcher + //{ + // string excelscript = ""; + // string pdfscript = ""; + + // string parameters = "?"; + // foreach (var item in param) + // { + // parameters += item.Key + "=" + item.Value + "&"; + // } + // if (self.FromFixedCon == true) + // { + // parameters += "DONOTUSECSName=" + self.CurrentCS + "&"; + // } + // parameters += "1=1"; + // if (gridid == null) + // { + // gridid = "Grid" + self.UniqueId; + // } + // if (MustSelect == false) + // { + // excelscript = string.Format("FF_ShowMask(\"{1}\");FF_DownloadExcelOrPdfPost(\"{0}\",\"/WebApi/Home/ExportExcel{2}\");", gridid, "正在生成文件...", parameters); + // pdfscript = string.Format("FF_ShowMask(\"{1}\");FF_DownloadExcelOrPdfPost(\"{0}\",\"/WebApi/Home/ExportPdf{2}\");", gridid, "正在生成文件...", parameters); + // } + // else + // { + // excelscript += "var sels = Ext.getCmp(\"" + gridid + "\").getSelectionModel().getSelection();"; + // excelscript += "if(sels.length == 0){ FF_OpenSimpleDialog(\"" + "错误" + "\",\"" + "请至少选择一条数据" + "\");} else{"; + // excelscript += string.Format("FF_ShowMask(\"{1}\");FF_DownloadExcelOrPdfPost(\"{0}\",\"/WebApi/Home/ExportExcel{2}\");", gridid, "正在生成文件...", parameters) + "}"; + + // pdfscript += "var sels = Ext.getCmp(\"" + gridid + "\").getSelectionModel().getSelection();"; + // pdfscript += "if(sels.length == 0){ FF_OpenSimpleDialog(\"" + "错误" + "\",\"" + "请至少选择一条数据" + "\");} else{"; + // pdfscript += string.Format("FF_ShowMask(\"{1}\");FF_DownloadExcelOrPdfPost(\"{0}\",\"/WebApi/Home/ExportPdf{2}\");", gridid, "正在生成文件...", parameters) + "}"; + // } + // GridAction ga = null; + // if (exportType == ExportEnum.Excel) + // { + // ga = new GridAction { Area = "WebApi", ControllerName = "Home", ActionName = "ExportExcel", Name = "导出Excel", ParameterType = GridActionParameterTypesEnum.NoId, OnClickFunc = excelscript, ShowInRow = false, Resizable = true }; + // } + // else if (exportType == ExportEnum.PDF) + // { + // ga = new GridAction { Area = "WebApi", ControllerName = "Home", ActionName = "ExportExcel", Name = "导出PDF", ParameterType = GridActionParameterTypesEnum.NoId, OnClickFunc = excelscript, ShowInRow = false, Resizable = true }; + // } + // else + // { + // ga = new GridAction { Area = "WebApi", ControllerName = "Home", ActionName = "ExportExcel", Name = "导出", ParameterType = GridActionParameterTypesEnum.NoId, OnClickFunc = excelscript, ShowInRow = false, Resizable = true }; + // GridAction excel = new GridAction { Area = "WebApi", ControllerName = "Home", ActionName = "ExportExcel", Name = "导出Excel", ParameterType = GridActionParameterTypesEnum.NoId, OnClickFunc = excelscript, ShowInRow = false, Resizable = true }; + // GridAction pdf = new GridAction { Area = "WebApi", ControllerName = "Home", ActionName = "ExportPdf", Name = "导出PDF", ParameterType = GridActionParameterTypesEnum.NoId, OnClickFunc = pdfscript, ShowInRow = false, Resizable = true }; + // ga.SubActions = new List { excel, pdf }; + // } + // return ga; + //} + #endregion + + } +} \ No newline at end of file diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/SystemExtensions/DateTimeHelper.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/SystemExtensions/DateTimeHelper.cs new file mode 100644 index 0000000..584e350 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/SystemExtensions/DateTimeHelper.cs @@ -0,0 +1,81 @@ +using System; + +namespace WalkingTec.Mvvm.Core.Extensions +{ + /// + /// DateTime Helper + /// + public static class DateTimeHelper + { + #region DateTime Helper + + public static int WeekOfYear(this DateTime self) + { + var startDayOfYear = new DateTime(self.Year,1,1); + var weekOffset = 7 - ( startDayOfYear.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)startDayOfYear.DayOfWeek) + 1; + var weekOfYear = (int)Math.Ceiling((self.DayOfYear - weekOffset) / 7.0 + (weekOffset == 0 ? 0 : 1)); + + return weekOfYear; + } + + /// + /// 获取 指定的一周所在年份 的开始及结束时间 + /// + /// 所在年份 + /// 周数 + /// 指定周开始时间 + /// 指定周结束时间 + public static void WeekDays(int yearNum, int weekOfYear, out DateTime startDay, out DateTime endDay) + { + var startDayOfYear = new DateTime(yearNum,1,1,0,0,0); + + var weekOffset = 7 - ( startDayOfYear.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)startDayOfYear.DayOfWeek) + 1; + startDay = startDayOfYear.AddDays(7 * (weekOfYear - (weekOffset == 0 ? 0 : 1)) + weekOffset - 7); + endDay = startDay.AddDays(7); + } + + #endregion + + #region DateTime Extensions + + private static readonly DateTime _jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0,DateTimeKind.Utc); + + /// + /// UTC 1970/01/01 00:00:00 + /// + public static DateTime Jan1st1970 => _jan1st1970; + + /// + /// 时间戳 ms + /// + /// + /// 返回标准时间戳 单位 毫秒 注:从 1970/01/01 00:00:00 开始 + public static long ToMilliseconds(this DateTime self) + { + return (long)(self.ToUniversalTime() - Jan1st1970).TotalMilliseconds; + } + + /// + /// 时间戳 microsecond + /// + /// + /// 返回标准时间戳 单位 微秒 注:从 1970/01/01 00:00:00 开始 + public static long ToMicroseconds(this DateTime self) + { + return (long)((self.ToUniversalTime() - Jan1st1970).TotalMilliseconds * 1000); + } + + /// + /// 获取当前时间所在周的开始及结束时间 + /// + /// + /// 指定周开始时间 + /// 指定周结束时间 + public static void WeekDays(this DateTime self, out DateTime startDay, out DateTime endDay) + { + WeekDays(self.Year, self.WeekOfYear(), out startDay, out endDay); + } + + #endregion + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/SystemExtensions/DistributedCacheExtensions.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/SystemExtensions/DistributedCacheExtensions.cs new file mode 100644 index 0000000..40a6093 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/SystemExtensions/DistributedCacheExtensions.cs @@ -0,0 +1,158 @@ +// +// DistributedCacheExtensions.cs +// +// Author: +// Michael,Vito +// +// Copyright (c) 2019 WTM +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +using System.Reflection; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +using Microsoft.Extensions.Caching.Distributed; + + +namespace WalkingTec.Mvvm.Core.Extensions +{ + public static class DistributedCacheExtensions + { + /// + /// CachingKey 分割符 + /// + private const string SPLIT_CHAR = ":"; + + private static string _instanceName; + private static string InstanceName + { + get + { + if (_instanceName == null) + { + _instanceName = Assembly.GetEntryAssembly().GetName().Name + SPLIT_CHAR; + } + return _instanceName; + } + } + + public static void SetInstanceName( + this IDistributedCache cache, + string instanceName) + { + _instanceName = instanceName + SPLIT_CHAR; + } + + #region Get + + public static T Get( + this IDistributedCache cache, + string key) + { + var value = cache.GetString(InstanceName + key.ToLower()); + if (value == null) + return default; + else + return JsonSerializer.Deserialize(value,Core.CoreProgram.DefaultJsonOption); + } + + public static async Task GetAsync( + this IDistributedCache cache, + string key, + CancellationToken token = default) + { + var value = await cache.GetStringAsync(InstanceName + key.ToLower(), token); + if (value == null) + return default; + else + return JsonSerializer.Deserialize(value, Core.CoreProgram.DefaultJsonOption); + } + + public static bool TryGetValue( + this IDistributedCache cache, + string key, + out T outValue) + { + var value = cache.GetString(InstanceName + key.ToLower()); + if (value == null) + { + outValue = default; + return false; + } + else + { + outValue = JsonSerializer.Deserialize(value, Core.CoreProgram.DefaultJsonOption); + return true; + } + } + + #endregion + + #region Set + + public static void Add( + this IDistributedCache cache, + string key, + T value, + DistributedCacheEntryOptions options = null) + { + if (options == null) + cache.Set(InstanceName + key.ToLower(), Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value, CoreProgram.DefaultJsonOption))); + else + cache.Set(InstanceName + key.ToLower(), Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value, CoreProgram.DefaultJsonOption)), options); + } + + public static async Task AddAsync( + this IDistributedCache cache, + string key, + T value, + DistributedCacheEntryOptions options = null, + CancellationToken token = default) + { + if (options == null) + await cache.SetAsync(InstanceName + key.ToLower(), Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value, CoreProgram.DefaultJsonOption)), token); + else + await cache.SetAsync(InstanceName + key.ToLower(), Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value, CoreProgram.DefaultJsonOption)), options, token); + } + + #endregion + + + #region Delete + + public static void Delete( + this IDistributedCache cache, + string key) + { + cache.Remove(InstanceName + key.ToLower()); + } + + public static async Task DeleteAsync( + this IDistributedCache cache, + string key, + CancellationToken token = default) + { + await cache.RemoveAsync(InstanceName + key.ToLower(), token); + } + + #endregion + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/SystemExtensions/EnumExtension.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/SystemExtensions/EnumExtension.cs new file mode 100644 index 0000000..a28cde8 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/SystemExtensions/EnumExtension.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace WalkingTec.Mvvm.Core.Extensions +{ + /// + /// 枚举扩展函数 + /// + public static class EnumExtension + { + #region 将枚举类型转化为下拉列表 + /// + /// 将枚举类型转化为下拉列表 + /// + /// 枚举类型 + /// value + /// pleaseSelect + /// 下拉菜单数据列表 + public static List ToListItems(this Type self, object value = null, bool pleaseSelect = false) + { + string[] names = null; + Array values = null; + //如果是枚举 + if (self.IsEnum) + { + names = Enum.GetNames(self); + values = Enum.GetValues(self); + } + //如果是nullable的枚举 + if (self.IsGenericType && self.GenericTypeArguments[0].IsEnum) + { + names = Enum.GetNames(self.GenericTypeArguments[0]); + values = Enum.GetValues(self.GenericTypeArguments[0]); + } + //生成下拉菜单数据 + List rv = new List(); + if (names != null) + { + for(int i=0;i + /// 字符串辅助类 + /// + public static class StringExtension + { + /// + /// 根据名字获取Id形式 + /// + /// 名字 + /// 将[].转换成_形式的Id + public static string GetIdByName(this string fieldName) + { + return fieldName == null ? "" : fieldName.Replace(".", "_").Replace("[", "_").Replace("]", "_"); + } + + /// + /// 格式化URL + /// + /// 初始url + /// 格式化后的url + public static string CorrectUrl(this string url) + { + if (string.IsNullOrWhiteSpace(url) == true) + { + url = ""; + } + else + { + url = url.ToLower(); + url = url.Trim('/', '\\'); + if (url.StartsWith("http://") == false && url.StartsWith("https://") == false) + { + url = "http://" + url; + } + } + return url; + } + /// + /// 将数据列表转化为逗号分隔的字符串 + /// + /// 源数据类 + /// 文本字段 + /// 源数据List + /// 要拼接的文本字段 + /// 转化文本字段的表达式 + /// 分隔符,默认为逗号 + /// 转化后的字符串 + public static string ToSepratedString(this IEnumerable self, Expression> textField, Func Format = null, string seperator = ",") + { + string rv = ""; + if (self == null) + { + return rv; + } + //循环所有数据 + for (int i = 0; i < self.Count(); i++) + { + //获取文本字段的值 + V text = textField.Compile().Invoke(self.ElementAt(i)); + string str = ""; + //如果有转换函数,则调用获取转换后的字符串 + if (Format == null) + { + if (text == null) + { + str = ""; + } + else + { + str = text.ToString(); + } + } + else + { + str = Format.Invoke(text); + } + rv += str; + //拼接分隔符 + if (i < self.Count() - 1) + { + rv += seperator; + } + } + //返回转化后的字符串 + return rv; + } + + public static string ToSepratedString(this IEnumerable self, Func Format = null, string seperator = ",") + { + string rv = ""; + if (self == null) + { + return rv; + } + foreach (var item in self) + { + var s = ""; + if (Format == null) + { + s = item.ToString(); + } + else + { + s = Format.Invoke(item); + } + if(string.IsNullOrEmpty(s) == false) + { + rv += s + seperator; + } + } + if (rv.Length > 0) + { + rv = rv.Substring(0, rv.Length - 1); + } + return rv; + } + + public static string ToSepratedString(this NameValueCollection self, string seperator = ",") + { + string rv = ""; + if (self == null) + { + return rv; + } + foreach (var item in self) + { + rv += item.ToString() + "=" + self[item.ToString()] + seperator; + } + if (rv.Length > 0) + { + rv = rv.Substring(0, rv.Length - 1); + } + return rv; + } + + public static string AppendQuery(this string self,string query) + { + if(self == null) + { + return null; + } + if (self.Contains("?")) + { + self += "&" + query; + } + else + { + self += "?" + query; + } + return self; + } + + public static string AppendQuery(this string self, IDictionary data) + { + if (self == null) + { + return null; + } + string query = ""; + foreach (IDictionaryEnumerator item in data) + { + query += item.Key + "=" + item.Value + "&"; + } + + if (self.Contains("?")) + { + self += "&" + query; + } + else + { + self += "?" + query; + } + return self; + } + + public static string AppendQuery(this string self, List> data) + { + if (self == null) + { + return null; + } + string query = ""; + foreach (var item in data) + { + query += item.Key + "=" + item.Value + "&"; + } + + if (self.Contains("?")) + { + self += "&" + query; + } + else + { + self += "?" + query; + } + return self; + } + + public static string ToQueryString(this IEnumerable self, string name=null) + { + if(self == null) + { + return ""; + } + if (string.IsNullOrEmpty(name)) + { + name = "id"; + } + string rv = ""; + foreach (var item in self) + { + rv += $"{name}={item?.ToString()}&"; + } + if(rv.Length > 0) + { + rv = rv[0..^1]; + } + return rv; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/SystemExtensions/SystemExtension.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/SystemExtensions/SystemExtension.cs new file mode 100644 index 0000000..d38ce8a --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/SystemExtensions/SystemExtension.cs @@ -0,0 +1,67 @@ +using System; +using System.Reflection; + +namespace WalkingTec.Mvvm.Core.Extensions +{ + /// + /// System Extension + /// + public static class SystemExtension + { + #region Guid Extensions + + public static string ToNoSplitString(this Guid self) + { + return self.ToString().Replace("-", string.Empty); + } + + #endregion + + /// + /// 将CrudVM中Entity的关联字段设为空并返回一个新的CrudVM + /// + /// + /// + public static object GetCleanCrudVM(this object self) + { + var mtype = self.GetType(); + if(typeof(IBaseCRUDVM).IsAssignableFrom(mtype)) + { + var rv = mtype.GetConstructor(Type.EmptyTypes).Invoke(null); + var toppros = mtype.GetAllProperties(); + foreach (var tpro in toppros) + { + if(tpro.Name == "Entity") + { + var entity = tpro.GetValue(self); + var pros = tpro.PropertyType.GetAllProperties(); + var newEntity = tpro.PropertyType.GetConstructor(Type.EmptyTypes).Invoke(null); + bool isBasePoco = typeof(IBasePoco).IsAssignableFrom(tpro.PropertyType); + //将所有TopBasePoco的属性赋空值,防止添加关联的重复内容 + foreach (var pro in pros) + { + if (pro.PropertyType.GetTypeInfo().IsSubclassOf(typeof(TopBasePoco)) == false) + { + if (isBasePoco == false || (pro.Name != "UpdateTime" && pro.Name != "UpdateBy")) + { + pro.SetValue(newEntity, pro.GetValue(entity)); + } + } + } + tpro.SetValue(rv, newEntity); + } + else + { + if (tpro.CanWrite) + { + tpro.SetValue(rv, tpro.GetValue(self)); + } + } + } + return rv; + } + return null; + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/SystemExtensions/TypeExtension.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/SystemExtensions/TypeExtension.cs new file mode 100644 index 0000000..71d092e --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Extensions/SystemExtensions/TypeExtension.cs @@ -0,0 +1,527 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Reflection; +using Fare; + +namespace WalkingTec.Mvvm.Core.Extensions +{ + /// + /// Type的扩展函数 + /// + public static class TypeExtension + { + public static ImmutableDictionary> _propertyCache { get; set; } = new Dictionary>().ToImmutableDictionary(); + /// + /// 判断是否是泛型 + /// + /// Type类 + /// 泛型类型 + /// 判断结果 + public static bool IsGeneric(this Type self, Type innerType) + { + if (self.GetTypeInfo().IsGenericType && self.GetGenericTypeDefinition() == innerType) + { + return true; + } + else + { + return false; + } + } + + /// + /// 判断是否为Nullable<>类型 + /// + /// Type类 + /// 判断结果 + public static bool IsNullable(this Type self) + { + return self.IsGeneric(typeof(Nullable<>)); + } + + /// + /// 判断是否为List<>类型 + /// + /// Type类 + /// 判断结果 + public static bool IsList(this Type self) + { + return self.IsGeneric(typeof(List<>)) || self.IsGeneric(typeof(IEnumerable<>)); + } + + /// + /// 判断是否为List<>类型 + /// + /// Type类 + /// 判断结果 + public static bool IsListOf(this Type self) + { + if (self.IsGeneric(typeof(List<>)) && typeof(T).IsAssignableFrom(self.GenericTypeArguments[0])) + { + return true; + } + else + { + return false; + } + } + + + #region 判断是否为枚举 + + /// + /// 判断是否为枚举 + /// + /// Type类 + /// 判断结果 + public static bool IsEnum(this Type self) + { + return self.GetTypeInfo().IsEnum; + } + + /// + /// 判断是否为枚举或者可空枚举 + /// + /// + /// + public static bool IsEnumOrNullableEnum(this Type self) + { + if (self == null) + { + return false; + } + if (self.IsEnum) + { + return true; + } + else + { + if (self.IsGenericType && self.GetGenericTypeDefinition() == typeof(Nullable<>) && self.GetGenericArguments()[0].IsEnum) + { + return true; + } + else + { + return false; + } + } + } + + #endregion + + /// + /// 判断是否为值类型 + /// + /// Type类 + /// 判断结果 + public static bool IsPrimitive(this Type self) + { + return self.GetTypeInfo().IsPrimitive || self == typeof(decimal); + } + + public static bool IsNumber(this Type self) + { + Type checktype = self; + if (self.IsNullable()) + { + checktype = self.GetGenericArguments()[0]; + } + if (checktype == typeof(int) || checktype == typeof(short) || checktype == typeof(long) || checktype == typeof(float) || checktype == typeof(decimal) || checktype == typeof(double)) + { + return true; + } + else + { + return false; + } + } + + + #region 判断是否是Bool + + public static bool IsBool(this Type self) + { + return self == typeof(bool); + } + + /// + /// 判断是否是 bool or bool?类型 + /// + /// + /// + public static bool IsBoolOrNullableBool(this Type self) + { + if (self == null) + { + return false; + } + if (self == typeof(bool) || self == typeof(bool?)) + { + return true; + } + else + { + return false; + } + } + + #endregion + + public static Dictionary GetRandomValues(this Type self) + { + Dictionary rv = new Dictionary(); + string pat = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; + var pros = self.GetAllProperties(); + List skipFields = new List() + { + nameof(TopBasePoco.BatchError), + nameof(TopBasePoco.Checked), + nameof(TopBasePoco.ExcelIndex), + }; + if (typeof(IBasePoco).IsAssignableFrom(self)) + { + skipFields.AddRange( + new string[]{ + nameof(IBasePoco.CreateBy), + nameof(IBasePoco.CreateTime), + nameof(IBasePoco.UpdateBy), + nameof(IBasePoco.UpdateTime) } + ); + } + if (typeof(IPersistPoco).IsAssignableFrom(self)) + { + skipFields.Add(nameof(IPersistPoco.IsValid)); + } + foreach (var pro in pros) + { + string key = pro.Name; + string val = ""; + var notmapped = pro.GetCustomAttribute(); + if (notmapped == null && + pro.PropertyType.IsList() == false && + pro.PropertyType.IsSubclassOf(typeof(TopBasePoco)) == false && + skipFields.Contains(key) == false + ) + { + if (pro.PropertyType.IsNumber()) + { + var range = pro.GetCustomAttribute(); + int start = 0; + int end = 100; + if (range != null) + { + try + { + start = (int)Math.Truncate(double.Parse(range.Minimum.ToString())); + end = (int)Math.Truncate(double.Parse(range.Maximum.ToString())); + } + catch { } + } + Random r = new Random(); + val = r.Next(start, end).ToString(); + } + else if (pro.PropertyType.IsBoolOrNullableBool()) + { + List boolvalues = new List { "true", "false" }; + if (pro.PropertyType.IsNullable()) + { + boolvalues.Add("null"); + } + Random r = new Random(); + var index = r.Next(0, boolvalues.Count); + val = boolvalues[index]; + } + else if (pro.PropertyType.IsEnumOrNullableEnum()) + { + List enumvalues = new List(); + Type enumtype = null; + if (pro.PropertyType.IsNullable()) + { + enumtype = pro.PropertyType.GenericTypeArguments[0]; + enumvalues.Add("null"); + } + else + { + enumtype = pro.PropertyType; + } + var vs = Enum.GetValues(enumtype); + Random r = new Random(); + var index = r.Next(0, vs.Length); + val = enumtype.FullName+"."+ vs.GetValue(index).ToString(); + } + else if (pro.PropertyType == typeof(string)) + { + var length = pro.GetCustomAttribute(); + var min = 1; + var max = 20; + var l = 0; + if (length != null) + { + if (length.MaximumLength > 0) + { + max = length.MaximumLength; + } + if(length.MinimumLength > 0) + { + min = length.MinimumLength; + } + } + if(min == max) + { + l = max; + } + else if(min < max) + { + l = new Random().Next(min, max); + } + Random r = new Random(); + for (int i = 0; i < l; i++) + { + int index = r.Next(pat.Length); + val += pat[index]; + } + val = "\"" + val + "\""; + } + else if(pro.PropertyType == typeof(DateTime) || pro.PropertyType == typeof(DateTime?)) + { + Random r = new Random(); + val = DateTime.Now.AddDays(r.Next(-500, 500)).ToString("yyyy-MM-dd HH:mm:ss"); + val = $"DateTime.Parse(\"{val}\")"; + } + if (pros.Where(x => x.Name.ToLower() + "id" == key.ToLower()).Any()) + { + val = "$fk$"; + } + if (val != "") + { + if (rv.ContainsKey(key) == false) + { + rv.Add(key, val); + } + } + } + } + return rv; + } + + public static Dictionary GetRandomValuesForTestData(this Type self) + { + Dictionary rv = new Dictionary(); + string pat = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; + var pros = self.GetAllProperties(); + List skipFields = new List() + { + nameof(TopBasePoco.BatchError), + nameof(TopBasePoco.Checked), + nameof(TopBasePoco.ExcelIndex), + }; + if (typeof(IBasePoco).IsAssignableFrom(self)) + { + skipFields.AddRange( + new string[]{ + nameof(IBasePoco.CreateBy), + nameof(IBasePoco.CreateTime), + nameof(IBasePoco.UpdateBy), + nameof(IBasePoco.UpdateTime) } + ); + } + if (typeof(IPersistPoco).IsAssignableFrom(self)) + { + skipFields.Add(nameof(IPersistPoco.IsValid)); + } + foreach (var pro in pros) + { + string key = pro.Name; + string val = ""; + var notmapped = pro.GetCustomAttribute(); + var required = pro.GetCustomAttributes() != null; + if (notmapped == null && + pro.PropertyType.IsList() == false && + pro.PropertyType.IsSubclassOf(typeof(TopBasePoco)) == false && + skipFields.Contains(key) == false + ) + { + if (pro.PropertyType.IsNumber()) + { + if (pro.Name == "ID") + { + val = ""; + } + else + { + var range = pro.GetCustomAttribute(); + int start = 0; + int end = 100; + if (range != null) + { + try + { + start = (int)Math.Truncate(double.Parse(range.Minimum.ToString())); + end = (int)Math.Truncate(double.Parse(range.Maximum.ToString())); + } + catch { } + } + Random r = new Random(); + val = r.Next(start, end).ToString(); + } + } + else if (pro.PropertyType.IsBoolOrNullableBool()) + { + List boolvalues = new List { "true", "false" }; + if (pro.PropertyType.IsNullable()) + { + if (required == false) + { + boolvalues.Add(""); + } + } + Random r = new Random(); + var index = r.Next(0, boolvalues.Count); + val = boolvalues[index]; + } + else if (pro.PropertyType.IsEnumOrNullableEnum()) + { + List enumvalues = new List(); + Type enumtype = null; + if (pro.PropertyType.IsNullable()) + { + enumtype = pro.PropertyType.GenericTypeArguments[0]; + if (required == false) + { + enumvalues.Add(""); + } + } + else + { + enumtype = pro.PropertyType; + } + var vs = Enum.GetValues(enumtype); + foreach (var item in vs) + { + enumvalues.Add((int)item + ""); + } + Random r = new Random(); + var index = r.Next(0, enumvalues.Count); + val = enumvalues[index]; + } + else if (pro.PropertyType == typeof(string)) + { + + var reg = pro.GetCustomAttribute(); + var length = pro.GetCustomAttribute(); + + if (reg != null) { + Xeger x = new Xeger(reg.Pattern); + val = x.Generate(); + if(length != null) + { + if(length.MaximumLength > 0 && val.Length > length.MaximumLength) + { + val = val.Substring(0, length.MaximumLength-1); + } + } + } + else + { + var min = 1; + var max = 20; + var l = 0; + if (length != null) + { + if (length.MaximumLength > 0) + { + max = length.MaximumLength; + } + if (length.MinimumLength > 0) + { + min = length.MinimumLength; + } + } + if (min == max) + { + l = max; + } + else if (min < max) + { + l = new Random().Next(min, max); + } + Random r = new Random(); + for (int i = 0; i < l; i++) + { + int index = r.Next(pat.Length); + val += pat[index]; + } + } + + val = "\"" + val + "\""; + } + else if (pro.PropertyType == typeof(DateTime) || pro.PropertyType == typeof(DateTime?)) + { + Random r = new Random(); + val = DateTime.Now.AddDays(r.Next(-500, 500)).ToString("yyyy-MM-dd HH:mm:ss"); + } + if (pros.Where(x => x.Name.ToLower() + "id" == key.ToLower()).Any()) + { + val = "$fk$"; + } + if (val != "") + { + if (rv.ContainsKey(key) == false) + { + rv.Add(key, val); + } + } + } + } + return rv; + } + + + public static PropertyInfo GetSingleProperty(this Type self, string name) + { + if (_propertyCache.ContainsKey(self.FullName) == false) + { + var properties = self.GetProperties().ToList(); + _propertyCache = _propertyCache.Add(self.FullName, properties); + return properties.Where(x => x.Name == name).FirstOrDefault(); + } + else + { + return _propertyCache[self.FullName].Where(x => x.Name == name).FirstOrDefault(); + } + } + + public static PropertyInfo GetSingleProperty(this Type self, Func where) + { + if (_propertyCache.ContainsKey(self.FullName) == false) + { + var properties = self.GetProperties().ToList(); + _propertyCache = _propertyCache.Add(self.FullName, properties); + return properties.Where(where).FirstOrDefault(); + } + else + { + return _propertyCache[self.FullName].Where(where).FirstOrDefault(); + } + } + + public static List GetAllProperties(this Type self) + { + if (_propertyCache.ContainsKey(self.FullName) == false) + { + var properties = self.GetProperties().ToList(); + _propertyCache = _propertyCache.Add(self.FullName, properties); + return properties; + } + else + { + return _propertyCache[self.FullName]; + } + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/GlobalConstants.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/GlobalConstants.cs new file mode 100644 index 0000000..c2bb83b --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/GlobalConstants.cs @@ -0,0 +1,10 @@ +namespace WalkingTec.Mvvm.Core +{ + public static class GlobalConstants + { + public static class CacheKey + { + public const string UserInfo = "WtmUserInfo"; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/GlobalData.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/GlobalData.cs new file mode 100644 index 0000000..e119c09 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/GlobalData.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using WalkingTec.Mvvm.Core.Support.Json; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// 应用全局缓存 + /// + public class GlobalData + { + + /// + /// 程序集 + /// + public List AllAssembly { get; set; } + + /// + /// 可访问的url地址 + /// + public List AllAccessUrls { get; set; } + + public Type CustomUserType { get; set; } + /// + /// 模块 + /// + public List AllModule { get; set; } + + private Func> MenuGetFunc; + + public List AllMenus => MenuGetFunc?.Invoke(); + + /// + /// 设置菜单委托 + /// + /// + public void SetMenuGetFunc(Func> func) => MenuGetFunc = func; + + public List GetTypesAssignableFrom() + { + var rv = new List(); + foreach (var ass in AllAssembly) + { + var types = new List(); + try + { + types.AddRange(ass.GetExportedTypes()); + } + catch { } + + rv.AddRange(types.Where(x => typeof(T).IsAssignableFrom(x) && x != typeof(T) && x.IsAbstract == false).ToList()); + } + return rv; + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/GlobalServices.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/GlobalServices.cs new file mode 100644 index 0000000..39d0f50 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/GlobalServices.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using Microsoft.Extensions.DependencyInjection; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// GlobalServices + /// + //public static class GlobalServices + //{ + // private static IServiceProvider _serviceProvider = null; + // /// + // /// IocContainer + // /// + // public static IServiceProvider ServiceProvider => _serviceProvider; + + // /// + // /// SetServiceProvider + // /// + // /// + // public static void SetServiceProvider(IServiceProvider container) { _serviceProvider = container; } + + // #region GetServicce + + // /// + // /// GetService + // /// + // /// + // /// + // public static T GetService() where T : class => ServiceProvider?.GetService(); + + // /// + // /// GetService + // /// + // /// + // /// + // public static object GetService(Type type) => ServiceProvider?.GetService(type); + + // /// + // /// GetServices + // /// + // /// + // /// + // public static IEnumerable GetServices() where T : class => ServiceProvider?.GetServices(); + + // /// + // /// GetServices + // /// + // /// + // /// + // public static IEnumerable GetServices(Type type) => ServiceProvider?.GetServices(type); + + // /// + // /// GetRequiredService + // /// + // /// + // /// + // public static T GetRequiredService() where T : class => ServiceProvider?.GetRequiredService(); + + // /// + // /// GetRequiredService + // /// + // /// + // /// + // public static object GetRequiredService(Type type) => ServiceProvider?.GetRequiredService(type); + + // #endregion + //} +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridAction.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridAction.cs new file mode 100644 index 0000000..2dba7cc --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridAction.cs @@ -0,0 +1,224 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Web; + +namespace WalkingTec.Mvvm.Core +{ + #region 列表动作类型 + /// + /// 列表动作类型 + /// + public enum GridActionParameterTypesEnum + { + /// + /// 不需要传递Id + /// + NoId, + /// + /// 只传递一个Id + /// + SingleId, + /// + /// 传递多个Id + /// + MultiIds, + /// + /// 只传递一个Id,但 Id 可能为null + /// + SingleIdWithNull, + /// + /// 传递多个 Id 或 null + /// + MultiIdWithNull, + AddRow, + RemoveRow + } + + #endregion + + + #region 标准列表动作 + /// + /// 标准列表动作 + /// + public enum GridActionStandardTypesEnum + { + Create, + Edit, + Delete, + SimpleDelete, + Details, + BatchEdit, + BatchDelete, + SimpleBatchDelete, + Import, + ExportExcel, + AddRow, + RemoveRow, + ActionsGroup + } + #endregion + + #region 导出枚举 + public enum ExportEnum + { + [Display(Name = "Excel")] + Excel = 0, + [Display(Name = "PDF")] + PDF = 1 + } + #endregion + + /// + /// 列表动作类,负责处理列表动作条中的动作按钮 + /// + public class GridAction + { + #region Action属性 + + /// + /// 按钮Id,一般不需要设定,系统会自动生成唯一Id。如果设定请确保 Id 的唯一性 + /// + public string ButtonId { get; set; } + + /// + /// 按钮名称 + /// + public string Name { get; set; } + + /// + /// 弹出窗口的标题 + /// + public string DialogTitle { get; set; } + + /// + /// 如果不为null,则只运行这个变量设定的script,其他的属性都不起作用 + /// + public string OnClickFunc { get; set; } + + /// + /// 是否在每行都显示 + /// + public bool ShowInRow { get; set; } + /// + /// 是否在工具栏上隐藏按钮 + /// + public bool HideOnToolBar { get; set; } + + /// + /// bind to a column name to deside whether or not to show this action + /// + public string BindVisiableColName { get; set; } + + /// + /// additional css class of button + /// + public string ButtonClass { get; set;} + /// + /// if the dialog need to be maximax + /// + public bool Max { get; set; } + + /// + /// If this action is to download a file + /// + public bool IsDownload { get; set; } + + #region 请求链接相关 + + /// + /// 动作的Area + /// + public string Area { get; set; } + + public bool IsExport { get; set; } + /// + /// 动作的Controller + /// + public string ControllerName { get; set; } + + /// + /// 动作的Action + /// + public string ActionName { get; set; } + + public string Url + { + get + { + var rv = ""; + if(string.IsNullOrEmpty(ControllerName) == false){ + rv = $"/{HttpUtility.UrlEncode(ControllerName)}/{HttpUtility.UrlEncode(ActionName)}"; + if (!string.IsNullOrEmpty(Area)) + { + rv = $"/{HttpUtility.UrlEncode(Area)}{rv}"; + } + if (!string.IsNullOrEmpty(QueryString)) + { + rv = $"{rv}?{QueryString}"; + } + else + { + rv = $"{rv}?1=1"; ; + } + } + return rv; + } + } + + #endregion + + /// + /// 是否跳转到新页面 + /// + public bool IsRedirect { get; set; } + + /// + /// 弹出问询框 + /// + public string PromptMessage { get; set; } + + /// + /// 动作类型 + /// + public GridActionParameterTypesEnum ParameterType { get; set; } + + public bool ForcePost { get; set; } + #endregion + + #region 暂时无用 + /// + /// 是否可以resizable + /// + public bool Resizable { get; set; } + /// + /// 动作图标css + /// + public string IconCls { get; set; } + /// + /// 动作的QueryString + /// + public string QueryString { get; set; } + /// + /// 弹出窗口的宽度 + /// + public int? DialogWidth { get; set; } + /// + /// 弹出窗口的高度 + /// + public int? DialogHeight { get; set; } + /// + /// 是否需要弹出窗口 + /// + public bool ShowDialog { get; set; } + + /// + /// 如果设定了SubActions,则代表需要用SplitButton的形式展示,主GridAction将不起作用 + /// + public List SubActions { get; set; } + + public string[] whereStr { get; set; } + + #endregion + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridActionExtension.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridActionExtension.cs new file mode 100644 index 0000000..739e20e --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridActionExtension.cs @@ -0,0 +1,424 @@ +using System; +using System.Collections.Generic; +using System.Linq.Expressions; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// GridActionExtension + /// + public static class GridActionExtensions + { + #region MakeStandardAction 创建标准动作 + + /// + /// 创建标准动作 + /// + /// 继承自TopBasePoco的类 + /// 继承自ISearcher的类 + /// self + /// 动作的Controller + /// 标准动作类型 + /// 弹出窗口的标题,可为空,代表使用默认文字 + /// 域名 + /// 弹出窗口的宽度 + /// 弹出窗口的高度 + /// 按钮显示的文字 + /// Button的id 默认自动生成 + /// whereStr + /// 列表动作 + /// + /// 根据标准动作类型,创建默认属性的标准动作 + /// + public static GridAction MakeStandardAction(this IBasePagedListVM self + , string controllerName + , GridActionStandardTypesEnum standardType + , string dialogTitle + , string areaName = null + , int? dialogWidth = null + , int? dialogHeight = null + , string name = null + , string buttonId = null + , params Expression>[] whereStr) + where T : TopBasePoco + where V : ISearcher + { + var iconcls = string.Empty; + var actionName = standardType.ToString(); + var gridname = string.Empty; + var paraType = GridActionParameterTypesEnum.NoId; + var showInRow = false; + var hideOnToolBar = false; + var showDialog = true; + var isexport = false; + string msg = null; + var ispost = false; + string qs = null; + switch (standardType) + { + case GridActionStandardTypesEnum.Create: + iconcls = "layui-icon layui-icon-add-1"; + gridname = CoreProgram._localizer?["Sys.Create"]; + paraType = GridActionParameterTypesEnum.NoId; + break; + case GridActionStandardTypesEnum.AddRow: + iconcls = "layui-icon layui-icon-add-1"; + gridname = CoreProgram._localizer?["Sys.Create"]; + paraType = GridActionParameterTypesEnum.AddRow; + break; + case GridActionStandardTypesEnum.Edit: + iconcls = "layui-icon layui-icon-edit"; + gridname = CoreProgram._localizer?["Sys.Edit"]; + paraType = GridActionParameterTypesEnum.SingleId; + showInRow = true; + hideOnToolBar = true; + break; + case GridActionStandardTypesEnum.Delete: + iconcls = "layui-icon layui-icon-delete"; + gridname = CoreProgram._localizer?["Sys.Delete"]; + paraType = GridActionParameterTypesEnum.SingleId; + showInRow = true; + hideOnToolBar = true; + break; + case GridActionStandardTypesEnum.SimpleDelete: + iconcls = "layui-icon layui-icon-delete"; + gridname = CoreProgram._localizer?["Sys.Delete"]; + paraType = GridActionParameterTypesEnum.SingleIdWithNull; + showInRow = true; + hideOnToolBar = true; + showDialog = false; + actionName = "BatchDelete"; + qs = "_donotuse_sd=1"; + ispost = true; + msg = CoreProgram._localizer?["Sys.DeleteConfirm"]; + break; + + case GridActionStandardTypesEnum.RemoveRow: + iconcls = "layui-icon layui-icon-delete"; + gridname = CoreProgram._localizer?["Sys.Delete"]; + paraType = GridActionParameterTypesEnum.RemoveRow; + showInRow = true; + hideOnToolBar = true; + break; + case GridActionStandardTypesEnum.Details: + iconcls = "layui-icon layui-icon-form"; + gridname = CoreProgram._localizer?["Sys.Details"]; + paraType = GridActionParameterTypesEnum.SingleId; + showInRow = true; + hideOnToolBar = true; + break; + case GridActionStandardTypesEnum.BatchEdit: + iconcls = "layui-icon layui-icon-edit"; + gridname = CoreProgram._localizer?["Sys.BatchEdit"]; + paraType = GridActionParameterTypesEnum.MultiIds; + break; + case GridActionStandardTypesEnum.BatchDelete: + iconcls = "layui-icon layui-icon-delete"; + gridname = CoreProgram._localizer?["Sys.BatchDelete"]; + paraType = GridActionParameterTypesEnum.MultiIds; + break; + case GridActionStandardTypesEnum.SimpleBatchDelete: + iconcls = "layui-icon layui-icon-delete"; + gridname = CoreProgram._localizer?["Sys.BatchDelete"]; + paraType = GridActionParameterTypesEnum.MultiIds; + showDialog = false; + msg = CoreProgram._localizer?["Sys.BatchDeleteConfirm"]; + actionName = "BatchDelete"; + ispost = true; + break; + case GridActionStandardTypesEnum.Import: + iconcls = "layui-icon layui-icon-templeate-1"; + gridname = CoreProgram._localizer?["Sys.Import"]; + paraType = GridActionParameterTypesEnum.NoId; + break; + case GridActionStandardTypesEnum.ExportExcel: + iconcls = "layui-icon layui-icon-download-circle"; + gridname = CoreProgram._localizer?["Sys.Export"]; + paraType = GridActionParameterTypesEnum.MultiIdWithNull; + name = CoreProgram._localizer?["Sys.ExportExcel"]; + showInRow = false; + showDialog = false; + hideOnToolBar = false; + isexport = true; + break; + default: + break; + } + + if (string.IsNullOrEmpty(dialogTitle)) + { + dialogTitle = gridname; + } + + var list = new List(); + foreach (var item in whereStr) + { + list.Add(PropertyHelper.GetPropertyName(item)); + } + + return new GridAction + { + ButtonId = buttonId, + Name = (name ?? gridname), + DialogTitle = dialogTitle, + Area = areaName, + ControllerName = controllerName, + ActionName = actionName, + ParameterType = paraType, + IconCls = iconcls, + DialogWidth = dialogWidth ?? 800, + DialogHeight = dialogHeight, + ShowInRow = showInRow, + ShowDialog = showDialog, + HideOnToolBar = hideOnToolBar, + PromptMessage = msg, + ForcePost = ispost, + QueryString = qs, + IsExport = isexport, + whereStr = list.ToArray() + }; + } + + #endregion + + #region MakeAction 创建按钮 + /// + /// 创建标准动作 + /// + /// 继承自TopBasePoco的类 + /// 继承自ISearcher的类 + /// self + /// 动作的Controller + /// actionName + /// 动作名,默认为‘新建’ + /// 弹出窗口的标题 + /// paraType + /// 域名 + /// 弹出窗口的宽度 + /// 弹出窗口的高度 + /// Button的id 默认自动生成 + /// whereStr + /// 列表动作 + /// + /// 根据标准动作类型,创建默认属性的标准动作 + /// + public static GridAction MakeAction(this IBasePagedListVM self + , string controllerName + , string actionName + , string name + , string dialogTitle + , GridActionParameterTypesEnum paraType + , string areaName = null + , int? dialogWidth = null + , int? dialogHeight = null + , string buttonId = null + , params Expression>[] whereStr) + where T : TopBasePoco + where V : ISearcher + { + var iconcls = string.Empty; + + var list = new List(); + foreach (var item in whereStr) + { + list.Add(PropertyHelper.GetPropertyName(item)); + } + + return new GridAction + { + ButtonId = buttonId, + Name = name, + DialogTitle = dialogTitle, + Area = areaName, + ControllerName = controllerName, + ActionName = actionName, + ParameterType = paraType, + IconCls = iconcls, + DialogWidth = dialogWidth ?? 800, + DialogHeight = dialogHeight, + ShowDialog = true, + whereStr = list.ToArray() + }; + } + + public static GridAction MakeActionsGroup(this IBasePagedListVM self + , string name + , List subActions + , params Expression>[] whereStr) + where T : TopBasePoco + where V : ISearcher + { + var iconcls = string.Empty; + + var list = new List(); + foreach (var item in whereStr) + { + list.Add(PropertyHelper.GetPropertyName(item)); + } + + return new GridAction + { + ButtonId = Guid.NewGuid().ToString(), + Name = name, + DialogTitle = "", + Area = "", + ControllerName = "", + ActionName = "ActionsGroup", + ParameterType = GridActionParameterTypesEnum.NoId, + IconCls = iconcls, + DialogWidth = 0, + DialogHeight = 0, + ShowDialog = false, + whereStr = list.ToArray(), + SubActions= subActions + }; + } + + #endregion + + #region MakeStandardExportAction 创建标准导出按钮 + + /// + /// 创建标准导出按钮 + /// + /// 继承自TopBasePoco的类 + /// 继承自ISearcher的类 + /// self + /// vmGuid + /// + /// 导出类型 默认null,支持所有导出 + /// 参数 + /// + [Obsolete("Will be removed in future, use MakeStandardAction with GridActionStandardTypesEnum.ExportExcel instead")] + public static GridAction MakeStandardExportAction(this IBasePagedListVM self + , string gridid = null + , bool MustSelect = false + , ExportEnum? exportType = null + , params KeyValuePair[] param) + where T : TopBasePoco + where V : ISearcher + { + exportType = ExportEnum.Excel; + + var action = new GridAction + { + Name = CoreProgram._localizer?["Sys.ExportExcel"], + DialogTitle = CoreProgram._localizer?["Sys.ExportExcel"], + Area = string.Empty, + ControllerName = "_Framework", + ActionName = "GetExportExcel", + ParameterType = GridActionParameterTypesEnum.MultiIdWithNull, + + IconCls = "layui-icon layui-icon-download-circle", + ShowInRow = false, + ShowDialog = false, + HideOnToolBar = false + }; + return action; + } + + #endregion + + #region Set Property + + /// + /// Set the dialog to be maximized + /// + /// + /// + /// + public static GridAction SetMax(this GridAction self, bool Max = true) + { + self.Max = Max; + return self; + } + + + /// + /// Set the dialog to be maximized + /// + /// + /// button class. + /// Some of the layui defined class to control color: + /// layui-btn-primary + /// layui-btn-normal + /// layui-btn-warm + /// layui-btn-danger + /// + /// + public static GridAction SetButtonClass(this GridAction self, string buttonclass) + { + self.ButtonClass = buttonclass; + return self; + } + + + + /// + /// Set the dialog to be maximized + /// + /// + /// + /// + public static GridAction SetIsDownload(this GridAction self, bool isDownload = true) + { + self.IsDownload = isDownload; + return self; + } + + public static GridAction SetIsExport(this GridAction self, bool isExport= true) + { + self.IsExport = isExport; + return self; + } + + + /// + /// Set prompt message + /// + /// + /// + /// + public static GridAction SetPromptMessage(this GridAction self, string msg) + { + self.PromptMessage = msg; + return self; + } + + + /// + /// 是否在每行都显示 + /// + /// + /// + /// + public static GridAction SetShowInRow(this GridAction self, bool showInRow = true) + { + self.ShowInRow = showInRow; + return self; + } + /// + /// 是否在工具栏上隐藏按钮 + /// + /// + /// + /// + public static GridAction SetHideOnToolBar(this GridAction self, bool hideOnToolBar = true) + { + self.HideOnToolBar = hideOnToolBar; + return self; + } + /// + /// 把按钮当作容器,添加按钮的子按钮 + /// + /// + /// 子按钮 + /// + public static GridAction SetSubActions(this GridAction self, List subActions) + { + self.SubActions = subActions; + return self; + } + #endregion + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridActionExtension`Old.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridActionExtension`Old.cs new file mode 100644 index 0000000..9f57c09 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridActionExtension`Old.cs @@ -0,0 +1,205 @@ +using System.Collections.Generic; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// GridActionExtension + /// + public static class GridActionExtension + { + /// + /// 按钮Id,一般不需要设定,系统会自动生成唯一Id。如果设定请确保 Id 的唯一性 + /// + /// + /// + /// + public static GridAction SetButtonId(this GridAction self, string buttonId) + { + self.ButtonId = buttonId; + return self; + } + /// + /// 按钮名称 + /// + /// + /// + /// + public static GridAction SetName(this GridAction self, string name) + { + self.Name = name; + return self; + } + /// + /// 弹出窗口的标题 + /// + /// + /// + /// + public static GridAction SetDialogTitle(this GridAction self, string dialogTitle) + { + self.DialogTitle = dialogTitle; + return self; + } + /// + /// 动作图标css + /// + /// + /// + /// + public static GridAction SetIconCls(this GridAction self, string iconCls) + { + self.IconCls = iconCls; + return self; + } + /// + /// 动作的Area + /// + /// + /// + /// + public static GridAction SetArea(this GridAction self, string area) + { + self.Area = area; + return self; + } + /// + /// 动作的Controller + /// + /// + /// + /// + public static GridAction SetControllerName(this GridAction self, string controllerName) + { + self.ControllerName = controllerName; + return self; + } + /// + /// 动作的Action + /// + /// + /// + /// + public static GridAction SetActionName(this GridAction self, string actionName) + { + self.ActionName = actionName; + return self; + } + /// + /// 动作的QueryString + /// + /// + /// + /// + public static GridAction SetQueryString(this GridAction self, string queryString) + { + self.QueryString = queryString; + return self; + } + /// + /// 弹出窗口的宽度、高度 + /// + /// + /// + /// + /// + public static GridAction SetSize(this GridAction self, int? dialogWidth, int? dialogHeight) + { + self.DialogWidth = dialogWidth; + self.DialogHeight = dialogHeight; + return self; + } + /// + /// 是否需要弹出窗口 + /// + /// + /// + /// + public static GridAction SetShowDialog(this GridAction self, bool showDialog = true) + { + self.ShowDialog = showDialog; + return self; + } + public static GridAction SetForcePost(this GridAction self, bool forcepost = true) + { + self.ForcePost = forcepost; + return self; + } + + + /// + /// 是否跳转到新页面 + /// + /// + /// + /// + public static GridAction SetIsRedirect(this GridAction self, bool isRedirect = true) + { + self.IsRedirect = isRedirect; + return self; + } + /// + /// 动作类型 + /// + /// + /// + /// + public static GridAction SetParameterType(this GridAction self, GridActionParameterTypesEnum parameterType) + { + self.ParameterType = parameterType; + return self; + } + /// + /// 如果不为null,则只运行这个变量设定的script,其他的属性都不起作用 + /// + /// + /// + /// + /// 如设置SetOnClickScript("test"),点击按钮时框架会调用页面上的javascript方法: function test(ids,datas){} + /// ids是勾选的id数组,datas是勾选的所有字段数组 + /// + /// + public static GridAction SetOnClickScript(this GridAction self, string onClickScript) + { + self.OnClickFunc = onClickScript; + return self; + } + /// + /// 如果设定了SubActions,则代表需要用SplitButton的形式展示,主GridAction将不起作用 + /// + /// + /// + /// + public static GridAction SetSubAction(this GridAction self, params GridAction[] gridActions) + { + if (self.SubActions == null) + { + self.SubActions = new List(); + } + self.SubActions.AddRange(gridActions); + return self; + } + /// + /// 是否可以拖动改变弹出窗体大小 + /// + /// + /// + /// + public static GridAction SetNotResizable(this GridAction self, bool resizable = false) + { + self.Resizable = resizable; + return self; + } + + /// + /// 设置一个布尔值的列名,当改列值为true的时候才显示本行的这个动作按钮 + /// + /// + /// + /// + public static GridAction SetBindVisiableColName(this GridAction self, string colName) + { + self.BindVisiableColName = colName; + return self; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridColumn.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridColumn.cs new file mode 100644 index 0000000..321db3d --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridColumn.cs @@ -0,0 +1,510 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Text.Json; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// 列表列的定义 + /// + /// 列表的数据源类 + public class GridColumn : IGridColumn where T : TopBasePoco + { + public bool? ShowTotal { get; set; } + public GridColumn(Expression> columnExp, int? width) + { + ColumnExp = columnExp; + Width = width; + } + + /// + /// 表头类型 + /// + public GridColumnTypeEnum ColumnType { get; set; } + private string _field; + /// + /// 设定字段名 + /// + public string Field + { + get + { + if (_field == null) + { + _field = PI?.Name; + if (_field == null) + { + _field = CompiledCol?.Invoke(null).ToString(); + } + } + return _field; + } + set + { + _field = value; + } + } + + private string _title; + /// + /// 标题名称 + /// + public string Title + { + get + { + if (_title == null && PI != null) + { + _title = PropertyHelper.GetPropertyDisplayName(PI) ?? string.Empty; + } + return _title; + } + set + { + _title = value; + } + } + + /// + /// 列宽 + /// + public int? Width { get; set; } + /// + /// //监听单元格事件 + /// + public string Event { get; set; } + /// + /// 是否允许排序 + /// + public bool? Sort { get; set; } + + /// + /// 是否固定列 + /// + public GridColumnFixedEnum? Fixed { get; set; } + + /// + /// 对齐方式 + /// + public GridColumnAlignEnum Align { get; set; } + + /// + /// 是否可改变列宽 + /// + public bool? UnResize { get; set; } + + /// + /// 隐藏列 + /// + public bool? Hide { get; set; } + + /// + /// 是否禁止导出此列 + /// + public bool DisableExport { get; set; } + + /// + /// 子列 + /// + public IEnumerable> Children { get; set; } + private int? _childrenLen; + /// + /// 底层子列数量 + /// + public int ChildrenLength + { + get + { + if (_childrenLen == null) + { + var len = 0; + if (Children != null && Children.Any()) + { + len += Children.Where(x => x.Children == null || !x.Children.Any()).Count(); + var tempChildren = Children.Where(x => x.Children != null && x.Children.Any()).ToList(); + foreach (var item in tempChildren) + { + len += item.ChildrenLength; + } + } + _childrenLen = len; + } + return _childrenLen.Value; + } + } + + public EditTypeEnum? EditType { get; set; } + + public List ListItems { get; set; } + + #region 只读属性 生成 Excel 及其 表头用 + + /// + /// 递归获取子列数量最大层的子列数量 + /// + public int MaxChildrenCount + { + get + { + int rv = 1; + if (this.Children != null && Children.Any()) + { + rv = 0; + foreach (var child in this.Children) + { + rv += child.MaxChildrenCount; + } + } + return rv; + } + } + /// + /// 获取最大层数 + /// + public int MaxLevel + { + get + { + int rv = 1; + if (this.Children != null && Children.Any()) + { + int max = 0; + foreach (var child in this.Children) + { + int temp = child.MaxLevel; + if (max < temp) + { + max = temp; + } + } + rv += max; + } + return rv; + + } + } + + #endregion + + private PropertyInfo _pi; + protected PropertyInfo PI + { + get + { + if (_pi == null && ColumnExp != null) + { + _pi = PropertyHelper.GetPropertyInfo(ColumnExp); + } + return _pi; + } + } + + /// + /// ColumnExp + /// + public Expression> ColumnExp { get; set; } + + private int? _maxDepth; + + /// + /// 最大深度 + /// + public int MaxDepth + { + get + { + if (_maxDepth == null) + { + _maxDepth = 1; + if (Children?.Count() > 0) + { + _maxDepth += Children.Max(x => x.MaxDepth); + } + } + return _maxDepth.Value; + } + } + + #region 暂时没有用 + /// + /// + /// + public string Id { get; set; } + + private Func _compiledCol; + protected Func CompiledCol + { + get + { + if (_compiledCol == null) + { + if (ColumnExp == null) + { + _compiledCol = (T) => ""; + } + else + { + _compiledCol = ColumnExp.Compile(); + } + } + return _compiledCol; + } + } + + + private Type _fieldType; + /// + /// 获取值域类型 + /// + /// + public Type FieldType + { + get + { + return _fieldType ?? PI?.PropertyType; + } + set + { + _fieldType = value; + } + } + + public string FieldName + { + get + { + return PI?.Name; + } + } + + /// + /// 本列是否需要分组 + /// + public bool NeedGroup { get; set; } + public bool IsLocked { get; set; } + public bool Sortable { get; set; } + /// + /// 是否允许换行 + /// + public bool AllowMultiLine { get; set; } + /// + /// 设置某列是否应该尽量充满 + /// + public int? Flex { get; set; } + /// + /// 列内容的格式化函数 + /// + public ColumnFormatCallBack Format { get; set; } + + /// + /// 本列前景色函数 + /// + public Func ForeGroundFunc { get; set; } + /// + /// 本列背景色函数 + /// + public Func BackGroundFunc { get; set; } + + + /// + /// 获取最底层的子列 + /// + public IEnumerable> BottomChildren + { + get + { + List> rv = new List>(); + if (Children != null && Children.Any()) + { + foreach (var child in Children) + { + rv.AddRange(child.BottomChildren); + } + } + else + { + rv.Add(this); + } + return rv; + } + } + + /// + /// 根据设置前景色的函数返回前景色 + /// + /// 源数据 + /// 前景色 + public string GetForeGroundColor(object source) + { + if (ForeGroundFunc == null) + { + return ""; + } + else + { + return ForeGroundFunc.Invoke(source as T); + } + } + + /// + /// 根据设置背景色的函数返回背景色 + /// + /// 源数据 + /// 背景色 + public string GetBackGroundColor(object source) + { + if (BackGroundFunc == null) + { + return ""; + } + else + { + return BackGroundFunc.Invoke(source as T); + } + } + + + public bool HasFormat() + { + if(Format != null) + { + return true; + } + else + { + return false; + } + } + + /// + /// 获取单元格要输出的内容 + /// + /// 源数据 + /// 是否使用format + /// Html内容 + public virtual object GetText(object source, bool needFormat = true) + { + object rv = null; + var col = CompiledCol?.Invoke(source as T); + if(needFormat == false && Format != null) + { + var test = Format.Invoke(source as T, col); + if(test is ColumnFormatInfo == false && test is List == false) + { + return test??""; + } + } + + if (Format == null || needFormat == false) + { + if (col == null) + { + rv = ""; + } + else if (col is DateTime || col is DateTime?) + { + var datevalue = col as DateTime?; + if(datevalue != null) + { + if (datevalue.Value.Hour == 0 && datevalue.Value.Minute == 0 && datevalue.Value.Second == 0) + { + rv = datevalue.Value.ToString("yyyy-MM-dd"); + } + else + { + rv = datevalue.Value.ToString("yyyy-MM-dd HH:mm:ss"); + } + } + else + { + rv = ""; + } + } + else if (col.GetType().IsEnumOrNullableEnum()) + { + rv = col.ToString(); + } + else if (col.GetType().Namespace.Equals("System") == false) + { + if (needFormat == false) + { + rv = JsonSerializer.Serialize(col, CoreProgram.DefaultJsonOption); + } + else + { + rv = col.ToString(); + } + } + else + { + rv = col.ToString(); + } + } + else + { + rv = Format.Invoke(source as T, col); + } + if (rv == null) + { + rv = ""; + } + return rv; + } + + public virtual object GetObject(object source) + { + object rv = CompiledCol?.Invoke(source as T); + return rv; + } + + /// + /// 获取列头内容 + /// + /// Html内容 + protected virtual string GetHeader() + { + string rv = PropertyHelper.GetPropertyDisplayName(PI); + return rv ?? ""; + } + /// + /// 默认构造函数 + /// + public GridColumn() + { + AllowMultiLine = true; + this.Sortable = true; + } + /// + /// 构造函数 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public GridColumn(Expression> ColumnExp, ColumnFormatCallBack Format = null, string Header = null, int? Width = null, int? Flex = null, bool AllowMultiLine = true, bool NeedGroup = false, Func ForeGroundFunc = null, Func BackGroundFunc = null, bool sortable = true) + { + this.ColumnExp = ColumnExp; + this.Format = Format; + this.Title = Header; + this.Width = Width; + this.NeedGroup = NeedGroup; + this.ForeGroundFunc = ForeGroundFunc; + this.BackGroundFunc = BackGroundFunc; + this.AllowMultiLine = AllowMultiLine; + this.Flex = Flex; + this.Sortable = sortable; + } + + #endregion + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridColumnExtension`Old.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridColumnExtension`Old.cs new file mode 100644 index 0000000..e82fc81 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridColumnExtension`Old.cs @@ -0,0 +1,218 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// GridColumnExtension + /// + public static class GridColumnExtension + { + /// + /// GetAllBottomColumns + /// + /// + /// + /// + public static IEnumerable> GetAllBottomColumns(this IEnumerable> self) + { + List> rv = new List>(); + foreach (var item in self) + { + rv.AddRange(item.BottomChildren); + } + return rv; + } + /// + /// Id + /// + /// + /// + /// + /// + public static GridColumn SetId(this GridColumn self, string id) where T : TopBasePoco + { + self.Id = id; + return self; + } + /// + /// 列头 + /// + /// + /// + /// + /// + public static GridColumn SetHeader(this GridColumn self, string header) where T : TopBasePoco + { + self.Title = header; + return self; + } + /// + /// 本列是否需要分组 + /// + /// + /// + /// + /// + public static GridColumn SetNeedGroup(this GridColumn self, bool needGroup) where T : TopBasePoco + { + self.NeedGroup = needGroup; + return self; + } + public static GridColumn SetLocked(this GridColumn self, bool locked) where T : TopBasePoco + { + self.IsLocked = locked; + return self; + } + public static GridColumn SetSortable(this GridColumn self, bool sortable = false) where T : TopBasePoco + { + self.Sortable = sortable; + return self; + } + /// + /// 列宽 + /// + /// + /// + /// + /// + public static GridColumn SetWidth(this GridColumn self, int? width) where T : TopBasePoco + { + self.Width = width; + return self; + } + /// + /// 是否允许换行 + /// + /// + /// + /// + /// + public static GridColumn SetAllowMultiLine(this GridColumn self, bool allowMultiLine) where T : TopBasePoco + { + self.AllowMultiLine = allowMultiLine; + return self; + } + /// + /// 设置某列是否应该尽量充满 + /// + /// + /// + /// + /// + public static GridColumn SetFlex(this GridColumn self, int? flex) where T : TopBasePoco + { + self.Flex = flex; + return self; + } + ///// + ///// 时间与数字类型Format + ///// + ///// + ///// + ///// + ///// + //public static GridColumn SetFormat(this GridColumn self, string format) where T : TopBasePoco + //{ + // self.StringFormat = format; + // return self; + //} + /// + /// 列内容的格式化函数 + /// + /// + /// + /// + /// + public static GridColumn SetFormat(this GridColumn self, ColumnFormatCallBack format) where T : TopBasePoco + { + self.Format = format; + return self; + } + /// + /// 计算列值的表达式 + /// + /// + /// + /// + /// + public static GridColumn SetColumnExp(this GridColumn self, Expression> columnExp) where T : TopBasePoco + { + self.ColumnExp = columnExp; + return self; + } + /// + /// 子列 + /// + /// + /// + /// + /// + public static GridColumn SetChildren(this GridColumn self, params GridColumn[] childrens) where T : TopBasePoco + { + List> temp = new List>(); + if (self.Children == null) + { + temp = new List>(); + } + else + { + temp = self.Children.Cast>().ToList(); + } + temp.AddRange(childrens); + self.Children = temp; + return self; + } + /// + /// 本列前景色函数 + /// + /// + /// + /// + /// + public static GridColumn SetForeGroundFunc(this GridColumn self, Func foreGroundFunc) where T : TopBasePoco + { + self.ForeGroundFunc = foreGroundFunc; + return self; + } + /// + /// 本列背景色函数 + /// + /// + /// + /// + /// + public static GridColumn SetBackGroundFunc(this GridColumn self, Func backGroundFunc) where T : TopBasePoco + { + self.BackGroundFunc = backGroundFunc; + return self; + } + + /// + /// 设置本列是否显示汇总 + /// + /// + /// + /// 是否显示 + /// + public static GridColumn SetShowTotal(this GridColumn self, bool show = true) where T : TopBasePoco + { + self.ShowTotal = show; + return self; + } + + /// + /// 设置禁止导出此列数据 + /// + /// + /// + /// + public static GridColumn SetDisableExport(this GridColumn self) where T : TopBasePoco + { + self.DisableExport = true; + return self; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridHeaderExtension.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridHeaderExtension.cs new file mode 100644 index 0000000..46dcde9 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/GridHeaderExtension.cs @@ -0,0 +1,310 @@ +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using System.Reflection; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// GridColumn Extension + /// + public static class GridHeaderExtension + { + /// + /// 创建表头 + /// + /// + /// + /// + /// 绑定猎头表达式 + /// 宽度 + /// + public static GridColumn MakeGridHeader(this IBasePagedListVM self + , Expression> columnExp + , int? width = null + ) + where T : TopBasePoco + where V : ISearcher + { + MemberExpression me = null; + if (columnExp is MemberExpression) + { + me = columnExp as MemberExpression; + } + else if (columnExp is LambdaExpression) + { + var le = columnExp as LambdaExpression; + if (le.Body is MemberExpression) + { + me = le.Body as MemberExpression; + } + } + var alignType = GridColumnAlignEnum.Center; + if (me != null) + { + var propType = me.Type; + if (propType == typeof(string)) + { + alignType = GridColumnAlignEnum.Left; + } + } + + return new GridColumn(columnExp, width) { ColumnType = GridColumnTypeEnum.Normal, Align = alignType }; + } + + /// + /// 创建一个间隙列 + /// + /// + /// + /// + /// + public static GridColumn MakeGridHeaderSpace(this IBasePagedListVM self) + where T : TopBasePoco + where V : ISearcher + { + return new GridColumn() { ColumnType = GridColumnTypeEnum.Space }; + } + + /// + /// 创建一个父级表头 + /// + /// + /// + /// + /// 标题 + /// + public static GridColumn MakeGridHeaderParent(this IBasePagedListVM self, string title + ) + where T : TopBasePoco + where V : ISearcher + { + return new GridColumn() { Title = title }; + } + + public static GridColumn MakeGridHeaderAction(this IBasePagedListVM self + , string title = null + , int? width = 160 + , int? rowspan = null + ) + where T : TopBasePoco + where V : ISearcher + { + return new GridColumn() + { + ColumnType = GridColumnTypeEnum.Action, + Width = width, + Fixed = GridColumnFixedEnum.Right, + Title = title ?? CoreProgram._localizer?["Sys.Operation"] + }; + } + + #region GridColumn Property Setter + + /// + /// 设定字段名 + /// + /// + /// + /// 字段名的设定非常重要,是表格数据列的唯一标识,默认属性对应的名字 + /// + public static GridColumn SetField(this GridColumn self, string field) + where T : TopBasePoco + { + self.Field = field; + return self; + } + + /// + /// 设定标题名称 + /// + /// + /// + /// 即表头各列的标题,默认属性对应的 DisplayName 或 属性名 + /// + public static GridColumn SetTitle(this GridColumn self, string title) + where T : TopBasePoco + { + self.Title = title; + return self; + } + + /// + /// 设定列宽 + /// + /// + /// + /// 列宽的设定也通常是必须的(“特殊列”除外,如:复选框列、工具列等),它关系到表格的整体美观程度。 + /// + public static GridColumn SetWidth(this GridColumn self, int width) + where T : TopBasePoco + { + self.Width = width; + return self; + } + /// + /// 单元格事件名称 + /// + /// + /// + /// + /// + public static GridColumn SetEvent(this GridColumn self, string eEvent) where T : TopBasePoco + { + self.Event = eEvent; + return self; + } + + ///// + ///// 设定当前列头 列横跨的单元格数 + ///// + ///// + ///// + ///// 这种情况下不用设置 Field 和 Width + ///// + //public static GridColumn SetColspan(this GridColumn self, int colspan) + // where T : TopBasePoco + //{ + // self.Colspan = colspan; + // return self; + //} + + ///// + ///// 设定当前列头 纵向跨越的单元格数 + ///// + ///// + ///// + ///// 纵向跨越的单元格数 + ///// + //public static GridColumn SetRowspan(this GridColumn self, int rowspan) + // where T : TopBasePoco + //{ + // self.Rowspan = rowspan; + // return self; + //} + + /// + /// 设定是否允许排序 (ASCII码排序) + /// + /// + /// + /// 如果设置 true,则在对应的表头显示排序icon,从而对列开启排序功能。 + /// + public static GridColumn SetSort(this GridColumn self, bool sort = true) + where T : TopBasePoco + { + self.Sort = sort; + return self; + } + + /// + /// 设定是否固定列 + /// + /// + /// + /// 如果设置 Left 或 Right,则对应的列将会被固定在左或右,不随滚动条而滚动。 + /// + public static GridColumn SetFixed(this GridColumn self, GridColumnFixedEnum? @fixed) + where T : TopBasePoco + { + self.Fixed = @fixed; + return self; + } + + /// + /// 设定对齐方式 + /// + /// + /// + /// + /// + public static GridColumn SetAlign(this GridColumn self, GridColumnAlignEnum align) + where T : TopBasePoco + { + self.Align = align; + return self; + } + + ///// + ///// 设定是否允许编辑 + ///// + ///// + ///// + ///// 如果设置 true,则对应列的单元格将会被允许编辑,目前只支持type="text"的input编辑。 + ///// + //public static GridColumn SetEdit(this GridColumn self, bool edit = true) + // where T : TopBasePoco + //{ + // self.Edit = edit; + // return self; + //} + + ///// + ///// 设定自定义模板 + ///// + ///// + ///// + ///// 在默认情况下,单元格的内容是完全按照数据接口返回的content原样输出的, + ///// 如果你想对某列的单元格添加链接等其它元素,你可以借助该参数来轻松实现。 + ///// 这是一个非常实用的功能,你的表格内容会因此而丰富多样。 + ///// + ///// + //public static GridColumn SetTemplet(this GridColumn self, string templet) + // where T : TopBasePoco + //{ + // self.Templet = templet; + // return self; + //} + + [Obsolete("该方法已经被弃用,请使用 SetHide 代替")] + public static GridColumn SetHidden(this GridColumn self, bool hidden = true) where T : TopBasePoco + { + return self; + } + + /// + /// 是否隐藏 + /// + /// + /// + /// + /// + public static GridColumn SetHide(this GridColumn self, bool hide = true) where T : TopBasePoco + { + self.Hide = hide; + return self; + } + + /// + /// 设定列宽不可改变 + /// + /// + /// + /// + /// + public static GridColumn SetUnResize(this GridColumn self, bool unresize = true) + where T : TopBasePoco + { + self.UnResize = unresize; + return self; + } + + /// + /// 设定单元格编辑类型 + /// + /// + /// + /// 单元格编辑类型 + /// listitems + /// + public static GridColumn SetEditType(this GridColumn self, EditTypeEnum editType = EditTypeEnum.Text, List listitems = null) + where T : TopBasePoco + { + self.EditType = editType; + self.ListItems = listitems; + return self; + } + + #endregion + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/IGridColumn.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/IGridColumn.cs new file mode 100644 index 0000000..c435831 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Grid/IGridColumn.cs @@ -0,0 +1,225 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Text.Json.Serialization; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// Grid Column Content Fixed Enum + /// + [JsonConverter(typeof(JsonStringEnumConverter))] + public enum GridColumnFixedEnum + { + /// + /// 规定在左侧 + /// + Left = 0, + /// + /// 规定在右侧 + /// + Right + } + + /// + /// Grid Column Edit Type Enum + /// + [JsonConverter(typeof(JsonStringEnumConverter))] + public enum EditTypeEnum + { + Text, + TextBox, + ComboBox, + Datetime, + CheckBox + } + + /// + /// Grid Column Content Align Enum + /// + [JsonConverter(typeof(JsonStringEnumConverter))] + public enum GridColumnAlignEnum + { + /// + /// Center + /// + Center = 0, + /// + /// Left + /// + Left, + /// + /// Right + /// + Right + } + + /// + /// Grid Column Type Enum + /// + [JsonConverter(typeof(JsonStringEnumConverter))] + public enum GridColumnTypeEnum + { + /// + /// 正常列 + /// + Normal = 0, + /// + /// 空列 + /// + Space, + /// + /// 操作列 + /// + Action + } + + /// + /// IGridColumn + /// + /// + public interface IGridColumn + { + /// + /// 表头类型 + /// + GridColumnTypeEnum ColumnType { get; set; } + + /// + /// 设定字段名 + /// + string Field { get; set; } + + /// + /// 标题名称 + /// + string Title { get; set; } + + /// + /// 列宽 + /// + int? Width { get; set; } + /// + /// //监听单元格事件 + /// + string Event { get; set; } + /// + /// 是否允许排序 + /// + bool? Sort { get; set; } + + /// + /// 是否固定列 + /// + GridColumnFixedEnum? Fixed { get; set; } + + /// + /// 对齐方式 + /// + GridColumnAlignEnum Align { get; set; } + + /// + /// 是否可改变列宽 + /// + bool? UnResize { get; set; } + + /// + /// 隐藏列 + /// + bool? Hide { get; set; } + + /// + /// 是否显示汇总 + /// + bool? ShowTotal { get; set; } + + /// + /// 子列 + /// + IEnumerable> Children { get; } + + /// + /// 底层子列数量 + /// + int ChildrenLength { get; } + + EditTypeEnum? EditType { get; set; } + + List ListItems { get; set; } + + #region 只读属性 生成 Excel 及其 表头用 + + /// + /// 最大子列数量 + /// + int MaxChildrenCount { get; } + + /// + /// 多表头的最大层数 + /// + int MaxLevel { get; } + + /// + /// 最下层列 + /// + IEnumerable> BottomChildren { get; } + + /// + /// 最大深度 + /// + int MaxDepth { get; } + + #endregion + + + #region 暂时没有用 + + string Id { get; set; } + + /// + /// 是否需要分组 + /// + bool NeedGroup { get; set; } + + bool IsLocked { get; set; } + + bool Sortable { get; set; } + /// + /// 是否允许多行 + /// + bool AllowMultiLine { get; set; } + /// + /// 是否填充 + /// + int? Flex { get; set; } + + Type FieldType { get; } + + string FieldName { get; } + + /// + /// 获取内容 + /// + /// 源数据 + /// 是否适用format + /// 内容 + object GetText(object source, bool needFormat = true); + + object GetObject(object source); + /// + /// 获取前景色 + /// + /// 源数据 + /// 前景色 + string GetForeGroundColor(object source); + /// + /// 获取背景色 + /// + /// 源数据 + /// 背景色 + string GetBackGroundColor(object source); + bool HasFormat(); + #endregion + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Helper/EntityHelper.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Helper/EntityHelper.cs new file mode 100644 index 0000000..65a7537 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Helper/EntityHelper.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Reflection; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// DataTable和Entity之间转换的辅助类 + /// + public static class EntityHelper + { + /// + /// 根据DataTable获取Entity列表 + /// + /// Entity类型 + /// DataTable + /// Entity列表 + public static IList GetEntityList(DataTable table) + { + IList entityList = new List(); + + if (typeof(T) == typeof(DynamicData)) + { + foreach (DataRow row in table.Rows) + { + //新建Entity + T entity = (T)Activator.CreateInstance(typeof(T)); + foreach (DataColumn col in table.Columns) + { + (entity as DynamicData).Add(col.ColumnName, row[col] == DBNull.Value ? null : row[col]); + } + entityList.Add(entity); + } + } + else + { + var properties = typeof(T).GetAllProperties().ToLookup(property => property.Name, property => property).ToDictionary(i => i.Key, i => i.First()).Values; + + //循环Datable中的每一行 + foreach (DataRow row in table.Rows) + { + //新建Entity + T entity = (T)Activator.CreateInstance(typeof(T)); + //循环Entity的每一个属性 + foreach (var item in properties) + { + //如果DataTable中有列名和属性名一致,则把单元格内容赋值给Entity的该属性 + if (row.Table.Columns.Contains(item.Name)) + { + //判断null值 + if (string.IsNullOrEmpty(row[item.Name].ToString())) + { + item.SetValue(entity, null); + } + else + { + var ptype = item.PropertyType; + if (ptype.IsNullable()) + { + ptype = ptype.GenericTypeArguments[0]; + } + //如果是Guid或Guid?类型 + if (ptype == typeof(Guid)) + { + item.SetValue(entity, Guid.Parse(row[item.Name].ToString())); + } + //如果是enum或enum?类型 + else if (ptype.IsEnum) + { + item.SetValue(entity, Enum.ToObject(ptype, row[item.Name])); + } + else + { + item.SetValue(entity, Convert.ChangeType(row[item.Name], ptype)); + } + + } + } + } + entityList.Add(entity); + } + } + return entityList; + } + + #region 实体类转换成DataTable + + /// + /// 实体类转换成DataSet + /// + /// 实体类列表 + /// DataSet + public static DataSet ToDataSet(List modelList) where T : new() + { + if (modelList == null || modelList.Count == 0) + { + return null; + } + else + { + DataSet ds = new DataSet(); + ds.Tables.Add(ToDataTable(modelList)); + return ds; + } + } + + /// + /// 实体类转换成DataTable + /// + /// 实体类列表 + /// DataTable + public static DataTable ToDataTable(List modelList) where T : new() + { + if (modelList == null || modelList.Count == 0) + { + return null; + } + DataTable dt = CreateData(modelList[0]); + + foreach (T model in modelList) + { + DataRow dataRow = dt.NewRow(); + //循环实体类所有属性,给对应的DataTable字段赋值 + foreach (PropertyInfo propertyInfo in typeof(T).GetAllProperties()) + { + var res = propertyInfo.GetValue(model); + dataRow[propertyInfo.Name] = res ?? DBNull.Value; + } + dt.Rows.Add(dataRow); + } + return dt; + } + + /// + /// 根据实体类得到表结构 + /// + /// 实体类 + /// DataTable + private static DataTable CreateData(T model) where T : new() + { + DataTable dataTable = new DataTable(typeof(T).Name); + foreach (PropertyInfo propertyInfo in typeof(T).GetAllProperties()) + { + if (propertyInfo.PropertyType.IsGenericType) + { + if (propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) && propertyInfo.PropertyType.GenericTypeArguments.Length > 0) + { + dataTable.Columns.Add(propertyInfo.Name, propertyInfo.PropertyType.GenericTypeArguments[0]); + continue; + } + else + { + continue; + } + } + dataTable.Columns.Add(propertyInfo.Name, propertyInfo.PropertyType); + } + return dataTable; + } + + #endregion + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Helper/IServiceExtension.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Helper/IServiceExtension.cs new file mode 100644 index 0000000..b029a6a --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Helper/IServiceExtension.cs @@ -0,0 +1,66 @@ +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Core.Support.FileHandlers; + +namespace WalkingTec.Mvvm.Core +{ + public static class IServiceExtension + { + public static IServiceCollection AddWtmContextForConsole(this IServiceCollection services, string jsonFileDir = null, string jsonFileName = null, Func fileSubDirSelector = null) + { + var configBuilder = new ConfigurationBuilder(); + IConfigurationRoot ConfigRoot = configBuilder.WTMConfig(null,jsonFileDir,jsonFileName).Build(); + var WtmConfigs = ConfigRoot.Get(); + services.Configure(ConfigRoot); + services.AddLogging(builder => + { + builder.ClearProviders(); + builder.AddConfiguration(ConfigRoot.GetSection("Logging")) + .AddConsole() + .AddDebug() + .AddWTMLogger(); + }); + var gd = GetGlobalData(); + services.AddHttpContextAccessor(); + services.AddSingleton(gd); + WtmFileProvider._subDirFunc = fileSubDirSelector; + services.TryAddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddHttpClient(); + if (WtmConfigs.Domains != null) + { + foreach (var item in WtmConfigs.Domains) + { + services.AddHttpClient(item.Key, x => + { + x.BaseAddress = new Uri(item.Value.Url); + x.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); + x.DefaultRequestHeaders.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"); + }); + } + } + services.AddDistributedMemoryCache(); + var cs = WtmConfigs.Connections; + foreach (var item in cs) + { + var dc = item.CreateDC(); + dc.Database.EnsureCreated(); + } + WtmFileProvider.Init(WtmConfigs, gd); + return services; + } + + private static GlobalData GetGlobalData() + { + GlobalData gd = new GlobalData(); + gd.AllAssembly = Utils.GetAllAssembly(); + return gd; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Helper/LogDebug.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Helper/LogDebug.cs new file mode 100644 index 0000000..a9273fa --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Helper/LogDebug.cs @@ -0,0 +1,62 @@ +//using System; +//using System.Diagnostics; + +//namespace WalkingTec.Mvvm.Core +//{ +// /// +// /// LogDebug 只有定义了DEBUG常量才会生效,可以理解为只在Debug模式下才会输出 +// /// +// public sealed class LogDebug +// { +// /// +// /// Debug +// /// +// /// +// /// +// [Conditional("DEBUG")] +// public static void Debug(string message, Exception ex = null) +// { +// LogTrace.Debug(message, ex); +// } +// /// +// /// Info +// /// +// /// +// /// +// [Conditional("DEBUG")] +// public static void Info(string message, Exception ex = null) +// { +// LogTrace.Info(message, ex); +// } +// /// +// /// Warn +// /// +// /// +// /// +// [Conditional("DEBUG")] +// public static void Warn(string message, Exception ex = null) +// { +// LogTrace.Warn(message, ex); +// } +// /// +// /// Error +// /// +// /// +// /// +// [Conditional("DEBUG")] +// public static void Error(string message, Exception ex = null) +// { +// LogTrace.Error(message, ex); +// } +// /// +// /// Fatal +// /// +// /// +// /// +// [Conditional("DEBUG")] +// public static void Fatal(string message, Exception ex = null) +// { +// LogTrace.Fatal(message, ex); +// } +// } +//} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Helper/LogTrace.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Helper/LogTrace.cs new file mode 100644 index 0000000..80526cd --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Helper/LogTrace.cs @@ -0,0 +1,126 @@ +//using System; +//using System.Diagnostics; +//using System.Reflection; +//using log4net; + +//namespace WalkingTec.Mvvm.Core +//{ +// /// +// /// Trace 只有定义了TRACE常量才会生效,可以理解为在Debug与Release下均会输出 +// /// +// public sealed class LogTrace +// { +// private static ILog _logger; +// private static ILog Logger +// { +// get +// { +// if (_logger == null) +// { +// _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); +// } +// return _logger; +// } +// } + +// /// +// /// Write +// /// +// /// +// /// +// public static void Write(string message, Exception ex = null) +// { +// OutputWindowWriteLine(message); +// if (ex == null) +// Logger.Debug(message); +// else +// Logger.Debug(message, ex); +// } +// /// +// /// Debug +// /// +// /// +// /// +// [Conditional("TRACE")] +// public static void Debug(string message, Exception ex = null) +// { +// Write(message, ex); +// } +// /// +// /// Info +// /// +// /// +// /// +// [Conditional("TRACE")] +// public static void Info(string message, Exception ex = null) +// { +// OutputWindowWriteLine(message); +// if (ex == null) +// Logger.Info(message); +// else +// Logger.Info(message, ex); +// } +// /// +// /// Warn +// /// +// /// +// /// +// [Conditional("TRACE")] +// public static void Warn(string message, Exception ex = null) +// { +// OutputWindowWriteLine(message); +// if (ex == null) +// Logger.Warn(message); +// else +// Logger.Warn(message, ex); +// } +// /// +// /// Error +// /// +// /// +// /// +// [Conditional("TRACE")] +// public static void Error(string message, Exception ex = null) +// { +// OutputWindowWriteLine(message); +// if (ex == null) +// Logger.Error(message); +// else +// Logger.Error(message, ex); +// } +// /// +// /// Fatal +// /// +// /// +// /// +// [Conditional("TRACE")] +// public static void Fatal(string message, Exception ex = null) +// { +// OutputWindowWriteLine(message); +// if (ex == null) +// Logger.Fatal(message); +// else +// Logger.Fatal(message, ex); +// } + +// #region Output Window +// [Conditional("DEBUG")] +// private static void OutputWindowWriteLine(string message, int level = 0, string category = null) +// { +// if (System.Diagnostics.Debugger.IsLogging()) +// { +// //调用Debugger.Log方法,这个方法可以输出信息到DebugView中 +// System.Diagnostics.Debugger.Log(level, category, $"{message}\r\n"); +// } +// } +// [Conditional("DEBUG")] +// private static void OutputWindowWrite(string message, int level = 0, string category = null) +// { +// if (System.Diagnostics.Debugger.IsLogging()) +// { +// System.Diagnostics.Debugger.Log(level, category, message); +// } +// } +// #endregion +// } +//} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Helper/PropertyHelper.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Helper/PropertyHelper.cs new file mode 100644 index 0000000..095b583 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Helper/PropertyHelper.cs @@ -0,0 +1,826 @@ +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Primitives; +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Text.RegularExpressions; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// 属性辅助类 + /// + public static class PropertyHelper + { + + public static object GetExpressionRootObj(Expression expression) + { + if (expression == null) + { + return ""; + } + Expression me = null; + LambdaExpression le = null; + if (expression is MemberExpression) + { + me = expression as MemberExpression; + } + if (expression is LambdaExpression) + { + le = expression as LambdaExpression; + if (le.Body is MemberExpression) + { + me = le.Body as MemberExpression; + } + if (le.Body is UnaryExpression) + { + me = (le.Body as UnaryExpression).Operand as MemberExpression; + } + } + while (me != null && me.NodeType == ExpressionType.MemberAccess) + { + Expression exp = (me as MemberExpression).Expression; + if (exp is MemberExpression) + { + me = exp as MemberExpression; + } + else if (exp is MethodCallExpression) + { + var mexp = exp as MethodCallExpression; + if (mexp.Method.Name == "get_Item") + { + object index = 0; + if (mexp.Arguments[0] is MemberExpression) + { + var obj = ((mexp.Arguments[0] as MemberExpression).Expression as ConstantExpression).Value; + index = obj.GetType().GetField((mexp.Arguments[0] as MemberExpression).Member.Name).GetValue(obj); + } + else + { + index = (mexp.Arguments[0] as ConstantExpression).Value; + } + me = mexp.Object as MemberExpression; + } + } + else + { + me = exp; + break; + } + } + if(me.NodeType == ExpressionType.Constant) + { + return (me as ConstantExpression)?.Value; + } + return null; + } + + public static Func GetPropertyExpression(Type objtype, string property) + { + property = Regex.Replace(property, @"\[[^\]]*\]", string.Empty); + List level = new List(); + if (property.Contains('.')) + { + level.AddRange(property.Split('.')); + } + else + { + level.Add(property); + } + + var pe = Expression.Parameter(objtype); + var member = Expression.Property(pe, objtype.GetSingleProperty(level[0])); + for (int i = 1; i < level.Count; i++) + { + member = Expression.Property(member, member.Type.GetSingleProperty(level[i])); + } + return Expression.Lambda>(member, pe).Compile(); + } + + /// + /// 获取属性名 + /// + /// 属性表达式 + /// 是否获取全部级别名称,比如a.b.c + /// 属性名 + public static string GetPropertyName(this Expression expression, bool getAll = true) + { + if (expression == null) + { + return ""; + } + MemberExpression me = null; + LambdaExpression le = null; + if (expression is MemberExpression) + { + me = expression as MemberExpression; + } + if (expression is LambdaExpression) + { + le = expression as LambdaExpression; + if (le.Body is MemberExpression) + { + me = le.Body as MemberExpression; + } + if (le.Body is UnaryExpression) + { + me = (le.Body as UnaryExpression).Operand as MemberExpression; + } + } + string rv = ""; + if (me != null) + { + rv = me.Member.Name; + } + while (me != null && getAll && me.NodeType == ExpressionType.MemberAccess) + { + Expression exp = me.Expression; + if (exp is MemberExpression) + { + rv = (exp as MemberExpression).Member.Name + "." + rv; + me = exp as MemberExpression; + } + else if (exp is MethodCallExpression) + { + var mexp = exp as MethodCallExpression; + if (mexp.Method.Name == "get_Item") + { + object index = 0; + if (mexp.Arguments[0] is MemberExpression) + { + var obj = ((mexp.Arguments[0] as MemberExpression).Expression as ConstantExpression).Value; + index = obj.GetType().GetField((mexp.Arguments[0] as MemberExpression).Member.Name).GetValue(obj); + } + else + { + index = (mexp.Arguments[0] as ConstantExpression).Value; + } + rv = (mexp.Object as MemberExpression).Member.Name + "[" + index + "]." + rv; + me = mexp.Object as MemberExpression; + } + } + else + { + break; + } + } + return rv; + } + + public static Expression GetMemberExp(this ParameterExpression self, Expression member) + { + return self.GetMemberExp(member.GetPropertyName()); + } + + public static Expression GetMemberExp(this ParameterExpression self, string memberName) + { + var names = memberName.Split(','); + Expression rv = Expression.PropertyOrField(self, names[0]); ; + for (int i = 1; i < names.Length; i++) + { + rv = Expression.PropertyOrField(rv, names[i]); + } + return rv; + } + + + /// + /// 获取属性名的Id形式,将属性名中的.转换为_,适合作为HTML中的Id使用 + /// + /// 属性表达式 + /// 是否获取全部级别名称,比如a.b.c + /// 属性Id + public static string GetPropertyId(this Expression expression, bool getAll = true) + { + return GetPropertyName(expression, getAll).GetIdByName(); + } + + /// + /// 获取正则表达式错误 + /// + /// 属性信息 + /// 错误文本 + public static string GetRegexErrorMessage(this MemberInfo pi) + { + string rv = ""; + + if (pi.GetCustomAttributes(typeof(RegularExpressionAttribute), false).FirstOrDefault() is RegularExpressionAttribute dis && !string.IsNullOrEmpty(dis.ErrorMessage)) + { + rv = dis.ErrorMessage; + if (CoreProgram._localizer != null) + { + rv = CoreProgram._localizer[rv]; + } + } + else + { + rv = ""; + } + return rv; + } + + /// + /// 获取属性显示名称 + /// + /// 属性信息 + /// + /// 属性名称 + public static string GetPropertyDisplayName(this MemberInfo pi, IStringLocalizer local = null) + { + string rv = ""; + if (pi.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault() is DisplayAttribute dis && !string.IsNullOrEmpty(dis.Name)) + { + rv = dis.Name; + if (local == null) + { + if (CoreProgram._localizer != null) + { + rv = CoreProgram._localizer[rv]; + } + } + else + { + rv = local[rv]; + } + } + else + { + rv = pi.Name; + } + return rv; + } + + /// + /// 获取属性显示名称 + /// + /// 属性表达式 + /// + /// 属性显示名称 + public static string GetPropertyDisplayName(this Expression expression, IStringLocalizer local = null) + { + return GetPropertyDisplayName(expression.GetPropertyInfo(), local); + } + + + /// + /// 获取枚举显示名称 + /// + /// 枚举值 + /// 枚举显示名称 + public static string GetEnumDisplayName(this Enum value) + { + return GetEnumDisplayName(value.GetType(), value.ToString()); + } + + /// + /// 获取属性信息 + /// + /// 属性表达式 + /// 属性信息 + public static PropertyInfo GetPropertyInfo(this Expression expression) + { + MemberExpression me = null; + LambdaExpression le = null; + if (expression is MemberExpression) + { + me = expression as MemberExpression; + } + if (expression is LambdaExpression) + { + le = expression as LambdaExpression; + if (le.Body is MemberExpression) + { + me = le.Body as MemberExpression; + } + if (le.Body is UnaryExpression) + { + me = (le.Body as UnaryExpression).Operand as MemberExpression; + } + } + PropertyInfo rv = null; + if (me != null) + { + rv = me.Member.DeclaringType.GetSingleProperty(me.Member.Name); + } + return rv; + } + + /// + /// 获取属性值 + /// + /// 属性表达式 + /// 属性所在实例 + /// 属性值 + public static object GetPropertyValue(this object obj, LambdaExpression exp) + { + //获取表达式的值,并过滤单引号 + try + { + var expValue = exp.Compile().DynamicInvoke(obj); + object val = expValue; + return val; + } + catch + { + return ""; + } + } + + public static object GetPropertyValue(this object obj, string property) + { + //获取表达式的值,并过滤单引号 + try + { + return obj.GetType().GetSingleProperty(property).GetValue(obj); ; + } + catch + { + return ""; + } + } + + + public static List GetPropertySiblingValues(this object obj, string propertyName) + { + if(obj == null) + { + return new List(); + } + Regex reg = new Regex("(.*?)\\[\\-?\\d?\\]\\.(.*?)$"); + var match = reg.Match(propertyName); + if (match.Success) + { + var name1 = match.Groups[1].Value; + var name2 = match.Groups[2].Value; + + var levels = name1.Split('.'); + var objtype = obj.GetType(); + var pe = Expression.Parameter(objtype); + var member = Expression.Property(pe, objtype.GetSingleProperty(levels[0])); + for (int i = 1; i < levels.Length; i++) + { + member = Expression.Property(member, member.Type.GetSingleProperty(levels[i])); + } + var pe2 = Expression.Parameter(member.Type.GetGenericArguments()[0]); + var cast = Expression.Call(typeof(Enumerable), "Cast", new Type[] { pe2.Type }, member); + + var name2exp = Expression.Property(pe2, pe2.Type.GetSingleProperty(name2)); + var selectexp = Expression.Call(name2exp, "ToString", Type.EmptyTypes); + + Expression select = Expression.Call( + typeof(Enumerable), + "Select", + new Type[] { pe2.Type, typeof(string) }, + cast, + Expression.Lambda(selectexp, pe2)); + + + var lambda = Expression.Lambda(select, pe); + var rv = new List(); + try + { + rv = (lambda.Compile().DynamicInvoke(obj) as IEnumerable)?.ToList(); + } + catch { } + return rv; + } + else + { + return new List(); + } + } + + /// + /// 判断属性是否必填 + /// + /// 属性信息 + /// 是否必填 + public static bool IsPropertyRequired(this MemberInfo pi) + { + bool isRequired = false; + if (pi != null) + { + //如果需要显示星号,则判断是否是必填项,如果是必填则在内容后面加上星号 + //所有int,float。。。这种Primitive类型的,肯定都是必填 + Type t = pi.GetMemberType(); + if (t != null && (t.IsPrimitive() || t.IsEnum() || t == typeof(decimal) || t == typeof(Guid))) + { + isRequired = true; + } + else + { + //对于其他类,检查是否有RequiredAttribute,如果有就是必填 + if (pi.GetCustomAttributes(typeof(RequiredAttribute), false).FirstOrDefault() is RequiredAttribute required && required.AllowEmptyStrings == false) + { + isRequired = true; + } + else if (pi.GetCustomAttributes(typeof(KeyAttribute), false).FirstOrDefault() != null) + { + isRequired = true; + } + } + } + return isRequired; + } + + /// + /// 设置属性值 + /// + /// 属性所在实例 + /// 属性名 + /// 要赋的值 + /// 属性前缀 + /// 是否为字符串格式的值 + public static void SetPropertyValue(this object source, string property, object value, string prefix = null, bool stringBasedValue = false) + { + try + { + property = Regex.Replace(property, @"\[[^\]]*\]", string.Empty); + List level = new List(); + if (property.Contains('.')) + { + level.AddRange(property.Split('.')); + } + else + { + level.Add(property); + } + + if (!string.IsNullOrWhiteSpace(prefix)) + { + level.Insert(0, prefix); + } + object temp = source; + Type tempType = source.GetType(); + for (int i = 0; i < level.Count - 1; i++) + { + var member = tempType.GetMember(level[i])[0]; + if (member != null) + { + var va = member.GetMemberValue(temp); + if (va != null) + { + temp = va; + } + else + { + var newInstance = member.GetMemberType().GetConstructor(Type.EmptyTypes).Invoke(null); + member.SetMemberValue(temp, newInstance, null); + temp = newInstance; + } + tempType = member.GetMemberType(); + + } + } + + var memberInfos = tempType.GetMember(level.Last()); + if (!memberInfos.Any()) + { + return; + } + var fproperty = memberInfos[0]; + if (value == null || ((value is StringValues s) && StringValues.IsNullOrEmpty(s))) + { + fproperty.SetMemberValue(temp, null, null); + return; + } + + bool isArray = false; + if (value != null && value.GetType().IsArray == true) + { + isArray = true; + } + + if (stringBasedValue == true) + { + Type propertyType = fproperty.GetMemberType(); + if (propertyType.IsGeneric(typeof(List<>)) == true) + { + var list = propertyType.GetConstructor(Type.EmptyTypes).Invoke(null) as IList; + + var gs = propertyType.GenericTypeArguments; + try + { + if (value.GetType() == typeof(StringValues)) + { + var strVals = (StringValues)value; + var a = strVals.ToArray(); + for (int i = 0; i < a.Length; i++) + { + list.Add(a[i].ConvertValue(gs[0])); + } + } + else if (isArray) + { + var a = (value as object[]); + for (int i = 0; i < a.Length; i++) + { + list.Add(a[i].ConvertValue(gs[0])); + } + } + else + { + list = value.ConvertValue(propertyType) as IList; + } + } + catch { } + fproperty.SetMemberValue(temp, list, null); + } + else if (propertyType.IsArray) + { + try + { + var strVals = (StringValues)value; + var eletype = propertyType.GetElementType(); + var arr = Array.CreateInstance(eletype, strVals.Count); + for (int i = 0; i < arr.Length; i++) + { + arr.SetValue(strVals[i].ConvertValue(eletype), i); + } + fproperty.SetMemberValue(temp, arr, null); + } + catch { } + } + else + { + if (isArray) + { + var a = (value as object[]); + if (a.Length == 1) + { + value = a[0]; + } + } + + if (value is string) + { + value = value.ToString().Replace("\\", "/"); + } + fproperty.SetMemberValue(temp, value, null); + } + } + else + { + if (value is string) + { + value = value.ToString().Replace("\\", "/"); + } + fproperty.SetMemberValue(temp, value, null); + } + } + catch + { + } + } + + /// + /// 根据MemberInfo获取值 + /// + /// MemberInfo + /// 所在实例 + /// 如果是数组,指定数组下标。默认为null + /// MemberInfo的值 + public static object GetMemberValue(this MemberInfo mi, object obj, object[] index = null) + { + object rv = null; + if (mi.MemberType == MemberTypes.Property) + { + rv = ((PropertyInfo)mi).GetValue(obj, index); + } + else if (mi.MemberType == MemberTypes.Field) + { + rv = ((FieldInfo)mi).GetValue(obj); + } + return rv; + } + + /// + /// 设定MemberInfo的值 + /// + /// MemberInfo + /// 所在实例 + /// 要赋的值 + /// 如果是数组,指定数组下标。默认为null + public static void SetMemberValue(this MemberInfo mi, object obj, object val, object[] index = null) + { + object newval = val; + if (val is string s) + { + if (string.IsNullOrEmpty(s)) + { + val = null; + } + } + if (val != null && val.GetType() != mi.GetMemberType()) + { + newval = val.ConvertValue(mi.GetMemberType()); + } + if (mi.MemberType == MemberTypes.Property) + { + ((PropertyInfo)mi).SetValue(obj, newval, index); + } + else if (mi.MemberType == MemberTypes.Field) + { + ((FieldInfo)mi).SetValue(obj, newval); + } + } + + /// + /// 获取某个MemberInfo的类型 + /// + /// MemberInfo + /// 类型 + public static Type GetMemberType(this MemberInfo mi) + { + Type rv = null; + if (mi != null) + { + if (mi.MemberType == MemberTypes.Property) + { + rv = ((PropertyInfo)mi).PropertyType; + } + else if (mi.MemberType == MemberTypes.Field) + { + rv = ((FieldInfo)mi).FieldType; + } + } + return rv; + } + + /// + /// 获取枚举显示名称 + /// + /// 枚举类型 + /// 枚举值 + /// 枚举显示名称 + public static string GetEnumDisplayName(Type enumType, string value) + { + string rv = ""; + FieldInfo field = null; + + if (enumType.IsEnum()) + { + field = enumType.GetField(value); + } + //如果是nullable的枚举 + if (enumType.IsGeneric(typeof(Nullable<>)) && enumType.GetGenericArguments()[0].IsEnum()) + { + field = enumType.GenericTypeArguments[0].GetField(value); + } + + if (field != null) + { + + var attribs = field.GetCustomAttributes(typeof(DisplayAttribute), true).ToList(); + if (attribs.Count > 0) + { + rv = ((DisplayAttribute)attribs[0]).GetName(); + if (CoreProgram._localizer != null) + { + rv = CoreProgram._localizer[rv]; + } + } + else + { + rv = value; + } + } + return rv; + } + + public static string GetEnumDisplayName(Type enumType, int value) + { + string rv = ""; + FieldInfo field = null; + string ename = ""; + if (enumType.IsEnum()) + { + ename = enumType.GetEnumName(value); + field = enumType.GetField(ename); + } + //如果是nullable的枚举 + if (enumType.IsGeneric(typeof(Nullable<>)) && enumType.GetGenericArguments()[0].IsEnum()) + { + ename = enumType.GenericTypeArguments[0].GetEnumName(value); + field = enumType.GenericTypeArguments[0].GetField(ename); + } + + if (field != null) + { + + var attribs = field.GetCustomAttributes(typeof(DisplayAttribute), true).ToList(); + if (attribs.Count > 0) + { + rv = ((DisplayAttribute)attribs[0]).GetName(); + if (CoreProgram._localizer != null) + { + rv = CoreProgram._localizer[rv]; + } + } + else + { + rv = ename; + } + } + return rv; + } + + /// + /// 转化值 + /// + /// 要转换的值 + /// 转换后的类型 + /// 转换后的值 + public static object ConvertValue(this object value, Type propertyType) + { + object val = null; + if (propertyType.IsGeneric(typeof(Nullable<>)) == true) + { + var gs = propertyType.GenericTypeArguments; + try + { + val = ConvertValue(value, gs[0]); + } + catch { } + } + else if (propertyType.IsEnum()) + { + val = Enum.Parse(propertyType, value.ToString()); + } + else if (propertyType == typeof(string)) + { + val = value?.ToString().Trim(); + } + else if (propertyType == typeof(Guid)) + { + bool suc = Guid.TryParse(value?.ToString(), out Guid g); + if (suc) + { + val = g; + } + else + { + val = Guid.Empty; + } + } + else if (propertyType == typeof(DateRange)) + { + if (DateRange.TryParse(value.ToString(), out var result)) + { + val = result; + } + else + { + val = DateRange.Default; + } + } + else + { + try + { + if (value.ToString().StartsWith("`") && value.ToString().EndsWith("`")) + { + string inner = value.ToString().Trim('`').TrimEnd(','); + if (!string.IsNullOrWhiteSpace(inner)) + { + val = propertyType.GetConstructor(Type.EmptyTypes).Invoke(null); + string[] pair = inner.Split(','); + var gs = propertyType.GetGenericArguments(); + foreach (var p in pair) + { + (val as IList).Add(Convert.ChangeType(p, gs[0])); + } + } + } + else + { + val = Convert.ChangeType(value.ToString(), propertyType); + } + } + catch + { + } + } + return val; + } + + public static object MakeList(Type innerType, string propertyName, object[] values) + { + object rv = typeof(List<>).MakeGenericType(innerType).GetConstructor(Type.EmptyTypes).Invoke(null); + var mi = rv.GetType().GetMethod("Add"); + var con = innerType.GetConstructor(Type.EmptyTypes); + foreach (var item in values) + { + var newobj = con.Invoke(null); + newobj.SetPropertyValue(propertyName, item); + mi.Invoke(rv, new object[] { newobj }); + } + return rv; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/IBasePagedListVM.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/IBasePagedListVM.cs new file mode 100644 index 0000000..4e19922 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/IBasePagedListVM.cs @@ -0,0 +1,162 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// ListVM接口 + /// + /// ListVM中的Model类 + /// ListVM使用的Searcher类 + public interface IBasePagedListVM : IBaseVM + where T : TopBasePoco + where S : ISearcher + { + Type ModelType { get; } + + /// + /// 多级表头深度 默认 1级 + /// + int GetChildrenDepth(); + + /// + /// GetHeaders + /// + /// + + IEnumerable> GetHeaders(); + + /// + /// 页面动作 + /// + List GetGridActions(); + + /// + /// 查询并生成Excel + /// + /// Excel文件 + byte[] GenerateExcel(); + + string TotalText { get; set; } + #region Old + event Action> OnAfterInitList; + /// + ///记录批量操作时列表中选择的Id + /// + List Ids { get; set; } + string SelectorValueField { get; set; } + + /// + /// 获取Model集合 + /// + /// Model集合 + IEnumerable GetEntityList(); + + void ClearEntityList(); + /// + /// 获取Searcher + /// + S Searcher { get; } + /// + /// GetIsSelected + /// + /// + /// + bool GetIsSelected(object item); + + /// + /// 是否已经搜索过 + /// + bool IsSearched { get; set; } + + /// + /// PassSearch + /// + bool PassSearch { get; set; } + + /// + /// 搜索模式 + /// + ListVMSearchModeEnum SearcherMode { get; set; } + + /// + /// 是否需要分页 + /// + bool NeedPage { get; set; } + + /// + /// 允许导出Excel的最大行数,超过行数会分成多个文件,最多不能超过100万 + /// + int ExportMaxCount { get; set; } + + /// + /// 根据允许导出的Excel最大行数,算出最终导出的Excel个数 + /// + int ExportExcelCount { get; set; } + + /// + /// 移除操作列 + /// + void RemoveActionColumn(object root = null); + + void RemoveAction(); + + /// + /// 填加错误信息列,用于批量操作的列表 + /// + void AddErrorColumn(); + + /// + /// 搜索条件Panel的Id + /// + string SearcherDivId { get; } + + /// + /// GetSearchQuery + /// + /// + IOrderedQueryable GetSearchQuery(); + /// + /// DoSearch + /// + void DoSearch(); + /// + /// CopyContext + /// + /// + void CopyContext(BaseVM vm); + + /// + /// ReplaceWhere + /// + Expression ReplaceWhere { get; set; } + + /// + /// SetFullRowColor + /// + /// + /// + string SetFullRowColor(object entity); + /// + /// SetFullRowBgColor + /// + /// + /// + string SetFullRowBgColor(object entity); + + T CreateEmptyEntity(); + + /// + /// 用于为子表生成可编辑Grid时,内部控件名称前缀 + /// + string DetailGridPrix { get; set; } + + void DoInitListVM(); + + #endregion + + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/IBaseVM.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/IBaseVM.cs new file mode 100644 index 0000000..477cafd --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/IBaseVM.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using Microsoft.Extensions.Caching.Distributed; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// IBaseVM + /// + public interface IBaseVM + { + #region Property + + WTMContext Wtm { get; set; } + + /// + /// UniqueId + /// + string UniqueId { get; } + /// + /// WindowIds + /// + string WindowIds { get;} + /// + /// ViewDivId + /// + string ViewDivId { get; set; } + /// + /// DC + /// + IDataContext DC { get; set; } + /// + /// VMFullName + /// + string VMFullName { get; } + /// + /// CreatorAssembly + /// + string CreatorAssembly { get; set; } + /// + /// CurrentCS + /// + string CurrentCS { get; } + /// + /// FC + /// + Dictionary FC { get; set; } + /// + /// Config + /// + Configs ConfigInfo { get; } + + ISessionService Session { get; } + + IDistributedCache Cache { get; } + + LoginUserInfo LoginUserInfo { get; } + #endregion + + #region Event + + /// + /// InitVM 完成后触发的事件 + /// + event Action OnAfterInit; + /// + /// ReInitVM 完成后触发的事件 + /// + event Action OnAfterReInit; + + #endregion + + #region Method + /// + /// 调用 InitVM 并触发 OnAfterInit 事件 + /// + void DoInit(); + + /// + /// 调用 ReInitVM 并触发 OnAfterReInit 事件 + /// + void DoReInit(); + #endregion + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/IDataContext.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/IDataContext.cs new file mode 100644 index 0000000..59c7509 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/IDataContext.cs @@ -0,0 +1,143 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq.Expressions; +using System.Threading; +using System.Threading.Tasks; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// IDataContext + /// + public interface IDataContext : IDisposable + { + /// + /// IsFake + /// + bool IsFake { get; set; } + + bool IsDebug { get; set; } + + DBTypeEnum DBType { get; set; } + /// + /// AddEntity + /// + /// + /// + void AddEntity(T entity) where T : TopBasePoco; + + /// + /// UpdateEntity + /// + void UpdateEntity(T entity) where T : TopBasePoco; + + /// + /// UpdateProperty + /// + void UpdateProperty(T entity, Expression> fieldExp) where T : TopBasePoco; + + /// + /// UpdateProperty + /// + void UpdateProperty(T entity, string fieldName) where T : TopBasePoco; + + /// + /// DeleteEntity + /// + void DeleteEntity(T entity) where T : TopBasePoco; + + /// + /// CascadeDelete + /// + void CascadeDelete(T entity) where T : TreePoco; + + /// + /// Set + /// + /// + /// + DbSet Set() where T : class; + + /// + /// Model + /// + IModel Model { get; } + + /// + /// Database + /// + DatabaseFacade Database { get; } + + /// + /// CSName + /// + string CSName { get; set; } + + #region SaveChange + + /// + /// SaveChanges + /// + /// + int SaveChanges(); + + /// + /// SaveChanges + /// + /// + int SaveChanges(bool acceptAllChangesOnSuccess); + + /// + /// SaveChangesAsync + /// + /// + Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// SaveChangesAsync + /// + /// + Task SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken)); + + #endregion + + /// + /// 初始化 + /// + /// + /// + /// 返回true即数据新建完成,进入初始化操作,返回false即数据库已经存在 + Task DataInit(object AllModel, bool IsSpa); + + IDataContext CreateNew(); + IDataContext ReCreate(); + + /// + /// 执行存储过程,返回datatable + /// + /// 存储过程名称 + /// 参数 + /// + DataTable RunSP(string command, params object[] paras); + IEnumerable RunSP(string command, params object[] paras); + + /// + /// 执行sql语句,返回datatable + /// + /// 查询sql语句 + /// 参数 + /// + DataTable RunSQL(string command, params object[] paras); + IEnumerable RunSQL(string sql, params object[] paras); + DataTable Run(string sql, CommandType commandType, params object[] paras); + IEnumerable Run(string sql, CommandType commandType, params object[] paras); + object CreateCommandParameter(string name, object value, ParameterDirection dir); + + void SetLoggerFactory(ILoggerFactory factory); + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ISessionService.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ISessionService.cs new file mode 100644 index 0000000..1beb714 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/ISessionService.cs @@ -0,0 +1,12 @@ +namespace WalkingTec.Mvvm.Core +{ + /// + /// Session接口 + /// + public interface ISessionService + { + T Get(string key); + void Set(string key, T val); + string SessionId { get; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/IUIService.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/IUIService.cs new file mode 100644 index 0000000..e8dfded --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/IUIService.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WalkingTec.Mvvm.Core +{ + public interface IUIService + { + string MakeButton(ButtonTypesEnum buttonType, string url, string buttonText, int? width, int? height, string title = null, string buttonID = null,bool resizable = true, bool max = false, string currentdivid = "", string buttonClass = null, string style = null, RedirectTypesEnum rtype = RedirectTypesEnum.Layer); + string MakeDialogButton(ButtonTypesEnum buttonType, string url, string buttonText, int? width, int? height, string title = null, string buttonID = null, bool showDialog = true, bool resizable = true, bool max = false,string buttonClass = null, string style = null); + + string MakeDownloadButton(ButtonTypesEnum buttonType, Guid fileID, string buttonText = null, string _DONOT_USE_CS = "default", string buttonClass = null, string style = null); + + string MakeViewButton(ButtonTypesEnum buttonType, Guid fileID, string buttonText = null, int? width = null, int? height = null, string title = null, bool resizable = true, string _DONOT_USE_CS = "default", bool maxed = false, string buttonClass = null, string style = null); + + string MakeScriptButton(ButtonTypesEnum buttonType, string buttonText, string script = "", string buttonID = null, string url = null, string buttonClass = null, string style = null); + + string MakeCheckBox(bool ischeck, string text = null, string name = null, string value = null, bool isReadOnly = false); + + string MakeRadio(bool ischeck, string text = null, string name = null, string value = null, bool isReadOnly = false); + + string MakeCombo(string name = null, List value = null, string selectedValue = null, string emptyText = null, bool isReadOnly = false); + + string MakeTextBox(string name = null, string value = null, string emptyText = null, bool isReadOnly = false); + string MakeDateTime(string name = null, string value = null, string emptyText = null, bool isReadOnly = false); + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Implement/DefaultUIService.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Implement/DefaultUIService.cs new file mode 100644 index 0000000..33daaf7 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Implement/DefaultUIService.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WalkingTec.Mvvm.Core.Implement +{ + public class DefaultUIService : IUIService + { + public string MakeDialogButton(ButtonTypesEnum buttonType, string url, string buttonText, int? width, int? height, string title = null, string buttonID = null, bool showDialog = true, bool resizable = true, bool max = false, string buttonClass = null, string style = null) + { + return ""; + } + + public string MakeDownloadButton(ButtonTypesEnum buttonType, Guid fileID, string buttonText = null, string _DONOT_USE_CS = "default", string buttonClass = null, string style = null) + { + return ""; + } + + public string MakeCheckBox(bool ischeck, string text = null, string name = null, string value = null, bool isReadOnly = false) + { + return ""; + } + + public string MakeButton(ButtonTypesEnum buttonType, string url, string buttonText, int? width, int? height, string title = null, string buttonID = null, bool resizable = true, bool max = false, string currentdivid = "", string buttonClass = null, string style = null, RedirectTypesEnum rtype = RedirectTypesEnum.Layer) + { + return ""; + } + + public string MakeViewButton(ButtonTypesEnum buttonType, Guid fileID, string buttonText = null, int? width = null, int? height = null, string title = null, bool resizable = true, string _DONOT_USE_CS = "default", bool maxed = false, string buttonClass = null, string style = null) + { + return ""; + } + + public string MakeScriptButton(ButtonTypesEnum buttonType, string buttonText, string script = "", string buttonID = null, string url = null, string buttonClass = null, string style = null) + { + return ""; + } + + public string MakeRadio(bool ischeck, string text = null, string name = null, string value = null, bool isReadOnly = false) + { + return ""; + } + + public string MakeCombo(string name = null, List value = null, string selectedValue = null, string emptyText = null, bool isReadOnly = false) + { + return ""; + } + + public string MakeTextBox(string name = null, string value = null, string emptyText = null, bool isReadOnly = false) + { + return ""; + } + + public string MakeDateTime(string name = null, string value = null, string emptyText = null, bool isReadOnly = false) + { + return ""; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/BodyConverter.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/BodyConverter.cs new file mode 100644 index 0000000..97815c7 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/BodyConverter.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Core.Json +{ + /// + /// StringIgnoreLTGTConvert + /// 忽略客户端提交的 <及>字符 + /// + public class BodyConverter : JsonConverter + { + public override PostedBody Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var rv = new PostedBody(); + rv.ProNames = new List(); + List prefix = new List(); + int depth = 0; + string lastObjecName = ""; + int insideArray = 0; + JsonTokenType lastToken = JsonTokenType.Null; + while (true) + { + if (reader.TokenType == JsonTokenType.StartArray) + { + insideArray++; + depth++; + prefix.Add(lastObjecName + "[0]"); + } + if (reader.TokenType == JsonTokenType.EndArray) + { + insideArray--; + depth--; + prefix.RemoveAt(prefix.Count - 1); + } + if (reader.TokenType == JsonTokenType.StartObject) + { + if (insideArray == 0) + { + depth++; + prefix.Add(lastObjecName); + if (rv.ProNames.Count > 0) + { + rv.ProNames.RemoveAt(rv.ProNames.Count - 1); + } + } + else + { + if (lastToken != JsonTokenType.StartArray) + { + reader.TrySkip(); + reader.Read(); + continue; + } + } + } + if (reader.TokenType == JsonTokenType.PropertyName) + { + var pname = reader.GetString(); + lastObjecName = pname; + var p = prefix.Take(depth).ToSepratedString(seperator: "."); + if (string.IsNullOrEmpty(p) == false) + { + pname = p + "." + pname; + } + if (rv.ProNames.Contains(pname) == false) + { + rv.ProNames.Add(pname); + } + } + if (reader.TokenType == JsonTokenType.EndObject) + { + if (insideArray == 0) + { + depth--; + prefix.RemoveAt(prefix.Count - 1); + } + if (reader.IsFinalBlock == true && reader.CurrentDepth == 0) + { + reader.Read(); + break; + } + } + lastToken = reader.TokenType; + reader.Read(); + } + return rv; + } + + + public override void Write(Utf8JsonWriter writer, PostedBody value, JsonSerializerOptions options) + { + return; + } + + } + + public class PostedBody + { + public List ProNames { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/BoolStringConverter.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/BoolStringConverter.cs new file mode 100644 index 0000000..ad00b3e --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/BoolStringConverter.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Unicode; +using NPOI.SS.Formula.Functions; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Core.Json +{ + public class BoolStringConverter : +JsonConverter + { + + public override bool Read( + ref Utf8JsonReader reader, + Type typeToConvert, + JsonSerializerOptions options) + { + + JsonTokenType token = reader.TokenType; + + if (token == JsonTokenType.String) + { + var s = reader.GetString() ?? ""; + if (s.ToLower() == "true") + { + return true; + } + else if (s.ToLower() == "false") + { + return false; + } + else + { + return false; + } + } + else if (token == JsonTokenType.True || token == JsonTokenType.False) + { + return reader.GetBoolean(); + } + else + { + return false; + } + } + + public override void Write( + Utf8JsonWriter writer, + bool data, + JsonSerializerOptions options) + { + writer.WriteBooleanValue(data); + + } + + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/DateRangeConverter.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/DateRangeConverter.cs new file mode 100644 index 0000000..4bafe8b --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/DateRangeConverter.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using WalkingTec.Mvvm.Core; + +namespace WalkingTec.Mvvm.Core.Json +{ + public class DateRangeConverter : JsonConverter + { + public override DateRange Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + { + return null; + } + + try + { + if (reader.TokenType == JsonTokenType.StartArray) + { + reader.Read(); + string[] ds = new string[2]; + ds[0] = reader.GetString(); + reader.Read(); + ds[1] = reader.GetString(); + reader.Read(); + if (DateRange.TryParse(ds, out var dateRange)) + { + return dateRange; + } + else + { + return null; + } + } + } + catch (Exception) + { + } + return null; + } + + public override void Write(Utf8JsonWriter writer, DateRange value, JsonSerializerOptions options) + { + if (value == null) + { + writer.WriteNullValue(); + } + else + { + //writer.WriteStringValue(JsonSerializer.Serialize(value),); + writer.WriteStartArray(); + writer.WriteStringValue(value.GetStartTime().ToString()); + writer.WriteStringValue(value.GetEndTime().ToString()); + writer.WriteEndArray(); + } + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/DateTimeConverter.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/DateTimeConverter.cs new file mode 100644 index 0000000..74628d4 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/DateTimeConverter.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace WalkingTec.Mvvm.Core.Json +{ + + public class DateTimeConverter : JsonConverter + { + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + { + if (DateTime.TryParse(reader.GetString(), out DateTime date)) + return date; + } + return reader.GetDateTime(); + } + + public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) + { + writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss")); + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/DynamicDataConverter.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/DynamicDataConverter.cs new file mode 100644 index 0000000..921c8a1 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/DynamicDataConverter.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Core.Json +{ + public class DynamicDataConverter : JsonConverter + { + public override DynamicData Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + try + { + DynamicData rv = new DynamicData(); + rv.Fields = new Dictionary(); + string currentkey = ""; + //object currentvalue; + int level = 0; + while (true) + { + if(reader.TokenType == JsonTokenType.StartObject) { + if(level > 0) + { + var inner = JsonSerializer.Deserialize(ref reader, options); + rv.Fields.Add(currentkey, inner); + } + level++; + } + if(reader.TokenType == JsonTokenType.EndObject) + { + level--; + } + if (reader.TokenType == JsonTokenType.PropertyName) + { + currentkey = reader.GetString(); + } + if(reader.TokenType == JsonTokenType.String || reader.TokenType == JsonTokenType.Number || reader.TokenType == JsonTokenType.True || reader.TokenType == JsonTokenType.False || reader.TokenType == JsonTokenType.Null) + { + var val = JsonSerializer.Deserialize(ref reader,options); + rv.Fields.Add(currentkey, val); + } + if (reader.IsFinalBlock && level == 0) + { + //reader.Read(); + break; + } + reader.Read(); + } + return rv; + } + catch + { + return null; + } + } + + public override void Write(Utf8JsonWriter writer, DynamicData value, JsonSerializerOptions options) + { + if (value == null || value.Fields == null) + { + writer.WriteNullValue(); + } + else + { + writer.WriteStartObject(); + foreach (var item in value.Fields) + { + if(item.Value == null) + { + if (options.IgnoreNullValues == false) + { + writer.WriteNull(item.Key); + } + } + else + { + writer.WritePropertyName(item.Key); + JsonSerializer.Serialize(writer, item.Value, options); + } + } + writer.WriteEndObject(); + } + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/PocoConverter.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/PocoConverter.cs new file mode 100644 index 0000000..3697017 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/PocoConverter.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; +using System.Text.Unicode; +using System.Threading.Tasks; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Core.Json +{ + public class PocoConverter : JsonConverterFactory + { + + public override bool CanConvert(Type typeToConvert) + { + return typeof(TopBasePoco).IsAssignableFrom(typeToConvert); + } + + public override JsonConverter CreateConverter( + Type type, + JsonSerializerOptions options) + { + + var temp = CloneOptions(options); + foreach (var item in options.Converters) + { + if(item.GetType() != typeof(PocoConverter)) + { + temp.Converters.Add(item); + } + } + JsonConverter converter = (JsonConverter)Activator.CreateInstance( + typeof(PocoConverterInner<>).MakeGenericType( + new Type[] { type }), + BindingFlags.Instance | BindingFlags.Public, + binder: null, + args: new object[] { temp }, + culture: null); + + return converter; + } + + private JsonSerializerOptions CloneOptions(JsonSerializerOptions op) + { + JsonSerializerOptions rv = new JsonSerializerOptions(); + rv.PropertyNamingPolicy = op.PropertyNamingPolicy; + rv.AllowTrailingCommas = op.AllowTrailingCommas; + rv.DefaultBufferSize = op.DefaultBufferSize; + rv.DefaultIgnoreCondition = op.DefaultIgnoreCondition; + rv.DictionaryKeyPolicy = op.DictionaryKeyPolicy; + rv.Encoder = op.Encoder; + rv.IgnoreNullValues = op.IgnoreNullValues; + rv.IgnoreReadOnlyFields = op.IgnoreReadOnlyFields; + rv.IgnoreReadOnlyProperties = op.IgnoreReadOnlyProperties; + rv.IncludeFields = op.IncludeFields; + rv.DefaultIgnoreCondition = op.DefaultIgnoreCondition; + rv.DictionaryKeyPolicy = op.DictionaryKeyPolicy; + rv.MaxDepth = op.MaxDepth; + rv.NumberHandling = op.NumberHandling; + rv.ReadCommentHandling = op.ReadCommentHandling; + rv.ReferenceHandler = op.ReferenceHandler; + rv.WriteIndented = op.WriteIndented; + return rv; + } + + private class PocoConverterInner : + JsonConverter where T : TopBasePoco + { + protected readonly JsonSerializerOptions _options; + public PocoConverterInner(JsonSerializerOptions options) + { + _options = options; + } + + public override T Read( + ref Utf8JsonReader reader, + Type typeToConvert, + JsonSerializerOptions options) + { + + return JsonSerializer.Deserialize(ref reader, _options); + } + + public override void Write( + Utf8JsonWriter writer, + T data, + JsonSerializerOptions options) + { + var _datacache = new Dictionary(); + RemoveCycleReference(data, _datacache); + JsonSerializer.Serialize(writer, data, typeof(T), _options); + } + + private void RemoveCycleReference(object Entity, Dictionary datacache) + { + var pros = Entity.GetType().GetAllProperties(); + var mainkey = Entity.GetType().FullName + (Entity as TopBasePoco).GetID(); + datacache.TryAdd(mainkey, 1); + + foreach (var pro in pros) + { + if (typeof(TopBasePoco).IsAssignableFrom(pro.PropertyType)) + { + var subentity = pro.GetValue(Entity) as TopBasePoco; + string key = pro.PropertyType.FullName + subentity?.GetID() ?? ""; + if (subentity != null && datacache.ContainsKey(key) == false) + { + RemoveCycleReference(subentity, datacache); + } + else + { + pro.SetValue(Entity,null); + } + } + //找到类型为List的字段 + if (pro.PropertyType.GenericTypeArguments.Count() > 0) + { + //获取xxx的类型 + var ftype = pro.PropertyType.GenericTypeArguments.First(); + //如果xxx继承自TopBasePoco + if (ftype.IsSubclassOf(typeof(TopBasePoco))) + { + //界面传过来的子表数据 + + if (pro.GetValue(Entity) is IEnumerable list && list.Count() > 0) + { + bool found = false; + foreach (var newitem in list) + { + if (newitem != null) + { + string subkey = ftype.FullName + newitem?.GetID() ?? ""; + if (datacache.ContainsKey(subkey) == false) + { + RemoveCycleReference(newitem, datacache.ToDictionary(x=>x.Key,x=>x.Value)); + found = true; + } + else + { + found = false; + break; + } + } + } + if(found == false) + { + pro.SetValue(Entity, null); + } + } + } + } + } + + } + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/RawStringConverter.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/RawStringConverter.cs new file mode 100644 index 0000000..fa9a3f1 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/RawStringConverter.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Unicode; +using NPOI.SS.Formula.Functions; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Core.Json +{ + public class RawStringConverter : JsonConverter + { + public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + { + return null; + } + + try + { + if (reader.TokenType == JsonTokenType.String) + { + string rv = reader.GetString(); + return rv; + } + } + catch (Exception) + { + } + return null; + } + + public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) + { + if (value == null) + { + writer.WriteNullValue(); + } + else + { + var txt = JsonEncodedText.Encode($"_raw_{value}_raw_", JavaScriptEncoder.UnsafeRelaxedJsonEscaping); + writer.WriteStringValue(txt); + } + } + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/StringConverter.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/StringConverter.cs new file mode 100644 index 0000000..3fb412e --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/StringConverter.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace System.Text.Json.Serialization +{ + public class JsonStringConverter : JsonConverter + { + public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + { + return null; + } + + if (reader.TokenType == JsonTokenType.String) + { + return reader.GetString(); + } + return null; + } + + public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) + { + if (value == null) + { + writer.WriteNullValue(); + } + else + { + writer.WriteStringValue(value); + } + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/StringIgnoreLTGTConverter.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/StringIgnoreLTGTConverter.cs new file mode 100644 index 0000000..ef3cedf --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/StringIgnoreLTGTConverter.cs @@ -0,0 +1,40 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace System.Text.Json.Serialization +{ + /// + /// StringIgnoreLTGTConvert + /// 忽略客户端提交的 <及>字符 + /// + public class StringIgnoreLTGTConverter : JsonConverter + { + public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + { + return null; + } + + if (reader.TokenType == JsonTokenType.String) + { + return reader.GetString().Replace("<", string.Empty).Replace(">", string.Empty); + } + + return null; + } + + public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) + { + if (value == null) + { + writer.WriteNullValue(); + } + else + { + writer.WriteStringValue(value); + } + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/TypeConverter.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/TypeConverter.cs new file mode 100644 index 0000000..3cd77a1 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Json/TypeConverter.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Unicode; +using NPOI.SS.Formula.Functions; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Core.Json +{ + public class TypeConverter : JsonConverter + { + public override Type Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return null; + } + + public override void Write(Utf8JsonWriter writer, Type value, JsonSerializerOptions options) + { + writer.WriteNullValue(); + } + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/JsonResultModel.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/JsonResultModel.cs new file mode 100644 index 0000000..550ec91 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/JsonResultModel.cs @@ -0,0 +1,38 @@ +using System.Collections.Generic; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// DataTableResult + /// + public class DataTableResult : JsonResultT> + where T : TopBasePoco + { + /// + /// Data Count + /// + public long Count { get; set; } + } + + /// + /// JsonResultT + /// + public class JsonResultT + { + /// + /// Status Code + /// + /// + public int Code { get; set; } + + /// + /// Message + /// + public string Msg { get; set; } + + /// + /// Data + /// + public T Data { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/LoginUserInfo.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/LoginUserInfo.cs new file mode 100644 index 0000000..0a3d0bb --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/LoginUserInfo.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using NPOI.SS.Formula.Functions; +using WalkingTec.Mvvm.Core.Support.Json; + +namespace WalkingTec.Mvvm.Core +{ + + /// + /// 用户登录信息,需要保存在Session中,所以使用Serializable标记 + /// + public class LoginUserInfo + { + public string UserId { get; set; } + + /// + /// 登录用户 + /// + public string ITCode { get; set; } + + public string TenantCode { get; set; } + + public string Name { get; set; } + + public string Memo { get; set; } + + public Guid? PhotoId { get; set; } + + public List Roles { get; set; } + + public List Groups { get; set; } + + public Dictionary Attributes { get; set; } + /// + /// 用户的页面权限列表 + /// + public List FunctionPrivileges { get; set; } + /// + /// 用户的数据权限列表 + /// + public List DataPrivileges { get; set; } + + public async System.Threading.Tasks.Task LoadBasicInfoAsync(WTMContext context) + { + if (string.IsNullOrEmpty(this.ITCode) || context?.DC == null || context.BaseUserQuery == null) + { + return; + } + var DC = context.DC; + var userInfo = await context.BaseUserQuery + .Where(x => x.ITCode.ToLower() == this.ITCode.ToLower() && x.IsValid) + .Select(x => new { + user = x, + UserRoles = DC.Set().Where(y => y.UserCode == x.ITCode).ToList(), + UserGroups = DC.Set().Where(y => y.UserCode == x.ITCode).ToList(), + }) + .FirstOrDefaultAsync(); + + if (userInfo != null) + { + // 初始化用户信息 + var roleIDs = userInfo.UserRoles.Select(x => x.RoleCode).ToList(); + var groupIDs = userInfo.UserGroups.Select(x => x.GroupCode).ToList(); + + + var dataPris = await DC.Set().AsNoTracking() + .Where(x => x.UserCode == userInfo.user.ITCode || (x.GroupCode != null && groupIDs.Contains(x.GroupCode))) + .Distinct() + .ToListAsync(); + ProcessTreeDp(dataPris,context); + + //查找登录用户的页面权限 + var funcPrivileges = await DC.Set().AsNoTracking() + .Where(x => x.RoleCode != null && roleIDs.Contains(x.RoleCode)) + .Distinct() + .ToListAsync(); + + var roles = DC.Set().AsNoTracking().Where(x => roleIDs.Contains(x.RoleCode)).ToList(); + var groups = DC.Set().AsNoTracking().Where(x => groupIDs.Contains(x.GroupCode)).ToList(); + this.ITCode = userInfo.user.ITCode; + if (string.IsNullOrEmpty(this.Name)) + { + this.Name = userInfo.user.Name; + } + if (this.PhotoId == null) + { + this.PhotoId = userInfo.user.PhotoId; + } + if (string.IsNullOrEmpty(this.TenantCode)) + { + this.TenantCode = userInfo.user.TenantCode; + } + this.Roles = roles.Select(x => new SimpleRole { ID = x.ID, RoleCode = x.RoleCode, RoleName = x.RoleName }).ToList(); + this.Groups = groups.Select(x => new SimpleGroup { ID = x.ID, GroupCode = x.GroupCode, GroupName = x.GroupName }).ToList(); + this.DataPrivileges = dataPris.Select(x => new SimpleDataPri { ID = x.ID, RelateId = x.RelateId, TableName = x.TableName, UserCode = x.UserCode, GroupCode = x.GroupCode }).ToList(); + this.FunctionPrivileges = funcPrivileges.Select(x => new SimpleFunctionPri { ID = x.ID, RoleCode = x.RoleCode, Allowed = x.Allowed, MenuItemId = x.MenuItemId }).ToList(); + } + } + + private void ProcessTreeDp(List dps, WTMContext context) + { + var dpsSetting = context.DataPrivilegeSettings; + foreach (var dp in dpsSetting) + { + if (typeof(TreePoco).IsAssignableFrom(dp.ModelType)) + { + var ids = dps.Where(x => x.TableName == dp.ModelName).Select(x => x.RelateId).ToList(); + if (ids.Count > 0 && ids.Contains(null) == false) + { + var skipids = dp.GetTreeParentIds(context, dps); + List subids = new List(); + subids.AddRange(GetSubIds(dp, ids, dp.ModelType, skipids,context)); + subids = subids.Distinct().ToList(); + subids.ForEach(x => dps.Add(new DataPrivilege + { + TableName = dp.ModelName, + RelateId = x.ToString() + })); + } + } + + } + } + private IEnumerable GetSubIds(IDataPrivilege dp, List p_id, Type modelType, List skipids,WTMContext context) + { + var ids = p_id.Where(x => skipids.Contains(x) == false).ToList(); + var subids = dp.GetTreeSubIds(context, ids); + if (subids.Count > 0) + { + return subids.Concat(GetSubIds(dp, subids, modelType, skipids,context)); + } + else + { + return new List(); + } + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/MSD.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/MSD.cs new file mode 100644 index 0000000..56ed5c4 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/MSD.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// 模型状态接口 + /// + public interface IModelStateService + { + /// + /// 索引 + /// + /// + /// + List this[string name] { get; } + /// + /// 添加模型错误 + /// + /// 字段名称 + /// 错误信息 + void AddModelError(string key, string errorMessage); + void RemoveModelError(string key); + int Count { get; } + + IEnumerable Keys { get; } + + void Clear(); + + string GetFirstError(); + + bool IsValid { get; } + } + + + + /// + /// 记录错误的简单类 + /// + public class MsdError + { + public string ErrorMessage { get; set; } + public Exception Exception { get; set; } + } + + + public class BasicMSD : IModelStateService + { + private Dictionary _states; + + public BasicMSD() + { + this._states = new Dictionary(); + } + + public List this[string name] + { + get + { + return _states.Where(x => x.Key == name).Select(x => new MsdError { ErrorMessage = x.Value }).ToList(); + } + } + + /// + /// 添加错误信息 + /// + /// 错误的字段名 + /// 错误信息 + public void AddModelError(string key, string errorMessage) + { + _states.Add(key, errorMessage); + } + + public void RemoveModelError(string key) + { + _states.Remove(key); + } + + public void Clear() + { + _states.Clear(); + } + + public string GetFirstError() + { + string rv = ""; + foreach (var key in Keys) + { + if (this[key].Count > 0) + { + rv = this[key].First().ErrorMessage; + } + } + return rv; + } + + public int Count => _states.Count; + + public IEnumerable Keys => _states.Keys; + + bool IModelStateService.IsValid => _states.Count > 0 ? false : true; + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/ActionLog.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/ActionLog.cs new file mode 100644 index 0000000..bf4433a --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/ActionLog.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace WalkingTec.Mvvm.Core +{ + public enum ActionLogTypesEnum + { + [Display(Name = "_Admin.Normal")] + Normal, + [Display(Name = "_Admin.Exception")] + Exception, + [Display(Name = "_Admin.Debug")] + Debug + }; + + /// + /// ActionLog + /// + [Table("ActionLogs")] + public class ActionLog : BasePoco, ICloneable + { + [Display(Name = "_Admin.Module")] + [StringLength(255, ErrorMessage = "Validate.{0}stringmax{1}")] + public string ModuleName { get; set; } + + [Display(Name = "_Admin.Action")] + [StringLength(255, ErrorMessage = "Validate.{0}stringmax{1}")] + public string ActionName { get; set; } + + [Display(Name = "_Admin.Account")] + [StringLength(50, ErrorMessage = "Validate.{0}stringmax{1}")] + public string ITCode { get; set; } + + [Display(Name = "Url")] + [StringLength(250, ErrorMessage = "Validate.{0}stringmax{1}")] + public string ActionUrl { get; set; } + + [Display(Name = "_Admin.ActionTime")] + public DateTime ActionTime { get; set; } + + [Display(Name = "_Admin.Duration")] + public double Duration { get; set; } + + [Display(Name = "_Admin.Remark")] + public string Remark { get; set; } + + [StringLength(50, ErrorMessage = "Validate.{0}stringmax{1}")] + [Display(Name = "IP")] + public string IP { get; set; } + + [Display(Name = "_Admin.LogType")] + public ActionLogTypesEnum LogType { get; set; } + + public object Clone() + { + return this.MemberwiseClone(); + } + + public string GetLogString() + { + return $@" +|-{Core.CoreProgram._localizer?["_Admin.ActionTime"]}:{this.ActionTime} +|-{Core.CoreProgram._localizer?["_Admin.Account"]}:{this.ITCode??""} +|-IP:{this.IP??""} +|-{Core.CoreProgram._localizer?["_Admin.Module"]}:{this.ModuleName??""} +|-{Core.CoreProgram._localizer?["_Admin.MethodName"]}:{this.ActionName ?? ""} +|-Url:{this.ActionUrl ?? ""} +|-{Core.CoreProgram._localizer?["_Admin.Duration"]}:{this.Duration.ToString("F2")+" s"} +|-{Core.CoreProgram._localizer?["_Admin.Remark"]}:{this.Remark} +"; + } + } + + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/BasePoco.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/BasePoco.cs new file mode 100644 index 0000000..4562706 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/BasePoco.cs @@ -0,0 +1,44 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.Text.Json.Serialization; + +namespace WalkingTec.Mvvm.Core +{ + + public interface IBasePoco + { + DateTime? CreateTime { get; set; } + string CreateBy { get; set; } + DateTime? UpdateTime { get; set; } + string UpdateBy { get; set; } + } + + /// + /// Model层的基类,所有的model都应该继承这个类。这会使所有的model层对应的数据库表都有一个自增主键 + /// + public class BasePoco : TopBasePoco, IBasePoco + { + /// + /// CreateTime + /// + [Display(Name = "_Admin.CreateTime")] + public DateTime? CreateTime { get; set; } + /// + /// CreateBy + /// + [Display(Name = "_Admin.CreateBy")] + [StringLength(50,ErrorMessage = "Validate.{0}stringmax{1}")] + public string CreateBy { get; set; } + /// + /// UpdateTime + /// + [Display(Name = "_Admin.UpdateTime")] + public DateTime? UpdateTime { get; set; } + /// + /// UpdateBy + /// + [Display(Name = "_Admin.UpdateBy")] + [StringLength(50,ErrorMessage = "Validate.{0}stringmax{1}")] + public string UpdateBy { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/DataPrivilege.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/DataPrivilege.cs new file mode 100644 index 0000000..898bf3e --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/DataPrivilege.cs @@ -0,0 +1,30 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Text.Json.Serialization; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// DataPrivilege + /// + [Table("DataPrivileges")] + public class DataPrivilege : BasePoco + { + [Display(Name = "_Admin.User")] + public string UserCode { get; set; } + + [Display(Name = "_Admin.Group")] + public string GroupCode { get; set; } + + [Required(ErrorMessage = "Validate.{0}required")] + [StringLength(50,ErrorMessage = "Validate.{0}stringmax{1}")] + [Display(Name = "_Admin.TableName")] + public string TableName { get; set; } + public string RelateId { get; set; } + + [Display(Name = "_Admin.Domain")] + public string Domain { get; set; } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FileAttachment.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FileAttachment.cs new file mode 100644 index 0000000..189a5f7 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FileAttachment.cs @@ -0,0 +1,60 @@ +using Microsoft.EntityFrameworkCore; +using System; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.IO; +using System.Text.Json.Serialization; +using WalkingTec.Mvvm.Core.Models; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// FileAttachment + /// + [Table("FileAttachments")] + public class FileAttachment : TopBasePoco, IWtmFile, IDisposable + { + [Display(Name = "_Admin.FileName")] + [Required(ErrorMessage = "Validate.{0}required")] + public string FileName { get; set; } + + [Display(Name = "_Admin.FileExt")] + [Required(ErrorMessage = "Validate.{0}required")] + [StringLength(10)] + public string FileExt { get; set; } + + [Display(Name = "_Admin.Path")] + public string Path { get; set; } + + [Display(Name = "_Admin.Length")] + public long Length { get; set; } + + public DateTime UploadTime { get; set; } + + public string SaveMode { get; set; } + + public byte[] FileData { get; set; } + + public string ExtraInfo { get; set; } + public string HandlerInfo { get; set; } + + + [NotMapped] + [JsonIgnore] + public Stream DataStream { get; set; } + + public void Dispose() + { + if(DataStream != null) + { + DataStream.Dispose(); + } + } + + string IWtmFile.GetID() + { + return ID.ToString(); + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkGroup.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkGroup.cs new file mode 100644 index 0000000..0d18d1d --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkGroup.cs @@ -0,0 +1,35 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Text.Json.Serialization; +using System.Xml.Serialization; + +namespace WalkingTec.Mvvm.Core +{ + + [Table("FrameworkGroups")] + public class FrameworkGroup : BasePoco + { + [Display(Name = "_Admin.GroupCode")] + [Required(ErrorMessage = "Validate.{0}required")] + [RegularExpression("^[0-9]*$", ErrorMessage = "Validate.{0}number")] + [StringLength(100, ErrorMessage = "Validate.{0}stringmax{1}")] + public string GroupCode { get; set; } + + [Display(Name = "_Admin.GroupName")] + [StringLength(50, ErrorMessage = "Validate.{0}stringmax{1}")] + [Required(ErrorMessage = "Validate.{0}required")] + public string GroupName { get; set; } + + [Display(Name = "_Admin.Remark")] + public string GroupRemark { get; set; } + + [NotMapped] + [Display(Name = "_Admin.UsersCount")] + public int UsersCount { get; set; } + + [Display(Name = "_Admin.Tenant")] + public string TenantCode { get; set; } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkMenu.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkMenu.cs new file mode 100644 index 0000000..68010ed --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkMenu.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Text.Json.Serialization; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// FrameworkMenu + /// + [Table("FrameworkMenus")] + public class FrameworkMenu : TreePoco + { + + [Display(Name = "_Admin.PageName")] + [StringLength(50, ErrorMessage = "Validate.{0}stringmax{1}")] + [Required(ErrorMessage = "Validate.{0}required")] + public string PageName { get; set; } + + [Display(Name = "_Admin.ActionName")] + public string ActionName { get; set; } + + [Display(Name = "Codegen.ModuleName")] + public string ModuleName { get; set; } + + [Display(Name = "_Admin.FolderOnly")] + [Required(ErrorMessage = "Validate.{0}required")] + public bool FolderOnly { get; set; } + + [Display(Name = "_Admin.IsInherit")] + [Required(ErrorMessage = "Validate.{0}required")] + public bool IsInherit { get; set; } + + [Display(Name = "_Admin.Privileges")] + public List Privileges { get; set; } + + /// + /// ClassName + /// + /// + public string ClassName { get; set; } + + /// + /// MethodName + /// + /// + public string MethodName { get; set; } + + [Display(Name = "_Admin.Domain")] + public string Domain { get; set; } + + [Display(Name = "_Admin.ShowOnMenu")] + [Required(ErrorMessage = "Validate.{0}required")] + public bool ShowOnMenu { get; set; } + + [Display(Name = "_Admin.IsPublic")] + [Required(ErrorMessage = "Validate.{0}required")] + public bool IsPublic { get; set; } + + [Display(Name = "_Admin.DisplayOrder")] + [Required(ErrorMessage = "Validate.{0}required")] + public int? DisplayOrder { get; set; } + + [Display(Name = "_Admin.IsInside")] + [Required(ErrorMessage = "Validate.{0}required")] + public bool? IsInside { get; set; } + + /// + /// Url + /// + /// + public string Url { get; set; } + + [Display(Name = "_Admin.Icon")] + [StringLength(50)] + public string Icon { get; set; } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkRole.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkRole.cs new file mode 100644 index 0000000..e461b72 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkRole.cs @@ -0,0 +1,39 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Text.Json.Serialization; +using System.Xml.Serialization; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// FrameworkRole + /// + [Table("FrameworkRoles")] + public class FrameworkRole : BasePoco + { + [Display(Name = "_Admin.RoleCode")] + [Required(ErrorMessage = "Validate.{0}required")] + [RegularExpression("^[0-9]*$", ErrorMessage = "Validate.{0}number")] + [StringLength(100, ErrorMessage = "Validate.{0}stringmax{1}")] + public string RoleCode { get; set; } + + [Display(Name = "_Admin.RoleName")] + [StringLength(50, ErrorMessage = "Validate.{0}stringmax{1}")] + [Required(ErrorMessage = "Validate.{0}required")] + public string RoleName { get; set; } + + [Display(Name = "_Admin.Remark")] + public string RoleRemark { get; set; } + + [Display(Name = "_Admin.Tenant")] + public string TenantCode { get; set; } + + + [NotMapped] + [Display(Name = "_Admin.UsersCount")] + public int UsersCount { get; set; } + + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkUser.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkUser.cs new file mode 100644 index 0000000..5885650 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkUser.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +using System.Xml.Serialization; +using Microsoft.EntityFrameworkCore; +using WalkingTec.Mvvm.Core.Support.Json; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// FrameworkUser + /// + [Table("FrameworkUsers")] + public class FrameworkUserBase : BasePoco + { + [Display(Name = "_Admin.Account")] + [Required(ErrorMessage = "Validate.{0}required")] + [StringLength(50,ErrorMessage = "Validate.{0}stringmax{1}")] + public string ITCode { get; set; } + + [Display(Name = "_Admin.Password")] + [Required(AllowEmptyStrings = false, ErrorMessage = "Validate.{0}required")] + [StringLength(32, ErrorMessage = "Validate.{0}stringmax{1}")] + public string Password { get; set; } + + [Display(Name = "_Admin.Name")] + [Required(ErrorMessage = "Validate.{0}required")] + [StringLength(50, ErrorMessage = "Validate.{0}stringmax{1}")] + public string Name { get; set; } + + [Display(Name = "_Admin.IsValid")] + public bool IsValid { get; set; } + + [Display(Name = "_Admin.Photo")] + public Guid? PhotoId { get; set; } + + [Display(Name = "_Admin.Photo")] + [JsonIgnore] + public FileAttachment Photo { get; set; } + + [Display(Name = "_Admin.Tenant")] + public string TenantCode { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkUserGroup.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkUserGroup.cs new file mode 100644 index 0000000..216e849 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkUserGroup.cs @@ -0,0 +1,19 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Text.Json.Serialization; +using WalkingTec.Mvvm.Core.Attributes; + +namespace WalkingTec.Mvvm.Core +{ + [Table("FrameworkUserGroups")] + public class FrameworkUserGroup : BasePoco + { + [Required] + public string UserCode { get; set; } + [Display(Name = "_Admin.Group")] + [Required] + public string GroupCode { get; set; } + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkUserRole.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkUserRole.cs new file mode 100644 index 0000000..7279b75 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FrameworkUserRole.cs @@ -0,0 +1,18 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Text.Json.Serialization; +using WalkingTec.Mvvm.Core.Attributes; + +namespace WalkingTec.Mvvm.Core +{ + [Table("FrameworkUserRoles")] + public class FrameworkUserRole : BasePoco + { + [Required] + public string UserCode { get; set; } + [Required] + [Display(Name = "_Admin.Role")] + public string RoleCode { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FunctionPrivilege.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FunctionPrivilege.cs new file mode 100644 index 0000000..d542c71 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/FunctionPrivilege.cs @@ -0,0 +1,26 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// FunctionPrivilege + /// + [Table("FunctionPrivileges")] + public class FunctionPrivilege : BasePoco + { + [Display(Name = "_Admin.Role")] + public string RoleCode { get; set; } + + [Display(Name = "_Admin.MenuItem")] + public Guid MenuItemId { get; set; } + + [Display(Name = "_Admin.MenuItem")] + public FrameworkMenu MenuItem { get; set; } + + [Display(Name = "_Admin.Allowed")] + [Required(ErrorMessage = "Validate.{0}required")] + public bool? Allowed { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/ISearcher.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/ISearcher.cs new file mode 100644 index 0000000..0293808 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/ISearcher.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using WalkingTec.Mvvm.Core; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// ISearcher + /// + public interface ISearcher + { + #region Property + + #region 分页相关 + /// + /// 当前页 + /// + int Page { get; set; } + /// + /// 每页数 + /// + int Limit { get; set; } + /// + /// 记录数 + /// + long Count { get; set; } + /// + /// 分页数 + /// + int PageCount { get; set; } + #endregion + + /// + /// 记录 Controller 中的表单数据 + /// + Dictionary FC { get; set; } + + IDataContext DC { get; set; } + /// + /// VMFullName + /// + string VMFullName { get; } + + ISessionService Session { get; } + + LoginUserInfo LoginUserInfo { get; } + /// + /// 排序信息 + /// + SortInfo SortInfo { get; set; } + /// + /// 用于框架判断列表页是否全局刷新 + /// + + #endregion + + #region Event + + /// + /// InitVM 完成后触发的事件 + /// + event Action OnAfterInit; + /// + /// ReInitVM 完成后触发的事件 + /// + event Action OnAfterReInit; + + #endregion + + #region Method + /// + /// 将源 VM 的 FC 等内容复制到本VM中 + /// + /// + void CopyContext(IBaseVM vm); + + /// + /// 调用 InitVM 并触发 OnAfterInit 事件 + /// + void DoInit(); + + /// + /// 调用 ReInitVM 并触发 OnAfterReInit 事件 + /// + void DoReInit(); + + #endregion + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/ISubFile.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/ISubFile.cs new file mode 100644 index 0000000..4aa27ac --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/ISubFile.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WalkingTec.Mvvm.Core +{ + public interface ISubFile + { + Guid FileId { get; set; } + FileAttachment File { get; set; } + int Order { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/IWtmFile.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/IWtmFile.cs new file mode 100644 index 0000000..f04d6f4 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/IWtmFile.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace WalkingTec.Mvvm.Core.Models +{ + public interface IWtmFile + { + string Path { get; set; } + + string FileName { get; set; } + string FileExt { get; set; } + long Length { get; set; } + + DateTime UploadTime { get; set; } + + string SaveMode { get; set; } + string ExtraInfo { get; set; } + string HandlerInfo { get; set; } + + Stream DataStream { get; set; } + + string GetID(); + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/PersistPoco.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/PersistPoco.cs new file mode 100644 index 0000000..6d8c17d --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/PersistPoco.cs @@ -0,0 +1,21 @@ +using System.ComponentModel.DataAnnotations; + +namespace WalkingTec.Mvvm.Core +{ + public interface IPersistPoco + { + bool IsValid { get; set; } + } + + /// + /// 所有持久化model的基类,所有的不应被物理删除的model都应该继承这个类 + /// + public abstract class PersistPoco : BasePoco, IPersistPoco + { + /// + /// IsValid + /// + [Display(Name = "_Admin.IsValid")] + public bool IsValid { get; set; } = true; + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/PersistedGrant.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/PersistedGrant.cs new file mode 100644 index 0000000..6b4b8a3 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/PersistedGrant.cs @@ -0,0 +1,34 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// PersistedGrant + /// + [Table("PersistedGrants")] + public class PersistedGrant : TopBasePoco + { + [StringLength(50)] + public string Type { get; set; } + + public string UserCode { get; set; } + + /// + /// 创建时间 + /// + /// The creation time. + public DateTime CreationTime { get; set; } = DateTime.Now; + + /// + /// 到期时间 + /// + /// The expiration. + public DateTime Expiration { get; set; } + + [StringLength(50)] + public string RefreshToken { get; set; } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/TopBasePoco.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/TopBasePoco.cs new file mode 100644 index 0000000..7a73aac --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/TopBasePoco.cs @@ -0,0 +1,116 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Reflection; +using System.Text.Json.Serialization; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// TopBasePoco + /// + public class TopBasePoco + { + /// + /// Id + /// + [Key] + public Guid ID + { + get; set; + } + + /// + /// 是否选中 + /// 标识当前行数据是否被选中 + /// + [NotMapped] + //[JsonConverter(typeof(InternalBoolConverter))] + //[JsonProperty("LAY_CHECKED")] + [JsonIgnore] + public bool Checked { get; set; } + + /// + /// BatchError + /// + [NotMapped] + [JsonIgnore] + public string BatchError { get; set; } + + /// + /// ExcelIndex + /// + [NotMapped] + [JsonIgnore] + public long ExcelIndex { get; set; } + + public object GetID() + { + var idpro = this.GetType().GetSingleProperty("ID"); + var id = idpro.GetValue(this); + return id; + } + + public bool HasID() + { + bool rv = false; + var id = this.GetID(); + switch (id) + { + case Guid g1 when g1 != Guid.Empty: + rv = true; + break; + case string s when string.IsNullOrEmpty(s) == false: + rv = true; + break; + case int i when i>0: + rv = true; + break; + case long l when l > 0: + rv = true; + break; + } + return rv; + } + + public object GetParentID() + { + var idpro = this.GetType().GetSingleProperty("ParentId"); + var id = idpro.GetValue(this) ?? ""; + return id; + } + + + public Type GetIDType() + { + var idpro = this.GetType().GetSingleProperty("ID"); + return idpro.PropertyType; + } + + public void SetID(object id) + { + var idpro = this.GetType().GetSingleProperty("ID"); + idpro.SetValue(this, id.ConvertValue(idpro.PropertyType)); + + } + + private bool? _isBasePoco = null; + [NotMapped] + [JsonIgnore] + public bool IsBasePoco + { + get + { + if(_isBasePoco == null) + { + _isBasePoco = typeof(IBasePoco).IsAssignableFrom(this.GetType()); + } + return _isBasePoco.Value; + } + } + } + + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/TrackingObj.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/TrackingObj.cs new file mode 100644 index 0000000..59e2af7 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/TrackingObj.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Components.Forms; + +namespace WalkingTec.Mvvm.Core.Models +{ + public class TrackingObj + { + public object Model { get; set; } + public List ChangedFields { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/TreePoco.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/TreePoco.cs new file mode 100644 index 0000000..7175d9c --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Models/TreePoco.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace WalkingTec.Mvvm.Core +{ + public abstract class TreePoco : TopBasePoco + { + [Display(Name = "_Admin.Parent")] + public Guid? ParentId { get; set; } + + } + + public class TreePoco : TreePoco where T:TreePoco + { + + [Display(Name = "_Admin.Parent")] + [JsonIgnore] + public T Parent { get; set; } + [InverseProperty("Parent")] + [Display(Name = "_Admin.Children")] + public List Children { get; set; } + + [NotMapped] + public bool HasChildren + { + get + { + return Children?.Any() == true; + } + } + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/AuthConstants.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/AuthConstants.cs new file mode 100644 index 0000000..529fc51 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/AuthConstants.cs @@ -0,0 +1,314 @@ +namespace WalkingTec.Mvvm.Core.Auth +{ + public static class AuthConstants + { + public const string JwtTokenType = "Bearer"; + public const string AuthenticationType = "WTMAuthentication"; + public const string CookieAuthName = "WTM.CookieWithJwtAuth"; + + public static class JwtClaimTypes + { + // + // Summary: + // Unique Identifier for the End-User at the Issuer. + public const string Subject = "sub"; + // + // Summary: + // The iat (issued at) claim identifies the time at which the JWT was issued, , + // specified as the number of seconds from 1970-01-01T0:0:0Z + public const string IssuedAt = "iat"; + // + // Summary: + // Authentication Methods References. JSON array of strings that are identifiers + // for authentication methods used in the authentication. + public const string AuthenticationMethod = "amr"; + // + // Summary: + // Session identifier. This represents a Session of an OP at an RP to a User Agent + // or device for a logged-in End-User. Its contents are unique to the OP and opaque + // to the RP. + public const string SessionId = "sid"; + // + // Summary: + // Authentication Context Class Reference. String specifying an Authentication Context + // Class Reference value that identifies the Authentication Context Class that the + // authentication performed satisfied. The value "0" indicates the End-User authentication + // did not meet the requirements of ISO/IEC 29115 level 1. Authentication using + // a long-lived browser cookie, for instance, is one example where the use of "level + // 0" is appropriate. Authentications with level 0 SHOULD NOT be used to authorize + // access to any resource of any monetary value. (This corresponds to the OpenID + // 2.0 PAPE nist_auth_level 0.) An absolute URI or an RFC 6711 registered name SHOULD + // be used as the acr value; registered names MUST NOT be used with a different + // meaning than that which is registered. Parties using this claim will need to + // agree upon the meanings of the values used, which may be context-specific. The + // acr value is a case sensitive string. + public const string AuthenticationContextClassReference = "acr"; + // + // Summary: + // Time when the End-User authentication occurred. Its value is a JSON number representing + // the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time. + // When a max_age request is made or when auth_time is requested as an Essential + // Claim, then this Claim is REQUIRED; otherwise, its inclusion is OPTIONAL. + public const string AuthenticationTime = "auth_time"; + // + // Summary: + // The party to which the ID Token was issued. If present, it MUST contain the OAuth + // 2.0 Client ID of this party. This Claim is only needed when the ID Token has + // a single audience value and that audience is different than the authorized party. + // It MAY be included even when the authorized party is the same as the sole audience. + // The azp value is a case sensitive string containing a StringOrURI value. + public const string AuthorizedParty = "azp"; + // + // Summary: + // Access Token hash value. Its value is the base64url encoding of the left-most + // half of the hash of the octets of the ASCII representation of the access_token + // value, where the hash algorithm used is the hash algorithm used in the alg Header + // Parameter of the ID Token's JOSE Header. For instance, if the alg is RS256, hash + // the access_token value with SHA-256, then take the left-most 128 bits and base64url + // encode them. The at_hash value is a case sensitive string. + public const string AccessTokenHash = "at_hash"; + // + // Summary: + // Code hash value. Its value is the base64url encoding of the left-most half of + // the hash of the octets of the ASCII representation of the code value, where the + // hash algorithm used is the hash algorithm used in the alg Header Parameter of + // the ID Token's JOSE Header. For instance, if the alg is HS512, hash the code + // value with SHA-512, then take the left-most 256 bits and base64url encode them. + // The c_hash value is a case sensitive string. + public const string AuthorizationCodeHash = "c_hash"; + // + // Summary: + // Time the End-User's information was last updated. Its value is a JSON number + // representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC + // until the date/time. + public const string UpdatedAt = "updated_at"; + // + // Summary: + // String value used to associate a Client session with an ID Token, and to mitigate + // replay attacks. The value is passed through unmodified from the Authentication + // Request to the ID Token. If present in the ID Token, Clients MUST verify that + // the nonce Claim Value is equal to the value of the nonce parameter sent in the + // Authentication Request. If present in the Authentication Request, Authorization + // Servers MUST include a nonce Claim in the ID Token with the Claim Value being + // the nonce value sent in the Authentication Request. Authorization Servers SHOULD + // perform no other processing on nonce values used. The nonce value is a case sensitive + // string. + public const string Nonce = "nonce"; + // + // Summary: + // Defines a set of event statements that each may add additional claims to fully + // describe a single logical event that has occurred. + public const string Events = "events"; + // + // Summary: + // OAuth 2.0 Client Identifier valid at the Authorization Server. + public const string ClientId = "client_id"; + // + // Summary: + // OpenID Connect requests MUST contain the "openid" scope value. If the openid + // scope value is not present, the behavior is entirely unspecified. Other scope + // values MAY be present. Scope values used that are not understood by an implementation + // SHOULD be ignored. + public const string Scope = "scope"; + // + // Summary: + // The "act" (actor) claim provides a means within a JWT to express that delegation + // has occurred and identify the acting party to whom authority has been delegated.The + // "act" claim value is a JSON object and members in the JSON object are claims + // that identify the actor. The claims that make up the "act" claim identify and + // possibly provide additional information about the actor. + public const string Actor = "act"; + // + // Summary: + // The "may_act" claim makes a statement that one party is authorized to become + // the actor and act on behalf of another party. The claim value is a JSON object + // and members in the JSON object are claims that identify the party that is asserted + // as being eligible to act for the party identified by the JWT containing the claim. + public const string MayAct = "may_act"; + // + // Summary: + // an identifier + public const string Id = "id"; + // + // Summary: + // The identity provider + public const string IdentityProvider = "idp"; + // + // Summary: + // The role + public const string Role = "role"; + public const string TenantCode = "tenant"; + // + // Summary: + // JWT ID. A unique identifier for the token, which can be used to prevent reuse + // of the token. These tokens MUST only be used once, unless conditions for reuse + // were negotiated between the parties; any such negotiation is beyond the scope + // of this specification. + public const string JwtId = "jti"; + // + // Summary: + // The exp (expiration time) claim identifies the expiration time on or after which + // the token MUST NOT be accepted for processing, specified as the number of seconds + // from 1970-01-01T0:0:0Z + public const string Expiration = "exp"; + // + // Summary: + // The time before which the JWT MUST NOT be accepted for processing, specified + // as the number of seconds from 1970-01-01T0:0:0Z + public const string NotBefore = "nbf"; + // + // Summary: + // Issuer Identifier for the Issuer of the response. The iss value is a case sensitive + // URL using the https scheme that contains scheme, host, and optionally, port number + // and path components and no query or fragment components. + public const string Issuer = "iss"; + // + // Summary: + // End-User's full name in displayable form including all name parts, possibly including + // titles and suffixes, ordered according to the End-User's locale and preferences. + public const string Name = "name"; + // + // Summary: + // Given name(s) or first name(s) of the End-User. Note that in some cultures, people + // can have multiple given names; all can be present, with the names being separated + // by space characters. + public const string GivenName = "given_name"; + // + // Summary: + // Surname(s) or last name(s) of the End-User. Note that in some cultures, people + // can have multiple family names or no family name; all can be present, with the + // names being separated by space characters. + public const string FamilyName = "family_name"; + // + // Summary: + // Middle name(s) of the End-User. Note that in some cultures, people can have multiple + // middle names; all can be present, with the names being separated by space characters. + // Also note that in some cultures, middle names are not used. + public const string MiddleName = "middle_name"; + // + // Summary: + // Casual name of the End-User that may or may not be the same as the given_name. + // For instance, a nickname value of Mike might be returned alongside a given_name + // value of Michael. + public const string NickName = "nickname"; + // + // Summary: + // Shorthand name by which the End-User wishes to be referred to at the RP, such + // as janedoe or j.doe. This value MAY be any valid JSON string including special + // characters such as @, /, or whitespace. The relying party MUST NOT rely upon + // this value being unique + // + // Remarks: + // The RP MUST NOT rely upon this value being unique, as discussed in http://openid.net/specs/openid-connect-basic-1_0-32.html#ClaimStability + public const string PreferredUserName = "preferred_username"; + // + // Summary: + // URL of the End-User's profile page. The contents of this Web page SHOULD be about + // the End-User. + public const string Profile = "profile"; + // + // Summary: + // URL of the End-User's profile picture. This URL MUST refer to an image file (for + // example, a PNG, JPEG, or GIF image file), rather than to a Web page containing + // an image. + // + // Remarks: + // Note that this URL SHOULD specifically reference a profile photo of the End-User + // suitable for displaying when describing the End-User, rather than an arbitrary + // photo taken by the End-User. + public const string Picture = "picture"; + // + // Summary: + // URL of the End-User's Web page or blog. This Web page SHOULD contain information + // published by the End-User or an organization that the End-User is affiliated + // with. + public const string WebSite = "website"; + // + // Summary: + // End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 [RFC5322] + // addr-spec syntax. The relying party MUST NOT rely upon this value being unique + public const string Email = "email"; + // + // Summary: + // "true" if the End-User's e-mail address has been verified; otherwise "false". + // + // Remarks: + // When this Claim Value is "true", this means that the OP took affirmative steps + // to ensure that this e-mail address was controlled by the End-User at the time + // the verification was performed. The means by which an e-mail address is verified + // is context-specific, and dependent upon the trust framework or contractual agreements + // within which the parties are operating. + public const string EmailVerified = "email_verified"; + // + // Summary: + // End-User's gender. Values defined by this specification are "female" and "male". + // Other values MAY be used when neither of the defined values are applicable. + public const string Gender = "gender"; + // + // Summary: + // End-User's birthday, represented as an ISO 8601:2004 [ISO8601‑2004] YYYY-MM-DD + // format. The year MAY be 0000, indicating that it is omitted. To represent only + // the year, YYYY format is allowed. Note that depending on the underlying platform's + // date related function, providing just year can result in varying month and day, + // so the implementers need to take this factor into account to correctly process + // the dates. + public const string BirthDate = "birthdate"; + // + // Summary: + // String from the time zone database (http://www.twinsun.com/tz/tz-link.htm) representing + // the End-User's time zone. For example, Europe/Paris or America/Los_Angeles. + public const string ZoneInfo = "zoneinfo"; + // + // Summary: + // End-User's locale, represented as a BCP47 [RFC5646] language tag. This is typically + // an ISO 639-1 Alpha-2 [ISO639‑1] language code in lowercase and an ISO 3166-1 + // Alpha-2 [ISO3166‑1] country code in uppercase, separated by a dash. For example, + // en-US or fr-CA. As a compatibility note, some implementations have used an underscore + // as the separator rather than a dash, for example, en_US; Relying Parties MAY + // choose to accept this locale syntax as well. + public const string Locale = "locale"; + // + // Summary: + // End-User's preferred telephone number. E.164 (https://www.itu.int/rec/T-REC-E.164/e) + // is RECOMMENDED as the format of this Claim, for example, +1 (425) 555-1212 or + // +56 (2) 687 2400. If the phone number contains an extension, it is RECOMMENDED + // that the extension be represented using the RFC 3966 [RFC3966] extension syntax, + // for example, +1 (604) 555-1234;ext=5678. + public const string PhoneNumber = "phone_number"; + // + // Summary: + // True if the End-User's phone number has been verified; otherwise false. When + // this Claim Value is true, this means that the OP took affirmative steps to ensure + // that this phone number was controlled by the End-User at the time the verification + // was performed. + // + // Remarks: + // The means by which a phone number is verified is context-specific, and dependent + // upon the trust framework or contractual agreements within which the parties are + // operating. When true, the phone_number Claim MUST be in E.164 format and any + // extensions MUST be represented in RFC 3966 format. + public const string PhoneNumberVerified = "phone_number_verified"; + // + // Summary: + // End-User's preferred postal address. The value of the address member is a JSON + // structure containing some or all of the members defined in http://openid.net/specs/openid-connect-basic-1_0-32.html#AddressClaim + public const string Address = "address"; + // + // Summary: + // Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 + // client_id of the Relying Party as an audience value. It MAY also contain identifiers + // for other audiences. In the general case, the aud value is an array of case sensitive + // strings. In the common special case when there is one audience, the aud value + // MAY be a single case sensitive string. + public const string Audience = "aud"; + // + // Summary: + // The reference token identifier + public const string ReferenceTokenId = "reference_token_id"; + // + // Summary: + // The confirmation + public const string Confirmation = "cnf"; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ChartData.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ChartData.cs new file mode 100644 index 0000000..b23d5a0 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ChartData.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WalkingTec.Mvvm.Core +{ + public class ChartData + { + //一级分类 + public string Category { get; set; } + + public double Value { get; set; } + //散点图 x值 + public double ValueX { get; set; } + + //二级分类 不同数据集 + public string Series { get; set; } + + public double Addition { get; set; } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ClaimComparer.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ClaimComparer.cs new file mode 100644 index 0000000..cc6b2f5 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ClaimComparer.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.Security.Claims; + +namespace WalkingTec.Mvvm.Core.Auth +{ + /// + /// Compares two instances of Claim + /// + public class ClaimComparer : EqualityComparer + { + /// + /// Claim comparison options + /// + public class Options + { + /// + /// Specifies if the issuer value is being taken into account + /// + public bool IgnoreIssuer { get; set; } = false; + + /// + /// Specifies if claim and issuer value comparison should be case-sensitive + /// + public bool IgnoreValueCase { get; set; } = false; + } + + private readonly Options _options = new Options(); + + /// + /// Initializes a new instance of the class with default options. + /// + public ClaimComparer() + { } + + /// + /// Initializes a new instance of the class with given comparison options. + /// + /// Comparison options. + public ClaimComparer(Options options) + { + _options = options ?? throw new ArgumentNullException(nameof(options)); + } + + /// + public override bool Equals(Claim x, Claim y) + { + if (x == null && y == null) return true; + if (x == null && y != null) return false; + if (x != null && y == null) return false; + + StringComparison valueComparison = StringComparison.Ordinal; + if (_options.IgnoreValueCase == true) valueComparison = StringComparison.OrdinalIgnoreCase; + + var equal = (String.Equals(x.Type, y.Type, StringComparison.OrdinalIgnoreCase) && + String.Equals(x.Value, y.Value, valueComparison) && + String.Equals(x.ValueType, y.ValueType, StringComparison.Ordinal)); + + + if (_options.IgnoreIssuer) + { + return equal; + } + else + { + return (equal && String.Equals(x.Issuer, y.Issuer, valueComparison)); + } + } + + /// + public override int GetHashCode(Claim claim) + { + if (claim is null) return 0; + + int typeHash = claim.Type?.ToLowerInvariant().GetHashCode() ?? 0 ^ claim.ValueType?.GetHashCode() ?? 0; + int valueHash; + int issuerHash; + + if (_options.IgnoreValueCase) + { + valueHash = claim.Value?.ToLowerInvariant().GetHashCode() ?? 0; + issuerHash = claim.Issuer?.ToLowerInvariant().GetHashCode() ?? 0; + } + else + { + valueHash = claim.Value?.GetHashCode() ?? 0; + issuerHash = claim.Issuer?.GetHashCode() ?? 0; + } + + if (_options.IgnoreIssuer) + { + return typeHash ^ valueHash; + + } + else + { + return typeHash ^ valueHash ^ issuerHash; + } + } + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ColumnFormatInfo.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ColumnFormatInfo.cs new file mode 100644 index 0000000..7b68b3b --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ColumnFormatInfo.cs @@ -0,0 +1,135 @@ +using System; + +namespace WalkingTec.Mvvm.Core +{ + + public class ColumnFormatInfo + { + public ColumnFormatTypeEnum FormatType { get; set; } + + public ButtonTypesEnum ButtonType { get; set; } + public string Text { get; set; } + public string Title { get; set; } + + public string Script { get; set; } + + public string WindowID { get; set; } + + public string Url { get; set; } + + public bool ShowDialog { get; set; } + + public bool Resizable { get; set; } + + public string ButtonID { get; set; } + + public int? Width { get; set; } + + public int? Height { get; set; } + + public Guid? FileID { get; set; } + + public string Html { get; set; } + + public bool Maxed { get; set; } + + public string ButtonClass { get; set; } + + public RedirectTypesEnum RType { get; set; } + + public string Style { get; set; } + public static ColumnFormatInfo MakeDialogButton(ButtonTypesEnum buttonType, string url, string buttonText, int? width, int? height, string title = null, string buttonID = null, bool showDialog = true, bool resizable = true, bool maxed = false,string buttonclass = null, string style=null) + { + ColumnFormatInfo rv = new ColumnFormatInfo(); + rv.FormatType = ColumnFormatTypeEnum.Dialog; + rv.ButtonType = buttonType; + rv.Url = url; + rv.Width = width; + rv.Height = height; + rv.Text = buttonText; + rv.Title = title; + rv.ButtonID = buttonID; + rv.ShowDialog = showDialog; + rv.Resizable = resizable; + rv.Maxed = maxed; + rv.ButtonClass = buttonclass; + rv.Style = style; + return rv; + } + + public static ColumnFormatInfo MakeScriptButton(ButtonTypesEnum buttonType, string url, string buttonText, string buttonID = null, string script = "", string buttonclass = null, string style = null) + { + ColumnFormatInfo rv = new ColumnFormatInfo(); + rv.FormatType = ColumnFormatTypeEnum.Script; + rv.ButtonType = buttonType; + rv.Url = url; + rv.Text = buttonText; + rv.ButtonID = buttonID; + rv.Script = script; + rv.ButtonClass = buttonclass; + rv.Style = style; + return rv; + } + + public static ColumnFormatInfo MakeButton(ButtonTypesEnum buttonType, string url, string buttonText, int? width, int? height, string title = null, string buttonID = null, bool resizable = true, bool maxed = false, string buttonclass = null, string style = null, RedirectTypesEnum rtype = RedirectTypesEnum.Layer) + { + ColumnFormatInfo rv = new ColumnFormatInfo(); + rv.FormatType = ColumnFormatTypeEnum.Button; + rv.ButtonType = buttonType; + rv.Url = url; + rv.Width = width; + rv.Height = height; + rv.Text = buttonText; + rv.Title = title; + rv.ButtonID = buttonID; + rv.Resizable = resizable; + rv.Maxed = maxed; + rv.ButtonClass = buttonclass; + rv.RType = rtype; + rv.Style = style; + return rv; + } + + public static ColumnFormatInfo MakeDownloadButton(ButtonTypesEnum buttonType, Guid? fileID, string buttonText = null, string buttonclass = null, string style = null) + { + ColumnFormatInfo rv = new ColumnFormatInfo(); + rv.FormatType = ColumnFormatTypeEnum.Download; + rv.ButtonType = buttonType; + rv.FileID = fileID; + rv.Text = buttonText?? CoreProgram._localizer?["Sys.Download"]; + rv.ButtonClass = buttonclass; + rv.Style = style; + return rv; + } + + public static ColumnFormatInfo MakeViewButton(ButtonTypesEnum buttonType, Guid? fileID, int? width = null, int? height = null, string title = null, string windowID = null, string buttonText = null, bool resizable = true, bool maxed = false, string buttonclass = null, string style = null) + { + ColumnFormatInfo rv = new ColumnFormatInfo(); + rv.FormatType = ColumnFormatTypeEnum.ViewPic; + rv.ButtonType = buttonType; + rv.FileID = fileID; + rv.Width = width; + rv.Height = height; + rv.WindowID = windowID; + rv.Text = buttonText ?? CoreProgram._localizer?["Sys.Preview"]; + rv.Title = title ?? CoreProgram._localizer?["Sys.Preview"]; + rv.Resizable = resizable; + rv.Maxed = maxed; + rv.ButtonClass = buttonclass; + rv.Style = style; + return rv; + } + + public static ColumnFormatInfo MakeHtml(string html) + { + ColumnFormatInfo rv = new ColumnFormatInfo(); + rv.FormatType = ColumnFormatTypeEnum.Html; + rv.Html = html; + if (string.IsNullOrEmpty(rv.Html) == false) + { + rv.Html += ""; + } + return rv; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/CommonEqualityComparer.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/CommonEqualityComparer.cs new file mode 100644 index 0000000..2e773f2 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/CommonEqualityComparer.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WalkingTec.Mvvm.Core +{ + public class CommonEqualityComparer : IEqualityComparer + { + private Func keySelector; + + public CommonEqualityComparer(Func keySelector) + { + this.keySelector = keySelector; + } + + public bool Equals(T x, T y) + { + return EqualityComparer.Default.Equals(keySelector(x), keySelector(y)); + } + + public int GetHashCode(T obj) + { + return EqualityComparer.Default.GetHashCode(keySelector(obj)); + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/DataPrivilegeInfo.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/DataPrivilegeInfo.cs new file mode 100644 index 0000000..7343546 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/DataPrivilegeInfo.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// 数据权限信息接口 + /// + public interface IDataPrivilege + { + //数据权限关联的表名 + string ModelName { get; set; } + //数据权限名称 + string PrivillegeName { get; set; } + + Type ModelType { get; set; } + //获取数据权限的下拉菜单 + List GetItemList (WTMContext wtmcontext, string filter = null, List ids = null); + List GetTreeParentIds(WTMContext wtmcontext, List dps); + List GetTreeSubIds(WTMContext wtmcontext, List pids); + } + + /// + /// 数据权限信息 + /// + /// 关联表类 + public class DataPrivilegeInfo : IDataPrivilege where T : TopBasePoco + { + //数据权限关联的表名 + public string ModelName { get; set; } + //数据权限名称 + public string PrivillegeName { get; set; } + //显示字段 + private Expression> _displayField; + //where过滤条件 + private Expression> _where; + public Type ModelType { get; set; } + + public DataPrivilegeInfo(string name, Expression> displayField, Expression> where = null) + { + ModelType = typeof(T); + ModelName = ModelType.Name; + PrivillegeName = name; + _displayField = displayField; + _where = where; + } + + /// + /// 获取数据权限的下拉菜单 + /// + /// wtm context + /// filter + /// ids + /// 数据权限关联表的下拉菜单 + public List GetItemList(WTMContext wtmcontext, string filter = null,List ids= null) + { + var user = wtmcontext?.LoginUserInfo; + Expression> where = null; + + if (ids != null) + { + where = ids.GetContainIdExpression(); + } + else + { + if (string.IsNullOrEmpty(filter) == false) + { + ChangePara cp = new ChangePara(); + ParameterExpression pe = Expression.Parameter(typeof(T)); + //var toString = Expression.Call(cp.Change(_displayField.Body, pe), "Cast", new Type[] { typeof(string)}); + var tolower = Expression.Call(cp.Change(_displayField.Body, pe), "ToLower", new Type[] { }); + var exp = Expression.Call(tolower, "Contains", null, Expression.Constant(filter.ToLower())); + where = Expression.Lambda>(exp, pe); + if (_where != null) + { + var temp = cp.Change(_where.Body, pe); + var together = Expression.And(where.Body, temp); + where = Expression.Lambda>(together, pe); + } + } + else + { + where = _where; + } + if (where == null) + { + where = x => 1 == 1; + } + } + List rv = new List(); + if (user.Roles?.Where(x => x.RoleCode == "001").FirstOrDefault() == null && user.DataPrivileges?.Where(x => x.RelateId == null).FirstOrDefault() == null) + { + rv = wtmcontext.DC.Set().CheckIDs(user.DataPrivileges.Select(y => y.RelateId).ToList()).Where(where).GetSelectListItems(wtmcontext, _displayField, null, ignorDataPrivilege: true); + } + else + { + rv = wtmcontext.DC.Set().Where(where).GetSelectListItems(wtmcontext, _displayField, null, ignorDataPrivilege: true); + } + return rv; + } + + public List GetTreeParentIds(WTMContext wtmcontext, List dps) + { + var ids = dps.Where(x => x.TableName == this.ModelName).Select(x => x.RelateId).ToList(); + var idscheck = ids.GetContainIdExpression(); + var modified = wtmcontext.DC.Set().Where(idscheck).CheckNotNull("ParentId").DynamicSelect("ParentId"); + var skipids = modified.ToList(); + return skipids; + } + + public List GetTreeSubIds(WTMContext wtmcontext, List pids) + { + ParameterExpression pe = Expression.Parameter(typeof(T)); + Expression parentid = Expression.Property(pe, typeof(T).GetSingleProperty("ParentId")); + return wtmcontext.DC.Set().Where(pids.GetContainIdExpression(parentid)).DynamicSelect("ID").ToList(); + } + } + + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/DateRange.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/DateRange.cs new file mode 100644 index 0000000..d85cb1d --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/DateRange.cs @@ -0,0 +1,451 @@ +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; + +namespace WalkingTec.Mvvm.Core +{ + public sealed class DateRange + { + private static readonly DateTime UtCDefaultEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + private static readonly DateTime DefaultEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local); + + private static readonly DateTimeTypeEnum DefaultType = DateTimeTypeEnum.DateTime; + + + private DateRange() { } + + + public DateRange(DateTime startTime, DateTime endTime) : this(startTime, endTime, DefaultType, DefaultEpoch) { } + + public DateRange(DateTime startTime, DateTime endTime, DateTimeTypeEnum type, DateTime epoch) + { + Type = type; + Epoch = epoch; + SetStartTime(startTime); + SetEndTime(endTime); + } + + + public DateRange(TimeSpan startSpan, TimeSpan endSpan) : this(startSpan, endSpan, DefaultType, DefaultEpoch) { } + + public DateRange(TimeSpan startSpan, TimeSpan endSpan, DateTimeTypeEnum type, DateTime epoch) + { + Type = type; + Epoch = epoch; + SetStartTime(epoch.Add(startSpan)); + SetEndTime(epoch.Add(endSpan)); + } + + public DateRange(DateTimeOffset startOffset, DateTimeOffset endOffset) : this(startOffset, endOffset, DefaultType, DefaultEpoch) { } + + public DateRange(DateTimeOffset startOffset, DateTimeOffset endOffset, DateTimeTypeEnum type, DateTime epoch) + { + Type = type; + Epoch = epoch; + SetStartTime(startOffset.DateTime); + SetEndTime(endOffset.DateTime); + } + + public readonly DateTime Epoch = DefaultEpoch; + + public readonly DateTimeTypeEnum Type = DefaultType; + + + public string Value => ToString(); + + + private DateTime? _startTime; + + public DateTime? GetStartTime() + { + return _startTime; + } + + public void SetStartTime(DateTime? value) + { + if (value == null) return; + + value = SwitchTime(value.Value); + + if (_endTime.HasValue && _endTime.Value < value) return; + _startTime = value; + } + + private DateTime? _endTime; + + public DateTime? GetEndTime() + { + switch (Type) + { + case DateTimeTypeEnum.Date: + return _endTime?.AddDays(1); + case DateTimeTypeEnum.DateTime when _startTime.HasValue && _endTime.HasValue && _startTime.Value == _endTime.Value: + case DateTimeTypeEnum.DateTime when _endTime.HasValue && _endTime.Value.Hour == 0 && _endTime.Value.Minute == 0 && _endTime.Value.Second == 0 && _endTime.Value.Millisecond == 0: + return _endTime?.AddDays(1); + default: + return _endTime; + } + } + + public void SetEndTime(DateTime? value) + { + if (value == null) return; + + value = SwitchTime(value.Value); + + if (_startTime.HasValue && _startTime.Value > value) return; + _endTime = value; + } + + + public DateTimeOffset? GetStartOffset() + { + if (_startTime == null) + return null; + return _startTime <= DateTimeOffset.MinValue.LocalDateTime ? DateTimeOffset.MinValue : new DateTimeOffset(GetStartTime().Value); + } + + public void SetStartOffset(DateTimeOffset? value) + { + if (value == null) return; + SetStartTime(value.Value.LocalDateTime); + } + + public DateTimeOffset? GetEndOffset() + { + if (_endTime == null) + return null; + return _endTime <= DateTimeOffset.MinValue.LocalDateTime ? DateTimeOffset.MinValue : new DateTimeOffset(GetEndTime().Value); + } + + public void SetEndOffset(DateTimeOffset? value) + { + if (value == null) return; + SetEndTime(value.Value.LocalDateTime); + } + + + public TimeSpan? GetStartSpan() + { + if (_endTime == null) + return null; + return GetStartTime() - Epoch.ToLocalTime(); + } + + public void SetStartSpan(TimeSpan? value) + { + if (value == null) return; + SetStartTime(Epoch.Add(value.Value)); + } + + public TimeSpan? GetEndSpan() + { + if (_endTime == null) + return null; + return GetEndTime() - Epoch.ToLocalTime(); + } + + public void SetEndSpan(TimeSpan? value) + { + if (value == null) return; + SetEndTime(Epoch.Add(value.Value)); + } + + public override string ToString() + { + return ToString(DateTimeFormatDic[Type], "~"); + } + + public string ToString(string format) + { + return ToString(format, "~"); + } + + public string ToString(string format, string rangeSplit) + { + if (_startTime.HasValue && _endTime.HasValue) + return $"{_startTime?.ToString(format)} {rangeSplit} {_endTime?.ToString(format)}"; + return string.Empty; + } + + public static readonly Dictionary DateTimeFormatDic = new Dictionary() + { + { DateTimeTypeEnum.Date,"yyyy-MM-dd"}, + { DateTimeTypeEnum.DateTime,"yyyy-MM-dd HH:mm:ss"}, + { DateTimeTypeEnum.Year,"yyyy"}, + { DateTimeTypeEnum.Month,"yyyy-MM"}, + { DateTimeTypeEnum.Time,"HH:mm:ss"}, + }; + + private DateTime SwitchTime(DateTime time) + { + if (Epoch.Kind == time.Kind) + return time; + switch (Epoch.Kind) + { + case DateTimeKind.Local: + switch (time.Kind) + { + case DateTimeKind.Unspecified: + return new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second, time.Millisecond, DateTimeKind.Local); + case DateTimeKind.Utc: + return time.ToLocalTime(); + } + break; + case DateTimeKind.Unspecified: + switch (time.Kind) + { + case DateTimeKind.Local: + return new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second, time.Millisecond, DateTimeKind.Unspecified); + case DateTimeKind.Utc: + return new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second, time.Millisecond, DateTimeKind.Unspecified); + } + break; + case DateTimeKind.Utc: + switch (time.Kind) + { + case DateTimeKind.Local: + return time.ToUniversalTime(); + case DateTimeKind.Unspecified: + return new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second, time.Millisecond, DateTimeKind.Utc); + } + break; + } + return time; + } + + public static DateRange Default => Today; + + public static DateRange NinetyDays + { + get + { + var result = new DateRange(DateTime.Today.AddDays(-90), DateTime.Today); + return result; + } + } + + public static DateRange ThirtyDays + { + get + { + var result = new DateRange(DateTime.Today.AddDays(-30), DateTime.Today); + return result; + } + } + + public static DateRange TwoWeek + { + get + { + var result = new DateRange(DateTime.Today.AddDays(-14), DateTime.Today); + return result; + } + } + + public static DateRange Week + { + get + { + var result = new DateRange(DateTime.Today.AddDays(-7), DateTime.Today); + return result; + } + } + + public static DateRange Today + { + get + { + var result = new DateRange(DateTime.Today, DateTime.Today); + return result; + } + } + + + public static DateRange Yesterday + { + get + { + var result = new DateRange(DateTime.Today.AddDays(-1), DateTime.Today.AddDays(-1)); + return result; + } + } + + + public static DateRange UtcDefault => UtcToday; + + public static DateRange UtcNinetyDays + { + get + { + var result = new DateRange(DateTime.UtcNow.Date.AddDays(-90), DateTime.UtcNow.Date); + return result; + } + } + + public static DateRange UtcThirtyDays + { + get + { + var result = new DateRange(DateTime.UtcNow.Date.AddDays(-30), DateTime.UtcNow.Date, DefaultType, UtCDefaultEpoch); + return result; + } + } + + public static DateRange UtcTwoWeek + { + get + { + var result = new DateRange(DateTime.UtcNow.Date.AddDays(-14), DateTime.UtcNow.Date, DefaultType, UtCDefaultEpoch); + return result; + } + } + + public static DateRange UtcWeek + { + get + { + var result = new DateRange(DateTime.UtcNow.Date.AddDays(-7), DateTime.UtcNow.Date, DefaultType, UtCDefaultEpoch); + return result; + } + + } + + public static DateRange UtcToday + { + get + { + var result = new DateRange(DateTime.UtcNow.Date.AddDays(-1), DateTime.UtcNow.Date, DefaultType, UtCDefaultEpoch); + return result; + } + } + + public static DateRange UtcYesterday + { + get + { + var result = new DateRange(DateTime.UtcNow.Date.AddDays(-1), DateTime.UtcNow.Date, DefaultType, UtCDefaultEpoch); + return result; + } + } + + + private static readonly Dictionary DateTimeRegexDic = new Dictionary() + { + { DateTimeTypeEnum.DateTime,@"((\d{4}|\d{3}|\d{2}|\d{1})[-](1[0-2]|0?[1-9])[-](3[01]|[12][0-9]|0?[1-9])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d)"}, + { DateTimeTypeEnum.Date,@"(\d{4}|\d{3}|\d{2}|\d{1})[-](1[0-2]|0?[1-9])[-](3[01]|[12][0-9]|0?[1-9])"}, + { DateTimeTypeEnum.Month,@"(\d{4}|\d{3}|\d{2}|\d{1})[-](1[0-2]|0?[1-9])"}, + { DateTimeTypeEnum.Time,@"(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d"}, + { DateTimeTypeEnum.Year,@"(\d{4}|\d{3}|\d{2}|\d{1})"}, + }; + + public static bool TryParse(string input, out DateRange result) + { + if (TryParse(input, new[] { '~' }, out result)) return true; + result = null; + foreach (var pair in DateTimeRegexDic) + { + if (Regex.IsMatch(input, pair.Value)) + { + var values = Regex.Matches(input, pair.Value, RegexOptions.IgnorePatternWhitespace); + return values.Count == 2 && TryParse(values[0].Value, values[1].Value, DefaultEpoch, out result); + } + } + return false; + } + + public static bool TryParse(string input, char[] separator, out DateRange result) + { + result = null; + if (string.IsNullOrEmpty(input)) + { + return false; + } + var values = input.Split(separator, StringSplitOptions.RemoveEmptyEntries); + return values.Length == 2 && TryParse(values[0], values[1], DefaultEpoch, out result); + } + + public static bool TryParse(string input, string[] separator, out DateRange result) + { + result = null; + if (string.IsNullOrEmpty(input)) + { + return false; + } + var values = input.Split(separator, StringSplitOptions.RemoveEmptyEntries); + return values.Length == 2 && TryParse(values[0], values[1], DefaultEpoch, out result); + } + + public static bool TryParse(string[] input, out DateRange result) + { + result = null; + return input.Length == 2 && TryParse(input[0], input[1], DefaultEpoch, out result); + } + + + public static bool TryParse(string startTime, string endTime, DateTime epoch, out DateRange result) + { + result = null; + switch (startTime.Trim().Length) + { + //Year + case 4: + { + if (!int.TryParse(startTime, out var y1)) return false; + if (y1 < 1 || y1 > 9999) return false; + + if (!int.TryParse(endTime, out var y2)) return false; + if (y2 < 1 || y2 > 9999) return false; + + result = new DateRange(new DateTime(y1, 1, 1, 0, 0, 0, epoch.Kind), new DateTime(y2, 1, 1, 0, 0, 0, epoch.Kind)); + return true; + + } + //Month + case 7: + { + if (!DateTime.TryParse(startTime, out var v1)) return false; + + if (!DateTime.TryParse(endTime, out var v2)) return false; + + result = new DateRange(v1, v2, DateTimeTypeEnum.Month, epoch); + + return true; + } + //Time + case 8: + { + if (!DateTime.TryParse(startTime, out var v1)) return false; + + if (!DateTime.TryParse(endTime, out var v2)) return false; + + result = new DateRange(v1, v2, DateTimeTypeEnum.Time, epoch); + + return true; + } + //Date + case 10: + { + if (!DateTime.TryParse(startTime, out var v1)) return false; + + if (!DateTime.TryParse(endTime, out var v2)) return false; + + result = new DateRange(v1, v2, DateTimeTypeEnum.Date, epoch); + + return true; + } + //DateTime + default: + { + if (!DateTime.TryParse(startTime, out var v1)) return false; + + if (!DateTime.TryParse(endTime, out var v2)) return false; + + result = new DateRange(v1, v2, DateTimeTypeEnum.DateTime, epoch); + + return true; + } + } + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/DuplicateInfo.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/DuplicateInfo.cs new file mode 100644 index 0000000..d444675 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/DuplicateInfo.cs @@ -0,0 +1,341 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// 重复数据组 + /// + /// 重复数据类 + public class DuplicatedGroup + { + public List> Fields { get; set; } + } + + /// + /// 重复数据信息 + /// + /// 数据类 + public class DuplicatedInfo + { + //重复数据分组 + public List> Groups { get; set; } + + public DuplicatedInfo() + { + Groups = new List>(); + } + + /// + /// 添加一组重复信息,一组中的多个字段必须同时重复才认为是重复数据 + /// + /// 一个或多个重复数据字段 + public DuplicatedInfo AddGroup(params DuplicatedField[] FieldExps) + { + DuplicatedGroup newGroup = new DuplicatedGroup() + { + Fields = new List>() + }; + foreach (var exp in FieldExps) + { + newGroup.Fields.Add(exp); + } + Groups.Add(newGroup); + return this; + } + } + + /// + /// 简单重复数据字段信息 + /// + /// 重复数据类 + public class DuplicatedField + { + //直接可顺序关联出的字段 + protected Expression> _directFieldExp { get; set; } + + public virtual List GetProperties() + { + List rv = new List + { + PropertyHelper.GetPropertyInfo(_directFieldExp) + }; + return rv; + } + + + /// + /// 根据设定的字段,生成查询重复数据的Lambda,最终返回类似 x=>x.property == val的lambda + /// + /// 要验证字段的实体类 + /// ParameterExpression + /// + public virtual Expression GetExpression(T Entity, ParameterExpression para) + { + var propName = PropertyHelper.GetPropertyName(_directFieldExp); + var prop = PropertyHelper.GetPropertyInfo(_directFieldExp); + var func = _directFieldExp.Compile(); + var val = func.Invoke(Entity); + + ////如果字段值为null则跳过,因为一般情况下null值不会被认为重复 + //if (val == null) + //{ + // return res; + //} + + //如果字段值是空字符串,则跳过 + if (val is string && val.ToString() == string.Empty) + { + var requiredAttrs = prop.GetCustomAttributes(typeof(RequiredAttribute), false).ToList(); + + if (requiredAttrs == null || requiredAttrs.Count == 0) + { + return null; + } + else + { + var requiredAtt = requiredAttrs[0] as RequiredAttribute; + if (requiredAtt.AllowEmptyStrings == true) + { + return null; + } + } + } + //生成一个表达式,类似于 x=>x.field == val + var splits = propName.Split('.'); + var idproperty = typeof(T).GetSingleProperty(splits[0]); + + Expression left = Expression.Property(para, idproperty); + for (int i = 1; i < splits.Length; i++) + { + var tempproperty = typeof(T).GetSingleProperty(splits[i]); + left = Expression.Property(left, tempproperty); + } + + if (val != null && left.Type.IsGeneric(typeof(Nullable<>))) + { + left = Expression.Property(left, "Value"); + } + if (left.Type == typeof(string)) + { + left = Expression.Call(left, typeof(String).GetMethod("Trim", Type.EmptyTypes)); + } + if (val is string) + { + val = val.ToString().Trim(); + } + var right = Expression.Constant(val); + var equal = Expression.Equal(left, right); + return equal; + } + + protected DuplicatedField() + { + + } + + /// + /// 创建一个包含可顺序关联出字段的简单重复字段信息 + /// + /// 字段 + /// 字段信息 + public DuplicatedField(Expression> FieldExp) + { + _directFieldExp = FieldExp; + } + + } + + /// + /// 复杂重复字段信息接口 + /// + public interface IComplexDuplicatedField + { + Type GetMiddleTableType(); + } + + + /// + /// 复杂重复数据字段信息 + /// + /// 重复数据类 + /// 重复数据关联的List中的类 + public class ComplexDuplicatedField : DuplicatedField, IComplexDuplicatedField + { + /// + /// 中间字段 + /// + private Expression>> _middleExp { get; set; } + /// + /// 最终字段 + /// + private List>> _subFieldExps { get; set; } + + protected ComplexDuplicatedField() + { + + } + + /// + /// 创建一个复杂字段 + /// + /// 中间字段类 + /// 最终字段类 + /// + public ComplexDuplicatedField(Expression>> MiddleExp, params Expression>[] FieldExps) + { + _middleExp = MiddleExp; + _subFieldExps = new List>>(); + _subFieldExps.AddRange(FieldExps); + } + + public Type GetMiddleTableType() + { + return typeof(V); + } + + /// + /// 生成验证复杂字段是否重复的Lambda + /// + /// 源数据 + /// 源数据类型 + /// Where语句 + public override Expression GetExpression(T Entity, ParameterExpression para) + { + ParameterExpression midPara = Expression.Parameter(typeof(V), "tm2"); + //获取中间表的List + var list = _middleExp.Compile().Invoke(Entity); + if (list == null) + { + return null; + } + List allExp = new List(); + Expression rv = null; + //循环中间表数据 + foreach (var li in list) + { + List innerExp = new List(); + bool needBreak = false; + //循环中间表要检查重复的字段 + foreach (var SubFieldExp in _subFieldExps) + { + //拼接字段表达式,使left等于类似 x.field 的形式 + Expression left = Expression.Property(midPara, SubFieldExp.GetPropertyName()); + //如果字段是nullable类型的,则拼接value,形成类似 x.field.Value的形式 + if (left.Type.IsGeneric(typeof(Nullable<>)) == true) + { + left = Expression.Property(left, "Value"); + } + //如果字段是string类型,则拼接trim,形成类似 x.field.Trim()的形式 + if (left.Type == typeof(string)) + { + left = Expression.Call(left, typeof(String).GetMethod("Trim", Type.EmptyTypes)); + } + //使用当前循环的中间表的数据获取字段的值 + object vv = SubFieldExp.Compile().Invoke(li); + //如果值为空则跳过 + if (vv == null) + { + needBreak = true; + continue; + } + //如果值为空字符串且没要求必填,则跳过 + if (vv is string && vv.ToString() == "") + { + var requiredAttrs = li.GetType().GetSingleProperty(SubFieldExp.GetPropertyName()).GetCustomAttributes(typeof(RequiredAttribute), false).ToList(); + + if (requiredAttrs == null || requiredAttrs.Count == 0) + { + needBreak = true; + continue; + } + else + { + var requiredAtt = requiredAttrs[0] as RequiredAttribute; + if (requiredAtt.AllowEmptyStrings == true) + { + needBreak = true; + continue; + } + } + } + //如果值为字符串,调用trim函数 + if (vv is string) + { + vv = vv.ToString().Trim(); + } + //拼接形成 x.field == value的形式 + ConstantExpression right = Expression.Constant(vv); + BinaryExpression equal = Expression.Equal(left, right); + innerExp.Add(equal); + } + if (needBreak) + { + continue; + } + //拼接多个 x.field==value,形成 x.field==value && x.field1==value1 .....的形式 + Expression exp = null; + if (innerExp.Count == 1) + { + exp = innerExp[0]; + } + if (innerExp.Count > 1) + { + exp = Expression.And(innerExp[0], innerExp[1]); + for (int i = 2; i < innerExp.Count; i++) + { + exp = Expression.And(exp, innerExp[i]); + } + } + //调用any函数,形成 .Any(x=> x.field==value && x.field1==value1....)的形式 + if (exp != null) + { + var any = Expression.Call( + typeof(Enumerable), + "Any", + new Type[] { typeof(V) }, + Expression.Property(para, _middleExp.GetPropertyName()), + Expression.Lambda>(exp, new ParameterExpression[] { midPara })); + allExp.Add(any); + } + } + //拼接多个any函数形成 .Any(x=> x.field==value && x.field1==value1....) || .Any(x=> x.field==value && x.field1==value1....)的形式并返回 + if (allExp.Count == 1) + { + rv = allExp[0]; + } + if (allExp.Count > 1) + { + rv = Expression.OrElse(allExp[0], allExp[1]); + for (int i = 2; i < allExp.Count; i++) + { + rv = Expression.OrElse(rv, allExp[i]); + } + } + return rv; + } + + /// + /// 获取字段属性 + /// + /// 字段属性列表 + public override List GetProperties() + { + List rv = new List(); + foreach (var subField in _subFieldExps) + { + var pro = subField.GetPropertyInfo(); + if (pro != null) + { + rv.Add(pro); + } + } + return rv; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/DynamicData.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/DynamicData.cs new file mode 100644 index 0000000..e4178ba --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/DynamicData.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Dynamic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WalkingTec.Mvvm.Core +{ + public class DynamicData : DynamicObject + { + public Dictionary Fields = new Dictionary(); + + public int Count { get { return Fields.Keys.Count; } } + + public void Add(string name, object val = null) + { + if (!Fields.ContainsKey(name)) + { + Fields.Add(name, val); + } + else + { + Fields[name] = val; + } + } + + public override bool TryGetMember(GetMemberBinder binder, out object result) + { + if (Fields.ContainsKey(binder.Name)) + { + result = Fields[binder.Name]; + return true; + } + return base.TryGetMember(binder, out result); + } + + public override bool TrySetMember(SetMemberBinder binder, object value) + { + if (!Fields.ContainsKey(binder.Name)) + { + Fields.Add(binder.Name, value); + } + else + { + Fields[binder.Name] = value; + } + return true; + } + + public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) + { + if (Fields.ContainsKey(binder.Name) && + Fields[binder.Name] is Delegate) + { + Delegate del = Fields[binder.Name] as Delegate; + result = del.DynamicInvoke(args); + return true; + } + return base.TryInvokeMember(binder, args, out result); + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ExcelPropety.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ExcelPropety.cs new file mode 100644 index 0000000..8a714bc --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ExcelPropety.cs @@ -0,0 +1,497 @@ +using NPOI.HSSF.UserModel; +using NPOI.OpenXmlFormats.Spreadsheet; +using NPOI.SS.UserModel; +using NPOI.SS.Util; +using NPOI.XSSF.UserModel; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Linq.Expressions; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Core +{ + public class ExcelPropety + { + #region 属性 + private string _columnName; + /// + /// 列名 + /// + public string ColumnName + { + get + { + string col = _columnName; + return col; + } + set + { + _columnName = value; + } + } + + public string FieldDisplayName { get; set; } + + public string FieldName { get; set; } + + //private string _backgroudColor; + ///// + ///// 背景色 + ///// + //public string BackgroudColor + //{ + // get { return _backgroudColor; } + // set { _backgroudColor = value; } + //} + + /// + /// 背景色 + /// + public BackgroudColorEnum BackgroudColor { get; set; } + + private Type _resourceType; + /// + /// 多语言 + /// + public Type ResourceType + { + get { return _resourceType; } + set { _resourceType = value; } + } + + private ColumnDataType _dataType; + /// + /// 数据类型 + /// + public ColumnDataType DataType + { + get { return _dataType; } + set { _dataType = value; } + } + + private Type _enumType; + public Type EnumType + { + get { return _enumType; } + set + { + _enumType = value; + this.ListItems = _enumType.ToListItems(); + } + } + + private string _minValueOrLength; + /// + /// 最小长度 + /// + public string MinValueOrLength + { + get { return _minValueOrLength; } + set { _minValueOrLength = value; } + } + + private string _maxValuseOrLength; + /// + /// 最大长度 + /// + public string MaxValuseOrLength + { + get { return _maxValuseOrLength; } + set { _maxValuseOrLength = value; } + } + + private bool _isNullAble; + /// + /// 是否可以为空 + /// + public bool IsNullAble + { + get { return _isNullAble; } + set { _isNullAble = value; } + } + + private IEnumerable _listItems; + /// + /// 类表中数据 + /// + public IEnumerable ListItems + { + get { return _listItems; } + set { _listItems = value; } + } + + private object _value; + /// + /// Value + /// + public object Value + { + get { return _value; } + set { _value = value; } + } + + private List _dynamicColumns; + /// + /// 动态列 + /// + public List DynamicColumns + { + get { return _dynamicColumns == null ? new List() : _dynamicColumns; } + set { _dynamicColumns = value; } + } + + public Type SubTableType { get; set; } + + public bool ReadOnly { get; set; } + /// + /// 字符数量 + /// + public int CharCount { get; set; } + + #endregion + + #region 设定Excel数据验证 + /// + /// 设置Excel单元格样式(标题),数据格式 + /// + /// 数据类型 + /// 单元格索引 + /// Sheet页 + /// 数据Sheet页 + /// 样式 + /// 格式 + public void SetColumnFormat(ColumnDataType dateType, int porpetyIndex, ISheet sheet, ISheet dataSheet, ICellStyle dataStyle, IDataFormat dataFormat) + { + XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper((XSSFSheet)sheet); + CellRangeAddressList CellRangeList = new CellRangeAddressList(1, 1048576 - 1, porpetyIndex, porpetyIndex); //超过1048576最大行数,打开Excel会报错 + XSSFDataValidationConstraint dvConstraint = null; + XSSFDataValidation dataValidation = null; + + switch (dateType) + { + case ColumnDataType.Date: + case ColumnDataType.DateTime: + //因为DateTime类型,添加Validation报错,所以去掉 + dataStyle.DataFormat = dataFormat.GetFormat("yyyy-MM-dd HH:mm:ss"); + break; + case ColumnDataType.Number: + this.MinValueOrLength = string.IsNullOrEmpty(this.MinValueOrLength) ? long.MinValue.ToString() : this.MinValueOrLength; + this.MaxValuseOrLength = string.IsNullOrEmpty(this.MaxValuseOrLength) ? long.MaxValue.ToString() : this.MaxValuseOrLength; + dvConstraint = (XSSFDataValidationConstraint)dvHelper.CreateNumericConstraint(ValidationType.INTEGER, OperatorType.BETWEEN, this.MinValueOrLength, this.MaxValuseOrLength); + dataValidation = (XSSFDataValidation)dvHelper.CreateValidation(dvConstraint, CellRangeList); + dataValidation.CreateErrorBox(CoreProgram._localizer?["Sys.Error"], CoreProgram._localizer?["Sys.PleaseInputNumber"]); + dataStyle.DataFormat = dataFormat.GetFormat("0"); + dataValidation.CreatePromptBox(CoreProgram._localizer?["Sys.PleaseInputNumberFormat"], CoreProgram._localizer?["Sys.DataRange", MinValueOrLength, MaxValuseOrLength]); + break; + case ColumnDataType.Float: + this.MinValueOrLength = string.IsNullOrEmpty(this.MinValueOrLength) ? decimal.MinValue.ToString() : this.MinValueOrLength; + this.MaxValuseOrLength = string.IsNullOrEmpty(this.MaxValuseOrLength) ? decimal.MaxValue.ToString() : this.MaxValuseOrLength; + dvConstraint = (XSSFDataValidationConstraint)dvHelper.CreateNumericConstraint(ValidationType.DECIMAL, OperatorType.BETWEEN, this.MinValueOrLength, this.MaxValuseOrLength); + dataValidation = (XSSFDataValidation)dvHelper.CreateValidation(dvConstraint, CellRangeList); + dataValidation.CreateErrorBox(CoreProgram._localizer?["Sys.Error"], CoreProgram._localizer?["Sys.PleaseInputDecimal"]); + dataStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00"); + dataValidation.CreatePromptBox(CoreProgram._localizer?["Sys.PleaseInputDecimalFormat"], CoreProgram._localizer?["Sys.DataRange", MinValueOrLength, MaxValuseOrLength]); + break; + case ColumnDataType.Bool: + dvConstraint = (XSSFDataValidationConstraint)dvHelper.CreateFormulaListConstraint("Sheet1!$A$1:$B$1"); + dataValidation = (XSSFDataValidation)dvHelper.CreateValidation(dvConstraint, CellRangeList); + dataValidation.CreateErrorBox(CoreProgram._localizer?["Sys.Error"], CoreProgram._localizer?["Sys.PleaseInputExistData"]); + dataValidation.CreatePromptBox(CoreProgram._localizer?["Sys.ComboBox"], CoreProgram._localizer?["Sys.PleaseInputExistData"]); + break; + case ColumnDataType.Text: + this.MinValueOrLength = string.IsNullOrEmpty(this.MinValueOrLength) ? "0" : this.MinValueOrLength; + this.MaxValuseOrLength = string.IsNullOrEmpty(this.MaxValuseOrLength) ? "2000" : this.MaxValuseOrLength; + dvConstraint = (XSSFDataValidationConstraint)dvHelper.CreateNumericConstraint(ValidationType.TEXT_LENGTH, OperatorType.BETWEEN, this.MinValueOrLength, this.MaxValuseOrLength); + dataValidation = (XSSFDataValidation)dvHelper.CreateValidation(dvConstraint, CellRangeList); + dataValidation.CreateErrorBox(CoreProgram._localizer?["Sys.Error"], CoreProgram._localizer?["Sys.WrongTextLength"]); + dataStyle.DataFormat = dataFormat.GetFormat("@"); + dataValidation.CreatePromptBox(CoreProgram._localizer?["Sys.PleaseInputText"], CoreProgram._localizer?["Sys.DataRange", MinValueOrLength, MaxValuseOrLength]); + break; + case ColumnDataType.ComboBox: + case ColumnDataType.Enum: + int count = this.ListItems.Count() == 0 ? 1 : this.ListItems.Count(); + string cloIndex = ""; + if (porpetyIndex > 25) + { + cloIndex += Convert.ToChar((int)(Math.Floor(porpetyIndex / 26d)) - 1 + 65); + } + cloIndex += Convert.ToChar(65 + porpetyIndex % 26).ToString(); + IName range = sheet.Workbook.CreateName(); + range.RefersToFormula = "Sheet2!$" + cloIndex + "$1:$" + cloIndex + "$" + count; + range.NameName = "dicRange" + porpetyIndex; + dvConstraint = (XSSFDataValidationConstraint)dvHelper.CreateFormulaListConstraint("dicRange" + porpetyIndex); + dataValidation = (XSSFDataValidation)dvHelper.CreateValidation(dvConstraint, CellRangeList); + dataValidation.CreateErrorBox(CoreProgram._localizer?["Sys.Error"], CoreProgram._localizer?["Sys.PleaseInputExistData"]); + var listItemsTemp = this.ListItems.ToList(); + for (int rowIndex = 0; rowIndex < this.ListItems.Count(); rowIndex++) + { + IRow dataSheetRow = dataSheet.GetRow(rowIndex); + if (dataSheetRow == null) + { + dataSheetRow = dataSheet.CreateRow(rowIndex); + } + dataSheetRow.CreateCell(porpetyIndex).SetCellValue(listItemsTemp[rowIndex].Text); + dataStyle.DataFormat = dataFormat.GetFormat("@"); + dataSheetRow.Cells.Where(x => x.ColumnIndex == porpetyIndex).FirstOrDefault().CellStyle = dataStyle; + } + dataValidation.CreatePromptBox(CoreProgram._localizer?["Sys.ComboBox"], CoreProgram._localizer?["Sys.PleaseInputExistData"]); + break; + default: + dvConstraint = (XSSFDataValidationConstraint)dvHelper.CreateNumericConstraint(ValidationType.TEXT_LENGTH, OperatorType.BETWEEN, this.MinValueOrLength, this.MaxValuseOrLength); + dataValidation = (XSSFDataValidation)dvHelper.CreateValidation(dvConstraint, CellRangeList); + dataValidation.CreateErrorBox(CoreProgram._localizer?["Sys.Error"], CoreProgram._localizer?["Sys.WrongTextLength"]); + dataStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@"); + break; + } + if (dataValidation == null) + { + return; + } + if (!this.IsNullAble) + { + dataValidation.EmptyCellAllowed = false; + } + sheet.SetDefaultColumnStyle(porpetyIndex, dataStyle); + dataValidation.ShowErrorBox = true; + sheet.AddValidationData(dataValidation); + } + #endregion + + #region 验证Excel数据 + /// + /// 验证Value 并生成错误信息(edit by dufei 2014-06-12,修改了当列设置为不验证时候,下拉列表获取不到值的问题) + /// + /// + /// + /// + public void ValueValidity(string value, List errorMessage, int rowIndex) + { + if (this.IsNullAble && string.IsNullOrEmpty(value)) + { + this.Value = value; + } + else + { + ErrorMessage err = null; + switch (this.DataType) + { + case ColumnDataType.Date: + case ColumnDataType.DateTime: + DateTime tryDateTimeResult; + if (!DateTime.TryParse(value, out tryDateTimeResult)) + { + err = new ErrorMessage { Index = rowIndex, Message = CoreProgram._localizer?["Sys.{0}formaterror", this.ColumnName] }; + } + this.Value = tryDateTimeResult; + break; + case ColumnDataType.Number: + int tryIntResult; + if (!int.TryParse(value, out tryIntResult)) + { + err = new ErrorMessage { Index = rowIndex, Message = CoreProgram._localizer?["Sys.{0}formaterror", this.ColumnName] }; + } + this.Value = tryIntResult; + break; + case ColumnDataType.Float: + decimal tryDecimalResult; + if (!decimal.TryParse(value, out tryDecimalResult)) + { + err = new ErrorMessage { Index = rowIndex, Message = CoreProgram._localizer?["Sys.{0}formaterror", this.ColumnName] }; + } + this.Value = tryDecimalResult; + break; + case ColumnDataType.Bool: + if (value == CoreProgram._localizer?["Sys.Yes"]) + { + this.Value = true; + } + else if (value == CoreProgram._localizer?["Sys.No"]) + { + this.Value = false; + } + else + { + err = new ErrorMessage { Index = rowIndex, Message = CoreProgram._localizer?["Sys.{0}formaterror", this.ColumnName] }; + } + break; + case ColumnDataType.Text: + this.Value = value; + break; + case ColumnDataType.ComboBox: + case ColumnDataType.Enum: + if (!this.ListItems.Any(x => x.Text == value)) + { + err = new ErrorMessage { Index = rowIndex, Message = CoreProgram._localizer?["Sys.{0}ValueNotExist", this.ColumnName] }; + } + else + { + this.Value = this.ListItems.Where(x => x.Text == value).FirstOrDefault().Value; + } + break; + default: + err = new ErrorMessage { Index = rowIndex, Message = CoreProgram._localizer?["Sys.{0}ValueTypeNotAllowed", this.ColumnName] }; + break; + } + + if (err != null && this.SubTableType == null) + { + errorMessage.Add(err); + } + } + } + #endregion + + #region 自定义委托处理excel数据 + /// + /// 处理为多列数据 + /// + public CopyData FormatData; + /// + /// 处理为单列数据 + /// + public CopySingleData FormatSingleData; + + #endregion + + public static ExcelPropety CreateProperty(Expression> field, bool isDateTime = false) + { + ExcelPropety cp = new ExcelPropety(); + cp.FieldDisplayName = field.GetPropertyDisplayName(); + var fname = field.GetPropertyName(); + Type t = field.GetPropertyInfo().PropertyType; + if (fname.Contains('.')) + { + int index = fname.LastIndexOf('.'); + cp.FieldName = fname.Substring(index + 1); + cp.SubTableType = field.GetPropertyInfo().DeclaringType; + } + else + { + cp.FieldName = fname; + } + if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + var req = field.GetPropertyInfo().GetCustomAttributes(typeof(RequiredAttribute), false).Cast().FirstOrDefault(); + if (req == null) + { + cp.IsNullAble = true; + } + t = t.GenericTypeArguments[0]; + } + if (t == typeof(int) || t == typeof(long) || t == typeof(short)) + { + var sl = t.GetCustomAttributes(typeof(RangeAttribute), false).Cast().FirstOrDefault(); + cp.DataType = ColumnDataType.Number; + if (sl != null) + { + if (sl.Maximum != null) + { + cp.MaxValuseOrLength = sl.Maximum.ToString(); + } + if (sl.Minimum != null) + { + cp.MinValueOrLength = sl.Minimum.ToString(); + } + } + } + else if (t == typeof(float) || t == typeof(double) || t == typeof(decimal)) + { + cp.DataType = ColumnDataType.Float; + } + else if (t == typeof(bool)) + { + cp.DataType = ColumnDataType.Bool; + } + else if (t.IsEnum) + { + cp.DataType = ColumnDataType.Enum; + cp.EnumType = t; + } + else if (t == typeof(DateTime)) + { + cp.DataType = ColumnDataType.Date; + if (isDateTime) + cp.DataType = ColumnDataType.DateTime; + } + else + { + var sl = field.GetPropertyInfo().GetCustomAttributes(typeof(StringLengthAttribute), false).Cast().FirstOrDefault(); + var req = field.GetPropertyInfo().GetCustomAttributes(typeof(RequiredAttribute), false).Cast().FirstOrDefault(); + cp.DataType = ColumnDataType.Text; + if (req == null) + { + cp.IsNullAble = true; + } + if (sl != null) + { + if (sl.MaximumLength != 0) + { + cp.MaxValuseOrLength = sl.MaximumLength + ""; + } + if (sl.MinimumLength != 0) + { + cp.MinValueOrLength = sl.MinimumLength + ""; + } + } + } + cp.CharCount = 20; + return cp; + } + + } + + #region 辅助类型 + + /// + /// 定义处理excel为单个字段的委托 + /// + /// excel中的值 + /// excel中的值 + /// 实体的值 + /// 错误消息,没有错误为空 + public delegate void CopySingleData(object excelValue, BaseTemplateVM excelTemplate, out string entityValue, out string errorMsg); + /// + /// 定义处理excel为多个字段的委托 + /// + /// excel中的值 + /// excel中的值 + /// 返回的处理结果 + public delegate ProcessResult CopyData(object excelValue, BaseTemplateVM excelTemplate); + + /// + /// 处理结果 + /// + public class ProcessResult + { + public List EntityValues { get; set; } + public ProcessResult() + { + EntityValues = new List(); + } + } + + /// + /// 单字段类 + /// + public class EntityValue + { + /// + /// 字段名称 + /// + public string FieldName { get; set; } + /// + /// 字段值 + /// + public string FieldValue { get; set; } + /// + /// 错误消息 + /// + public string ErrorMsg { get; set; } + } + + public enum ColumnDataType { Text, Number, Date, Float, Bool, ComboBox, Enum, Dynamic, DateTime } + + #endregion +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ExpressionVisitors.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ExpressionVisitors.cs new file mode 100644 index 0000000..cffe9a0 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ExpressionVisitors.cs @@ -0,0 +1,676 @@ +using Microsoft.EntityFrameworkCore.Query; +using Microsoft.EntityFrameworkCore.Query.Internal; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// 分析x==y这种类型的表达式,并储存在Dictionary中 + /// + public class SetValuesParser : ExpressionVisitor + { + private Dictionary _rv = new Dictionary(); + + /// + /// 开始分析表达式 + /// + /// 源表达式 + /// 将x==y这种表达式变为Dictionary并返回 + public Dictionary Parse(Expression expression) + { + Visit(expression); + return _rv; + } + + /// + /// 处理所有二进制类型的表达式 + /// + /// 当前表达式节点 + /// 修改后的表达式 + protected override Expression VisitBinary(BinaryExpression node) + { + //如果表达式是x==y的类型,则获取y的值,并使用x最为key,y的值作为value添加到Dictionary中保存 + if (node.NodeType == ExpressionType.Equal) + { + var pi = PropertyHelper.GetPropertyName(node.Left.NodeType == ExpressionType.Convert ? ((UnaryExpression)node.Left).Operand : node.Left); + if (!_rv.ContainsKey(pi)) + { + _rv.Add(pi, Expression.Lambda(node.Right).Compile().DynamicInvoke()); + } + } + return base.VisitBinary(node); + } + } + + /// + /// 替换表达式中的OrderBy语句 + /// + public class OrderReplaceModifier : ExpressionVisitor + { + private bool _addMode = false; + private SortInfo _sortinfo; + + /// + /// 构造函数 + /// + /// sortinfo + public OrderReplaceModifier(SortInfo sortinfo) + { + _sortinfo = sortinfo; + } + + /// + /// 修改where + /// + /// 表达式 + /// 修改后的表达式 + public Expression Modify(Expression expression) + { + //先调用一次Visit,删除所有的where表达式 + var rv = Visit(expression); + if ((rv is QueryRootExpression) || rv.Type.IsGeneric(typeof(EnumerableQuery<>))) + { + var modelType = rv.Type.GenericTypeArguments[0]; + ParameterExpression pe = Expression.Parameter(modelType, "x"); + Expression left1 = Expression.Constant(1); + Expression right1 = Expression.Constant(1); + Expression trueExp = Expression.Equal(left1, right1); + rv = Expression.Call( +typeof(Queryable), +"Where", +new Type[] { modelType }, +rv, +Expression.Lambda(trueExp, new ParameterExpression[] { pe })); + + } + //将模式设为addMode,再调用一次Visit来添加新的表达式 + _addMode = true; + rv = Visit(rv); + return rv; + } + + /// + /// 向表达式树上层寻找不是where的节点 + /// + /// 表达式 + /// 返回表达式上层第一个不是where的节点 + private Expression GetParentExpNotOrder(MethodCallExpression exp) + { + var parentNode = exp.Arguments[0] as MethodCallExpression; + if (parentNode == null || (parentNode.Method.Name.ToLower() != "orderby" && parentNode.Method.Name.ToLower() != "orderbydescending")) + { + if (parentNode == null) + { + return exp.Arguments[0]; + } + return parentNode; + } + else + { + return GetParentExpNotOrder(parentNode); + } + } + + /// + /// 检查方法调用类型的表达式 + /// + /// 表达式节点 + /// 修改后的表达式 + protected override Expression VisitMethodCall(MethodCallExpression node) + { + //如果不是添加模式,那么删除所有的order + if (_addMode == false) + { + var aType = node.Arguments[0].Type; + //如果节点是order + if (node != null && (node.Method.Name.ToLower() == "orderby" || node.Method.Name.ToLower() == "orderbydescending" || node.Method.Name.ToLower() == "thenby" || node.Method.Name.ToLower() == "thenbydescending") && aType.GetTypeInfo().IsGenericType) + { + //继续往上找到不是where的节点 + return GetParentExpNotOrder(node); + } + } + //如果是添加模式 + else + { + var modelType = node.Type.GenericTypeArguments[0]; + List info = new List() { _sortinfo }; + Expression rv = null; + foreach (var item in info) + { + var idproperty = modelType.GetSingleProperty(item.Property); + if (idproperty == null) + { + return node; + } + var reftype = idproperty.DeclaringType; + ParameterExpression pe = Expression.Parameter(modelType, "x"); + Expression pro = Expression.Property(pe, reftype.GetSingleProperty(item.Property)); + Type proType = idproperty.PropertyType; + if (item.Direction == SortDir.Asc) + { + if (rv == null) + { + rv = Expression.Call( + typeof(Queryable), + "OrderBy", + new Type[] { modelType, proType }, + node, + Expression.Lambda(pro, new ParameterExpression[] { pe })); + } + else + { + rv = Expression.Call( + typeof(Queryable), + "ThenBy", + new Type[] { modelType, proType }, + rv, + Expression.Lambda(pro, new ParameterExpression[] { pe })); + } + } + if (item.Direction == SortDir.Desc) + { + if (rv == null) + { + rv = Expression.Call( + typeof(Queryable), + "OrderByDescending", + new Type[] { modelType, proType }, + node, + Expression.Lambda(pro, new ParameterExpression[] { pe })); + } + else + { + rv = Expression.Call( + typeof(Queryable), + "ThenByDescending", + new Type[] { modelType, proType }, + rv, + Expression.Lambda(pro, new ParameterExpression[] { pe })); + } + } + } + return rv; + + } + return base.VisitMethodCall(node); + } + } + + + /// + /// 替换表达式中的Where语句 + /// + public class WhereReplaceModifier : ExpressionVisitor where T : TopBasePoco + { + private Type _modelType; + private bool _addMode = false; + private Expression> _where; + + /// + /// 构造函数 + /// + /// 需要替换的新where语句 + public WhereReplaceModifier(Expression> where) + { + _where = where; + } + + /// + /// 获取表达式的源数据类 + /// + /// 表达式 + /// 表达式的源数据类型 + private Type GetDCModel(Expression expression) + { + //如果表达式是方法调用的类型,则一直向上寻找,知道找到参数为ObjectQuery<>的表达式,它的类型就是整个表达式的源数据类型 + if (expression.NodeType == ExpressionType.Call) + { + var exp = (expression as MethodCallExpression).Arguments[0]; + if (exp is QueryRootExpression) + { + return exp.Type.GenericTypeArguments[0]; + } + else + { + return GetDCModel(exp); + } + } + else if (expression.NodeType == ExpressionType.Constant) + { + if (expression is QueryRootExpression || expression.Type.IsGeneric(typeof(EnumerableQuery<>))) + { + return expression.Type.GenericTypeArguments[0]; + } + else + { + return null; + } + } + else + { + return null; + } + } + + /// + /// 修改where + /// + /// 表达式 + /// 修改后的表达式 + public Expression Modify(Expression expression) + { + //获取源类型 + var checkType = GetDCModel(expression); + + if (checkType != null) + { + _modelType = checkType; + //先调用一次Visit,删除所有的where表达式 + var rv = Visit(expression); + //将模式设为addMode,再调用一次Visit来添加新的表达式 + _addMode = true; + rv = Visit(rv); + return rv; + } + else + { + return expression; + } + } + + /// + /// 向表达式树上层寻找不是where的节点 + /// + /// 表达式 + /// 返回表达式上层第一个不是where的节点 + private Expression GetParentExpNotWhere(MethodCallExpression exp) + { + if (!(exp.Arguments[0] is MethodCallExpression parentNode)) + { + return exp.Arguments[0]; + } + else if (parentNode.Method.Name.ToLower() != "where") + { + return parentNode; + } + else + { + return GetParentExpNotWhere(parentNode); + } + } + + protected override Expression VisitExtension(Expression node) + { + if (_addMode == true && node is QueryRootExpression) + { + if (node.Type.GenericTypeArguments[0] == _modelType) + { + ParameterExpression pe = Expression.Parameter(_modelType); + ChangePara cp = new ChangePara(); + //传递过来的where条件,其源类型不一定和表达式中原有的相符,所以先将新where条件的源类型修改成和query一样的 + //也就是说新的where条件可能是 x=>x.id==1, 而在表达式中不一定有x,所以要先统一 + var modifiedWhere = cp.Change(_where.Body, pe); + var rv = Expression.Call( + typeof(Queryable), + "Where", + new Type[] { _modelType }, + node, + Expression.Lambda(modifiedWhere, new ParameterExpression[] { pe })); + return rv; + } + } + return base.VisitExtension(node); + } + + /// + /// 检查方法调用类型的表达式 + /// + /// 表达式节点 + /// 修改后的表达式 + protected override Expression VisitMethodCall(MethodCallExpression node) + { + //如果不是添加模式,那么删除所有的where条件 + if (_addMode == false) + { + if (node.Arguments.Count == 0) + { + return base.VisitMethodCall(node); + } + var aType = node.Arguments[0].Type; + //如果节点的上一个节点是where + if (node.Arguments[0] is MethodCallExpression parentNode && parentNode.Method.Name.ToLower() == "where" && aType.GetTypeInfo().IsGenericType) + { + //继续往上找到不是where的节点 + var nowhereNode = GetParentExpNotWhere(parentNode); + Type gType = aType.GetGenericTypeDefinition(); + Type argType = aType.GenericTypeArguments[0]; + //使用上面不是where的节点直接拼接本节点,从而删除了中间的where + if ((gType == typeof(IQueryable<>) || gType == typeof(QueryRootExpression)) && argType == _modelType) + { + var paras = new List + { + nowhereNode + }; + paras.AddRange(node.Arguments.Skip(1).ToList()); + var rv = Expression.Call( + node.Method, + paras); + return rv; + } + } + } + return base.VisitMethodCall(node); + } + } + + /// + /// 用于PersistPoco的搜索,检查查询语句中是否有IsValid的搜索条件,如果没有,默认加上IsValid=true + /// + public class IsValidModifier : ExpressionVisitor + { + private Type _modelType; + private bool _needAdd = true; + private int _mode = 0; //0是搜素模式,1是添加模式 + private Expression> _where; + + /// + /// 构造函数 + /// + public IsValidModifier() + { + _where = x => x.IsValid == true; + } + + /// + /// 获取表达式的源数据类 + /// + /// 表达式 + /// 表达式的源数据类型 + private Type GetDCModel(Expression expression) + { + //如果表达式是方法调用的类型,则一直向上寻找,知道找到参数为ObjectQuery<>的表达式,它的类型就是整个表达式的源数据类型 + if (expression.NodeType == ExpressionType.Call) + { + var exp = (expression as MethodCallExpression).Arguments[0]; + if (exp is QueryRootExpression) + { + return exp.Type.GenericTypeArguments[0]; + } + else + { + return GetDCModel(exp); + } + } + else if (expression.NodeType == ExpressionType.Constant) + { + if (expression is QueryRootExpression || expression.Type.IsGeneric(typeof(EnumerableQuery<>))) + { + return expression.Type.GenericTypeArguments[0]; + } + else + { + return null; + } + } + else + { + return null; + } + } + + /// + /// 修改where + /// + /// 表达式 + /// 修改后的表达式 + public Expression Modify(Expression expression) + { + //获取源类型 + var checkType = GetDCModel(expression); + + if (checkType != null && typeof(IPersistPoco).IsAssignableFrom( checkType)) + { + _modelType = checkType; + //先调用一次Visit,删除所有的where表达式 + var rv = Visit(expression); + //将模式设为addMode,再调用一次Visit来添加新的表达式 + if (_needAdd == true) + { + _mode = 1; + rv = Visit(rv); + } + return rv; + } + else + { + return expression; + } + } + + /// + /// 向表达式树上层寻找不是where的节点 + /// + /// 表达式 + /// 返回表达式上层第一个不是where的节点 + private Expression GetParentExpNotWhere(MethodCallExpression exp) + { + if (!(exp.Arguments[0] is MethodCallExpression parentNode)) + { + return exp.Arguments[0]; + } + else if (parentNode.Method.Name.ToLower() != "where") + { + return parentNode; + } + else + { + return GetParentExpNotWhere(parentNode); + } + } + + protected override Expression VisitExtension(Expression node) + { + if (_mode == 1 && node is QueryRootExpression) + { + if (node.Type.GenericTypeArguments[0] == _modelType) + { + ParameterExpression pe = Expression.Parameter(_modelType); + ChangePara cp = new ChangePara(); + //传递过来的where条件,其源类型不一定和表达式中原有的相符,所以先将新where条件的源类型修改成和query一样的 + //也就是说新的where条件可能是 x=>x.id==1, 而在表达式中不一定有x,所以要先统一 + var modifiedWhere = cp.Change(_where.Body, pe); + var rv = Expression.Call( + typeof(Queryable), + "Where", + new Type[] { _modelType }, + node, + Expression.Lambda(modifiedWhere, new ParameterExpression[] { pe })); + return rv; + } + } + return base.VisitExtension(node); + } + + /// + /// 查找where中是否出现过对于IsValid的判断 + /// + /// + /// + protected override Expression VisitBinary(BinaryExpression node) + { + //如果表达式是x==y的类型,则获取y的值,并使用x最为key,y的值作为value添加到Dictionary中保存 + if (_mode == 0) + { + if (node.NodeType == ExpressionType.Equal) + { + var pi = PropertyHelper.GetPropertyName(node.Left); + if (pi.ToLower() == "isvalid") + { + _needAdd = false; + } + } + } + return base.VisitBinary(node); + } + + } + + + /// + /// 修改表达式参数 + /// + public class ChangePara : ExpressionVisitor + { + ParameterExpression _pe; + + /// + /// 修改参数 + /// + /// 要修改的表达式 + /// 新的参数 + /// 修改后的表达式 + public Expression Change(Expression expression, ParameterExpression pe) + { + _pe = pe; + return Visit(expression); + } + + /// + /// 检查所有参数类型的表达式 + /// + /// 表达式节点 + /// 新的参数类型 + protected override Expression VisitParameter(ParameterExpression node) + { + return _pe; + } + + /// + /// 检查所有成员访问类型的表达式 + /// + /// 表达式节点 + /// 修改后的表达式 + protected override Expression VisitMember(MemberExpression node) + { + if (node.Expression.NodeType == ExpressionType.Parameter) + { + var rv = Expression.MakeMemberAccess(_pe, node.Member); + return rv; + } + else + { + return base.VisitMember(node); + } + } + } + + /// + /// 获取Select语句中选择的列的信息 + /// + public class SelectInfo : ExpressionVisitor + { + private List _columns; + private bool _found; + /// + /// 构造函数 + /// + public SelectInfo() + { + } + + /// + /// 获取Select语句中选择的列的名字 + /// + /// 表达式 + /// 列的名字 + public List GetColumns(Expression expression) + { + Visit(expression); + return _columns; + } + + + /// + /// 检查方法调用类型的表达式 + /// + /// 表达式节点 + /// 修改后的表达式 + protected override Expression VisitMethodCall(MethodCallExpression node) + { + if (_found == false) + { + if (node.Method.Name.ToLower() == "select") + { + if (node.Arguments[1] is UnaryExpression ue) + { + var inner = ue.Operand as LambdaExpression; + if (inner.Body is MemberInitExpression memberinit) + { + _columns = new List(); + foreach (var m in memberinit.Bindings) + { + _columns.Add(m.Member.Name); + } + _found = true; + } + } + } + } + return base.VisitMethodCall(node); + } + } + + public class ClearSelectMany : ExpressionVisitor + { + /// + /// 构造函数 + /// + public ClearSelectMany() + { + } + + /// + /// 获取Select语句中选择的列的名字 + /// + /// 表达式 + /// 列的名字 + public Expression Clear(Expression expression) + { + return Visit(expression); + } + + protected override Expression VisitMemberInit(MemberInitExpression node) + { + List newbinding = new List(); + for (int i = 0; i < node.Bindings.Count; i++) + { + bool islist = false; + if (node.Bindings[i] is MemberAssignment ma && ma.Expression.Type.GetTypeInfo().IsGenericType == true) + { + if (ma.Expression.Type.GetGenericTypeDefinition() != typeof(Nullable<>)) + { + islist = true; + } + } + if (islist == false) + { + newbinding.Add(node.Bindings[i]); + } + } + if (newbinding.Count < node.Bindings.Count) + { + return node.Update(node.NewExpression, newbinding); + } + else + { + return base.VisitMemberInit(node); + } + } + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ExtraClass.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ExtraClass.cs new file mode 100644 index 0000000..8f1ffd2 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ExtraClass.cs @@ -0,0 +1,68 @@ +using System.Collections.Generic; +using System.Linq; +using System.Net; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// 简单属性结构类 + /// + public class SimpleTreeTextAndValue + { + + public object Id { get; set; } + public object Text { get; set; } + public object ParentId { get; set; } + } + + /// + /// 简单键值对类,用来存著生成下拉菜单的数据 + /// + public class SimpleTextAndValue + { + public object Text { get; set; } + public object Value { get; set; } + } + + /// + /// 数据库排序类 + /// + public class SortInfo + { + public string Property { get; set; } + public SortDir Direction { get; set; } + } + + public class ApiResult + { + public T Data { get; set; } + public HttpStatusCode? StatusCode { get; set; } + public ErrorObj Errors { get; set; } + public string ErrorMsg { get; set; } + + public ApiResult() + { + Data = default(T); + } + } + + public class ErrorObj + { + public Dictionary Form { get; set; } + public List Message { get; set; } + + public string GetFirstError() + { + if(Message != null && Message.Any()) + { + return Message.First(); + } + if(Form != null && Form.Any()) + { + return Form.First().Value; + } + return ""; + } + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/IWtmFileHandler.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/IWtmFileHandler.cs new file mode 100644 index 0000000..ec2a145 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/IWtmFileHandler.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using WalkingTec.Mvvm.Core.Models; + +namespace WalkingTec.Mvvm.Core.Support.FileHandlers +{ + public interface IWtmFileHandler + { + (string path,string handlerInfo) Upload(string fileName, long fileLength, Stream data, string group=null, string subdir=null, string extra=null); + Stream GetFileData(IWtmFile file); + + void DeleteFile(IWtmFile file); + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/WtmDataBaseFileHandler.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/WtmDataBaseFileHandler.cs new file mode 100644 index 0000000..45a7bf3 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/WtmDataBaseFileHandler.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.IO; +using System.Linq; +using System.Text; +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Core.Models; + +namespace WalkingTec.Mvvm.Core.Support.FileHandlers +{ + [Display(Name = "database")] + public class WtmDataBaseFileHandler : WtmFileHandlerBase + { + private static string _modeName = "database"; + + public WtmDataBaseFileHandler(Configs config, IDataContext dc) : base(config, dc) + { + } + + public override Stream GetFileData(IWtmFile file) + { + var rv = _dc.Set().CheckID(file.GetID()).FirstOrDefault(); + if (rv != null) + { + return new MemoryStream((rv as FileAttachment).FileData); + } + return null; + } + + + public IWtmFile UploadToDB(string fileName, long fileLength, Stream data, string groupName = null, string subdir = null, string extra = null) + { + FileAttachment file = new FileAttachment(); + file.FileName = fileName; + file.Length = fileLength; + file.UploadTime = DateTime.Now; + file.SaveMode = _modeName; + file.ExtraInfo = extra; + var ext = string.Empty; + if (string.IsNullOrEmpty(fileName) == false) + { + var dotPos = fileName.LastIndexOf('.'); + ext = fileName.Substring(dotPos + 1); + } + file.FileExt = ext; + using (var dataStream = new MemoryStream()) + { + data.CopyTo(dataStream); + file.FileData = dataStream.ToArray(); + } + _dc.AddEntity(file); + _dc.SaveChanges(); + return file; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/WtmFileHandlerBase.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/WtmFileHandlerBase.cs new file mode 100644 index 0000000..363bab8 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/WtmFileHandlerBase.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Microsoft.EntityFrameworkCore; +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Core.Models; + +namespace WalkingTec.Mvvm.Core.Support.FileHandlers +{ + public abstract class WtmFileHandlerBase : IWtmFileHandler + { + protected Configs _config; + protected IDataContext _dc; + + public WtmFileHandlerBase(Configs config, IDataContext dc) + { + _config = config; + _dc = dc; + if (_dc == null) + { + _dc = _config.CreateDC(); + } + } + + + public virtual void DeleteFile(IWtmFile file) + { + } + + public virtual Stream GetFileData(IWtmFile file) + { + return null; + } + + public virtual (string path, string handlerInfo) Upload(string fileName, long fileLength, Stream data, string group=null, string subdir = null, string extra=null) + { + return ("", ""); + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/WtmFileProvider.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/WtmFileProvider.cs new file mode 100644 index 0000000..0e67060 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/WtmFileProvider.cs @@ -0,0 +1,205 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using Microsoft.Extensions.Options; +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Core.Models; + +namespace WalkingTec.Mvvm.Core.Support.FileHandlers +{ + public class WtmFileProvider + { + public string SaveMode { get; set; } + private static Dictionary _handlers; + private static ConstructorInfo _defaultHandler; + private WTMContext _wtm; + public static Func _subDirFunc; + + public WtmFileProvider(WTMContext wtm) + { + _wtm = wtm; + } + + public static void Init(Configs config, GlobalData gd) + { + _handlers = new Dictionary(); + var types = gd.GetTypesAssignableFrom(); + int count = 1; + foreach (var item in types) + { + var cons = item.GetConstructor(new Type[] { typeof(Configs), typeof(IDataContext) }); + var nameattr = item.GetCustomAttribute(); + string name = ""; + if (nameattr == null) + { + name = "FileHandler" + count; + count++; + } + else + { + name = nameattr.Name; + } + name = name.ToLower(); + if (name == config.FileUploadOptions.SaveFileMode.ToString().ToLower()) + { + _defaultHandler = cons; + } + _handlers.Add(name, cons); + } + if (_defaultHandler == null && types.Count > 0) + { + _defaultHandler = types[0].GetConstructor(new Type[] { typeof(Configs), typeof(IDataContext) }); + } + + } + + public IWtmFileHandler CreateFileHandler(string saveMode = null, IDataContext dc = null) + { + ConstructorInfo ci = null; + if(dc == null) + { + dc = _wtm.CreateDC(); + } + if (string.IsNullOrEmpty(saveMode)) + { + ci = _defaultHandler; + } + else + { + saveMode = saveMode.ToLower(); + if (_handlers.ContainsKey(saveMode)) + { + ci = _handlers[saveMode]; + } + } + if (ci == null) + { + return new WtmDataBaseFileHandler(_wtm.ConfigInfo, dc); + } + else + { + return ci.Invoke(new object[] { _wtm.ConfigInfo, dc }) as IWtmFileHandler; + } + } + + public IWtmFile Upload(string fileName, long fileLength, Stream data, string group = null, string subdir = null, string extra = null, string saveMode = null, IDataContext dc =null) + { + if (dc == null) + { + dc = _wtm.CreateDC(); + } + var fh = CreateFileHandler(saveMode, dc); + if (fh is WtmDataBaseFileHandler lfh) + { + return lfh.UploadToDB(fileName, fileLength, data, group, subdir, extra); + } + else + { + var rv = fh.Upload(fileName, fileLength, data, group, subdir, extra); + if (string.IsNullOrEmpty(rv.path) == false) + { + FileAttachment file = new FileAttachment(); + file.FileName = fileName; + file.Length = fileLength; + file.UploadTime = DateTime.Now; + file.SaveMode = string.IsNullOrEmpty(saveMode) == true ? _wtm.ConfigInfo.FileUploadOptions.SaveFileMode : saveMode; + file.ExtraInfo = extra; + var ext = string.Empty; + if (string.IsNullOrEmpty(fileName) == false) + { + var dotPos = fileName.LastIndexOf('.'); + ext = fileName[(dotPos + 1)..]; + } + file.FileExt = ext; + file.Path = rv.path; + file.HandlerInfo = rv.handlerInfo; + dc.AddEntity(file); + dc.SaveChanges(); + return file; + } + else + { + return null; + } + } + } + + public IWtmFile GetFile(string id, bool withData = true, IDataContext dc = null) + { + IWtmFile rv; + if (dc == null) + { + dc = _wtm.CreateDC(); + } + rv = dc.Set().CheckID(id).Select(x => new FileAttachment + { + ID = x.ID, + ExtraInfo = x.ExtraInfo, + FileExt = x.FileExt, + FileName = x.FileName, + Length = x.Length, + Path = x.Path, + SaveMode = x.SaveMode, + UploadTime = x.UploadTime + }).FirstOrDefault(); + if (rv != null && withData == true) + { + var fh = CreateFileHandler(rv.SaveMode, dc); + rv.DataStream = fh.GetFileData(rv); + } + return rv; + + } + + public void DeleteFile(string id, IDataContext dc = null) + { + FileAttachment file = null; + if (dc == null) + { + dc = _wtm.CreateDC(); + } + file = dc.Set().CheckID(id) + .Select(x => new FileAttachment + { + ID = x.ID, + ExtraInfo = x.ExtraInfo, + FileExt = x.FileExt, + FileName = x.FileName, + Path = x.Path, + SaveMode = x.SaveMode, + Length = x.Length, + UploadTime = x.UploadTime + }) + .FirstOrDefault(); + if (file != null) + { + try + { + dc.Set().Remove(file); + dc.SaveChanges(); + var fh = CreateFileHandler(file.SaveMode, dc); + fh.DeleteFile(file); + } + catch { } + } + + } + + + public string GetFileName(string id, IDataContext dc = null) + { + string rv; + if (dc == null) + { + dc = _wtm.CreateDC(); + } + rv = dc.Set().CheckID(id).Select(x => x.FileName).FirstOrDefault(); + return rv; + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/WtmLocalFileHandler.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/WtmLocalFileHandler.cs new file mode 100644 index 0000000..a370451 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/WtmLocalFileHandler.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.IO; +using System.Linq; +using System.Text; +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Core.Models; + +namespace WalkingTec.Mvvm.Core.Support.FileHandlers +{ + + [Display(Name = "local")] + public class WtmLocalFileHandler : WtmFileHandlerBase + { + + public WtmLocalFileHandler(Configs config, IDataContext dc) : base(config, dc) + { + } + + public override Stream GetFileData(IWtmFile file) + { + return File.OpenRead(GetFullPath(file.Path)); + } + + + public override (string path, string handlerInfo) Upload(string fileName, long fileLength, Stream data, string group = null, string subdir = null, string extra = null) + { + var localSettings = _config.FileUploadOptions.Settings.Where(x => x.Key.ToLower() == "local").Select(x => x.Value).FirstOrDefault(); + + var groupdir = ""; + if (string.IsNullOrEmpty(group)) + { + groupdir = localSettings?.FirstOrDefault().GroupLocation; + } + else { + groupdir = localSettings?.Where(x => x.GroupName.ToLower() == group.ToLower()).FirstOrDefault().GroupLocation; + } + if (string.IsNullOrEmpty(groupdir)) + { + groupdir = "./uploads"; + } + string pathHeader = groupdir; + if (string.IsNullOrEmpty(subdir) == false) + { + pathHeader = Path.Combine(pathHeader, subdir); + } + else + { + var sub = WtmFileProvider._subDirFunc?.Invoke(this); + if(string.IsNullOrEmpty(sub)== false) + { + pathHeader = Path.Combine(pathHeader, sub); + } + } + string fulldir = GetFullPath(pathHeader); + if (!Directory.Exists(fulldir)) + { + Directory.CreateDirectory(fulldir); + } + var ext = string.Empty; + if (string.IsNullOrEmpty(fileName) == false) + { + var dotPos = fileName.LastIndexOf('.'); + ext = fileName.Substring(dotPos + 1); + } + var filename = $"{Guid.NewGuid().ToNoSplitString()}.{ext}"; + var fullPath = Path.Combine(fulldir, filename); + using (var fileStream = File.Create(fullPath)) + { + data.CopyTo(fileStream); + } + data.Dispose(); + return (Path.Combine(pathHeader, filename),""); + } + + public override void DeleteFile(IWtmFile file) + { + if (string.IsNullOrEmpty(file?.Path) == false) + { + try + { + File.Delete(GetFullPath(file?.Path)); + } + catch { } + } + } + + private string GetFullPath(string path) + { + string rv = ""; + if (path.StartsWith(".")) + { + rv = Path.Combine(_config.HostRoot, path); + } + else + { + rv = path; + } + rv = Path.GetFullPath(rv); + return rv ; + } + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/WtmOssFileHandler.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/WtmOssFileHandler.cs new file mode 100644 index 0000000..9db8ff4 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/FileHandlers/WtmOssFileHandler.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.IO; +using System.Linq; +using System.Text; +using Aliyun.OSS; +using WalkingTec.Mvvm.Core.ConfigOptions; +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Core.Models; + +namespace WalkingTec.Mvvm.Core.Support.FileHandlers +{ + + [Display(Name = "oss")] + public class WtmOssFileHandler : WtmFileHandlerBase + { + //private static string _modeName = "oss"; + + public WtmOssFileHandler(Configs config, IDataContext dc) : base(config, dc) + { + } + + public override Stream GetFileData(IWtmFile file) + { + var ossSettings = _config.FileUploadOptions.Settings.Where(x => x.Key.ToLower() == "oss").Select(x => x.Value).FirstOrDefault(); + FileHandlerOptions groupInfo = null; + if (string.IsNullOrEmpty(file.HandlerInfo)) + { + groupInfo = ossSettings?.FirstOrDefault(); + } + else + { + groupInfo = ossSettings?.Where(x => x.GroupName.ToLower() == file.HandlerInfo.ToLower()).FirstOrDefault(); + if (groupInfo == null) + { + groupInfo = ossSettings?.FirstOrDefault(); + } + } + if (groupInfo == null) + { + return null; + } + + OssClient client = new OssClient(groupInfo.ServerUrl, groupInfo.Key, groupInfo.Secret); + var rv = new MemoryStream(); + client.GetObject(new GetObjectRequest(groupInfo.GroupLocation, file.Path), rv); + rv.Position = 0; + return rv; + + } + + + public override (string path, string handlerInfo) Upload(string fileName, long fileLength, Stream data, string group = null, string subdir = null, string extra = null) + { + var ext = string.Empty; + if (string.IsNullOrEmpty(fileName) == false) + { + var dotPos = fileName.LastIndexOf('.'); + ext = fileName.Substring(dotPos + 1); + } + + var ossSettings = _config.FileUploadOptions.Settings.Where(x => x.Key.ToLower() == "oss").Select(x => x.Value).FirstOrDefault(); + FileHandlerOptions groupInfo = null; + if (string.IsNullOrEmpty(group)) + { + groupInfo = ossSettings?.FirstOrDefault(); + } + else + { + groupInfo = ossSettings?.Where(x => x.GroupName.ToLower() == group.ToLower()).FirstOrDefault(); + if (groupInfo == null) + { + groupInfo = ossSettings?.FirstOrDefault(); + } + } + if (groupInfo == null) + { + return (null,null); + } + + + string pathHeader = ""; + if (string.IsNullOrEmpty(subdir) == false) + { + pathHeader = Path.Combine(pathHeader, subdir); + } + else + { + var sub = WtmFileProvider._subDirFunc?.Invoke(this); + if (string.IsNullOrEmpty(sub) == false) + { + pathHeader = Path.Combine(pathHeader, sub); + } + } + var fullPath = Path.Combine(pathHeader, $"{Guid.NewGuid().ToNoSplitString()}.{ext}"); + fullPath = fullPath.Replace("\\", "/"); + OssClient client = new OssClient(groupInfo.ServerUrl, groupInfo.Key, groupInfo.Secret); + var result = client.PutObject(groupInfo.GroupLocation, fullPath, data); + if (result.HttpStatusCode == System.Net.HttpStatusCode.OK) + { + return (fullPath, groupInfo.GroupName); + } + else + { + return (null, null); + } + } + + public override void DeleteFile(IWtmFile file) + { + var ossSettings = _config.FileUploadOptions.Settings.Where(x => x.Key.ToLower() == "oss").Select(x => x.Value).FirstOrDefault(); + FileHandlerOptions groupInfo = null; + if (string.IsNullOrEmpty(file.HandlerInfo)) + { + groupInfo = ossSettings?.FirstOrDefault(); + } + else + { + groupInfo = ossSettings?.Where(x => x.GroupName.ToLower() == file.HandlerInfo.ToLower()).FirstOrDefault(); + if (groupInfo == null) + { + groupInfo = ossSettings?.FirstOrDefault(); + } + } + if (groupInfo == null) + { + return; + } + try + { + OssClient client = new OssClient(groupInfo.ServerUrl, groupInfo.Key, groupInfo.Secret); + client.DeleteObject(groupInfo.GroupLocation, file.Path); + } + catch { } + return; + } + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleAction.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleAction.cs new file mode 100644 index 0000000..50d969f --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleAction.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WalkingTec.Mvvm.Core.Support.Json +{ + public class SimpleAction + { + public Guid ID { get; set; } + public ActionDescriptionAttribute ActionDes { get; set; } + public string _name; + public string ActionName + { + get + { + if (ActionDes?._localizer != null && string.IsNullOrEmpty(ActionDes?.Description) == false) + { + return ActionDes._localizer[ActionDes.Description]; + } + else + { + return _name ?? ""; + } + } + set + { + _name = value; + } + } + + public string MethodName { get; set; } + + public Guid? ModuleId { get; set; } + + public SimpleModule Module { get; set; } + + public string Parameter { get; set; } + + public List ParasToRunTest { get; set; } + + public bool IgnorePrivillege { get; set; } + + private string _url; + public string Url + { + get + { + if (_url == null) + { + if (this.Module.Area != null) + { + _url = "/" + this.Module.Area.Prefix + "/" + this.Module.ClassName + "/" + this.MethodName; + } + else + { + _url = "/" + this.Module.ClassName + "/" + this.MethodName; + } + } + return _url; + } + set + { + _url = value; + } + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleArea.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleArea.cs new file mode 100644 index 0000000..98c17d2 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleArea.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WalkingTec.Mvvm.Core.Support.Json +{ + public class SimpleArea + { + public Guid ID { get; set; } + public string AreaName { get; set; } + public string Prefix { get; set; } + + public List Modules { get; set; } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleDataPri.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleDataPri.cs new file mode 100644 index 0000000..c87ccb8 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleDataPri.cs @@ -0,0 +1,19 @@ +using System; + +namespace WalkingTec.Mvvm.Core.Support.Json +{ + [Serializable] + public class SimpleDataPri + { + public Guid ID { get; set; } + + public string UserCode { get; set; } + public string GroupCode { get; set; } + + public string TableName { get; set; } + + public string RelateId { get; set; } + + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleFunctionPri.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleFunctionPri.cs new file mode 100644 index 0000000..47f3710 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleFunctionPri.cs @@ -0,0 +1,18 @@ +using System; + +namespace WalkingTec.Mvvm.Core.Support.Json +{ + [Serializable] + public class SimpleFunctionPri + { + public Guid ID { get; set; } + public string RoleCode{ get; set; } + + public Guid MenuItemId { get; set; } + + public string Url { get; set; } + + public bool? Allowed { get; set; } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleGroup.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleGroup.cs new file mode 100644 index 0000000..4d8ef35 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleGroup.cs @@ -0,0 +1,13 @@ +using System; + +namespace WalkingTec.Mvvm.Core.Support.Json +{ + [Serializable] + public class SimpleGroup + { + public Guid ID { get; set; } + public string GroupCode { get; set; } + public string GroupName { get; set; } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleLog.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleLog.cs new file mode 100644 index 0000000..af8687a --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleLog.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WalkingTec.Mvvm.Core.Support.Json +{ + + public class SimpleLog + { + + public ActionLog GetActionLog() + { + return new ActionLog + { + ActionName = this.ActionName, + ActionTime = this.ActionTime, + ActionUrl = this.ActionUrl, + CreateBy = this.CreateBy, + CreateTime = this.CreateTime, + Duration = this.Duration, + IP = this.IP, + ITCode = this.ITCode, + LogType = this.LogType, + ModuleName = this.ModuleName, + Remark = this.Remark, + UpdateBy = this.UpdateBy, + UpdateTime = this.UpdateTime, + }; + } + + public string ModuleName { get; set; } + + public string ActionName { get; set; } + + public string ITCode { get; set; } + + public string ActionUrl { get; set; } + + public DateTime ActionTime { get; set; } + + public double Duration { get; set; } + + public string Remark { get; set; } + + public string IP { get; set; } + + public ActionLogTypesEnum LogType { get; set; } + + public DateTime? CreateTime { get; set; } + /// + /// CreateBy + /// + public string CreateBy { get; set; } + /// + /// UpdateTime + /// + public DateTime? UpdateTime { get; set; } + /// + /// UpdateBy + /// + public string UpdateBy { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleMenu.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleMenu.cs new file mode 100644 index 0000000..f831a3f --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleMenu.cs @@ -0,0 +1,41 @@ +using System; + +namespace WalkingTec.Mvvm.Core.Support.Json +{ + [Serializable] + public class SimpleMenu + { + public Guid ID { get; set; } + public bool? IsInherit { get; set; } + + public Guid? ActionId { get; set; } + + public bool? IsPublic { get; set; } + + public string Url { get; set; } + + public Guid? ParentId { get; set; } + + public string PageName { get; set; } + + public int? DisplayOrder { get; set; } + + public string Icon { get; set; } + + public bool ShowOnMenu { get; set; } + } + + public class SimpleMenuApi + { + public string Id { get; set; } + + public string ParentId { get; set; } + + public string Text { get; set; } + + public string Url { get; set; } + + public string Icon { get; set; } + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleModule.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleModule.cs new file mode 100644 index 0000000..39b5216 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleModule.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace WalkingTec.Mvvm.Core.Support.Json +{ + public class SimpleModule + { + public Guid ID { get; set; } + + public ActionDescriptionAttribute ActionDes { get; set; } + + public string _name; + public string ModuleName + { + get + { + if (ActionDes?._localizer != null && string.IsNullOrEmpty(ActionDes?.Description) == false) + { + return ActionDes._localizer[ActionDes.Description]; + } + else + { + return _name ?? ""; + } + } + set + { + _name = value; + } + } + + public string ClassName { get; set; } + + public List Actions { get; set; } + + public Guid? AreaId { get; set; } + public SimpleArea Area { get; set; } + + public string NameSpace { get; set; } + + public bool IgnorePrivillege { get; set; } + + public bool IsApi { get; set; } + + public string FullName + { + get + { + return this.NameSpace + "," + this.ClassName; + } + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleRole.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleRole.cs new file mode 100644 index 0000000..35c74ec --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleRole.cs @@ -0,0 +1,13 @@ +using System; + +namespace WalkingTec.Mvvm.Core.Support.Json +{ + [Serializable] + public class SimpleRole + { + public Guid ID { get; set; } + public string RoleCode { get; set; } + public string RoleName { get; set; } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleUserInfo.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleUserInfo.cs new file mode 100644 index 0000000..98691d3 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/Json/SimpleUserInfo.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; + +namespace WalkingTec.Mvvm.Core.Support.Json +{ + public class SimpleUserInfo + { + public Guid Id { get; set; } + /// + /// 登录用户 + /// + public string ITCode { get; set; } + + public string Name { get; set; } + + public string Memo { get; set; } + + public List Roles { get; set; } + /// + /// 用户的页面权限列表 + /// + public List FunctionPrivileges { get; set; } + + public List DataPrivileges { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ListItem.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ListItem.cs new file mode 100644 index 0000000..169a493 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/ListItem.cs @@ -0,0 +1,69 @@ +using System.Collections.Generic; +using System.Linq; + +namespace WalkingTec.Mvvm.Core +{ + public class ListItem + { + /// + /// The value to display + /// + public string Text { get; set; } + + /// + /// The value to be submitted + /// + public object Value { get; set; } + + } + + public class MenuItem : ListItem + { + /// + /// Icon + /// + /// + public string Icon { get; set; } + } + + /// + /// 下拉菜单项 + /// + public class ComboSelectListItem : ListItem + { + /// + /// Whether it is selected + /// + public bool Selected { get; set; } + + /// + /// Whether it is disabled + /// + public bool Disabled { get; set; } + + /// + /// ParentId + /// + public string ParentId { get; set; } + + /// + /// Icon + /// + /// + public string Icon { get; set; } + + } + + /// + /// 树形下拉菜单项 + /// + public class TreeSelectListItem: ComboSelectListItem + { + public bool Expended { get; set; } + public string Url { get; set; } + public string Tag { get; set; } + public bool Leaf => Children == null || Children.Count() == 0; + public List Children { get; set; } + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/NugetInfo.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/NugetInfo.cs new file mode 100644 index 0000000..08439da --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/NugetInfo.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WalkingTec.Mvvm.Core.Support +{ + public class NugetInfo + { + public List data { get; set; } + } + + public class NugetInfoData + { + public string version { get; set; } + public List versions {get;set;} + } + + public class NugetVersionData + { + public string version { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/SupportedGroupMapping.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/SupportedGroupMapping.cs new file mode 100644 index 0000000..c6ca583 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/SupportedGroupMapping.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// DFS 业务类型与Group映射关系 + /// + public class SupportedBusinessTypeMapping + { + public string BusinessTypeName { get; set; } + public List GroupMappings { get; set; } + } + + /// + /// DFS Group与内外网地址映射关系 + /// + public class SupportedGroupMapping + { + /// + /// 群组名 + /// + public string Group { get; set; } + /// + /// 内网地址头 + /// + public string InsideUrlHeader { get; set; } + /// + /// 外网地址头 + /// + public string OutsideUrlHeader { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/TypeComparer.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/TypeComparer.cs new file mode 100644 index 0000000..b36e631 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/TypeComparer.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; + +namespace WalkingTec.Mvvm.Core +{ + /// + /// Type 类型比较器 + /// + public class TypeComparer : IEqualityComparer + { + public bool Equals(Type x, Type y) => x.AssemblyQualifiedName == y.AssemblyQualifiedName; + + public int GetHashCode(Type obj) => throw new NotImplementedException(); + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/WTMLogger.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/WTMLogger.cs new file mode 100644 index 0000000..ca5ffa8 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/WTMLogger.cs @@ -0,0 +1,149 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Configuration; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace WalkingTec.Mvvm.Core +{ + + public static class WTMeLoggerExtensions + { + public static ILoggingBuilder AddWTMLogger(this ILoggingBuilder builder) + { + builder.AddConfiguration(); + builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); + return builder; + } + } + + public class WTMLoggerProvider : ILoggerProvider + { + private IServiceProvider sp = null; + private LoggerFilterOptions logConfig; + + public WTMLoggerProvider( IOptionsMonitor _logConfig, IServiceProvider sp) + { + this.sp = sp; + logConfig = _logConfig.CurrentValue; + } + + public ILogger CreateLogger(string categoryName) + { + return new WTMLogger(categoryName, logConfig,sp); + } + public void Dispose() { } + } + + public class WTMLogger : ILogger + { + private readonly string categoryName; + private IServiceProvider sp; + private LoggerFilterOptions logConfig; + + public WTMLogger(string categoryName, LoggerFilterOptions logConfig, IServiceProvider sp) + { + this.categoryName = categoryName; + this.logConfig = logConfig; + this.sp = sp; + } + + public bool IsEnabled(LogLevel logLevel) + { + if(logConfig == null) + { + return false; + } + var level = logConfig.Rules.Where(x => + x.ProviderName == "WTM" && + ( + (x.CategoryName != null && categoryName.ToLower().StartsWith(x.CategoryName.ToLower()) ) || + categoryName == "WalkingTec.Mvvm.Core.ActionLog" + ) + ) + .Select(x => x.LogLevel).FirstOrDefault(); + if (level == null) + { + level = LogLevel.Error; + } + if (logLevel >= level) + { + return true; + } + else + { + return false; + } + } + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) + { + if (IsEnabled(logLevel)) + { + ActionLog log = null; + if (typeof(TState) != typeof(ActionLog)) + { + ActionLogTypesEnum ll = ActionLogTypesEnum.Normal; + if (logLevel == LogLevel.Trace || logLevel == LogLevel.Debug) + { + ll = ActionLogTypesEnum.Debug; + } + if (logLevel == LogLevel.Error || logLevel == LogLevel.Warning || logLevel == LogLevel.Critical) + { + ll = ActionLogTypesEnum.Exception; + } + + log = new ActionLog + { + Remark = formatter?.Invoke(state, exception), + CreateTime = DateTime.Now, + ActionTime = DateTime.Now, + ActionName = "WtmLog", + ModuleName = "WtmLog", + LogType = ll + }; + } + else + { + log = state as ActionLog; + } + + WTMContext wtm = null; + var hc = sp.GetRequiredService().HttpContext; + if (hc == null) + { + using (var scope = sp.CreateScope()) + { + wtm = scope.ServiceProvider.GetRequiredService(); + } + } + else + { + wtm = hc.RequestServices.GetRequiredService(); + } + if (wtm != null) + { + using (var dc = wtm.CreateDC(true)) + { + if (dc != null) + { + try + { + dc.AddEntity(log); + dc.SaveChanges(); + } + catch { } + } + } + } + } + } + + public IDisposable BeginScope(TState state) => null; + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/WebProxy.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/WebProxy.cs new file mode 100644 index 0000000..e7cdab5 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/WebProxy.cs @@ -0,0 +1,33 @@ +using System; +using System.Net; + +namespace WalkingTec.Mvvm.Core +{ + public class WebProxy : IWebProxy + { + public WebProxy(string proxyUri) + : this(new Uri(proxyUri)) + { + } + + public WebProxy(Uri proxyUri) + { + this.ProxyUri = proxyUri; + } + + public Uri ProxyUri { get; set; } + + public ICredentials Credentials { get; set; } + + public Uri GetProxy(Uri destination) + { + return this.ProxyUri; + } + + public bool IsBypassed(Uri host) + { + return false; /* Proxy all requests */ + } + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/WtmLocalizationOption.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/WtmLocalizationOption.cs new file mode 100644 index 0000000..8ad42a3 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Support/WtmLocalizationOption.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace WalkingTec.Mvvm.Core +{ + public class WtmLocalizationOption + { + public Type LocalizationType { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Utils.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Utils.cs new file mode 100644 index 0000000..e6ad09e --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/Utils.cs @@ -0,0 +1,824 @@ +using Microsoft.Extensions.Caching.Distributed; +using NPOI.HSSF.Util; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Reflection; +using System.Runtime.Loader; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Core.Support; +using WalkingTec.Mvvm.Core.Support.Json; + +namespace WalkingTec.Mvvm.Core +{ + public class Utils + { + + private static List _allAssemblies; + + public static string GetCurrentComma() + { + if (CultureInfo.CurrentUICulture.Name == "zh-cn") + { + return ":"; + } + else + { + return ":"; + } + } + + public static List GetAllAssembly() + { + if (_allAssemblies == null) + { + _allAssemblies = new List(); + string path = null; + string singlefile = null; + try + { + path = Assembly.GetEntryAssembly()?.Location; + } + catch { } + if (string.IsNullOrEmpty(path)) + { + singlefile = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; + path = Path.GetDirectoryName(singlefile); + } + var dir = new DirectoryInfo(Path.GetDirectoryName(path)); + + var dlls = dir.GetFiles("*.dll", SearchOption.TopDirectoryOnly); + string[] systemdll = new string[] + { + "Microsoft.", + "System.", + "Swashbuckle.", + "ICSharpCode", + "Newtonsoft.", + "Oracle.", + "Pomelo.", + "SQLitePCLRaw.", + "Aliyun.OSS", + "BouncyCastle.", + "FreeSql.", + "Google.Protobuf.dll", + "Humanizer.dll", + "IdleBus.dll", + "K4os.", + "MySql.Data.", + "Npgsql.", + "NPOI.", + "netstandard", + "MySqlConnector", + "VueCliMiddleware" + }; + + var filtered = dlls.Where(x => systemdll.Any(y => x.Name.StartsWith(y)) == false); + foreach (var dll in filtered) + { + try + { + AssemblyLoadContext.Default.LoadFromAssemblyPath(dll.FullName); + } + catch + { + } + } + var dlllist = AssemblyLoadContext.Default.Assemblies.Where(x => systemdll.Any(y => x.FullName.StartsWith(y)) == false).ToList(); + _allAssemblies.AddRange(dlllist); + } + return _allAssemblies; + } + + public static SimpleMenu FindMenu(string url, List menus) + { + if (url == null) + { + return null; + } + url = url.ToLower(); + if (menus == null) + { + return null; + } + //寻找菜单中是否有与当前判断的url完全相同的 + var menu = menus.Where(x => x.Url != null && x.Url.ToLower() == url).FirstOrDefault(); + + //如果没有,抹掉当前url的参数,用不带参数的url比对 + if (menu == null) + { + var pos = url.IndexOf("?"); + if (pos > 0) + { + url = url.Substring(0, pos); + menu = menus.Where(x => x.Url != null && (x.Url.ToLower() == url || x.Url.ToLower() + "async" == url)).FirstOrDefault(); + } + } + + //如果还没找到,则判断url是否为/controller/action/id这种格式,如果是则抹掉/id之后再对比 + if (menu == null && url.EndsWith("/index")) + { + url = url.Substring(0, url.Length - 6); + menu = menus.Where(x => x.Url != null && x.Url.ToLower() == url).FirstOrDefault(); + } + if (menu == null && url.EndsWith("/indexasync")) + { + url = url.Substring(0, url.Length - 11); + menu = menus.Where(x => x.Url != null && x.Url.ToLower() == url).FirstOrDefault(); + } + return menu; + } + + + public static string GetIdByName(string fieldName) + { + return fieldName == null ? "" : fieldName.Replace(".", "_").Replace("[", "_").Replace("]", "_").Replace("-","minus"); + } + + public static void CheckDifference(IEnumerable oldList, IEnumerable newList, out IEnumerable ToRemove, out IEnumerable ToAdd) where T : TopBasePoco + { + List tempToRemove = new List(); + List tempToAdd = new List(); + oldList = oldList ?? new List(); + newList = newList ?? new List(); + foreach (var oldItem in oldList) + { + bool exist = false; + foreach (var newItem in newList) + { + if (oldItem.GetID().ToString() == newItem.GetID().ToString()) + { + exist = true; + break; + } + } + if (exist == false) + { + tempToRemove.Add(oldItem); + } + } + foreach (var newItem in newList) + { + bool exist = false; + foreach (var oldItem in oldList) + { + if (newItem.GetID().ToString() == oldItem.GetID().ToString()) + { + exist = true; + break; + } + } + if (exist == false) + { + tempToAdd.Add(newItem); + } + } + ToRemove = tempToRemove.AsEnumerable(); + ToAdd = tempToAdd.AsEnumerable(); + } + + public static short GetExcelColor(string color) + { + var colors = typeof(HSSFColor).GetNestedTypes().ToList(); + foreach (var col in colors) + { + var pro = col.GetField("hexString"); + if (pro == null) + { + continue; + } + var hex = pro.GetValue(null); + var rgb = hex.ToString().Split(':'); + for (int i = 0; i < rgb.Length; i++) + { + if (rgb[i].Length > 2) + { + rgb[i] = rgb[i].Substring(0, 2); + } + } + int r = Convert.ToInt16(rgb[0], 16); + int g = Convert.ToInt16(rgb[1], 16); + int b = Convert.ToInt16(rgb[2], 16); + + if (color.Length == 8) + { + color = color.Substring(2); + } + string c1 = color.Substring(0, 2); + string c2 = color.Substring(2, 2); + string c3 = color.Substring(4, 2); + + int r1 = Convert.ToInt16(c1, 16); + int g1 = Convert.ToInt16(c2, 16); + int b1 = Convert.ToInt16(c3, 16); + + + if (r == r1 && g == g1 && b == b1) + { + return (short)col.GetField("index").GetValue(null); + } + } + return HSSFColor.COLOR_NORMAL; + } + + /// + /// 获取Bool类型的下拉框 + /// + /// + /// + /// + /// + /// + /// + public static List GetBoolCombo(BoolComboTypes boolType, bool? defaultValue = null, string trueText = null, string falseText = null, string selectText = null) + { + List rv = new List(); + string yesText = ""; + string noText = ""; + switch (boolType) + { + case BoolComboTypes.YesNo: + yesText = CoreProgram._localizer?["Sys.Yes"]; + noText = CoreProgram._localizer?["Sys.No"]; + break; + case BoolComboTypes.ValidInvalid: + yesText = CoreProgram._localizer?["Sys.Valid"]; + noText = CoreProgram._localizer?["Sys.Invalid"]; + break; + case BoolComboTypes.MaleFemale: + yesText = CoreProgram._localizer?["Sys.Male"]; + noText = CoreProgram._localizer?["Sys.Female"]; + break; + case BoolComboTypes.HaveNotHave: + yesText = CoreProgram._localizer?["Sys.Have"]; + noText = CoreProgram._localizer?["Sys.NotHave"]; + break; + case BoolComboTypes.Custom: + yesText = trueText ?? CoreProgram._localizer?["Sys.Yes"]; + noText = falseText ?? CoreProgram._localizer?["Sys.No"]; + break; + default: + break; + } + ComboSelectListItem yesItem = new ComboSelectListItem() + { + Text = yesText, + Value = "true" + }; + if (defaultValue == true) + { + yesItem.Selected = true; + } + ComboSelectListItem noItem = new ComboSelectListItem() + { + Text = noText, + Value = "false" + }; + if (defaultValue == false) + { + noItem.Selected = true; + } + if(selectText != null) + { + rv.Add(new ComboSelectListItem { Text = selectText, Value = "" }); + } + rv.Add(yesItem); + rv.Add(noItem); + return rv; + } + + + /// + /// + /// + /// + /// + public static string ZipAndBase64Encode(string input) + { + byte[] buffer = Encoding.UTF8.GetBytes(input); + MemoryStream inputms = new MemoryStream(buffer); + MemoryStream outputms = new MemoryStream(); + using (GZipStream zip = new GZipStream(outputms, CompressionMode.Compress)) + { + inputms.CopyTo(zip); + } + byte[] rv = outputms.ToArray(); + inputms.Dispose(); + return Convert.ToBase64String(rv); + } + /// + /// + /// + /// + /// + public static string UnZipAndBase64Decode(string input) + { + byte[] inputstr = Convert.FromBase64String(input); + MemoryStream inputms = new MemoryStream(inputstr); + MemoryStream outputms = new MemoryStream(); + using (GZipStream zip = new GZipStream(inputms, CompressionMode.Decompress)) + { + zip.CopyTo(outputms); + } + byte[] rv = outputms.ToArray(); + outputms.Dispose(); + return Encoding.UTF8.GetString(rv); + } + /// + /// + /// + /// + /// + public static string EncodeScriptJson(string input) + { + if (input == null) + { + return ""; + } + else + { + return input.Replace(Environment.NewLine, "").Replace("\"", "\\\\\\\"").Replace("'", "\\'"); + } + } + + /// + /// + /// + /// + public static void DeleteFile(string path) + { + try + { + System.IO.File.Delete(path); + } + catch { } + } + + #region 格式化文本 add by wuwh 2014.6.12 + /// + /// 格式化文本 + /// + /// 要格式化的字符串 + /// 是否是纯代码 + /// + public static string FormatText(string text, bool isCode = false) + { + + if (isCode) + { + return FormatCode(text); + } + else + { + #region 截取需要格式化的代码段 + List listInt = new List(); + int index = 0; + int _index; + while (true) + { + _index = text.IndexOf("&&", index); + index = _index + 1; + if (_index >= 0 && _index <= text.Length) + { + listInt.Add(_index); + } + else + { + break; + } + } + + List listStr = new List(); + for (int i = 0; i < listInt.Count; i++) + { + string temp = text.Substring(listInt[i] + 2, listInt[i + 1] - listInt[i] - 2); + + listStr.Add(temp); + i++; + } + #endregion + + #region 格式化代码段 + //先将 < >以及空格替换掉,防止下面替换出现 html标签后出现问题 + for (int i = 0; i < listStr.Count; i++) + { + //将 &&代码&& 替换成&&1&& + text = text.Replace("&&" + listStr[i] + "&&", FormatCode(listStr[i])); + } + #endregion + + return text; + } + } + #endregion + + #region 格式化代码 edit by wuwh + /// + /// 格式化代码 + /// + /// + /// + public static string FormatCode(string code) + { + //先将 < >以及空格替换掉,防止下面替换出现 html标签后出现问题 + code = code.Replace("<", "<").Replace(">", ">").Replace(" ", " "); + string csKeyWords = "abstract|as|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|do|double|else|enum|event|explicit|extern|false|finally|fixed|float|for|foreach|from|get|goto|group|if|implicit|in|int|interface|internal|into|is|join|let|lock|long|namespace|new|null|object|operator|orderby|out|override|params|partial|private|protected|public|readonly|ref|return|sbyte|sealed|select|set|short|sizeof|stackalloc|static|string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|value|var|virtual|void|volatile|where|while|yield"; + + string r1 = "(#if DBG[\\s\\S]+?#endif)"; + string r2 = "(#[a-z ]*)"; + string r3 = "(///\\ *<[/\\w]+>)"; + string r4 = "(/\\*[\\s\\S]*?\\*/)";//匹配三杠注释 + string r5 = "(//.*)";//匹配双杠注释 + string r6 = @"(@?"".*?"")";//匹配字符串 + string r7 = "('.*?')";//匹配字符串 + string r8 = "\\b(" + csKeyWords + ")\\b";//匹配关键字 + //string r9 = "class (.+) ";//匹配类 + //string r10 = "<(.+)>";//匹配泛型类 + + string rs = string.Format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}", r1, r2, r3, r4, r5, r6, r7, r8); + //string rs = string.Format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}", r1, r2, r3, r4, r5, r6, r7, r8, r9,r10); + + //$9$10 + string rr = "$1$2$3$4$5$6$7$8"; + + Regex re = new Regex(rs, RegexOptions.None); + code = Regex.Replace(code, rs, rr); + //替换换行符"\r\n" 以及"\r" "\n" + code = code.Replace("\r\n", "
").Replace("\n", "").Replace("\r", "
"); + //取消空标签 + //|C#类的颜色 + code = Regex.Replace(code, "|||", ""); + + return code; + } + #endregion + + #region 读取txt文件 + /// + /// 读取文件 + /// + /// 文件路径绝对 + /// + public static string ReadTxt(string path) + { + string result = string.Empty; + + if (File.Exists(path)) + { + using (Stream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + using (TextReader sr = new StreamReader(fs, UnicodeEncoding.UTF8)) + { + result = sr.ReadToEnd(); + } + } + } + + return result; + } + #endregion + + /// + /// 得到目录下所有文件 + /// + /// + /// + public static List GetAllFileName(string dirpath) + { + DirectoryInfo dir = new DirectoryInfo(dirpath); + var files = dir.GetFileSystemInfos(); + return files.Select(x => x.Name).ToList(); + } + + #region add by wuwh 2014.10.18 递归获取目录下所有文件 + /// + /// 递归获取目录下所有文件 + /// + /// + /// + /// + public static List GetAllFilePathRecursion(string dirPath, List allFiles) + { + if (allFiles == null) + { + allFiles = new List(); + } + string[] subPaths = Directory.GetDirectories(dirPath); + foreach (var item in subPaths) + { + GetAllFilePathRecursion(item, allFiles); + } + allFiles.AddRange(Directory.GetFiles(dirPath).ToList()); + + return allFiles; + } + #endregion + + + /// + /// ConvertToColumnXType + /// + /// + /// + public static string ConvertToColumnXType(Type type) + { + if (type == typeof(bool) || type == typeof(bool?)) + { + return "checkcolumn"; + } + else if (type == typeof(DateTime) || type == typeof(DateTime?)) + { + return "datecolumn"; + } + else if (type == typeof(decimal) || type == typeof(decimal?) || type == typeof(double) || type == typeof(double?) || type == typeof(int) || type == typeof(int?) || type == typeof(long) || type == typeof(long?)) + { + return "numbercolumn"; + } + return "textcolumn"; + } + + + public static string GetCS(string cs, string mode, Configs config) + { + if (string.IsNullOrEmpty(cs) || config.Connections.Any(x => x.Key.ToLower() == cs.ToLower()) == false) + { + cs = "default"; + } + int index = cs.LastIndexOf("_"); + if (index > 0) + { + cs = cs.Substring(0, index); + } + if (mode?.ToLower() == "read") + { + var reads = config.Connections.Where(x => x.Key.StartsWith(cs + "_")).Select(x => x.Key).ToList(); + if (reads.Count > 0) + { + Random r = new Random(); + var v = r.Next(0, reads.Count); + cs = reads[v]; + } + } + return cs; + } + + public static string GetUrlByFileAttachmentId(IDataContext dc, Guid? fileAttachmentId, bool isIntranetUrl = false, string urlHeader = null) + { + string url = string.Empty; + var fileAttachment = dc.Set().Where(x => x.ID == fileAttachmentId.Value).FirstOrDefault(); + if (fileAttachment != null) + { + url = "/_Framework/GetFile/" + fileAttachmentId.ToString(); + + } + return url; + } + + #region 加解密 + /// + /// 通过密钥将内容加密 + /// + /// 要加密的字符串 + /// 加密密钥 + /// + public static string EncryptString(string stringToEncrypt, string encryptKey) + { + if (string.IsNullOrEmpty(stringToEncrypt)) + { + return ""; + } + + string stringEncrypted = string.Empty; + byte[] bytIn = UTF8Encoding.UTF8.GetBytes(stringToEncrypt); + MemoryStream encryptStream = new System.IO.MemoryStream(); + CryptoStream encStream = new CryptoStream(encryptStream, GenerateDESCryptoServiceProvider(encryptKey).CreateEncryptor(), CryptoStreamMode.Write); + + try + { + encStream.Write(bytIn, 0, bytIn.Length); + encStream.FlushFinalBlock(); + stringEncrypted = Convert.ToBase64String(encryptStream.ToArray(), 0, (int)encryptStream.Length); + } + catch + { + return ""; + } + finally + { + encryptStream.Close(); + encStream.Close(); + } + + return stringEncrypted; + } + + /// + /// 通过密钥讲内容解密 + /// + /// 要解密的字符串 + /// 密钥 + /// + public static string DecryptString(string stringToDecrypt, string encryptKey) + { + if (String.IsNullOrEmpty(stringToDecrypt)) + { + return ""; + } + + string stringDecrypted = string.Empty; + byte[] bytIn = Convert.FromBase64String(stringToDecrypt.Replace(" ", "+")); + MemoryStream decryptStream = new MemoryStream(); + CryptoStream encStream = new CryptoStream(decryptStream, GenerateDESCryptoServiceProvider(encryptKey).CreateDecryptor(), CryptoStreamMode.Write); + + try + { + encStream.Write(bytIn, 0, bytIn.Length); + encStream.FlushFinalBlock(); + stringDecrypted = Encoding.Default.GetString(decryptStream.ToArray()); + } + catch + { + return ""; + } + finally + { + decryptStream.Close(); + encStream.Close(); + } + + return stringDecrypted; + } + + private static DESCryptoServiceProvider GenerateDESCryptoServiceProvider(string key) + { + DESCryptoServiceProvider dCrypter = new DESCryptoServiceProvider(); + + string sTemp; + if (dCrypter.LegalKeySizes.Length > 0) + { + int moreSize = dCrypter.LegalKeySizes[0].MinSize; + while (key.Length > 8) + { + key = key.Substring(0, 8); + } + sTemp = key.PadRight(moreSize / 8, ' '); + } + else + { + sTemp = key; + } + byte[] bytKey = UTF8Encoding.UTF8.GetBytes(sTemp); + + dCrypter.Key = bytKey; + dCrypter.IV = bytKey; + + return dCrypter; + } + + #endregion + + #region MD5加密 + /// + /// 字符串MD5加密 + /// + /// + /// 返回大写32位MD5值 + public static string GetMD5String(string str) + { + byte[] buffer = Encoding.UTF8.GetBytes(str); + + return MD5String(buffer); + } + + /// + /// 流MD5加密 + /// + /// + /// + public static string GetMD5Stream(Stream stream) + { + byte[] buffer = new byte[stream.Length]; + stream.Read(buffer, 0, buffer.Length); + return MD5String(buffer); + } + + /// + /// 文件MD5加密 + /// + /// + /// 返回大写32位MD5值 + public static string GetMD5File(string path) + { + if (File.Exists(path)) + { + using (FileStream fs = new FileStream(path, FileMode.Open)) + { + return GetMD5Stream(fs); + } + } + else + { + return string.Empty; + } + } + + private static string MD5String(byte[] buffer) + { + MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); + byte[] cryptBuffer = md5.ComputeHash(buffer); + StringBuilder sb = new StringBuilder(); + foreach (byte item in cryptBuffer) + { + sb.Append(item.ToString("X2")); + } + return sb.ToString(); + } + #endregion + + /// + /// 重新处理 返回所有ispage模块 + /// + /// + /// 是否需要action + /// + public static List ResetModule(List modules, bool submit = true) + { + var m = modules.Select(x => new SimpleModule + { + ActionDes = x.ActionDes, + Actions = x.Actions.Select(y => new SimpleAction + { + ActionDes = y.ActionDes, + ActionName = y.ActionName, + Url = y.Url, + MethodName = y.MethodName, + IgnorePrivillege = y.IgnorePrivillege, + ID = y.ID, + Module = y.Module, + ModuleId = y.ModuleId, + Parameter = y.Parameter, + ParasToRunTest = y.ParasToRunTest + }).ToList(), + Area = x.Area, + AreaId = x.AreaId, + ClassName = x.ClassName, + _name = x._name, + ID = x.ID, + IgnorePrivillege = x.IgnorePrivillege, + IsApi = x.IsApi, + ModuleName = x.ModuleName, + NameSpace = x.NameSpace, + }).ToList(); + var mCount = m.Count; + var toRemove = new List(); + for (int i = 0; i < mCount; i++) + { + var pages = m[i].Actions?.Where(x => x.ActionDes?.IsPage == true).ToList(); + if (pages != null) + { + for (int j = 0; j < pages.Count; j++) + { + if (j == 0 && !m[i].Actions.Any(x => x.MethodName.ToLower() == "index")) + { + m.Add(new SimpleModule + { + ModuleName = pages[j].ActionDes._localizer[pages[j].ActionDes.Description], + NameSpace = m[i].NameSpace, + ClassName = pages[j].MethodName, + Actions = m[i].Actions, + Area = m[i].Area + }); + if (submit) + m[i].Actions.Remove(pages[j]); + toRemove.Add(m[i]); + } + else + { + if (pages[j].MethodName.ToLower() != "index") + { + m.Add(new SimpleModule + { + ModuleName = pages[j].ActionDes._localizer[pages[j].ActionDes.Description], + NameSpace = m[i].NameSpace, + ClassName = pages[j].MethodName, + Actions = submit ? new List() : new List() { pages[j] }, + Area = m[i].Area + }); + m[i].Actions.Remove(pages[j]); + } + } + } + } + } + toRemove.ForEach(x => m.Remove(x)); + return m; + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/WTMContext.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/WTMContext.cs new file mode 100644 index 0000000..3dea8de --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/WTMContext.cs @@ -0,0 +1,966 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Net.Http; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Console; +using Microsoft.Extensions.Logging.Debug; +using Microsoft.Extensions.Options; +using WalkingTec.Mvvm.Core.Auth; +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Core.Json; +using WalkingTec.Mvvm.Core.Support.Json; + +namespace WalkingTec.Mvvm.Core +{ + public class WTMContext + { + private HttpContext _httpContext; + public HttpContext HttpContext { get => _httpContext; } + + private IServiceProvider _serviceProvider; + public IServiceProvider ServiceProvider { get => _serviceProvider ?? _httpContext?.RequestServices; } + + + private List _dps; + public List DataPrivilegeSettings { get => _dps; } + + private Configs _configInfo; + public Configs ConfigInfo { get => _configInfo; } + + private GlobalData _globaInfo; + public GlobalData GlobaInfo { get => _globaInfo; } + + private IUIService _uiservice; + public IUIService UIService { get => _uiservice; } + + private IDistributedCache _cache; + public IDistributedCache Cache + { + get + { + return _cache; + } + } + + public string CurrentCS { get; set; } + + public DBTypeEnum? CurrentDbType { get; set; } + + public string ParentWindowId + { + get + { + string rv = null; + if (WindowIds != null) + { + var ids = WindowIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + if (ids.Length > 1) + { + rv = ids[ids.Length - 2]; + } + } + + return rv ?? string.Empty; + } + } + + public string CurrentWindowId + { + get + { + string rv = null; + if (WindowIds != null) + { + var ids = WindowIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + if (ids.Length > 0) + { + rv = ids[ids.Length - 1]; + } + } + + return rv ?? string.Empty; + } + } + + public string WindowIds + { + get + { + string rv = string.Empty; + try + { + if (HttpContext.Request.Cookies.TryGetValue($"{ConfigInfo?.CookiePre}windowguid", out string windowguid) == true) + { + + if (HttpContext.Request.Cookies.TryGetValue($"{ConfigInfo?.CookiePre}{windowguid}windowids", out string windowid) == true) + { + rv = windowid; + } + } + } + catch { } + return rv; + } + } + + public ISessionService Session { get; set; } + + public IModelStateService MSD { get; set; } + + public static Func ReloadUserFunc { get; set; } + + #region DataContext + + private IDataContext _dc; + public IDataContext DC + { + get + { + if (_dc == null) + { + _dc = this.CreateDC(); + } + return _dc; + } + set + { + _dc = value; + } + } + + #endregion + + #region Current User + + private LoginUserInfo _loginUserInfo; + public LoginUserInfo LoginUserInfo + { + get + { + if (_loginUserInfo == null && HttpContext?.User?.Identity?.IsAuthenticated == true ) // 用户认证通过后,当前上下文不包含用户数据 + { + var userIdStr = HttpContext.User.Claims.Where(x => x.Type == AuthConstants.JwtClaimTypes.Subject).Select(x => x.Value).FirstOrDefault(); + var tenant = HttpContext.User.Claims.Where(x => x.Type == AuthConstants.JwtClaimTypes.TenantCode).Select(x=>x.Value).FirstOrDefault(); + string usercode = userIdStr; + var cacheKey = $"{GlobalConstants.CacheKey.UserInfo}:{userIdStr + "$`$" + tenant}"; + _loginUserInfo = Cache.Get(cacheKey); + if (_loginUserInfo == null) + { + try + { + _loginUserInfo = ReloadUser(usercode).Result; + } + catch { } + if (_loginUserInfo != null) + { + Cache.Add(cacheKey, _loginUserInfo); + } + else + { + return null; + } + } + } + return _loginUserInfo; + } + set + { + if (value == null) + { + Cache.Delete($"{GlobalConstants.CacheKey.UserInfo}:{_loginUserInfo?.ITCode + "$`$" + _loginUserInfo?.TenantCode}"); + _loginUserInfo = value; + } + else + { + _loginUserInfo = value; + Cache.Add($"{GlobalConstants.CacheKey.UserInfo}:{_loginUserInfo.ITCode+ "$`$" + _loginUserInfo?.TenantCode}", value); + } + } + } + + private Type _localizerType; + private IStringLocalizerFactory _stringLocalizerFactory; + private IStringLocalizer _localizer; + private ILoggerFactory _loggerFactory; + public IStringLocalizer Localizer + { + get + { + if (_localizer == null && _stringLocalizerFactory != null) + { + if(_localizerType == null) + { + _localizerType = Assembly.GetEntryAssembly().GetTypes().Where(x => x.Name == "Program").FirstOrDefault(); + } + _localizer = _stringLocalizerFactory.Create(_localizerType); + } + return _localizer ?? WalkingTec.Mvvm.Core.CoreProgram._localizer; + } + } + + /// + /// 从数据库读取用户 + /// + /// 用户名 + /// 用户信息 + public virtual async Task + ReloadUser(string itcode) + { + if (ReloadUserFunc != null) + { + var reload = ReloadUserFunc.Invoke(this, itcode); + if (reload != null) + { + return reload; + } + } + if (DC == null) + { + return null; + } + + + var code = await BaseUserQuery.Where(x => x.ITCode.ToLower() == itcode.ToLower()).Select(x =>new { itcode = x.ITCode, id= x.GetID(), photoid=x.PhotoId, name=x.Name }).SingleOrDefaultAsync(); + if (code == null) + { + return null; + } + LoginUserInfo rv = new LoginUserInfo + { + ITCode = code.itcode, + UserId = code.id?.ToString(), + Name = code.name, + PhotoId = code.photoid + }; + await rv.LoadBasicInfoAsync(this); + return rv; + } + + #endregion + + #region URL + public string BaseUrl { get; set; } + #endregion + + public SimpleLog Log { get; set; } + + protected ILogger Logger { get; set; } + + + private IQueryable _baseUserQuery; + public IQueryable BaseUserQuery + { + get + { + if(_baseUserQuery == null && this.GlobaInfo?.CustomUserType != null && DC != null) + { + var set = DC.GetType().GetMethod("Set", Type.EmptyTypes).MakeGenericMethod(GlobaInfo.CustomUserType); + _baseUserQuery = set.Invoke(DC, null) as IQueryable; + } + return _baseUserQuery; + } + } + + public WTMContext(IOptionsMonitor _config, GlobalData _gd = null, IHttpContextAccessor _http = null, IUIService _ui = null, List _dp = null, IDataContext dc = null, IStringLocalizerFactory stringLocalizer = null, ILoggerFactory loggerFactory = null, WtmLocalizationOption lop=null, IDistributedCache cache=null) + { + _configInfo = _config?.CurrentValue ?? new Configs(); + _globaInfo = _gd ?? new GlobalData(); + _httpContext = _http?.HttpContext; + _cache = cache; + _stringLocalizerFactory = stringLocalizer; + _loggerFactory = loggerFactory; + _localizerType = lop?.LocalizationType; + this.Logger = loggerFactory?.CreateLogger(); + if (_httpContext == null) + { + MSD = new BasicMSD(); + } + _uiservice = _ui; + if (_dp == null) + { + _dp = new List(); + } + _dps = _dp; + if (dc is NullContext) + { + _dc = null; + } + else + { + _dc = dc; + } + } + + public void SetServiceProvider(IServiceProvider sp) + { + this._serviceProvider = sp; + } + + + public T ReadFromCache(string key, Func setFunc, int? timeout = null) + { + if (Cache.TryGetValue(key, out T rv) == false || rv == null) + { + T data = setFunc(); + if (timeout == null) + { + Cache.Add(key, data); + } + else + { + Cache.Add(key, data, new DistributedCacheEntryOptions() + { + SlidingExpiration = new TimeSpan(0, 0, timeout.Value) + }); + } + return data; + } + else + { + return rv; + } + } + + public async Task RemoveUserCache( + params string[] userIds) + { + foreach (var userId in userIds) + { + var key = $"{GlobalConstants.CacheKey.UserInfo}:{userId+"$`$"+LoginUserInfo?.TenantCode}"; + await Cache.DeleteAsync(key); + } + } + + + #region CreateDC + public virtual IDataContext CreateDC(bool isLog = false, string cskey = null) + { + string cs = cskey ?? CurrentCS; + if (isLog == true) + { + if (ConfigInfo.Connections?.Where(x => x.Key.ToLower() == "defaultlog").FirstOrDefault() != null) + { + cs = "defaultlog"; + } + } + if (cs == null) + { + cs = "default"; + } + var rv = ConfigInfo.Connections.Where(x => x.Key.ToLower() == cs.ToLower()).FirstOrDefault().CreateDC(); + rv.IsDebug = ConfigInfo.IsQuickDebug; + rv.SetLoggerFactory(_loggerFactory); + return rv; + } + + #endregion + + /// + /// 判断某URL是否有权限访问 + /// + /// url地址 + /// true代表可以访问,false代表不能访问 + public bool IsAccessable(string url) + { + // 如果是调试 或者 url 为 null or 空字符串 + if (_configInfo.IsQuickDebug || string.IsNullOrEmpty(url) || IsUrlPublic(url)) + { + return true; + } + //循环所有不限制访问的url,如果含有当前判断的url,则认为可以访问 + var publicActions = _globaInfo.AllAccessUrls; + foreach (var au in publicActions) + { + if (new Regex("^"+au + "[/\\?]?", RegexOptions.IgnoreCase).IsMatch(url)) + { + return true; + } + } + //如果没有任何页面权限,则直接返回false + if (LoginUserInfo?.FunctionPrivileges == null) + { + return false; + } + + + url = Regex.Replace(url, "/do(batch.*)", "/$1", RegexOptions.IgnoreCase); + + //如果url以#开头,一般是javascript使用的临时地址,不需要判断,直接返回true + url = url.Trim(); + + if (url.StartsWith("#")) + { + return true; + } + var menus = _globaInfo.AllMenus; + var menu = Utils.FindMenu(url, GlobaInfo.AllMenus); + //如果最终没有找到,说明系统菜单中并没有配置这个url,返回false + if (menu == null) + { + return false; + } + //如果找到了,则继续验证其他权限 + else + { + return IsAccessable(menu, menus); + } + } + + /// + /// 判断某菜单是否有权限访问 + /// + /// 菜单项 + /// 所有系统菜单 + /// true代表可以访问,false代表不能访问 + protected bool IsAccessable(SimpleMenu menu, List menus) + { + //寻找当前菜单的页面权限 + var find = LoginUserInfo?.FunctionPrivileges.Where(x => x.MenuItemId == menu.ID && x.Allowed == true).FirstOrDefault(); + //如果能找到直接对应的页面权限 + if (find != null) + { + return true; + } + return false; + } + + public bool IsUrlPublic(string url) + { + var isPublic = false; + try + { + url = Regex.Replace(url, "/do(batch.*)", "/$1", RegexOptions.IgnoreCase); + url = url.Trim(); + + if (url.StartsWith("#")) + { + isPublic = true; + } + var menus = GlobaInfo.AllMenus; + var menu = Utils.FindMenu(url, menus); + if (menu != null && menu.IsPublic == true) + { + isPublic = true; + } + } + catch { } + return isPublic; + } + + public void DoLog(string msg, ActionLogTypesEnum logtype = ActionLogTypesEnum.Normal) + { + var log = this.Log?.GetActionLog(); + if (log == null) + { + log = new ActionLog(); + } + log.LogType = logtype; + log.ActionTime = DateTime.Now; + log.Remark = msg; + LogLevel ll = LogLevel.Information; + switch (logtype) + { + case ActionLogTypesEnum.Normal: + ll = LogLevel.Information; + break; + case ActionLogTypesEnum.Exception: + ll = LogLevel.Error; + break; + case ActionLogTypesEnum.Debug: + ll = LogLevel.Debug; + break; + default: + break; + } + + Logger?.Log(ll, new EventId(), log, null, (a, b) => + { + return $@" +===WTM Log=== +内容:{a.Remark} +地址:{a.ActionUrl} +时间:{a.ActionTime} +===WTM Log=== +"; + }); + } + + + #region CreateVM + /// + /// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + /// + /// The type of the viewmodel + /// If the viewmodel is a BaseCRUDVM, the data having this id will be fetched + /// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + /// properties of the viewmodel that you want to assign values + /// if true, the viewmodel will not call InitVM internally + /// ViewModel + private BaseVM CreateVM(Type VMType, object Id = null, object[] Ids = null, Dictionary values = null, bool passInit = false) + { + //Use reflection to create viewmodel + var ctor = VMType.GetConstructor(Type.EmptyTypes); + BaseVM rv = ctor.Invoke(null) as BaseVM; + rv.Wtm = this; + + rv.FC = new Dictionary(); + rv.CreatorAssembly = this.GetType().AssemblyQualifiedName; + rv.ControllerName = this.HttpContext?.Request?.Path; + if (HttpContext != null && HttpContext.Request != null) + { + try + { + if (HttpContext.Request.QueryString != QueryString.Empty) + { + foreach (var key in HttpContext.Request.Query.Keys) + { + if (rv.FC.Keys.Contains(key) == false) + { + rv.FC.Add(key, HttpContext.Request.Query[key]); + } + } + } + if (HttpContext.Request.HasFormContentType) + { + var f = HttpContext.Request.Form; + foreach (var key in f.Keys) + { + if (rv.FC.Keys.Contains(key) == false) + { + rv.FC.Add(key, f[key]); + } + } + } + } + catch { } + } + //try to set values to the viewmodel's matching properties + if (values != null) + { + foreach (var v in values) + { + PropertyHelper.SetPropertyValue(rv, v.Key, v.Value, null, false); + } + } + //if viewmodel is derrived from BaseCRUDVM<> and Id has value, call ViewModel's GetById method + if (Id != null && rv is IBaseCRUDVM cvm) + { + cvm.SetEntityById(Id); + } + //if viewmodel is derrived from IBaseBatchVM<>,set ViewMode's Ids property,and init it's ListVM and EditModel properties + if (rv is IBaseBatchVM temp) + { + temp.Ids = new string[] { }; + if (Ids != null) + { + var tempids = new List(); + foreach (var iid in Ids) + { + tempids.Add(iid.ToString()); + } + temp.Ids = tempids.ToArray(); + } + if (temp.ListVM != null) + { + temp.ListVM.CopyContext(rv); + temp.ListVM.Ids = Ids == null ? new List() : temp.Ids.ToList(); + temp.ListVM.SearcherMode = ListVMSearchModeEnum.Batch; + temp.ListVM.NeedPage = false; + } + if (temp.LinkedVM != null) + { + temp.LinkedVM.CopyContext(rv); + } + if (temp.ListVM != null) + { + //Remove the action columns from list + temp.ListVM.OnAfterInitList += (self) => + { + self.RemoveActionColumn(); + self.RemoveAction(); + if (temp.ErrorMessage.Count > 0) + { + self.AddErrorColumn(); + } + }; + temp.ListVM.DoInitListVM(); + if (temp.ListVM.Searcher != null) + { + var searcher = temp.ListVM.Searcher; + searcher.CopyContext(rv); + if (passInit == false) + { + searcher.DoInit(); + } + } + } + temp.LinkedVM?.DoInit(); + //temp.ListVM.DoSearch(); + } + //if the viewmodel is a ListVM, Init it's searcher + if (rv is IBasePagedListVM lvm) + { + var searcher = lvm.Searcher; + searcher.CopyContext(rv); + if (passInit == false) + { + searcher.DoInit(); + } + lvm.DoInitListVM(); + + } + if (rv is IBaseImport tvm) + { + var template = tvm.Template; + template.CopyContext(rv); + template.DoInit(); + var errorlist = tvm.ErrorListVM; + errorlist.CopyContext(rv); + } + + //if passinit is not set, call the viewmodel's DoInit method + if (passInit == false) + { + rv.DoInit(); + } + return rv; + } + + /// + /// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + /// + /// The type of the viewmodelThe type of the viewmodel + /// use Lambda to set viewmodel's properties,use && for multiply properties, for example Wtm.CreateVM(values: x=>x.Field1=='a' && x.Field2 == 'b'); will set viewmodel's Field1 to 'a' and Field2 to 'b' + /// if true, the viewmodel will not call InitVM internally + /// ViewModel + public T CreateVM(Expression> values = null, bool passInit = false) where T : BaseVM + { + SetValuesParser p = new SetValuesParser(); + var dir = p.Parse(values); + return CreateVM(typeof(T), null, new object[] { }, dir, passInit) as T; + } + + /// + /// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + /// + /// The type of the viewmodelThe type of the viewmodel + /// If the viewmodel is a BaseCRUDVM, the data having this id will be fetched + /// properties of the viewmodel that you want to assign values + /// if true, the viewmodel will not call InitVM internally + /// ViewModel + public T CreateVM(object Id, Expression> values = null, bool passInit = false) where T : BaseVM + { + SetValuesParser p = new SetValuesParser(); + var dir = p.Parse(values); + return CreateVM(typeof(T), Id, new object[] { }, dir, passInit) as T; + } + + /// + /// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + /// + /// The type of the viewmodelThe type of the viewmodel + /// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + /// use Lambda to set viewmodel's properties,use && for multiply properties, for example Wtm.CreateVM(values: x=>x.Field1=='a' && x.Field2 == 'b'); will set viewmodel's Field1 to 'a' and Field2 to 'b' + /// if true, the viewmodel will not call InitVM internally + /// ViewModel + public T CreateVM(object[] Ids, Expression> values = null, bool passInit = false) where T : BaseVM + { + SetValuesParser p = new SetValuesParser(); + var dir = p.Parse(values); + return CreateVM(typeof(T), null, Ids, dir, passInit) as T; + } + + + /// + /// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + /// + /// The type of the viewmodelThe type of the viewmodel + /// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + /// use Lambda to set viewmodel's properties,use && for multiply properties, for example Wtm.CreateVM(values: x=>x.Field1=='a' && x.Field2 == 'b'); will set viewmodel's Field1 to 'a' and Field2 to 'b' + /// if true, the viewmodel will not call InitVM internally + /// ViewModel + public T CreateVM(Guid[] Ids, Expression> values = null, bool passInit = false) where T : BaseVM + { + SetValuesParser p = new SetValuesParser(); + var dir = p.Parse(values); + return CreateVM(typeof(T), null, Ids.Cast().ToArray(), dir, passInit) as T; + } + + /// + /// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + /// + /// The type of the viewmodelThe type of the viewmodel + /// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + /// use Lambda to set viewmodel's properties,use && for multiply properties, for example Wtm.CreateVM(values: x=>x.Field1=='a' && x.Field2 == 'b'); will set viewmodel's Field1 to 'a' and Field2 to 'b' + /// if true, the viewmodel will not call InitVM internally + /// ViewModel + public T CreateVM(int[] Ids, Expression> values = null, bool passInit = false) where T : BaseVM + { + SetValuesParser p = new SetValuesParser(); + var dir = p.Parse(values); + return CreateVM(typeof(T), null, Ids.Cast().ToArray(), dir, passInit) as T; + } + + /// + /// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + /// + /// The type of the viewmodelThe type of the viewmodel + /// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + /// use Lambda to set viewmodel's properties,use && for multiply properties, for example Wtm.CreateVM(values: x=>x.Field1=='a' && x.Field2 == 'b'); will set viewmodel's Field1 to 'a' and Field2 to 'b' + /// if true, the viewmodel will not call InitVM internally + /// ViewModel + public T CreateVM(long[] Ids, Expression> values = null, bool passInit = false) where T : BaseVM + { + SetValuesParser p = new SetValuesParser(); + var dir = p.Parse(values); + return CreateVM(typeof(T), null, Ids.Cast().ToArray(), dir, passInit) as T; + } + /// + /// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + /// + /// The type of the viewmodelThe type of the viewmodel + /// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + /// use Lambda to set viewmodel's properties,use && for multiply properties, for example Wtm.CreateVM(values: x=>x.Field1=='a' && x.Field2 == 'b'); will set viewmodel's Field1 to 'a' and Field2 to 'b' + /// if true, the viewmodel will not call InitVM internally + /// ViewModel + public T CreateVM(string[] Ids, Expression> values = null, bool passInit = false) where T : BaseVM + { + SetValuesParser p = new SetValuesParser(); + var dir = p.Parse(values); + return CreateVM(typeof(T), null, Ids.Cast().ToArray(), dir, passInit) as T; + } + + /// + /// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + /// + /// the fullname of the viewmodel's type + /// If the viewmodel is a BaseCRUDVM, the data having this id will be fetched + /// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + /// if true, the viewmodel will not call InitVM internally + /// ViewModel + public BaseVM CreateVM(string VmFullName, object Id = null, object[] Ids = null, bool passInit = false) + { + return CreateVM(Type.GetType(VmFullName), Id, Ids, null, passInit); + } + #endregion + + #region CallApi + public async Task> CallAPI(string domainName, string url, HttpMethodEnum method, HttpContent content, int? timeout = null, string proxy = null) where T:class + { + ApiResult rv = new ApiResult(); + try + { + var factory = this.ServiceProvider.GetRequiredService(); + if (string.IsNullOrEmpty(url)) + { + return rv; + } + //新建http请求 + HttpClient client = null; + if (string.IsNullOrEmpty(domainName)) + { + client = factory.CreateClient(); + } + else + { + client = factory.CreateClient(domainName); + } + //如果配置了代理,则使用代理 + //设置超时 + if (timeout.HasValue) + { + client.Timeout = new TimeSpan(0, 0, 0, timeout.Value, 0); + } + //填充表单数据 + HttpResponseMessage res = null; + switch (method) + { + case HttpMethodEnum.GET: + res = await client.GetAsync(url); + break; + case HttpMethodEnum.POST: + res = await client.PostAsync(url, content); + break; + case HttpMethodEnum.PUT: + res = await client.PutAsync(url, content); + break; + case HttpMethodEnum.DELETE: + res = await client.DeleteAsync(url); + break; + default: + break; + } + if (res == null) + { + return rv; + } + rv.StatusCode = res.StatusCode; + if (res.IsSuccessStatusCode == true) + { + Type dt = typeof(T); + if (dt == typeof(byte[])) + { + rv.Data = await res.Content.ReadAsByteArrayAsync() as T; + } + else + { + string responseTxt = await res.Content.ReadAsStringAsync(); + if (dt == typeof(string)) + { + rv.Data = responseTxt as T; + } + else + { + rv.Data = JsonSerializer.Deserialize(responseTxt, CoreProgram.DefaultJsonOption); + } + } + } + else + { + string responseTxt = await res.Content.ReadAsStringAsync(); + if (res.StatusCode == System.Net.HttpStatusCode.BadRequest) + { + + try + { + rv.Errors = JsonSerializer.Deserialize(responseTxt, CoreProgram.DefaultJsonOption); + } + catch { } + } + rv.ErrorMsg = responseTxt; + } + + return rv; + } + catch (Exception ex) + { + rv.ErrorMsg = ex.ToString(); + return rv; + } + } + + /// + /// 使用Get方法调用api + /// + /// + /// Appsettings中配置的Domain key + /// 调用地址 + /// 超时时间,单位秒 + /// 代理地址 + /// + public async Task> CallAPI(string domainName, string url, int? timeout = null, string proxy = null) where T : class + { + HttpContent content = null; + //填充表单数据 + return await CallAPI(domainName, url, HttpMethodEnum.GET, content, timeout, proxy); + } + + /// + /// + /// + /// + /// Appsettings中配置的Domain key + /// 调用地址 + /// 调用方式 + /// 提交字段 + /// 超时时间,单位秒 + /// 代理地址 + /// + public async Task> CallAPI(string domainName, string url, HttpMethodEnum method, IDictionary postdata, int? timeout = null, string proxy = null) where T : class + { + HttpContent content = null; + //填充表单数据 + if (!(postdata == null || postdata.Count == 0)) + { + List> paras = new List>(); + foreach (string key in postdata.Keys) + { + paras.Add(new KeyValuePair(key, postdata[key])); + } + content = new FormUrlEncodedContent(paras); + } + return await CallAPI(domainName, url, method, content, timeout, proxy); + } + + /// + /// + /// + /// + /// Appsettings中配置的Domain key + /// 调用地址 + /// 调用方式 + /// 提交的object,会被转成json提交 + /// 超时时间,单位秒 + /// 代理地址 + /// + public async Task> CallAPI(string domainName, string url, HttpMethodEnum method, object postdata, int? timeout = null, string proxy = null) where T : class + { + HttpContent content = new StringContent(JsonSerializer.Serialize(postdata, CoreProgram.DefaultPostJsonOption), System.Text.Encoding.UTF8, "application/json"); + return await CallAPI(domainName, url, method, content, timeout, proxy); + } + + public async Task> CallAPI(string domainName, string url, HttpMethodEnum method, HttpContent content, int? timeout = null, string proxy = null) + { + return await CallAPI(domainName, url, method, content, timeout, proxy); + } + + /// + /// 使用Get方法调用api + /// + /// Appsettings中配置的Domain key + /// 调用地址 + /// 超时时间,单位秒 + /// 代理地址 + /// + public async Task> CallAPI(string domainName, string url, int? timeout = null, string proxy = null) + { + return await CallAPI(domainName, url, timeout, proxy); + } + + /// + /// + /// + /// Appsettings中配置的Domain key + /// 调用地址 + /// 调用方式 + /// 提交字段 + /// 超时时间,单位秒 + /// 代理地址 + /// + public async Task> CallAPI(string domainName, string url, HttpMethodEnum method, IDictionary postdata,int? timeout = null, string proxy = null) + { + return await CallAPI(domainName, url, method, postdata, timeout, proxy); + + } + + /// + /// + /// + /// Appsettings中配置的Domain key + /// 调用地址 + /// 调用方式 + /// 提交的object,会被转成json提交 + /// 超时时间,单位秒 + /// 代理地址 + /// + public async Task> CallAPI(string domainName, string url, HttpMethodEnum method, object postdata, int? timeout = null, string proxy = null) + { + return await CallAPI(domainName, url, method, postdata, timeout, proxy); + } + + #endregion + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/WalkingTec.Mvvm.Core.csproj b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/WalkingTec.Mvvm.Core.csproj new file mode 100644 index 0000000..0fa8616 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Core/WalkingTec.Mvvm.Core.csproj @@ -0,0 +1,45 @@ + + + net5.0 + WalkingTec.Mvvm + WalkingTec.Mvvm.Core + $(AssemblyName) + true + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers + + + + + + + + + + + + + + + + + + + diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/Attribute/AuthorizeCookieAttribute.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/Attribute/AuthorizeCookieAttribute.cs new file mode 100644 index 0000000..5c9b54f --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/Attribute/AuthorizeCookieAttribute.cs @@ -0,0 +1,14 @@ +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authorization; + +namespace WalkingTec.Mvvm.Mvc +{ + public class AuthorizeCookieAttribute : AuthorizeAttribute + { + public AuthorizeCookieAttribute() + { + AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme; + } + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/Attribute/AuthorizeJwtAttribute.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/Attribute/AuthorizeJwtAttribute.cs new file mode 100644 index 0000000..be1cbe5 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/Attribute/AuthorizeJwtAttribute.cs @@ -0,0 +1,14 @@ +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authorization; + +namespace WalkingTec.Mvvm.Mvc +{ + public class AuthorizeJwtAttribute : AuthorizeAttribute + { + public AuthorizeJwtAttribute() + { + AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme; + } + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/Attribute/AuthorizeJwtWithCookieAttribute.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/Attribute/AuthorizeJwtWithCookieAttribute.cs new file mode 100644 index 0000000..e6acb88 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/Attribute/AuthorizeJwtWithCookieAttribute.cs @@ -0,0 +1,14 @@ +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authorization; + +namespace WalkingTec.Mvvm.Mvc +{ + public class AuthorizeJwtWithCookieAttribute : AuthorizeAttribute + { + public AuthorizeJwtWithCookieAttribute() + { + AuthenticationSchemes = $"{CookieAuthenticationDefaults.AuthenticationScheme},{JwtBearerDefaults.AuthenticationScheme}"; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/JwtAuth/ITokenService.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/JwtAuth/ITokenService.cs new file mode 100644 index 0000000..9f2dcfa --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/JwtAuth/ITokenService.cs @@ -0,0 +1,30 @@ +using System.Threading.Tasks; +using WalkingTec.Mvvm.Core; + +namespace WalkingTec.Mvvm.Mvc.Auth +{ + public interface ITokenService + { + IDataContext DC { get; } + + /// + /// Issue token + /// + /// + /// + Task IssueTokenAsync(LoginUserInfo loginUserInfo); + + /// + /// refresh token + /// + /// refreshToken + /// + Task RefreshTokenAsync(string refreshToken); + + /// + /// clear expired refresh tokens + /// + /// + Task ClearExpiredRefreshTokenAsync(); + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/JwtAuth/Token.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/JwtAuth/Token.cs new file mode 100644 index 0000000..0a3a258 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/JwtAuth/Token.cs @@ -0,0 +1,20 @@ + +using System.Text.Json.Serialization; + +namespace WalkingTec.Mvvm.Mvc.Auth +{ + public class Token + { + [JsonPropertyName("access_token")] + public string AccessToken { get; set; } + + [JsonPropertyName("expires_in")] + public int ExpiresIn { get; set; } + + [JsonPropertyName("token_type")] + public string TokenType { get; set; } + + [JsonPropertyName("refresh_token")] + public string RefreshToken { get; set; } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/JwtAuth/TokenService.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/JwtAuth/TokenService.cs new file mode 100644 index 0000000..1dc61f4 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Auth/JwtAuth/TokenService.cs @@ -0,0 +1,155 @@ +using System; +using System.Collections.Generic; +using System.IdentityModel.Tokens.Jwt; +using System.Linq; +using System.Security.Claims; +using System.Text; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; +using WalkingTec.Mvvm.Core; +using WalkingTec.Mvvm.Core.Auth; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Mvc.Auth +{ + public class TokenService : ITokenService + { + private readonly ILogger _logger; + private readonly JwtOption _jwtOptions; + + private const Token _emptyToken = null; + + private readonly Configs _configs; + private readonly IDataContext _dc; + public IDataContext DC => _dc; + + public TokenService( + ILogger logger, + IOptionsMonitor configs + ) + { + _configs = configs.CurrentValue; + _jwtOptions = _configs.JwtOptions; + _logger = logger; + _dc = CreateDC(); + } + + public async Task IssueTokenAsync(LoginUserInfo loginUserInfo) + { + if (loginUserInfo == null) + throw new ArgumentNullException(nameof(loginUserInfo)); + + var signinCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.SecurityKey)), SecurityAlgorithms.HmacSha256); + + + var cls = new List() + { + new Claim(AuthConstants.JwtClaimTypes.Subject, loginUserInfo.ITCode.ToString()) + }; + if (string.IsNullOrEmpty(loginUserInfo.TenantCode) == false) + { + cls.Add(new Claim(AuthConstants.JwtClaimTypes.TenantCode, loginUserInfo.TenantCode.ToString())); + } + var tokeOptions = new JwtSecurityToken( + issuer: _jwtOptions.Issuer, + audience: _jwtOptions.Audience, + claims: cls, + expires: DateTime.Now.AddSeconds(_jwtOptions.Expires), + signingCredentials: signinCredentials + ); + + var refreshToken = new PersistedGrant() + { + UserCode = loginUserInfo.ITCode + "$`$" + loginUserInfo.TenantCode, + Type = "refresh_token", + CreationTime = DateTime.Now, + RefreshToken = Guid.NewGuid().ToString("N"), + Expiration = DateTime.Now.AddSeconds(_jwtOptions.RefreshTokenExpires) + }; + _dc.AddEntity(refreshToken); + await _dc.SaveChangesAsync(); + + var token = new JwtSecurityTokenHandler().WriteToken(tokeOptions); + + return await Task.FromResult(new Token() + { + AccessToken = token, + ExpiresIn = _jwtOptions.Expires, + TokenType = AuthConstants.JwtTokenType, + RefreshToken = refreshToken.RefreshToken + }); + } + + private IDataContext CreateDC() + { + string cs = "tokendefault"; + if (_configs.Connections.Any(x => x.Key.ToLower() == cs) == false) + { + cs = "default"; + } + return _configs.Connections.Where(x => x.Key.ToLower() == cs).FirstOrDefault().CreateDC(); + } + + + /// + /// refresh token + /// + /// refreshToken + /// + public async Task RefreshTokenAsync(string refreshToken) + { + // 获取 RefreshToken + PersistedGrant persistedGrant = await _dc.Set().Where(x => x.RefreshToken == refreshToken).SingleOrDefaultAsync(); + if (persistedGrant != null) + { + // 校验 regresh token 有效期 + if (persistedGrant.Expiration < DateTime.Now) + throw new Exception("refresh token 已过期"); + + // 删除 refresh token + _dc.DeleteEntity(persistedGrant); + await _dc.SaveChangesAsync(); + + var pair = persistedGrant.UserCode?.Split("$`$"); + //生成并返回登录用户信息 + var loginUserInfo = new LoginUserInfo() + { + ITCode = pair[0], + TenantCode = pair[1], + }; + + // 清理过期 refreshtoken + var sql = $"DELETE FROM {DC.GetTableName()} WHERE Expiration<'{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}'"; + _dc.RunSQL(sql); + _logger.LogDebug("清理过期的refreshToken:【sql:{0}】", sql); + + // 颁发 token + return await IssueTokenAsync(loginUserInfo); + } + else + { + return null; + } + } + + /// + /// clear expired refresh tokens + /// + /// + public async Task ClearExpiredRefreshTokenAsync() + { + var dataTime = DateTime.Now; + var mapping = _dc.GetTableName(); + var sql = $"DELETE FROM {mapping} WHERE Expiration<=@dataTime"; + _dc.RunSQL(sql, new + { + dataTime = dataTime + }); + await Task.CompletedTask; + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/BaseApiController.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/BaseApiController.cs new file mode 100644 index 0000000..78aaf86 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/BaseApiController.cs @@ -0,0 +1,313 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Text.Json.Serialization; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Logging; +using WalkingTec.Mvvm.Core; +using WalkingTec.Mvvm.Core.Auth; +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Core.Implement; +using WalkingTec.Mvvm.Core.Support.Json; + +namespace WalkingTec.Mvvm.Mvc +{ + public abstract class BaseApiController : ControllerBase, IBaseController + { + + [JsonIgnore] + [BindNever] + public WTMContext Wtm { get; set; } + + [JsonIgnore] + [BindNever] + public Configs ConfigInfo { get => Wtm?.ConfigInfo; } + + [JsonIgnore] + [BindNever] + public GlobalData GlobaInfo { get => Wtm?.GlobaInfo; } + + + [JsonIgnore] + [BindNever] + public IDistributedCache Cache { get => Wtm?.Cache; } + + [JsonIgnore] + [BindNever] + public string CurrentCS { get => Wtm?.CurrentCS; } + + [JsonIgnore] + [BindNever] + public DBTypeEnum? CurrentDbType { get => Wtm?.CurrentDbType; } + + [JsonIgnore] + [BindNever] + public IDataContext DC { get => Wtm?.DC; } + + [JsonIgnore] + [BindNever] + public string BaseUrl { get => Wtm?.BaseUrl; } + [JsonIgnore] + [BindNever] + public IStringLocalizer Localizer { get => Wtm?.Localizer; } + + + //-------------------------------------------方法------------------------------------// + + //#region CreateVM + ///// + ///// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + ///// + ///// The type of the viewmodel + ///// If the viewmodel is a BaseCRUDVM, the data having this id will be fetched + ///// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + ///// properties of the viewmodel that you want to assign values + ///// if true, the viewmodel will not call InitVM internally + ///// ViewModel + //[NonAction] + //private BaseVM CreateVM(Type VMType, object Id = null, object[] Ids = null, Dictionary values = null, bool passInit = false) + //{ + // //通过反射创建ViewModel并赋值 + // var ctor = VMType.GetConstructor(Type.EmptyTypes); + // BaseVM rv = ctor.Invoke(null) as BaseVM; + // rv.Wtm = Wtm; + // rv.FC = new Dictionary(); + // rv.CreatorAssembly = this.GetType().AssemblyQualifiedName; + // rv.ControllerName = this.GetType().FullName; + // if (HttpContext != null && HttpContext.Request != null) + // { + // try + // { + // if (Request.QueryString != QueryString.Empty) + // { + // foreach (var key in Request.Query.Keys) + // { + // if (rv.FC.Keys.Contains(key) == false) + // { + // rv.FC.Add(key, Request.Query[key]); + // } + // } + // } + // var f = HttpContext.Request.Form; + // foreach (var key in f.Keys) + // { + // if (rv.FC.Keys.Contains(key) == false) + // { + // rv.FC.Add(key, f[key]); + // } + // } + // } + // catch { } + // } + // //如果传递了默认值,则给vm赋值 + // if (values != null) + // { + // foreach (var v in values) + // { + // PropertyHelper.SetPropertyValue(rv, v.Key, v.Value, null, false); + // } + // } + // //如果ViewModel T继承自BaseCRUDVM<>且Id有值,那么自动调用ViewModel的GetById方法 + // if (Id != null && rv is IBaseCRUDVM cvm) + // { + // cvm.SetEntityById(Id); + // } + // //如果ViewModel T继承自IBaseBatchVM,则自动为其中的ListVM和EditModel初始化数据 + // if (rv is IBaseBatchVM temp) + // { + // temp.Ids = new string[] { }; + // if (Ids != null) + // { + // var tempids = new List(); + // foreach (var iid in Ids) + // { + // tempids.Add(iid.ToString()); + // } + // temp.Ids = tempids.ToArray(); + // } + // if (temp.ListVM != null) + // { + // temp.ListVM.CopyContext(rv); + // temp.ListVM.Ids = Ids == null ? new List() : temp.Ids.ToList(); + // temp.ListVM.SearcherMode = ListVMSearchModeEnum.Batch; + // temp.ListVM.NeedPage = false; + // } + // if (temp.LinkedVM != null) + // { + // temp.LinkedVM.CopyContext(rv); + // } + // if (temp.ListVM != null) + // { + // //绑定ListVM的OnAfterInitList事件,当ListVM的InitList完成时,自动将操作列移除 + // temp.ListVM.OnAfterInitList += (self) => + // { + // self.RemoveActionColumn(); + // self.RemoveAction(); + // if (temp.ErrorMessage.Count > 0) + // { + // self.AddErrorColumn(); + // } + // }; + // if (temp.ListVM.Searcher != null) + // { + // var searcher = temp.ListVM.Searcher; + // searcher.CopyContext(rv); + // if (passInit == false) + // { + // searcher.DoInit(); + // } + // } + // } + // temp.LinkedVM?.DoInit(); + // //temp.ListVM?.DoSearch(); + // } + // //如果ViewModel是ListVM,则初始化Searcher并调用Searcher的InitVM方法 + // if (rv is IBasePagedListVM lvm) + // { + // var searcher = lvm.Searcher; + // searcher.CopyContext(rv); + // if (passInit == false) + // { + // //获取保存在Cookie中的搜索条件的值,并自动给Searcher中的对应字段赋值 + // string namePre = ConfigInfo.CookiePre + "`Searcher" + "`" + rv.VMFullName + "`"; + // Type searcherType = searcher.GetType(); + // var pros = searcherType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance).ToList(); + // pros.Add(searcherType.GetProperty("IsValid")); + + // searcher.DoInit(); + // } + // } + // if (rv is IBaseImport tvm) + // { + // var template = tvm.Template; + // template.CopyContext(rv); + // template.DoInit(); + // } + + // //自动调用ViewMode的InitVM方法 + // if (passInit == false) + // { + // rv.DoInit(); + // } + // return rv; + //} + + ///// + ///// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + ///// + ///// The type of the viewmodel + ///// If the viewmodel is a BaseCRUDVM, the data having this id will be fetched + ///// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + ///// use Lambda to set viewmodel's properties,use && for multiply properties, for example Wtm.CreateVM(values: x=>x.Field1=='a' && x.Field2 == 'b'); will set viewmodel's Field1 to 'a' and Field2 to 'b' + ///// if true, the viewmodel will not call InitVM internally + ///// ViewModel + //[NonAction] + //public T Wtm.CreateVM(object Id = null, object[] Ids = null, Expression> values = null, bool passInit = false) where T : BaseVM + //{ + // SetValuesParser p = new SetValuesParser(); + // var dir = p.Parse(values); + // return CreateVM(typeof(T), Id, Ids, dir, passInit) as T; + //} + + ///// + ///// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + ///// + ///// the fullname of the viewmodel's type + ///// If the viewmodel is a BaseCRUDVM, the data having this id will be fetched + ///// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + ///// if true, the viewmodel will not call InitVM internally + ///// ViewModel + //[NonAction] + //public BaseVM CreateVM(string VmFullName, object Id = null, object[] Ids = null, bool passInit = false) + //{ + // return CreateVM(Type.GetType(VmFullName), Id, Ids, null, passInit); + //} + //#endregion + + + #region ReInit model + [NonAction] + private void SetReInit(ModelStateDictionary msd, BaseVM model) + { + var reinit = model.GetType().GetTypeInfo().GetCustomAttributes(typeof(ReInitAttribute), false).Cast().SingleOrDefault(); + + if (ModelState.IsValid) + { + if (reinit != null && (reinit.ReInitMode == ReInitModes.SUCCESSONLY || reinit.ReInitMode == ReInitModes.ALWAYS)) + { + model.DoReInit(); + } + } + else + { + if (reinit == null || (reinit.ReInitMode == ReInitModes.FAILEDONLY || reinit.ReInitMode == ReInitModes.ALWAYS)) + { + model.DoReInit(); + } + } + } + #endregion + + #region Validate model + [NonAction] + public Dictionary RedoValidation(object item) + { + Dictionary rv = new Dictionary(); + TryValidateModel(item); + + foreach (var e in ControllerContext.ModelState) + { + if (e.Value.ValidationState == ModelValidationState.Invalid) + { + rv.Add(e.Key, e.Value.Errors.Select(x => x.ErrorMessage).ToSepratedString()); + } + } + + return rv; + } + #endregion + + #region update viewmodel + /// + /// Set viewmodel's properties to the matching items posted by user + /// + /// ViewModel + /// prefix + /// true if success + [NonAction] + public bool RedoUpdateModel(object vm, string prefix = null) + { + try + { + BaseVM bvm = vm as BaseVM; + foreach (var item in bvm.FC.Keys) + { + PropertyHelper.SetPropertyValue(vm, item, bvm.FC[item], prefix, true); + } + return true; + } + catch + { + return false; + } + } + #endregion + + protected JsonResult JsonMore(object data, int statusCode = StatusCodes.Status200OK, string msg = "success") + { + return new JsonResult(new JsonResultT { Msg = msg, Code = statusCode, Data = data }); + } + + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/BaseController.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/BaseController.cs new file mode 100644 index 0000000..c89f1c8 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/BaseController.cs @@ -0,0 +1,435 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Text.Json.Serialization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +using WalkingTec.Mvvm.Core; +using WalkingTec.Mvvm.Core.Auth; +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Core.Support.Json; + +namespace WalkingTec.Mvvm.Mvc +{ + public abstract class BaseController : Controller, IBaseController + { + [JsonIgnore] + [BindNever] + public WTMContext Wtm { get; set; } + + + [JsonIgnore] + [BindNever] + public Configs ConfigInfo { get => Wtm?.ConfigInfo; } + + [JsonIgnore] + [BindNever] + public GlobalData GlobaInfo { get => Wtm?.GlobaInfo; } + + [JsonIgnore] + [BindNever] + public IUIService UIService { get => Wtm?.UIService; } + + [JsonIgnore] + [BindNever] + public IDistributedCache Cache { get => Wtm?.Cache; } + + [JsonIgnore] + [BindNever] + public string CurrentCS { get => Wtm?.CurrentCS; } + + [JsonIgnore] + [BindNever] + public DBTypeEnum? CurrentDbType { get => Wtm?.CurrentDbType; } + + [JsonIgnore] + [BindNever] + public string ParentWindowId { get => Wtm?.ParentWindowId; } + + [JsonIgnore] + [BindNever] + public string CurrentWindowId { get => Wtm?.CurrentWindowId; } + + [JsonIgnore] + [BindNever] + public string WindowIds { get => Wtm?.WindowIds; } + + #region DataContext + + [JsonIgnore] + [BindNever] + public IDataContext DC { get => Wtm?.DC; } + + #endregion + + #region URL + [JsonIgnore] + [BindNever] + public string BaseUrl { get => Wtm?.BaseUrl; } + #endregion + + [JsonIgnore] + [BindNever] + public IStringLocalizer Localizer { get => Wtm?.Localizer; } + + + //-------------------------------------------方法------------------------------------// + + //#region CreateVM + ///// + ///// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + ///// + ///// The type of the viewmodel + ///// If the viewmodel is a BaseCRUDVM, the data having this id will be fetched + ///// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + ///// properties of the viewmodel that you want to assign values + ///// if true, the viewmodel will not call InitVM internally + ///// ViewModel + //private BaseVM CreateVM(Type VMType, object Id = null, object[] Ids = null, Dictionary values = null, bool passInit = false) + //{ + // //Use reflection to create viewmodel + // var ctor = VMType.GetConstructor(Type.EmptyTypes); + // BaseVM rv = ctor.Invoke(null) as BaseVM; + // rv.Wtm = this.Wtm; + + // rv.FC = new Dictionary(); + // rv.CreatorAssembly = this.GetType().AssemblyQualifiedName; + // rv.Controller = this; + // rv.ControllerName = this.GetType().FullName; + // if (HttpContext != null && HttpContext.Request != null) + // { + // try + // { + // if (Request.QueryString != QueryString.Empty) + // { + // foreach (var key in Request.Query.Keys) + // { + // if (rv.FC.Keys.Contains(key) == false) + // { + // rv.FC.Add(key, Request.Query[key]); + // } + // } + // } + // if (HttpContext.Request.HasFormContentType) + // { + // var f = HttpContext.Request.Form; + // foreach (var key in f.Keys) + // { + // if (rv.FC.Keys.Contains(key) == false) + // { + // rv.FC.Add(key, f[key]); + // } + // } + // } + // } + // catch { } + // } + // //try to set values to the viewmodel's matching properties + // if (values != null) + // { + // foreach (var v in values) + // { + // PropertyHelper.SetPropertyValue(rv, v.Key, v.Value, null, false); + // } + // } + // //if viewmodel is derrived from BaseCRUDVM<> and Id has value, call ViewModel's GetById method + // if (Id != null && rv is IBaseCRUDVM cvm) + // { + // cvm.SetEntityById(Id); + // } + // //if viewmodel is derrived from IBaseBatchVM<>,set ViewMode's Ids property,and init it's ListVM and EditModel properties + // if (rv is IBaseBatchVM temp) + // { + // temp.Ids = new string[] { }; + // if (Ids != null) + // { + // var tempids = new List(); + // foreach (var iid in Ids) + // { + // tempids.Add(iid.ToString()); + // } + // temp.Ids = tempids.ToArray(); + // } + // if (temp.ListVM != null) + // { + // temp.ListVM.CopyContext(rv); + // temp.ListVM.Ids = Ids == null ? new List() : temp.Ids.ToList(); + // temp.ListVM.SearcherMode = ListVMSearchModeEnum.Batch; + // temp.ListVM.NeedPage = false; + // } + // if (temp.LinkedVM != null) + // { + // temp.LinkedVM.CopyContext(rv); + // } + // if (temp.ListVM != null) + // { + // //Remove the action columns from list + // temp.ListVM.OnAfterInitList += (self) => + // { + // self.RemoveActionColumn(); + // self.RemoveAction(); + // if (temp.ErrorMessage.Count > 0) + // { + // self.AddErrorColumn(); + // } + // }; + // temp.ListVM.DoInitListVM(); + // if (temp.ListVM.Searcher != null) + // { + // var searcher = temp.ListVM.Searcher; + // searcher.CopyContext(rv); + // if (passInit == false) + // { + // searcher.DoInit(); + // } + // } + // } + // temp.LinkedVM?.DoInit(); + // //temp.ListVM.DoSearch(); + // } + // //if the viewmodel is a ListVM, Init it's searcher + // if (rv is IBasePagedListVM lvm) + // { + // var searcher = lvm.Searcher; + // searcher.CopyContext(rv); + // if (passInit == false) + // { + // searcher.DoInit(); + // } + // lvm.DoInitListVM(); + + // } + // if (rv is IBaseImport tvm) + // { + // var template = tvm.Template; + // template.CopyContext(rv); + // template.DoInit(); + // } + + // //if passinit is not set, call the viewmodel's DoInit method + // if (passInit == false) + // { + // rv.DoInit(); + // } + // return rv; + //} + + ///// + ///// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + ///// + ///// The type of the viewmodelThe type of the viewmodel + ///// use Lambda to set viewmodel's properties,use && for multiply properties, for example Wtm.CreateVM(values: x=>x.Field1=='a' && x.Field2 == 'b'); will set viewmodel's Field1 to 'a' and Field2 to 'b' + ///// if true, the viewmodel will not call InitVM internally + ///// ViewModel + //public T Wtm.CreateVM(Expression> values = null, bool passInit = false) where T : BaseVM + //{ + // SetValuesParser p = new SetValuesParser(); + // var dir = p.Parse(values); + // return CreateVM(typeof(T), null, new object[] { }, dir, passInit) as T; + //} + + ///// + ///// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + ///// + ///// The type of the viewmodelThe type of the viewmodel + ///// If the viewmodel is a BaseCRUDVM, the data having this id will be fetched + ///// properties of the viewmodel that you want to assign values + ///// if true, the viewmodel will not call InitVM internally + ///// ViewModel + //public T Wtm.CreateVM(object Id, Expression> values = null, bool passInit = false) where T : BaseVM + //{ + // SetValuesParser p = new SetValuesParser(); + // var dir = p.Parse(values); + // return CreateVM(typeof(T), Id, new object[] { }, dir, passInit) as T; + //} + + ///// + ///// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + ///// + ///// The type of the viewmodelThe type of the viewmodel + ///// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + ///// use Lambda to set viewmodel's properties,use && for multiply properties, for example Wtm.CreateVM(values: x=>x.Field1=='a' && x.Field2 == 'b'); will set viewmodel's Field1 to 'a' and Field2 to 'b' + ///// if true, the viewmodel will not call InitVM internally + ///// ViewModel + //public T Wtm.CreateVM(object[] Ids, Expression> values = null, bool passInit = false) where T : BaseVM + //{ + // SetValuesParser p = new SetValuesParser(); + // var dir = p.Parse(values); + // return CreateVM(typeof(T), null, Ids, dir, passInit) as T; + //} + + + ///// + ///// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + ///// + ///// The type of the viewmodelThe type of the viewmodel + ///// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + ///// use Lambda to set viewmodel's properties,use && for multiply properties, for example Wtm.CreateVM(values: x=>x.Field1=='a' && x.Field2 == 'b'); will set viewmodel's Field1 to 'a' and Field2 to 'b' + ///// if true, the viewmodel will not call InitVM internally + ///// ViewModel + //public T Wtm.CreateVM(Guid[] Ids, Expression> values = null, bool passInit = false) where T : BaseVM + //{ + // SetValuesParser p = new SetValuesParser(); + // var dir = p.Parse(values); + // return CreateVM(typeof(T), null, Ids.Cast().ToArray(), dir, passInit) as T; + //} + + ///// + ///// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + ///// + ///// The type of the viewmodelThe type of the viewmodel + ///// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + ///// use Lambda to set viewmodel's properties,use && for multiply properties, for example Wtm.CreateVM(values: x=>x.Field1=='a' && x.Field2 == 'b'); will set viewmodel's Field1 to 'a' and Field2 to 'b' + ///// if true, the viewmodel will not call InitVM internally + ///// ViewModel + //public T Wtm.CreateVM(int[] Ids, Expression> values = null, bool passInit = false) where T : BaseVM + //{ + // SetValuesParser p = new SetValuesParser(); + // var dir = p.Parse(values); + // return CreateVM(typeof(T), null, Ids.Cast().ToArray(), dir, passInit) as T; + //} + + ///// + ///// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + ///// + ///// The type of the viewmodelThe type of the viewmodel + ///// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + ///// use Lambda to set viewmodel's properties,use && for multiply properties, for example Wtm.CreateVM(values: x=>x.Field1=='a' && x.Field2 == 'b'); will set viewmodel's Field1 to 'a' and Field2 to 'b' + ///// if true, the viewmodel will not call InitVM internally + ///// ViewModel + //public T Wtm.CreateVM(long[] Ids, Expression> values = null, bool passInit = false) where T : BaseVM + //{ + // SetValuesParser p = new SetValuesParser(); + // var dir = p.Parse(values); + // return CreateVM(typeof(T), null, Ids.Cast().ToArray(), dir, passInit) as T; + //} + ///// + ///// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + ///// + ///// The type of the viewmodelThe type of the viewmodel + ///// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + ///// use Lambda to set viewmodel's properties,use && for multiply properties, for example Wtm.CreateVM(values: x=>x.Field1=='a' && x.Field2 == 'b'); will set viewmodel's Field1 to 'a' and Field2 to 'b' + ///// if true, the viewmodel will not call InitVM internally + ///// ViewModel + //public T Wtm.CreateVM(string[] Ids, Expression> values = null, bool passInit = false) where T : BaseVM + //{ + // SetValuesParser p = new SetValuesParser(); + // var dir = p.Parse(values); + // return CreateVM(typeof(T), null, Ids.Cast().ToArray(), dir, passInit) as T; + //} + + ///// + ///// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel + ///// + ///// the fullname of the viewmodel's type + ///// If the viewmodel is a BaseCRUDVM, the data having this id will be fetched + ///// If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned + ///// if true, the viewmodel will not call InitVM internally + ///// ViewModel + //public BaseVM CreateVM(string VmFullName, object Id = null, object[] Ids = null, bool passInit = false) + //{ + // return CreateVM(Type.GetType(VmFullName), Id, Ids, null, passInit); + //} + //#endregion + + #region ReInit model + private void SetReInit(ModelStateDictionary msd, BaseVM model) + { + var reinit = model.GetType().GetTypeInfo().GetCustomAttributes(typeof(ReInitAttribute), false).Cast().SingleOrDefault(); + + if (ModelState.IsValid) + { + if (reinit != null && (reinit.ReInitMode == ReInitModes.SUCCESSONLY || reinit.ReInitMode == ReInitModes.ALWAYS)) + { + model.DoReInit(); + } + } + else + { + if (reinit == null || (reinit.ReInitMode == ReInitModes.FAILEDONLY || reinit.ReInitMode == ReInitModes.ALWAYS)) + { + model.DoReInit(); + } + } + } + #endregion + + #region Validate model + [NonAction] + public Dictionary RedoValidation(object item) + { + Dictionary rv = new Dictionary(); + TryValidateModel(item); + + foreach (var e in ControllerContext.ModelState) + { + if (e.Value.ValidationState == ModelValidationState.Invalid) + { + rv.Add(e.Key, e.Value.Errors.Select(x => x.ErrorMessage).ToSepratedString()); + } + } + + return rv; + } + #endregion + + #region update viewmodel + /// + /// Set viewmodel's properties to the matching items posted by user + /// + /// ViewModel + /// prefix + /// true if success + [NonAction] + public bool RedoUpdateModel(object vm, string prefix = null) + { + try + { + BaseVM bvm = vm as BaseVM; + foreach (var item in bvm.FC.Keys) + { + PropertyHelper.SetPropertyValue(vm, item, bvm.FC[item], prefix, true); + } + return true; + } + catch + { + return false; + } + } + #endregion + + [NonAction] + public FResult FFResult() + { + var rv = new FResult + { + Controller = this + }; + try + { + rv.Controller.Response?.Headers?.Add("IsScript", "true"); + } + catch { } + return rv; + } + + protected JsonResult JsonMore(object data, int statusCode = StatusCodes.Status200OK, string msg = "success") + { + return new JsonResult(new JsonResultT { Msg = msg, Code = statusCode, Data = data }); + } + + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Binders/DateRangeBinder.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Binders/DateRangeBinder.cs new file mode 100644 index 0000000..028373e --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Binders/DateRangeBinder.cs @@ -0,0 +1,56 @@ +using System; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using WalkingTec.Mvvm.Core; + +namespace WalkingTec.Mvvm.Mvc.Binders +{ + /// + /// DateRangeBinder + /// DataRange model binding + /// + public class DateRangeBinder : IModelBinder + { + /// + /// BindModelAsync + /// + /// + /// + public Task BindModelAsync(ModelBindingContext bindingContext) + { + if (bindingContext == null) + { + throw new ArgumentNullException(nameof(bindingContext)); + } + var modelName = bindingContext.ModelName; + if (string.IsNullOrEmpty(modelName)) + { + bindingContext.Result = ModelBindingResult.Success(null); + return Task.CompletedTask; + } + + var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName); + if (valueProviderResult == ValueProviderResult.None) + { + modelName += "[Value]"; + valueProviderResult = bindingContext.ValueProvider.GetValue(modelName); + } + + if (valueProviderResult == ValueProviderResult.None) + return Task.CompletedTask; + + bindingContext.ModelState.SetModelValue(modelName, valueProviderResult); + + var value = valueProviderResult.FirstValue; + + if (string.IsNullOrEmpty(value)) + { + return Task.CompletedTask; + } + + if(DateRange.TryParse(value,out var dateRange)) + bindingContext.Result = ModelBindingResult.Success(dateRange); + return Task.CompletedTask; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Binders/EnumBinder.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Binders/EnumBinder.cs new file mode 100644 index 0000000..807b189 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Binders/EnumBinder.cs @@ -0,0 +1,55 @@ +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using System; +using System.Linq; +using System.Threading.Tasks; + +namespace WalkingTec.Mvvm.Mvc.Binders +{ + /// + /// EnumBinder + /// 忽略enum转换空字符串时的错误 + /// + public class EnumBinder : IModelBinder + { + /// + /// BindModelAsync + /// + /// + /// + public Task BindModelAsync(ModelBindingContext bindingContext) + { + if (bindingContext == null) + { + throw new ArgumentNullException(nameof(bindingContext)); + } + var modelName = bindingContext.ModelName; + if (string.IsNullOrEmpty(modelName)) + { + bindingContext.Result = ModelBindingResult.Success(null); + return Task.CompletedTask; + } + + var valueProviderResult = + bindingContext.ValueProvider.GetValue(modelName); + + if (valueProviderResult == ValueProviderResult.None) + { + return Task.CompletedTask; + } + + bindingContext.ModelState.SetModelValue(modelName, valueProviderResult); + + var value = valueProviderResult.FirstValue; + if (string.IsNullOrEmpty(value)) + { + return Task.CompletedTask; + } + else + { + bindingContext.Result = ModelBindingResult.Success(Enum.Parse(bindingContext.ModelType,value)); + } + return Task.CompletedTask; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Binders/StringBinderProvider.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Binders/StringBinderProvider.cs new file mode 100644 index 0000000..46a6298 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Binders/StringBinderProvider.cs @@ -0,0 +1,36 @@ +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.ModelBinding.Binders; +using System; +using System.Collections; +using WalkingTec.Mvvm.Core; + +namespace WalkingTec.Mvvm.Mvc.Binders +{ + /// + /// CustomBinderProvider + /// + public class StringBinderProvider : IModelBinderProvider + { + /// + /// GetBinder + /// + /// + /// + public IModelBinder GetBinder(ModelBinderProviderContext context) + { + if (context == null) + { + throw new ArgumentNullException(nameof(context)); + } + + if (context.Metadata.ModelType == typeof(DateRange)) + return new BinderTypeModelBinder(typeof(DateRangeBinder)); + + if (context.Metadata.ModelType == typeof(string)) + { + return new BinderTypeModelBinder(typeof(StringIgnoreLTGTBinder)); + } + return null; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Binders/StringIgnoreLTGTBinder.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Binders/StringIgnoreLTGTBinder.cs new file mode 100644 index 0000000..17e99e2 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Binders/StringIgnoreLTGTBinder.cs @@ -0,0 +1,61 @@ +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using System; +using System.Linq; +using System.Threading.Tasks; +using System.Web; + +namespace WalkingTec.Mvvm.Mvc.Binders +{ + /// + /// StringIgnoreLTGTBinder + /// 忽略客户端提交的 <及>字符 + /// + public class StringIgnoreLTGTBinder : IModelBinder + { + /// + /// BindModelAsync + /// + /// + /// + public Task BindModelAsync(ModelBindingContext bindingContext) + { + if (bindingContext == null) + { + throw new ArgumentNullException(nameof(bindingContext)); + } + var modelName = bindingContext.ModelName; + if (string.IsNullOrEmpty(modelName)) + { + bindingContext.Result = ModelBindingResult.Success(null); + return Task.CompletedTask; + } + + var valueProviderResult = + bindingContext.ValueProvider.GetValue(modelName); + + if (valueProviderResult == ValueProviderResult.None) + { + return Task.CompletedTask; + } + + bindingContext.ModelState.SetModelValue(modelName, valueProviderResult); + + var value = valueProviderResult.FirstValue; + + var actDescriptor = bindingContext.ActionContext.ActionDescriptor as ControllerActionDescriptor; + var count = actDescriptor + .MethodInfo + .CustomAttributes + .Where(x => x.AttributeType == typeof(StringNeedLTGTAttribute)).Count(); + + if (count == 0) + { + value = HttpUtility.HtmlEncode(value); + } + + bindingContext.Result = ModelBindingResult.Success(value); + return Task.CompletedTask; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Binders/StringNeedLTGTAttribute.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Binders/StringNeedLTGTAttribute.cs new file mode 100644 index 0000000..2f2174d --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Binders/StringNeedLTGTAttribute.cs @@ -0,0 +1,12 @@ +using System; + +namespace WalkingTec.Mvvm.Mvc.Binders +{ + /// + /// StringNeedLTGT + /// + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] + public class StringNeedLTGTAttribute : Attribute + { + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/CodeGenListVM.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/CodeGenListVM.cs new file mode 100644 index 0000000..1f44ced --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/CodeGenListVM.cs @@ -0,0 +1,272 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using WalkingTec.Mvvm.Core; +using WalkingTec.Mvvm.Core.Attributes; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Mvc +{ + public class CodeGenListVM : BasePagedListVM + { + + public string ModelFullName { get; set; } + + public CodeGenListVM() + { + NeedPage = false; + } + + protected override IEnumerable> InitGridHeader() + { + return new List> + { + this.MakeGridHeader(x=>x.FieldName,200).SetFormat((entity,val)=>{return withHidden($"FieldInfos[{entity.Index}].FieldName",entity.FieldName); }), + this.MakeGridHeader(x=>x.FieldDes,200), + this.MakeGridHeader(x=>x.SubField,200).SetFormat((entity,val)=>{return subField($"FieldInfos[{entity.Index}]",entity); }), + this.MakeGridHeader(x=>x.IsSearcherField,150).SetFormat((entity,val)=>{return getCheckBox($"FieldInfos[{entity.Index}].IsSearcherField",entity.IsSearcherField); }), + this.MakeGridHeader(x=>x.IsListField,150).SetFormat((entity,val)=>{return getCheckBox($"FieldInfos[{entity.Index}].IsListField",entity.IsListField); }), + this.MakeGridHeader(x=>x.IsFormField,150).SetFormat((entity,val)=>{return getCheckBox($"FieldInfos[{entity.Index}].IsFormField",entity.IsFormField); }), + this.MakeGridHeader(x=>x.IsImportField,150).SetFormat((entity,val)=>{return getCheckBox($"FieldInfos[{entity.Index}].IsImportField",entity.IsImportField); }), + this.MakeGridHeader(x=>x.IsBatchField,150).SetFormat((entity,val)=>{return getCheckBox($"FieldInfos[{entity.Index}].IsBatchField",entity.IsBatchField); }) + }; + } + + private string getCheckBox(string fieldname, bool val) + { + return UIService.MakeCheckBox(val, name: fieldname, value:"true"); + } + + private string withHidden(string fieldname, string val) + { + return val + $""; + } + + private string subField(string fieldname, CodeGenListView entity) + { + string rv = $""; + rv += $""; + if (string.IsNullOrEmpty(entity.LinkedType) == false) + { + var linktype = Type.GetType(entity.LinkedType); + if (linktype != typeof(FileAttachment)) + { + var subpros = Type.GetType(entity.LinkedType).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).Where(x=>x.GetMemberType() == typeof(string) && x.Name != "BatchError").OrderBy(x => x.Name).ToList().ToListItems(x => x.Name, x => x.Name); + var subproswithname = subpros.Where(x => x.Text.ToLower().Contains("name")).ToList(); + var subproswithoutname = subpros.Where(x => x.Text.ToLower().Contains("name") == false).ToList(); + subpros = new List(); + subpros.AddRange(subproswithname); + subpros.AddRange(subproswithoutname); + if(subpros.Count == 0) + { + subpros.Add(new ComboSelectListItem { Text = "Id", Value = "Id" }); + } + rv += UIService.MakeCombo(fieldname + ".SubField", subpros); + } + else + { + rv += $""; + } + } + return rv; + } + + public override IOrderedQueryable GetSearchQuery() + { + Type modeltype = Type.GetType(ModelFullName); + var pros = modeltype.GetAllProperties(); + List lv = new List(); + int count = 0; + List skipFields = new List() + { + nameof(TopBasePoco.BatchError), + nameof(TopBasePoco.Checked), + nameof(TopBasePoco.ExcelIndex), + }; + if (typeof(IBasePoco).IsAssignableFrom(modeltype)) + { + skipFields.AddRange( + new string[]{ + nameof(IBasePoco.CreateBy), + nameof(IBasePoco.CreateTime), + nameof(IBasePoco.UpdateBy), + nameof(IBasePoco.UpdateTime) } + ); + } + if (typeof(IPersistPoco).IsAssignableFrom(modeltype)) + { + skipFields.Add(nameof(IPersistPoco.IsValid)); + } + + List ignoreField = new List(); + foreach (var pro in pros) + { + if (skipFields.Contains(pro.Name) == false) + { + if(pro.CanWrite == false) + { + continue; + } + if(pro.Name.ToLower() == "id" && pro.PropertyType != typeof(string)) + { + continue; + } + CodeGenListView view = new CodeGenListView() + { + FieldName = pro.Name, + FieldDes = pro.GetPropertyDisplayName(), + SubIdField = "", + Index = count + }; + var notmapped = pro.GetCustomAttributes(typeof(NotMappedAttribute), false).FirstOrDefault(); + Type checktype = pro.PropertyType; + if (pro.PropertyType.IsNullable()) + { + checktype = pro.PropertyType.GetGenericArguments()[0]; + } + if (ignoreField.Contains(checktype.Name)) + { + continue; + } + bool show = false; + view.IsFormField = true; + view.IsListField = true; + view.IsImportField = true; + if (checktype.IsPrimitive || checktype == typeof(string) || checktype == typeof(DateTime) || checktype.IsEnum() || checktype == typeof(decimal)) + { + show = true; + } + if (typeof(TopBasePoco).IsAssignableFrom(checktype)){ + var fk = DC.GetFKName2(modeltype, pro.Name); + if(fk != null) + { + ignoreField.Add(fk); + show = true; + } + if (checktype == typeof(FileAttachment)) + { + view.IsImportField = false; + view.FieldDes += $"({MvcProgram._localizer["Codegen.Attachment"]})"; + } + else + { + view.FieldDes += $"({MvcProgram._localizer["Codegen.OneToMany"]})"; + } + view.LinkedType = checktype.AssemblyQualifiedName; + if (fk != null) + { + if (modeltype.GetSingleProperty(fk) == null) + { + view.FieldDes = $"(Error:Can't find {fk.Replace("ID","Id")} in {checktype.Name})"; + } + } + } + if (checktype.IsList()) + { + checktype = pro.PropertyType.GetGenericArguments()[0]; + if (checktype.IsNullable()) + { + checktype = checktype.GetGenericArguments()[0]; + } + var middletable = checktype.GetCustomAttributes(typeof(MiddleTableAttribute), false).FirstOrDefault(); + if (middletable != null) + { + view.FieldDes += $"({MvcProgram._localizer["Codegen.ManyToMany"]})"; + view.IsImportField = false; + var subpros = checktype.GetAllProperties(); + foreach (var spro in subpros) + { + if(skipFields.Contains(spro.Name) == false) + { + Type subchecktype = spro.PropertyType; + if (spro.PropertyType.IsNullable()) + { + subchecktype = spro.PropertyType.GetGenericArguments()[0]; + } + if (typeof(TopBasePoco).IsAssignableFrom(subchecktype) && subchecktype != modeltype) + { + view.LinkedType = subchecktype.AssemblyQualifiedName; + var fk = DC.GetFKName2(checktype, spro.Name); + view.SubIdField = fk; + show = true; + if(checktype.GetSingleProperty(fk) == null) { + view.FieldDes = $"(Error:Can't find {fk.Replace("ID", "Id")} in {checktype.Name})"; + } + } + } + } + } + } + if (notmapped != null) + { + view.FieldDes += "(NotMapped)"; + view.IsFormField = false; + view.IsSearcherField = false; + view.IsBatchField = false; + view.IsImportField = false; + view.IsListField = false; + } + if (show == true) + { + lv.Add(view); + count++; + } + } + } + + for (int i = 0; i < lv.Count; i++) + { + if (ignoreField.Contains(lv[i].FieldName)) + { + for(int j = i; j < lv.Count; j++) + { + lv[j].Index--; + } + lv.RemoveAt(i); + i--; + } + } + + return lv.AsQueryable().OrderBy(x => x.FieldName); + } + } + + public class CodeGenListView : BasePoco + { + [Display(Name = "_Admin.FieldName")] + public string FieldName { get; set; } + + [Display(Name = "Codegen.FieldDes")] + public string FieldDes { get; set; } + + + [Display(Name = "Codegen.IsSearcherField")] + public bool IsSearcherField { get; set; } + + [Display(Name = "Codegen.IsListField")] + public bool IsListField { get; set; } + + [Display(Name = "Codegen.IsFormField")] + public bool IsFormField { get; set; } + + + [Display(Name = "Codegen.SubField")] + public string SubField { get; set; } + + public string SubIdField { get; set; } + + [Display(Name = "Codegen.IsImportField")] + public bool IsImportField { get; set; } + + [Display(Name = "Codegen.IsBatchField")] + public bool IsBatchField { get; set; } + + public int Index { get; set; } + + [Display(Name = "Codegen.LinkedType")] + public string LinkedType { get; set; } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/CodeGenVM.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/CodeGenVM.cs new file mode 100644 index 0000000..810ac9a --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/CodeGenVM.cs @@ -0,0 +1,2737 @@ +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using WalkingTec.Mvvm.Core; +using WalkingTec.Mvvm.Core.Extensions; + +namespace WalkingTec.Mvvm.Mvc +{ + public enum ApiAuthMode + { + [Display(Name = "Both Jwt and Cookie")] + Both, + [Display(Name = "Jwt")] + Jwt, + [Display(Name = "Cookie")] + Cookie + } + + [ReInit(ReInitModes.ALWAYS)] + public class CodeGenVM : BaseVM + { + public CodeGenListVM FieldList { get; set; } + + public List FieldInfos { get; set; } + + public string PreviewFile { get; set; } + + public UIEnum UI { get; set; } + + [Display(Name = "Codegen.GenApi")] + public bool IsApi { get; set; } + + [Display(Name = "Codegen.AuthMode")] + public ApiAuthMode AuthMode { get; set; } + + public string ModelName + { + get + { + return SelectedModel?.Split(',').FirstOrDefault()?.Split('.').LastOrDefault() ?? ""; + } + } + [Display(Name = "Codegen.ModelNS")] + [ValidateNever()] + public string ModelNS => SelectedModel?.Split(',').FirstOrDefault()?.Split('.').SkipLast(1).ToSepratedString(seperator: "."); + [Display(Name = "Codegen.ModuleName")] + [Required(ErrorMessage = "Validate.{0}required")] + public string ModuleName { get; set; } + [RegularExpression("^[A-Za-z_]+", ErrorMessage = "Codegen.EnglishOnly")] + public string Area { get; set; } + [ValidateNever()] + [BindNever()] + public List AllModels { get; set; } + [Required(ErrorMessage = "Validate.{0}required")] + [Display(Name = "_Admin.SelectedModel")] + public string SelectedModel { get; set; } + [ValidateNever()] + public string EntryDir { get; set; } + + + public string _mainDir; + [ValidateNever()] + public string MainDir + { + get + { + if (_mainDir == null) + { + int? index = EntryDir?.IndexOf($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}Debug{Path.DirectorySeparatorChar}"); + if (index == null || index < 0) + { + index = EntryDir?.IndexOf($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}Release{Path.DirectorySeparatorChar}") ?? 0; + } + + _mainDir = EntryDir?.Substring(0, index.Value); + } + return _mainDir; + } + set + { + _mainDir = value; + } + } + + public string _vmdir; + [ValidateNever()] + public string VmDir + { + get + { + if (_vmdir == null) + { + var up = Directory.GetParent(MainDir); + var vmdir = up.GetDirectories().Where(x => x.Name.ToLower().EndsWith(".viewmodel")).FirstOrDefault(); + if (vmdir == null) + { + if (string.IsNullOrEmpty(Area)) + { + vmdir = Directory.CreateDirectory(MainDir + $"{Path.DirectorySeparatorChar}ViewModels{Path.DirectorySeparatorChar}{ModelName}VMs"); + } + else + { + vmdir = Directory.CreateDirectory(MainDir + $"{Path.DirectorySeparatorChar}Areas{Path.DirectorySeparatorChar}{Area}{Path.DirectorySeparatorChar}ViewModels{Path.DirectorySeparatorChar}{ModelName}VMs"); + } + } + else + { + if (string.IsNullOrEmpty(Area)) + { + vmdir = Directory.CreateDirectory(vmdir.FullName + $"{Path.DirectorySeparatorChar}{ModelName}VMs"); + } + else + { + vmdir = Directory.CreateDirectory(vmdir.FullName + $"{Path.DirectorySeparatorChar}{Area}{Path.DirectorySeparatorChar}{ModelName}VMs"); + } + + } + _vmdir = vmdir.FullName; + } + return _vmdir; + } + } + + public string _sharedir; + [ValidateNever()] + public string ShareDir + { + get + { + if (_sharedir == null) + { + var up = Directory.GetParent(MainDir); + var sharedir = up.GetDirectories().Where(x => x.Name.ToLower().EndsWith(".shared")).FirstOrDefault(); + if (string.IsNullOrEmpty(Area)) + { + sharedir = Directory.CreateDirectory(sharedir.FullName + $"{Path.DirectorySeparatorChar}Pages{Path.DirectorySeparatorChar}{ModelName}"); + } + else + { + sharedir = Directory.CreateDirectory(sharedir.FullName + $"{Path.DirectorySeparatorChar}Pages{Path.DirectorySeparatorChar}{Area}{Path.DirectorySeparatorChar}{ModelName}"); + } + + _sharedir = sharedir.FullName; + } + return _sharedir; + } + } + + + public string _testdir; + [ValidateNever()] + public string TestDir + { + get + { + if (_testdir == null) + { + var up = Directory.GetParent(MainDir); + var testdir = up.GetDirectories().Where(x => x.Name.ToLower().EndsWith(".test")).FirstOrDefault(); + _testdir = testdir?.FullName; + } + return _testdir; + } + } + + + public string _controllerdir; + [ValidateNever()] + public string ControllerDir + { + get + { + if (_controllerdir == null) + { + if (string.IsNullOrEmpty(Area)) + { + _controllerdir = Directory.CreateDirectory(MainDir + $"{Path.DirectorySeparatorChar}Controllers").FullName; + } + else + { + _controllerdir = Directory.CreateDirectory(MainDir + $"{Path.DirectorySeparatorChar}Areas{Path.DirectorySeparatorChar}{Area}{Path.DirectorySeparatorChar}Controllers").FullName; + } + } + return _controllerdir; + } + } + + public string _viewdir; + [ValidateNever()] + public string ViewDir + { + get + { + if (_viewdir == null) + { + if (string.IsNullOrEmpty(Area)) + { + _viewdir = Directory.CreateDirectory(MainDir + $"{Path.DirectorySeparatorChar}Views{Path.DirectorySeparatorChar}{ModelName}").FullName; + } + else + { + _viewdir = Directory.CreateDirectory(MainDir + $"{Path.DirectorySeparatorChar}Areas{Path.DirectorySeparatorChar}{Area}{Path.DirectorySeparatorChar}Views{Path.DirectorySeparatorChar}{ModelName}").FullName; + } + } + return _viewdir; + } + } + + + private string _mainNs; + public string MainNS + { + get + { + int index = MainDir.LastIndexOf(Path.DirectorySeparatorChar); + if (index > 0) + { + _mainNs = MainDir[(index + 1)..]; + } + else + { + _mainNs = MainDir; + } + return _mainNs; + } + set + { + _mainNs = value; + } + + } + + private string _controllerNs; + [Display(Name = "Codegen.ControllerNs")] + [ValidateNever()] + public string ControllerNs + { + get + { + if (_controllerNs == null) + { + _controllerNs = MainNS + ".Controllers"; + } + return _controllerNs; + } + set + { + _controllerNs = value; + } + } + + private string _testNs; + [Display(Name = "Codegen.TestNs")] + [ValidateNever()] + public string TestNs + { + get + { + if (_testNs == null) + { + _testNs = MainNS + ".Test"; + } + return _testNs; + } + set + { + _testNs = value; + } + } + + private string _dataNs; + [Display(Name = "Codegen.DataNs")] + [ValidateNever()] + public string DataNs + { + get + { + if (_dataNs == null) + { + var up = Directory.GetParent(MainDir); + var vmdir = up.GetDirectories().Where(x => x.Name.ToLower().EndsWith(".dataaccess")).FirstOrDefault(); + if (vmdir == null) + { + _dataNs = MainNS; + } + else + { + _dataNs = MainNS + ".DataAccess"; ; + } + } + return _dataNs; + } + set + { + _dataNs = value; + } + } + + + private string _vmNs; + [Display(Name = "Codegen.VMNs")] + [ValidateNever()] + public string VMNs + { + get + { + if (_vmNs == null) + { + var up = Directory.GetParent(MainDir); + var vmdir = up.GetDirectories().Where(x => x.Name.ToLower().EndsWith(".viewmodel")).FirstOrDefault(); + if (vmdir == null) + { + if (string.IsNullOrEmpty(Area)) + { + _vmNs = MainNS + $".ViewModels.{ModelName}VMs"; + } + else + { + _vmNs = MainNS + $".{Area}.ViewModels.{ModelName}VMs"; + } + } + else + { + int index = vmdir.FullName.LastIndexOf(Path.DirectorySeparatorChar); + if (index > 0) + { + _vmNs = vmdir.FullName[(index + 1)..]; + } + else + { + _vmNs = vmdir.FullName; + } + if (string.IsNullOrEmpty(Area)) + { + _vmNs += $".{ModelName}VMs"; + } + else + { + _vmNs += $".{Area}.{ModelName}VMs"; + } + } + } + return _vmNs; + } + set + { + _vmNs = value; + } + } + + protected override void InitVM() + { + if (string.IsNullOrEmpty(SelectedModel) == false) + { + foreach (var item in ConfigInfo.Connections) + { + var dc = item.CreateDC(); + Type t = typeof(DbSet<>).MakeGenericType(Type.GetType(SelectedModel)); + var exist = dc.GetType().GetSingleProperty(x => x.PropertyType == t); + if (exist != null) + { + this.DC = dc; + } + } + + } + + FieldList = new CodeGenListVM(); + FieldList.CopyContext(this); + } + public void DoGen() + { + File.WriteAllText($"{ControllerDir}{Path.DirectorySeparatorChar}{ModelName}{(IsApi == true ? "Api" : "")}Controller.cs", GenerateController(), Encoding.UTF8); + + File.WriteAllText($"{VmDir}{Path.DirectorySeparatorChar}{ModelName}{(IsApi == true ? "Api" : "")}VM.cs", GenerateVM("CrudVM"), Encoding.UTF8); + File.WriteAllText($"{VmDir}{Path.DirectorySeparatorChar}{ModelName}{(IsApi == true ? "Api" : "")}ListVM.cs", GenerateVM("ListVM"), Encoding.UTF8); + File.WriteAllText($"{VmDir}{Path.DirectorySeparatorChar}{ModelName}{(IsApi == true ? "Api" : "")}BatchVM.cs", GenerateVM("BatchVM"), Encoding.UTF8); + File.WriteAllText($"{VmDir}{Path.DirectorySeparatorChar}{ModelName}{(IsApi == true ? "Api" : "")}ImportVM.cs", GenerateVM("ImportVM"), Encoding.UTF8); + File.WriteAllText($"{VmDir}{Path.DirectorySeparatorChar}{ModelName}{(IsApi == true ? "Api" : "")}Searcher.cs", GenerateVM("Searcher"), Encoding.UTF8); + + if (IsApi == false) + { + if (UI == UIEnum.LayUI) + { + File.WriteAllText($"{ViewDir}{Path.DirectorySeparatorChar}Index.cshtml", GenerateView("ListView"), Encoding.UTF8); + File.WriteAllText($"{ViewDir}{Path.DirectorySeparatorChar}Create.cshtml", GenerateView("CreateView"), Encoding.UTF8); + File.WriteAllText($"{ViewDir}{Path.DirectorySeparatorChar}Edit.cshtml", GenerateView("EditView"), Encoding.UTF8); + File.WriteAllText($"{ViewDir}{Path.DirectorySeparatorChar}Delete.cshtml", GenerateView("DeleteView"), Encoding.UTF8); + File.WriteAllText($"{ViewDir}{Path.DirectorySeparatorChar}Details.cshtml", GenerateView("DetailsView"), Encoding.UTF8); + File.WriteAllText($"{ViewDir}{Path.DirectorySeparatorChar}Import.cshtml", GenerateView("ImportView"), Encoding.UTF8); + File.WriteAllText($"{ViewDir}{Path.DirectorySeparatorChar}BatchEdit.cshtml", GenerateView("BatchEditView"), Encoding.UTF8); + File.WriteAllText($"{ViewDir}{Path.DirectorySeparatorChar}BatchDelete.cshtml", GenerateView("BatchDeleteView"), Encoding.UTF8); + } + if (UI == UIEnum.React || UI == UIEnum.VUE) + { + if (Directory.Exists($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}") == false) + { + Directory.CreateDirectory($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}"); + } + if (Directory.Exists($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}views") == false) + { + Directory.CreateDirectory($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}views"); + } + if (Directory.Exists($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}store") == false) + { + Directory.CreateDirectory($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}store"); + } + if (UI == UIEnum.React) + { + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}views{Path.DirectorySeparatorChar}action.tsx", GenerateReactView("action"), Encoding.UTF8); + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}views{Path.DirectorySeparatorChar}forms.tsx", GenerateReactView("forms"), Encoding.UTF8); + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}views{Path.DirectorySeparatorChar}models.tsx", GenerateReactView("models"), Encoding.UTF8); + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}views{Path.DirectorySeparatorChar}other.tsx", GenerateReactView("other"), Encoding.UTF8); + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}views{Path.DirectorySeparatorChar}search.tsx", GenerateReactView("search"), Encoding.UTF8); + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}views{Path.DirectorySeparatorChar}table.tsx", GenerateReactView("table"), Encoding.UTF8); + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}store{Path.DirectorySeparatorChar}index.ts", GetResource("index.txt", "Spa.React.store").Replace("$modelname$", ModelName.ToLower()), Encoding.UTF8); + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}index.tsx", GetResource("index.txt", "Spa.React").Replace("$modelname$", ModelName.ToLower()), Encoding.UTF8); + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}style.less", GetResource("style.txt", "Spa.React").Replace("$modelname$", ModelName.ToLower()), Encoding.UTF8); + } + if (UI == UIEnum.VUE) + { + List apipneeded = new List(); + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}index.vue", GenerateVUEView("index", apipneeded), Encoding.UTF8); + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}config.ts", GenerateVUEView("config", apipneeded), Encoding.UTF8); + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}views{Path.DirectorySeparatorChar}dialog-form.vue", GenerateVUEView("views.dialog-form", apipneeded), Encoding.UTF8); + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}store{Path.DirectorySeparatorChar}index.ts", GetResource("index.txt", "Spa.Vue.store").Replace("$modelname$", ModelName.ToLower()), Encoding.UTF8); + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}store{Path.DirectorySeparatorChar}api.ts", GenerateVUEView("store.api", apipneeded), Encoding.UTF8); + } + var index = File.ReadAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}index.ts"); + if (index.Contains($"path: '/{ModelName.ToLower()}'") == false) + { + if (UI == UIEnum.React) + { + index = index.Replace("/**WTM**/", $@" +, {ModelName.ToLower()}: {{ + name: '{ModuleName.ToLower()}', + path: '/{ModelName.ToLower()}', + controller: '{ControllerNs},{ModelName}', + component: React.lazy(() => import('./{ModelName.ToLower()}')) + }} +/**WTM**/ + "); + } + if (UI == UIEnum.VUE) + { + index = index.Replace("/**WTM**/", $@" +, {ModelName.ToLower()}: {{ + name: '{ModuleName.ToLower()}', + path: '/{ModelName.ToLower()}', + controller: '{ControllerNs},{ModelName}' + }} +/**WTM**/ + "); + + } + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}pages{Path.DirectorySeparatorChar}index.ts", index, Encoding.UTF8); + } + string menu = ""; + if (UI == UIEnum.React) + { + menu = File.ReadAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}public{Path.DirectorySeparatorChar}subMenu.json"); + if (menu.Contains($@"""Url"": ""/{ModelName.ToLower()}""") == false) + { + var i = menu.LastIndexOf("}"); + menu = menu.Insert(i + 1, $@" +,{{ + ""Id"": ""{Guid.NewGuid()}"", + ""ParentId"": null, + ""Text"": ""{ModuleName.ToLower()}"", + ""Url"": ""/{ModelName.ToLower()}"" + }} +"); + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}public{Path.DirectorySeparatorChar}subMenu.json", menu, Encoding.UTF8); + + } + } + if (UI == UIEnum.VUE) + { + menu = File.ReadAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}subMenu.json"); + if (menu.Contains($@"""Url"": ""/{ModelName.ToLower()}""") == false) + { + var i = menu.LastIndexOf("}"); + menu = menu.Insert(i + 1, $@" +,{{ + ""Id"": ""{Guid.NewGuid()}"", + ""ParentId"": null, + ""Text"": ""{ModuleName.ToLower()}"", + ""Url"": ""/{ModelName.ToLower()}"" + }} +"); + File.WriteAllText($"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}subMenu.json", menu, Encoding.UTF8); + + } + } + } + + if(UI == UIEnum.Blazor) + { + File.WriteAllText($"{ShareDir}{Path.DirectorySeparatorChar}Index.razor", GenerateBlazorView("Index"), Encoding.UTF8); + File.WriteAllText($"{ShareDir}{Path.DirectorySeparatorChar}Create.razor", GenerateBlazorView("Create"), Encoding.UTF8); + File.WriteAllText($"{ShareDir}{Path.DirectorySeparatorChar}Edit.razor", GenerateBlazorView("Edit"), Encoding.UTF8); + File.WriteAllText($"{ShareDir}{Path.DirectorySeparatorChar}Details.razor", GenerateBlazorView("Details"), Encoding.UTF8); + File.WriteAllText($"{ShareDir}{Path.DirectorySeparatorChar}Import.razor", GenerateBlazorView("Import"), Encoding.UTF8); + } + } + var test = GenerateTest(); + if (test != "") + { + if (UI == UIEnum.LayUI && IsApi == false) + { + File.WriteAllText($"{TestDir}{Path.DirectorySeparatorChar}{ModelName}ControllerTest.cs", test, Encoding.UTF8); + } + else + { + File.WriteAllText($"{TestDir}{Path.DirectorySeparatorChar}{ModelName}ApiTest.cs", test, Encoding.UTF8); + } + } + } + + public string GenerateController() + { + string dir = ""; + string jwt = ""; + if (UI == UIEnum.LayUI && IsApi == false) + { + dir = "Mvc"; + } + else + { + dir = "Spa"; + if(UI == UIEnum.Blazor) + { + dir = "Spa.Blazor"; + } + switch (AuthMode) + { + case ApiAuthMode.Both: + jwt = "[AuthorizeJwtWithCookie]"; + break; + case ApiAuthMode.Jwt: + jwt = "[AuthorizeJwt]"; + break; + case ApiAuthMode.Cookie: + jwt = "[AuthorizeCookie]"; + break; + default: + break; + } + } + var rv = GetResource("Controller.txt", dir).Replace("$jwt$", jwt).Replace("$vmnamespace$", VMNs).Replace("$namespace$", ControllerNs).Replace("$des$", ModuleName).Replace("$modelname$", ModelName).Replace("$modelnamespace$", ModelNS).Replace("$controllername$", $"{ModelName}{(IsApi == true ? "Api" : "")}"); + if (string.IsNullOrEmpty(Area)) + { + rv = rv.Replace("$area$", ""); + } + else + { + rv = rv.Replace("$area$", $"[Area(\"{Area}\")]"); + } + //生成api中获取下拉菜单数据的api + //如果一个一对多关联其他类的字段是搜索条件或者表单字段,则生成对应的获取关联表数据的api + if (UI != UIEnum.LayUI || IsApi == true) + { + StringBuilder other = new StringBuilder(); + List pros = FieldInfos.Where(x => x.IsSearcherField == true || x.IsFormField == true).ToList(); + List existSubPro = new List(); + for (int i = 0; i < pros.Count; i++) + { + var item = pros[i]; + if ((item.InfoType == FieldInfoType.One2Many || item.InfoType == FieldInfoType.Many2Many) && item.SubField != "`file") + { + var subtype = Type.GetType(item.RelatedField); + var subpro = subtype.GetSingleProperty(item.SubField); + var key = subtype.FullName + ":" + subpro.Name; + existSubPro.Add(key); + int count = existSubPro.Where(x => x == key).Count(); + if (count == 1) + { + + other.AppendLine($@" + [HttpGet(""Get{subtype.Name}s"")] + public ActionResult Get{subtype.Name}s() + {{ + return Ok(DC.Set<{subtype.Name}>().GetSelectListItems(Wtm, x => x.{item.SubField})); + }}"); + } + } + } + rv = rv.Replace("$other$", other.ToString()); + rv = GetRelatedNamespace(pros, rv); + } + return rv; + } + + public string GenerateVM(string name) + { + var rv = GetResource($"{name}.txt").Replace("$modelnamespace$", ModelNS).Replace("$vmnamespace$", VMNs).Replace("$modelname$", ModelName).Replace("$area$", $"{Area ?? ""}").Replace("$classname$", $"{ModelName}{(IsApi == true ? "Api" : "")}"); + if (name == "Searcher" || name == "BatchVM") + { + string prostring = ""; + string initstr = ""; + Type modelType = Type.GetType(SelectedModel); + List pros = null; + if (name == "Searcher") + { + pros = FieldInfos.Where(x => x.IsSearcherField == true).ToList(); + } + if (name == "BatchVM") + { + pros = FieldInfos.Where(x => x.IsBatchField == true).ToList(); + } + foreach (var pro in pros) + { + //对于一对一或者一对多的搜索和批量修改字段,需要在vm中生成对应的变量来获取关联表的数据 + if (pro.InfoType != FieldInfoType.Normal) + { + var subtype = Type.GetType(pro.RelatedField); + if (typeof(TopBasePoco).IsAssignableFrom(subtype) == false || subtype == typeof(FileAttachment)) + { + continue; + } + if (UI == UIEnum.LayUI && IsApi == false) + { + var fname = "All" + pro.FieldName + "s"; + prostring += $@" + public List {fname} {{ get; set; }}"; + initstr += $@" + {fname} = DC.Set<{subtype.Name}>().GetSelectListItems(Wtm, y => y.{pro.SubField});"; + } + } + + //生成普通字段定义 + var proType = modelType.GetSingleProperty(pro.FieldName); + var display = proType.GetCustomAttribute(); + if (display != null) + { + prostring += $@" + [Display(Name = ""{display.Name}"")]"; + } + string typename = proType.PropertyType.Name; + string proname = pro.GetField(DC, modelType); + + switch (pro.InfoType) + { + case FieldInfoType.Normal: + if (proType.PropertyType.IsNullable()) + { + typename = proType.PropertyType.GetGenericArguments()[0].Name + "?"; + } + else if (proType.PropertyType != typeof(string)) + { + typename = proType.PropertyType.Name + "?"; + } + break; + case FieldInfoType.One2Many: + typename = pro.GetFKType(DC, modelType); + if (typename != "string") + { + typename += "?"; + } + break; + case FieldInfoType.Many2Many: + proname = $@"Selected{pro.FieldName}IDs"; + typename = $"List<{pro.GetFKType(DC, modelType)}>"; + break; + default: + break; + } + if ((typename == "DateTime" || typename == "DateTime?") && name == "Searcher") + { + typename = "DateRange"; + } + prostring += $@" + public {typename} {proname} {{ get; set; }}"; + } + rv = rv.Replace("$pros$", prostring).Replace("$init$", initstr); + rv = GetRelatedNamespace(pros, rv); + } + if (name == "ListVM") + { + string headerstring = ""; + string selectstring = ""; + string wherestring = ""; + string subprostring = ""; + string formatstring = ""; + string actionstring = ""; + + if (UI == UIEnum.LayUI && IsApi == false) + { + actionstring = $@" + protected override List InitGridAction() + {{ + return new List + {{ + this.MakeStandardAction(""{ModelName}"", GridActionStandardTypesEnum.Create, Localizer[""Sys.Create""],""{Area ?? ""}"", dialogWidth: 800), + this.MakeStandardAction(""{ModelName}"", GridActionStandardTypesEnum.Edit, Localizer[""Sys.Edit""], ""{Area ?? ""}"", dialogWidth: 800), + this.MakeStandardAction(""{ModelName}"", GridActionStandardTypesEnum.Delete, Localizer[""Sys.Delete""], ""{Area ?? ""}"", dialogWidth: 800), + this.MakeStandardAction(""{ModelName}"", GridActionStandardTypesEnum.Details, Localizer[""Sys.Details""], ""{Area ?? ""}"", dialogWidth: 800), + this.MakeStandardAction(""{ModelName}"", GridActionStandardTypesEnum.BatchEdit, Localizer[""Sys.BatchEdit""], ""{Area ?? ""}"", dialogWidth: 800), + this.MakeStandardAction(""{ModelName}"", GridActionStandardTypesEnum.BatchDelete, Localizer[""Sys.BatchDelete""], ""{Area ?? ""}"", dialogWidth: 800), + this.MakeStandardAction(""{ModelName}"", GridActionStandardTypesEnum.Import, Localizer[""Sys.Import""], ""{Area ?? ""}"", dialogWidth: 800), + this.MakeStandardAction(""{ModelName}"", GridActionStandardTypesEnum.ExportExcel, Localizer[""Sys.Export""], ""{Area ?? ""}""), + }}; + }} +"; + } + + var pros = FieldInfos.Where(x => x.IsListField == true).ToList(); + Type modelType = Type.GetType(SelectedModel); + List existSubPro = new List(); + foreach (var pro in pros) + { + if (pro.InfoType == FieldInfoType.Normal) + { + headerstring += $@" + this.MakeGridHeader(x => x.{pro.FieldName}),"; + if (pro.FieldName.ToLower() != "id") + { + selectstring += $@" + {pro.FieldName} = x.{pro.FieldName},"; + } + } + else + { + var subtype = Type.GetType(pro.RelatedField); + if (subtype == typeof(FileAttachment)) + { + var filefk = DC.GetFKName2(modelType, pro.FieldName); + headerstring += $@" + this.MakeGridHeader(x => x.{filefk}).SetFormat({filefk}Format),"; + selectstring += $@" + {filefk} = x.{filefk},"; + formatstring += GetResource("HeaderFormat.txt").Replace("$modelname$", ModelName).Replace("$field$", filefk).Replace("$classname$", $"{ModelName}{(IsApi == true ? "Api" : "")}"); + } + else + { + var subpro = subtype.GetSingleProperty(pro.SubField); + existSubPro.Add(subpro); + string prefix = ""; + int count = existSubPro.Where(x => x.Name == subpro.Name).Count(); + if (count > 1) + { + prefix = count + ""; + } + string subtypename = subpro.PropertyType.Name; + if (subpro.PropertyType.IsNullable()) + { + subtypename = subpro.PropertyType.GetGenericArguments()[0].Name + "?"; + } + + var subdisplay = subpro.GetCustomAttribute(); + headerstring += $@" + this.MakeGridHeader(x => x.{pro.SubField + "_view" + prefix}),"; + if (pro.InfoType == FieldInfoType.One2Many) + { + selectstring += $@" + {pro.SubField + "_view" + prefix} = x.{pro.FieldName}.{pro.SubField},"; + } + else + { + var middleType = modelType.GetSingleProperty(pro.FieldName).PropertyType.GenericTypeArguments[0]; + var middlename = DC.GetPropertyNameByFk(middleType, pro.SubIdField); + if(typeof(IPersistPoco).IsAssignableFrom(Type.GetType(pro.RelatedField))) + { + selectstring += $@" + {pro.SubField + "_view" + prefix} = x.{pro.FieldName}.Where(y=>y.{middlename}.IsValid==true).Select(y=>y.{middlename}.{pro.SubField}).ToSepratedString(null,"",""), "; + } + else + { + selectstring += $@" + {pro.SubField + "_view" + prefix} = x.{pro.FieldName}.Select(y=>y.{middlename}.{pro.SubField}).ToSepratedString(null,"",""), "; + } + } + if (subdisplay?.Name != null) + { + subprostring += $@" + [Display(Name = ""{subdisplay.Name}"")]"; + } + subprostring += $@" + public {subtypename} {pro.SubField + "_view" + prefix} {{ get; set; }}"; + } + } + + } + var wherepros = FieldInfos.Where(x => x.IsSearcherField == true).ToList(); + foreach (var pro in wherepros) + { + if (pro.SubField == "`file") + { + continue; + } + var proType = modelType.GetSingleProperty(pro.FieldName)?.PropertyType; + + switch (pro.InfoType) + { + case FieldInfoType.Normal: + if (proType == typeof(string)) + { + wherestring += $@" + .CheckContain(Searcher.{pro.FieldName}, x=>x.{pro.FieldName})"; + } + else if (proType == typeof(DateTime) || proType == typeof(DateTime?)) + { + wherestring += $@" + .CheckBetween(Searcher.{pro.FieldName}?.GetStartTime(), Searcher.{pro.FieldName}?.GetEndTime(), x => x.{pro.FieldName}, includeMax: false)"; + } + else + { + wherestring += $@" + .CheckEqual(Searcher.{pro.FieldName}, x=>x.{pro.FieldName})"; + } + break; + case FieldInfoType.One2Many: + var fk = DC.GetFKName2(modelType, pro.FieldName); + wherestring += $@" + .CheckEqual(Searcher.{fk}, x=>x.{fk})"; + break; + case FieldInfoType.Many2Many: + var subtype = Type.GetType(pro.RelatedField); + var fk2 = DC.GetFKName(modelType, pro.FieldName); + wherestring += $@" + .CheckWhere(Searcher.Selected{pro.FieldName}IDs,x=>DC.Set<{proType.GetGenericArguments()[0].Name}>().Where(y=>Searcher.Selected{pro.FieldName}IDs.Contains(y.{pro.SubIdField})).Select(z=>z.{fk2}).Contains(x.ID))"; + break; + default: + break; + } + } + rv = rv.Replace("$headers$", headerstring).Replace("$where$", wherestring).Replace("$select$", selectstring).Replace("$subpros$", subprostring).Replace("$format$", formatstring).Replace("$actions$", actionstring); + rv = GetRelatedNamespace(pros, rv); + } + if (name == "CrudVM") + { + string prostr = ""; + string initstr = ""; + string includestr = ""; + string addstr = ""; + string editstr = ""; + var pros = FieldInfos.Where(x => x.IsFormField == true && string.IsNullOrEmpty(x.RelatedField) == false).ToList(); + foreach (var pro in pros) + { + var subtype = Type.GetType(pro.RelatedField); + if (typeof(TopBasePoco).IsAssignableFrom(subtype) == false || subtype == typeof(FileAttachment)) + { + continue; + } + var fname = "All" + pro.FieldName + "s"; + if (UI == UIEnum.LayUI) + { + prostr += $@" + public List {fname} {{ get; set; }}"; + initstr += $@" + {fname} = DC.Set<{subtype.Name}>().GetSelectListItems(Wtm, y => y.{pro.SubField});"; + } + includestr += $@" + SetInclude(x => x.{pro.FieldName});"; + + if (pro.InfoType == FieldInfoType.Many2Many) + { + Type modelType = Type.GetType(SelectedModel); + var protype = modelType.GetSingleProperty(pro.FieldName); + prostr += $@" + [Display(Name = ""{protype.GetPropertyDisplayName()}"")] + public List Selected{pro.FieldName}IDs {{ get; set; }}"; + initstr += $@" + Selected{pro.FieldName}IDs = Entity.{pro.FieldName}?.Select(x => x.{pro.SubIdField}.ToString()).ToList();"; + addstr += $@" + Entity.{pro.FieldName} = new List<{protype.PropertyType.GetGenericArguments()[0].Name}>(); + if (Selected{pro.FieldName}IDs != null) + {{ + foreach (var id in Selected{pro.FieldName}IDs) + {{ + {protype.PropertyType.GetGenericArguments()[0].Name} middle = new {protype.PropertyType.GetGenericArguments()[0].Name}(); + middle.SetPropertyValue(""{pro.SubIdField}"", id); + Entity.{pro.FieldName}.Add(middle); + }} + }} +"; + editstr += $@" + Entity.{pro.FieldName} = new List<{protype.PropertyType.GetGenericArguments()[0].Name}>(); + if(Selected{pro.FieldName}IDs != null ) + {{ + foreach (var item in Selected{pro.FieldName}IDs) + {{ + {protype.PropertyType.GetGenericArguments()[0].Name} middle = new {protype.PropertyType.GetGenericArguments()[0].Name}(); + middle.SetPropertyValue(""{pro.SubIdField}"", item); + Entity.{pro.FieldName}.Add(middle); + }} + }} +"; + } + } + if ((UI == UIEnum.LayUI && IsApi == false) || UI == UIEnum.Blazor) + { + rv = rv.Replace("$pros$", prostr).Replace("$init$", initstr).Replace("$include$", includestr).Replace("$add$", addstr).Replace("$edit$", editstr); + } + else + { + rv = rv.Replace("$pros$", "").Replace("$init$", "").Replace("$include$", includestr).Replace("$add$", "").Replace("$edit$", ""); + } + rv = GetRelatedNamespace(pros, rv); + } + if (name == "ImportVM") + { + string prostring = ""; + string initstr = ""; + Type modelType = Type.GetType(SelectedModel); + List pros = FieldInfos.Where(x => x.IsImportField == true).ToList(); + foreach (var pro in pros) + { + if (pro.InfoType == FieldInfoType.Many2Many) + { + continue; + } + + if (string.IsNullOrEmpty(pro.RelatedField) == false) + { + var subtype = Type.GetType(pro.RelatedField); + if (typeof(TopBasePoco).IsAssignableFrom(subtype) == false || subtype == typeof(FileAttachment)) + { + continue; + } + initstr += $@" + {pro.FieldName + "_Excel"}.DataType = ColumnDataType.ComboBox; + {pro.FieldName + "_Excel"}.ListItems = DC.Set<{subtype.Name}>().GetSelectListItems(Wtm, y => y.{pro.SubField});"; + } + var proType = modelType.GetSingleProperty(pro.FieldName); + var display = proType.GetCustomAttribute(); + var filefk = DC.GetFKName2(modelType, pro.FieldName); + if (display != null) + { + prostring += $@" + [Display(Name = ""{display.Name}"")]"; + } + if (string.IsNullOrEmpty(pro.RelatedField) == false) + { + prostring += $@" + public ExcelPropety {pro.FieldName + "_Excel"} = ExcelPropety.CreateProperty<{ModelName}>(x => x.{filefk});"; + } + else + { + prostring += $@" + public ExcelPropety {pro.FieldName + "_Excel"} = ExcelPropety.CreateProperty<{ModelName}>(x => x.{pro.FieldName});"; + } + } + rv = rv.Replace("$pros$", prostring).Replace("$init$", initstr); + rv = GetRelatedNamespace(pros, rv); + + } + return rv; + } + + public string GenerateView(string name) + { + var rv = GetResource($"{name}.txt", "Mvc").Replace("$vmnamespace$", VMNs).Replace("$modelname$", ModelName); + if (name == "CreateView" || name == "EditView" || name == "DeleteView" || name == "DetailsView" || name == "BatchEditView") + { + StringBuilder fieldstr = new StringBuilder(); + string pre = ""; + List pros = null; + if (name == "BatchEditView") + { + pros = FieldInfos.Where(x => x.IsBatchField == true).ToList(); + pre = "LinkedVM"; + } + else + { + pros = FieldInfos.Where(x => x.IsFormField == true).ToList(); + pre = "Entity"; + } + Type modelType = Type.GetType(SelectedModel); + fieldstr.Append(Environment.NewLine); + fieldstr.Append(@""); + fieldstr.Append(Environment.NewLine); + foreach (var item in pros) + { + if (name == "DeleteView" || name == "DetailsView") + { + if (string.IsNullOrEmpty(item.SubIdField) == true) + { + if (string.IsNullOrEmpty(item.RelatedField) == false && item.SubField != "`file") + { + fieldstr.Append($@""); + } + else + { + string idname = item.FieldName; + if (string.IsNullOrEmpty(item.RelatedField) == false && item.SubField == "`file") + { + var filefk = DC.GetFKName2(modelType, item.FieldName); + idname = filefk; + } + fieldstr.Append($@""); + } + } + } + else + { + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + var filefk = DC.GetFKName2(modelType, item.FieldName); + if (item.SubField == "`file") + { + if (name != "BatchEditView") + { + fieldstr.Append($@""); + } + } + else + { + var fname = "All" + item.FieldName + "s"; + if (name == "BatchEditView") + { + fname = "LinkedVM." + fname; + } + if (string.IsNullOrEmpty(item.SubIdField)) + { + fieldstr.Append($@""); + } + else + { + if (name == "BatchEditView") + { + fieldstr.Append($@""); + } + else + { + fieldstr.Append($@""); + } + } + } + } + else + { + var proType = modelType.GetSingleProperty(item.FieldName)?.PropertyType; + Type checktype = proType; + if (proType.IsNullable()) + { + checktype = proType.GetGenericArguments()[0]; + } + if(checktype == typeof(bool) && proType.IsNullable() == false) + { + fieldstr.Append($@""); + + } + else if (checktype == typeof(bool) || checktype.IsEnum()) + { + fieldstr.Append($@""); + } + else if (checktype.IsPrimitive || checktype == typeof(string) || checktype == typeof(decimal)) + { + fieldstr.Append($@""); + } + else if (checktype == typeof(DateTime)) + { + fieldstr.Append($@""); + } + } + } + fieldstr.Append(Environment.NewLine); + } + fieldstr.Append(""); + rv = rv.Replace("$fields$", fieldstr.ToString()); + } + if (name == "ListView") + { + StringBuilder fieldstr = new StringBuilder(); + var pros = FieldInfos.Where(x => x.IsSearcherField == true).ToList(); + Type modelType = Type.GetType(SelectedModel); + fieldstr.Append(Environment.NewLine); + fieldstr.Append(@""); + fieldstr.Append(Environment.NewLine); + foreach (var item in pros) + { + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + if (item.SubField == "`file") + { + continue; + } + var fname = "All" + item.FieldName + "s"; + var fk = ""; + if (string.IsNullOrEmpty(item.SubIdField)) + { + fk = DC.GetFKName2(modelType, item.FieldName); ; + } + else + { + fk = $@"Selected{item.FieldName}IDs"; + } + fieldstr.Append($@""); + } + else + { + var proType = modelType.GetSingleProperty(item.FieldName)?.PropertyType; + Type checktype = proType; + if (proType.IsNullable()) + { + checktype = proType.GetGenericArguments()[0]; + } + if ((checktype.IsPrimitive && checktype != typeof(bool)) || checktype == typeof(string) || checktype == typeof(decimal)) + { + fieldstr.Append($@""); + } + if (checktype == typeof(DateTime)) + { + fieldstr.Append($@""); + } + if (checktype.IsEnum() || checktype.IsBool()) + { + fieldstr.Append($@""); + } + } + fieldstr.Append(Environment.NewLine); + } + fieldstr.Append($@""); + string url = ""; + if (string.IsNullOrEmpty(Area)) + { + url = $"/{ModelName}/Search"; + } + else + { + url = $"/{Area}/{ModelName}/Search"; + } + rv = rv.Replace("$fields$", fieldstr.ToString()).Replace("$searchurl$", url); + } + return rv; + } + + public string GenerateTest() + { + var rv = ""; + if (TestDir != null) + { + Type modelType = Type.GetType(SelectedModel); + if (UI == UIEnum.LayUI && IsApi == false) + { + if (typeof(IBasePoco).IsAssignableFrom( modelType) || typeof(IPersistPoco).IsAssignableFrom(modelType)) + { + rv = GetResource($"ControllerTest.txt").Replace("$cns$", ControllerNs).Replace("$tns$", TestNs).Replace("$vns$", VMNs).Replace("$model$", ModelName).Replace("$mns$", ModelNS).Replace("$dns$", DataNs); + } + else + { + rv = GetResource($"ControllerTestTopPoco.txt").Replace("$cns$", ControllerNs).Replace("$tns$", TestNs).Replace("$vns$", VMNs).Replace("$model$", ModelName).Replace("$mns$", ModelNS).Replace("$dns$", DataNs); + } + } + else + { + if (typeof(IBasePoco).IsAssignableFrom(modelType) || typeof(IPersistPoco).IsAssignableFrom(modelType)) + { + rv = GetResource($"ApiTest.txt").Replace("$cns$", ControllerNs).Replace("$tns$", TestNs).Replace("$vns$", VMNs).Replace("$model$", ModelName).Replace("$mns$", ModelNS).Replace("$dns$", DataNs).Replace("$classnamel$", $"{ModelName}{(IsApi == true ? "Api" : "")}"); + } + else + { + rv = GetResource($"ApiTestTopPoco.txt").Replace("$cns$", ControllerNs).Replace("$tns$", TestNs).Replace("$vns$", VMNs).Replace("$model$", ModelName).Replace("$mns$", ModelNS).Replace("$dns$", DataNs).Replace("$classnamel$", $"{ModelName}{(IsApi == true ? "Api" : "")}"); + } + } + var modelprops = modelType.GetRandomValues(); + var batchpros = FieldInfos.Where(x => x.IsBatchField == true).ToList(); + string cpros = ""; + string epros = ""; + string pros = ""; + string mpros = ""; + string assert = ""; + string eassert = ""; + string fc = ""; + string add = ""; + string linkedpros = ""; + string linkedfc = ""; + string meassert = ""; + List addexist = new List(); + foreach (var pro in modelprops) + { + if (pro.Value == "$fk$") + { + var fktype = modelType.GetSingleProperty(pro.Key[0..^2])?.PropertyType; + add += GenerateAddFKModel(pro.Key[0..^2], fktype, addexist); + } + } + + foreach (var pro in modelprops) + { + if (pro.Value == "$fk$") + { + var fktype = modelType.GetSingleProperty(pro.Key[0..^2])?.PropertyType; + cpros += $@" + v.{pro.Key} = Add{fktype.Name}();"; + pros += $@" + v.{pro.Key} = Add{fktype.Name}();"; + mpros += $@" + v1.{pro.Key} = Add{fktype.Name}();"; + } + else + { + cpros += $@" + v.{pro.Key} = {pro.Value};"; + pros += $@" + v.{pro.Key} = {pro.Value};"; + mpros += $@" + v1.{pro.Key} = {pro.Value};"; + assert += $@" + Assert.AreEqual(data.{pro.Key}, {pro.Value});"; + } + fc += $@" + vm.FC.Add(""Entity.{pro.Key}"", """");"; + + } + + var modelpros2 = modelType.GetRandomValues(); + foreach (var pro in modelpros2) + { + //if (pro.Key.ToLower() == "id") + //{ + // continue; + //} + + if (pro.Value == "$fk$") + { + mpros += $@" + v2.{ pro.Key} = v1.{pro.Key}; "; + + } + else + { + mpros += $@" + v2.{pro.Key} = {pro.Value};"; + if (pro.Key.ToLower() != "id") + { + epros += $@" + v.{pro.Key} = {pro.Value};"; + eassert += $@" + Assert.AreEqual(data.{pro.Key}, {pro.Value});"; + } + } + } + + var modelpros3 = modelType.GetRandomValues(); + foreach (var pro in modelpros3) + { + if (batchpros.Any(x => x.FieldName == pro.Key) && pro.Key.ToLower() != "id") + { + linkedpros += $@" + vm.LinkedVM.{pro.Key} = {pro.Value};"; + linkedfc += $@" + vm.FC.Add(""LinkedVM.{pro.Key}"", """");"; + meassert += $@" + Assert.AreEqual(data1.{pro.Key}, {pro.Value});"; + meassert += $@" + Assert.AreEqual(data2.{pro.Key}, {pro.Value});"; + } + } + + + string del = $"Assert.AreEqual(data, null);"; + string mdel = @"Assert.AreEqual(data1, null); + Assert.AreEqual(data2, null);"; + if (typeof(IPersistPoco).IsAssignableFrom( modelType)) + { + del = $"Assert.AreEqual(data.IsValid, false);"; + mdel = @"Assert.AreEqual(data1.IsValid, false); + Assert.AreEqual(data2.IsValid, false);"; + } + + rv = rv.Replace("$cpros$", cpros).Replace("$epros$", epros).Replace("$pros$", pros).Replace("$mpros$", mpros) + .Replace("$assert$", assert).Replace("$eassert$", eassert).Replace("$fc$", fc).Replace("$add$", add).Replace("$del$", del).Replace("$mdel$", mdel) + .Replace("$linkedpros$", linkedpros).Replace("$linkedfc$", linkedfc).Replace("$meassert$", meassert); + + rv = GetRelatedNamespace(FieldInfos.Where(x=>string.IsNullOrEmpty( x.RelatedField) == false).ToList(), rv); + } + return rv; + } + + private string GenerateAddFKModel(string keyname, Type t, List exist) + { + if(exist == null) + { + exist = new List(); + } + if(exist.Contains(t) == true) + { + return ""; + } + exist.Add(t); + var modelprops = t.GetRandomValues(); + var mname = t.Name?.Split(',').FirstOrDefault()?.Split('.').LastOrDefault() ?? ""; + string cpros = ""; + string rv = ""; + foreach (var pro in modelprops) + { + if (pro.Value == "$fk$") + { + var fktype = t.GetSingleProperty(pro.Key[0..^2])?.PropertyType; + if (fktype != t) + { + rv += GenerateAddFKModel(pro.Key[0..^2], fktype, exist); + } + } + } + + + foreach (var pro in modelprops) + { + if (pro.Value == "$fk$") + { + var fktype = t.GetSingleProperty(pro.Key[0..^2])?.PropertyType; + if (fktype != t) + { + cpros += $@" + v.{pro.Key} = Add{fktype.Name}();"; + } + } + else + { + cpros += $@" + v.{pro.Key} = {pro.Value};"; + } + } + var idpro = t.GetSingleProperty("ID"); + rv += $@" + private {idpro.PropertyType.Name} Add{t.Name}() + {{ + {mname} v = new {mname}(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + {{ + try{{ +{cpros} + context.Set<{mname}>().Add(v); + context.SaveChanges(); + }} + catch{{}} + }} + return v.ID; + }} +"; + return rv; + } + + public string GenerateReactView(string name) + { + var rv = GetResource($"{name}.txt", "Spa.React.views") + .Replace("$modelname$", ModelName.ToLower()); + Type modelType = Type.GetType(SelectedModel); + if (name == "table") + { + StringBuilder fieldstr = new StringBuilder(); + var pros = FieldInfos.Where(x => x.IsListField == true).ToList(); + fieldstr.Append(Environment.NewLine); + List existSubPro = new List(); + int rowheight = 30; + for (int i = 0; i < pros.Count; i++) + { + var item = pros[i]; + var mpro = modelType.GetSingleProperty(item.FieldName); + string label = mpro.GetPropertyDisplayName(); + string render = ""; + string newname = item.FieldName; + if (mpro.PropertyType.IsBoolOrNullableBool()) + { + render = "columnsRenderBoolean"; + } + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + var subtype = Type.GetType(item.RelatedField); + string prefix = ""; + if (subtype == typeof(FileAttachment)) + { + if (item.FieldName.ToLower().Contains("photo") || item.FieldName.ToLower().Contains("pic") || item.FieldName.ToLower().Contains("icon")) + { + render = "columnsRenderImg"; + rowheight = 110; + } + else + { + render = "columnsRenderDownload"; + } + var fk = DC.GetFKName2(modelType, item.FieldName); + newname = fk; + } + else + { + var subpro = subtype.GetSingleProperty(item.SubField); + existSubPro.Add(subpro); + int count = existSubPro.Where(x => x.Name == subpro.Name).Count(); + if (count > 1) + { + prefix = count + ""; + } + newname = item.SubField + "_view" + prefix; + } + } + fieldstr.Append($@" + {{ + field: ""{newname}"", + headerName: ""{label}"""); + + if (render != "") + { + fieldstr.Append($@", + cellRenderer: ""{render}"" "); + } + fieldstr.Append($@" + }}"); + if (i < pros.Count - 1) + { + fieldstr.Append(','); + } + fieldstr.Append(Environment.NewLine); + } + return rv.Replace("$columns$", fieldstr.ToString()).Replace("$rowheight$", rowheight.ToString()); + } + if (name == "models") + { + StringBuilder fieldstr = new StringBuilder(); + StringBuilder fieldstr2 = new StringBuilder(); + var pros = FieldInfos.Where(x => x.IsFormField == true).ToList(); + var pros2 = FieldInfos.Where(x => x.IsSearcherField == true).ToList(); + + //生成表单model + for (int i = 0; i < pros.Count; i++) + { + var item = pros[i]; + var property = modelType.GetSingleProperty(item.FieldName); + string label = property.GetPropertyDisplayName(); + bool isrequired = property.IsPropertyRequired(); + var fktest = DC.GetFKName2(modelType, item.FieldName); + if (string.IsNullOrEmpty(fktest) == false) + { + isrequired = modelType.GetSingleProperty(fktest).IsPropertyRequired(); + } + string rules = "rules: []"; + if (isrequired == true) + { + rules = $@"rules: [{{ ""required"": true, ""message"": }}]"; + } + fieldstr.AppendLine($@" /** {label} */"); + if (string.IsNullOrEmpty(item.RelatedField) == false && string.IsNullOrEmpty(item.SubIdField) == true) + { + var fk = DC.GetFKName2(modelType, item.FieldName); + fieldstr.AppendLine($@" ""Entity.{fk}"":{{"); + } + else + { + fieldstr.AppendLine($@" ""Entity.{item.FieldName}"":{{"); + } + fieldstr.AppendLine($@" label: ""{label}"","); + fieldstr.AppendLine($@" {rules},"); + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + var subtype = Type.GetType(item.RelatedField); + if (item.SubField == "`file") + { + fieldstr.AppendLine($@" formItem: "); + } + else + { + if (string.IsNullOrEmpty(item.SubIdField) == true) + { + fieldstr.AppendLine($@" formItem: "); + } + else + { + fieldstr.AppendLine($@" formItem: "); + + } + } + } + else + { + var proType = modelType.GetSingleProperty(item.FieldName)?.PropertyType; + Type checktype = proType; + if (proType.IsNullable()) + { + checktype = proType.GetGenericArguments()[0]; + } + if (checktype == typeof(bool)) + { + fieldstr.AppendLine($@" formItem: }} unCheckedChildren={{}} />"); + } + else if (checktype.IsEnum()) + { + var es = checktype.ToListItems(); + fieldstr.AppendLine($@" formItem: "); + } + else if (checktype.IsNumber()) + { + fieldstr.AppendLine($@" formItem: "); + } + else if (checktype == typeof(string)) + { + fieldstr.AppendLine($@" formItem: "); + } + else if (checktype == typeof(DateTime)) + { + fieldstr.AppendLine($@" formItem: "); + } + } + fieldstr.Append(" }"); + if (i < pros.Count - 1) + { + fieldstr.Append(','); + } + fieldstr.Append(Environment.NewLine); + } + + //生成searchmodel + for (int i = 0; i < pros2.Count; i++) + { + var item = pros2[i]; + if (item.SubField == "`file") + { + continue; + } + var property = modelType.GetSingleProperty(item.FieldName); + string label = property.GetPropertyDisplayName(); + string rules = "rules: []"; + + fieldstr2.AppendLine($@" /** {label} */"); + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + if (string.IsNullOrEmpty(item.SubIdField) == true) + { + var fk = DC.GetFKName2(modelType, item.FieldName); + fieldstr2.AppendLine($@" ""{fk}"":{{"); + } + else + { + fieldstr2.AppendLine($@" ""Selected{item.FieldName}IDs"":{{"); + } + } + else + { + fieldstr2.AppendLine($@" ""{item.FieldName}"":{{"); + } + fieldstr2.AppendLine($@" label: ""{label}"","); + fieldstr2.AppendLine($@" {rules},"); + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + var subtype = Type.GetType(item.RelatedField); + if (string.IsNullOrEmpty(item.SubIdField) == true) + { + fieldstr2.AppendLine($@" formItem: "); + } + else + { + fieldstr2.AppendLine($@" formItem: "); + + } + } + else + { + var proType = modelType.GetSingleProperty(item.FieldName)?.PropertyType; + Type checktype = proType; + if (proType.IsNullable()) + { + checktype = proType.GetGenericArguments()[0]; + } + if (checktype == typeof(bool)) + { + fieldstr2.AppendLine($@" formItem: , Value: true }},{{ Text: , Value: false }} + ]}}/>"); + } + else if (checktype.IsEnum()) + { + var es = checktype.ToListItems(); + fieldstr2.AppendLine($@" formItem: "); + } + else if (checktype.IsNumber()) + { + fieldstr2.AppendLine($@" formItem: "); + } + else if (checktype == typeof(string)) + { + fieldstr2.AppendLine($@" formItem: "); + } + else if (checktype == typeof(DateTime)) + { + fieldstr2.AppendLine($@" formItem: "); + } + } + fieldstr2.Append(" }"); + if (i < pros.Count - 1) + { + fieldstr2.Append(','); + } + fieldstr2.Append(Environment.NewLine); + } + + return rv.Replace("$fields$", fieldstr.ToString()).Replace("$fields2$", fieldstr2.ToString()); + } + + if (name == "search") + { + return rv; + } + if (name == "forms") + { + StringBuilder fieldstr = new StringBuilder(); + var pros = FieldInfos.Where(x => x.IsFormField == true).ToList(); + + for (int i = 0; i < pros.Count; i++) + { + var item = pros[i]; + if (string.IsNullOrEmpty(item.SubIdField)) + { + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + var fk = DC.GetFKName2(modelType, item.FieldName); + fieldstr.AppendLine($@" "); + } + else + { + var proType = modelType.GetSingleProperty(item.FieldName)?.PropertyType; + Type checktype = proType; + if (proType.IsNullable()) + { + checktype = proType.GetGenericArguments()[0]; + } + if (checktype == typeof(bool)) + { + fieldstr.AppendLine($@" "); + } + else + { + fieldstr.AppendLine($@" "); + } + } + } + else + { + fieldstr.AppendLine($@" + + "); + } + } + return rv.Replace("$fields$", fieldstr.Replace("$switchdefaultvalue$", "value={false}").ToString()).Replace("$efields$", fieldstr.Replace("$switchdefaultvalue$", "").ToString()); + } + + return rv; + } + + + public string GenerateVUEView(string name, List apineeded) + { + var rv = GetResource($"{name}.txt", "Spa.Vue") + .Replace("$modelname$", ModelName.ToLower()); + if (apineeded == null) + { + apineeded = new List(); + } + Type modelType = Type.GetType(SelectedModel); + if (name == "config") + { + StringBuilder fieldstr = new StringBuilder(); + StringBuilder enumstr = new StringBuilder(); + var pros = FieldInfos.Where(x => x.IsListField == true || x.IsSearcherField == true).ToList(); + fieldstr.Append(Environment.NewLine); + List existSubPro = new List(); + List existEnum = new List(); + int rowheight = 30; + for (int i = 0; i < pros.Count; i++) + { + var item = pros[i]; + var mpro = modelType.GetSingleProperty(item.FieldName); + string label = mpro.GetPropertyDisplayName(); + string render = ""; + string newname = item.FieldName; + if (mpro.PropertyType.IsBoolOrNullableBool()) + { + render = "columnsRenderBoolean"; + } + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + var subtype = Type.GetType(item.RelatedField); + string prefix = ""; + if (subtype == typeof(FileAttachment)) + { + if (item.FieldName.ToLower().Contains("photo") || item.FieldName.ToLower().Contains("pic") || item.FieldName.ToLower().Contains("icon")) + { + render = "columnsRenderImg"; + rowheight = 110; + } + else + { + render = "columnsRenderDownload"; + } + var fk = DC.GetFKName2(modelType, item.FieldName); + newname = fk; + } + else + { + var subpro = subtype.GetSingleProperty(item.SubField); + existSubPro.Add(subpro); + int count = existSubPro.Where(x => x.Name == subpro.Name).Count(); + if (count > 1) + { + prefix = count + ""; + } + newname = item.SubField + "_view" + prefix; + } + } + + else + { + var proType = modelType.GetSingleProperty(item.FieldName)?.PropertyType; + Type checktype = proType; + if (proType.IsNullable()) + { + checktype = proType.GetGenericArguments()[0]; + } + if (checktype.IsEnum()) + { + if (existEnum.Contains(checktype.Name) == false) + { + var es = checktype.ToListItems(); + enumstr.AppendLine($@"export const {item.FieldName}Types: Array = ["); + for (int a = 0; a < es.Count; a++) + { + var e = es[a]; + enumstr.Append($@" {{ Text: ""{e.Text}"", Value: ""{e.Value}"" }}"); + if (a < es.Count - 1) + { + enumstr.Append(','); + } + enumstr.AppendLine(); + } + enumstr.AppendLine($@"];"); + existEnum.Add(checktype.Name); + } + } + } + fieldstr.Append($@" + {{ + key: ""{newname}"", + label: ""{label}"""); + + if (render != "") + { + fieldstr.Append($@", + isSlot: true "); + } + fieldstr.Append($@" + }}"); + fieldstr.Append(','); + } + return rv.Replace("$fields$", fieldstr.ToString()).Replace("$rowheight$", rowheight.ToString()).Replace("$enums$", enumstr.ToString()); + } + if (name == "views.dialog-form") + { + StringBuilder fieldstr = new StringBuilder(); + List actions = new List(); + List enums = new List(); + var pros = FieldInfos.Where(x => x.IsFormField == true).ToList(); + + //生成表单model + for (int i = 0; i < pros.Count; i++) + { + var item = pros[i]; + var property = modelType.GetSingleProperty(item.FieldName); + string label = property.GetPropertyDisplayName(); + bool isrequired = property.IsPropertyRequired(); + var fktest = DC.GetFKName2(modelType, item.FieldName); + if (string.IsNullOrEmpty(fktest) == false) + { + isrequired = modelType.GetSingleProperty(fktest).IsPropertyRequired(); + } + string rules = "rules: []"; + if (isrequired == true) + { + rules = $@"rules: [{{ required: true, message: ""{label}""+this.$t(""form.notnull""),trigger: ""blur"" }}]"; + } + if (string.IsNullOrEmpty(item.RelatedField) == false && string.IsNullOrEmpty(item.SubIdField) == true) + { + var fk = DC.GetFKName2(modelType, item.FieldName); + fieldstr.AppendLine($@" ""Entity.{fk}"":{{"); + } + else + { + fieldstr.AppendLine($@" ""Entity.{item.FieldName}"":{{"); + } + fieldstr.AppendLine($@" label: ""{label}"","); + fieldstr.AppendLine($@" {rules},"); + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + var subtype = Type.GetType(item.RelatedField); + if (item.SubField == "`file") + { + if (item.FieldName.ToLower().Contains("photo") || item.FieldName.ToLower().Contains("pic") || item.FieldName.ToLower().Contains("icon")) + { + fieldstr.AppendLine($@" type: ""wtmUploadImg"", + props: {{ + isHead: true, + imageStyle: {{ width: ""100px"", height: ""100px"" }} + }} +"); + } + else + { + fieldstr.AppendLine($@" type: ""upload"""); + } + } + else + { + if (string.IsNullOrEmpty(item.SubIdField) == true) + { + fieldstr.AppendLine($@" type: ""select"", + children: this.get{subtype.Name}Data, + props: {{ + clearable: true + }}"); + } + else + { + fieldstr.AppendLine($@" type: ""transfer"", + mapKey: ""{item.SubIdField}"", + props: {{ + data: this.get{subtype.Name}Data.map(item => ({{ + key: item.Value, + label: item.Text + }})), + titles: [this.$t(""form.all""), this.$t(""form.selected"")], + filterable: true, + filterMethod: filterMethod + }}, + span: 24, + defaultValue: []"); + + } + apineeded.Add($"get{subtype.Name}"); + actions.Add($"get{subtype.Name}"); + } + } + else + { + var proType = modelType.GetSingleProperty(item.FieldName)?.PropertyType; + Type checktype = proType; + if (proType.IsNullable()) + { + checktype = proType.GetGenericArguments()[0]; + } + if (checktype == typeof(bool)) + { + fieldstr.AppendLine($@" type: ""switch"""); + } + else if (checktype.IsEnum()) + { + fieldstr.AppendLine($@" type: ""select"", + children: {item.FieldName}Types, + props: {{ + clearable: true + }}"); + + enums.Add(item.FieldName + "Types"); + } + else if (checktype.IsNumber()) + { + fieldstr.AppendLine($@" type: ""input"""); + } + else if (checktype == typeof(string)) + { + fieldstr.AppendLine($@" type: ""input"""); + } + else if (checktype == typeof(DateTime)) + { + fieldstr.AppendLine($@" type: ""datePicker"""); + } + } + fieldstr.Append(" }"); + if (i < pros.Count - 1) + { + fieldstr.Append(','); + } + fieldstr.Append(Environment.NewLine); + } + string a1 = ""; + string a2 = ""; + foreach (var item in actions.Distinct()) + { + a1 += $@" @Action + {item}; + @State + {item}Data; +"; + a2 += $@" this.{item}(); +"; + } + string import = ""; + if (enums.Count > 0) + { + import = $@"import {{ {enums.Distinct().ToSepratedString()} }} from ""../config"";"; + } + return rv.Replace("$fields$", fieldstr.ToString()).Replace("$actions$", a1).Replace("$runactions$", a2).Replace("$import$", import); + } + + if (name == "index") + { + StringBuilder fieldstr2 = new StringBuilder(); + StringBuilder actions = new StringBuilder(); + List acts = new List(); + List enums = new List(); + var pros2 = FieldInfos.Where(x => x.IsSearcherField == true || x.IsListField).ToList(); + int searchcount = 0; + for (int i = 0; i < pros2.Count; i++) + { + + var item = pros2[i]; + if (item.IsListField == true) + { + var mpro = modelType.GetSingleProperty(item.FieldName); + if (mpro.PropertyType.IsBoolOrNullableBool()) + { + actions.AppendLine($@" +"); + } + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + var subtype = Type.GetType(item.RelatedField); + var fk = DC.GetFKName2(modelType, item.FieldName); + if (subtype == typeof(FileAttachment)) + { + if (item.FieldName.ToLower().Contains("photo") || item.FieldName.ToLower().Contains("pic") || item.FieldName.ToLower().Contains("icon")) + { + actions.AppendLine($@" +"); + } + else + { + actions.AppendLine($@" +"); + } + } + } + } + if (item.IsSearcherField == true) + { + if (item.SubField == "`file") + { + continue; + } + searchcount++; + var property = modelType.GetSingleProperty(item.FieldName); + string label = property.GetPropertyDisplayName(); + string rules = "rules: []"; + + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + if (string.IsNullOrEmpty(item.SubIdField) == true) + { + var fk = DC.GetFKName2(modelType, item.FieldName); + fieldstr2.AppendLine($@" ""{fk}"":{{"); + } + else + { + fieldstr2.AppendLine($@" ""Selected{item.FieldName}IDs"":{{"); + } + } + else + { + fieldstr2.AppendLine($@" ""{item.FieldName}"":{{"); + } + fieldstr2.AppendLine($@" label: ""{label}"","); + fieldstr2.AppendLine($@" {rules},"); + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + var subtype = Type.GetType(item.RelatedField); + if (string.IsNullOrEmpty(item.SubIdField) == true) + { + fieldstr2.AppendLine($@" type: ""select"", + children: this.get{subtype.Name}Data, + props: {{ + clearable: true, + placeholder: '全部' + }}"); + + } + else + { + fieldstr2.AppendLine($@" type: ""select"", + children: this.get{subtype.Name}Data, + props: {{ + clearable: true , + multiple: true, + ""collapse-tags"": true + }}"); + + } + apineeded.Add($"get{subtype.Name}"); + acts.Add($"get{subtype.Name}"); + } + else + { + var proType = modelType.GetSingleProperty(item.FieldName)?.PropertyType; + Type checktype = proType; + if (proType.IsNullable()) + { + checktype = proType.GetGenericArguments()[0]; + } + if (checktype == typeof(bool)) + { + fieldstr2.AppendLine($@" type: ""switch"""); + } + else if (checktype.IsEnum()) + { + fieldstr2.AppendLine($@" type: ""select"", + children: {item.FieldName}Types, + props: {{ + clearable: true, + placeholder: this.$t(""form.all"") + }}"); + + enums.Add(item.FieldName + "Types"); + } + else if (checktype.IsNumber()) + { + fieldstr2.AppendLine($@" type: ""input"""); + } + else if (checktype == typeof(string)) + { + fieldstr2.AppendLine($@" type: ""input"""); + } + else if (checktype == typeof(DateTime)) + { + fieldstr2.AppendLine($@" type: ""datePicker"", + span: 12, + props: {{ + type: ""datetimerange"", + ""value-format"": ""yyyy-MM-dd HH:mm:ss"", + ""range-separator"": ""-"", + ""start-placeholder"": this.$t(""table.startdate""), + ""end-placeholder"": this.$t(""table.enddate"") + }}"); + } + } + if (searchcount > 2) + { + fieldstr2.AppendLine(" ,isHidden: !this.isActive"); + } + fieldstr2.Append(" },"); + fieldstr2.Append(Environment.NewLine); + } + } + + string a1 = ""; + string a2 = ""; + foreach (var item in acts.Distinct()) + { + a1 += $@" @Action + {item}; + @State + {item}Data; +"; + a2 += $@" this.{item}(); +"; + } + + + return rv.Replace("$fields$", fieldstr2.ToString()).Replace("$actions$", actions.ToString()).Replace("$enums$", enums.Distinct().ToSepratedString()) + .Replace("$acts$", a1).Replace("$runactions$", a2); + + } + if (name == "store.api") + { + StringBuilder fieldstr = new StringBuilder(); + StringBuilder efieldstr = new StringBuilder(); + + var apis = apineeded.Distinct().ToList(); + for (int i = 0; i < apis.Count; i++) + { + var item = apis[i]; + fieldstr.AppendLine($@"const {item} = {{ + url: reqPath + ""{item}s"", + method: ""get"", + dataType: ""array"" +}}; "); + efieldstr.AppendLine($"{item},"); + } + return rv.Replace("$fields$", fieldstr.ToString()).Replace("$efields$", efieldstr.ToString()); + } + + return rv; + } + + public string GenerateBlazorView(string name) + { + string pagepath = string.IsNullOrEmpty(Area) ? $"/{ModelName}" : $"/{Area}/{ModelName}"; + if(name != "Index") + { + pagepath += $"/{name}"; + } + if (name == "Edit" || name == "Details") + { + pagepath += "/{id}"; + } + var rv = GetResource($"{name}.txt", "Spa.Blazor") + .Replace("$modelname$", ModelName) + .Replace("$vmnamespace$", VMNs) + .Replace("$des$", ModuleName) + .Replace("$controllername$", $"{ControllerNs},{ModelName}") + .Replace("$pagepath$", pagepath); + Type modelType = Type.GetType(SelectedModel); + if (name == "Index") + { + StringBuilder fieldstr = new StringBuilder(); + StringBuilder fieldstr2 = new StringBuilder(); + var pros = FieldInfos.Where(x => x.IsListField == true).ToList(); + var pros2 = FieldInfos.Where(x => x.IsSearcherField == true).ToList(); + List existSubPro = new List(); + Dictionary apis = new Dictionary(); + Dictionary multiapis = new Dictionary(); + for (int i = 0; i < pros.Count; i++) + { + var item = pros[i]; + var mpro = modelType.GetSingleProperty(item.FieldName); + string render = ""; + string template = ""; + string newname = item.FieldName; + if (mpro.PropertyType.IsBoolOrNullableBool()) + { + render = "ComponentType=\"@typeof(Switch)\""; + } + if (mpro.PropertyType == typeof(DateTime) || mpro.PropertyType == typeof(DateTime?)) + { + render = "FormatString=\"yyyy-MM-dd HH: mm: ss\""; + + } + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + var subtype = Type.GetType(item.RelatedField); + string prefix = ""; + if (subtype == typeof(FileAttachment)) + { + if (item.FieldName.ToLower().Contains("photo") || item.FieldName.ToLower().Contains("pic") || item.FieldName.ToLower().Contains("icon") || item.FieldName.ToLower().Contains("zhaopian") || item.FieldName.ToLower().Contains("tupian")) + { + template = @" + "; + } + else + { + template = @" + "; + } + var fk = DC.GetFKName2(modelType, item.FieldName); + newname = fk; + } + else + { + var subpro = subtype.GetSingleProperty(item.SubField); + existSubPro.Add(subpro); + int count = existSubPro.Where(x => x.Name == subpro.Name).Count(); + if (count > 1) + { + prefix = count + ""; + } + newname = item.SubField + "_view" + prefix; + } + } + if (template == "") + { + fieldstr.Append($@" + "); + } + else + { + fieldstr.Append($@" + +{template} + "); + } + } + + for (int i = 0; i < pros2.Count; i++) + { + string controltype = "BootstrapInput"; + string sitems = ""; + string bindfield = ""; + string ph = ""; + var item = pros2[i]; + if (item.SubField == "`file") + { + continue; + } + + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + if (string.IsNullOrEmpty(item.SubIdField) == true) + { + var fk = DC.GetFKName2(modelType, item.FieldName); + bindfield = fk; + } + else + { + bindfield = $"Selected{item.FieldName}IDs"; + } + } + else + { + bindfield = item.FieldName; + } + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + var subtype = Type.GetType(item.RelatedField); + if (string.IsNullOrEmpty(item.SubIdField) == true) + { + controltype = "Select"; + } + else + { + controltype = "MultiSelect"; + } + var tempname = $"All{subtype.Name}s"; + sitems = $"Items=\"@{tempname}\""; + if (apis.ContainsKey(tempname) == false && multiapis.ContainsKey(tempname) == false) + { + if (controltype == "Select") + { + apis.Add(tempname, $"/api/{ModelName}/Get{subtype.Name}s"); + } + else + { + multiapis.Add(tempname, $"/api/{ModelName}/Get{subtype.Name}s"); + } + } + } + else + { + var proType = modelType.GetSingleProperty(item.FieldName)?.PropertyType; + Type checktype = proType; + if (proType.IsNullable()) + { + checktype = proType.GetGenericArguments()[0]; + } + if (checktype == typeof(bool)) + { + controltype = "Select"; + sitems = "Items=\"@WtmBlazor.GlobalSelectItems.SearcherBoolItems\""; + } + else if (checktype.IsEnum()) + { + controltype = "Select"; + } + else if (checktype.IsNumber()) + { + controltype = "BootstrapInputNumber"; + } + else if (checktype == typeof(string)) + { + } + else if (checktype == typeof(DateTime)) + { + controltype = "WTDateRange"; + } + } + if(controltype == "Select" || controltype == "MultiSelect") + { + ph = "PlaceHolder=\"@WtmBlazor.Localizer[\"Sys.All\"]\""; + } + fieldstr2.Append($@" + <{controltype} @bind-Value=""@SearchModel.{bindfield}"" {sitems} {ph}/>"); + } + + StringBuilder apiinit = new StringBuilder(); + StringBuilder fieldinit = new StringBuilder(); + foreach (var item in apis) + { + apiinit.Append(@$" + {item.Key} = await WtmBlazor.Api.CallItemsApi(""{item.Value}"", placeholder: WtmBlazor.Localizer[""Sys.All""]); +"); + fieldinit.Append($@" + private List {item.Key} = new List(); +"); + } + foreach (var item in multiapis) + { + apiinit.Append(@$" + {item.Key} = await WtmBlazor.Api.CallItemsApi(""{item.Value}""); +"); + fieldinit.Append($@" + private List {item.Key} = new List(); +"); + } + + return rv.Replace("$columns$", fieldstr.ToString()).Replace("$searchfields$",fieldstr2.ToString()).Replace("$init$", apiinit.ToString()).Replace("$fieldinit$", fieldinit.ToString()); + } + + + if (name == "Create" || name == "Edit") + { + StringBuilder fieldstr = new StringBuilder(); + var pros = FieldInfos.Where(x => x.IsFormField == true).ToList(); + + //生成表单model + Dictionary apis = new Dictionary(); + Dictionary multiapis = new Dictionary(); + for (int i = 0; i < pros.Count; i++) + { + var item = pros[i]; + string controltype = "BootstrapInput"; + string sitems = ""; + string bindfield = ""; + string ph = ""; + var property = modelType.GetSingleProperty(item.FieldName); + + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + if (string.IsNullOrEmpty(item.SubIdField) == true) + { + var fk = DC.GetFKName2(modelType, item.FieldName); + bindfield = "Entity." + fk; + } + else + { + bindfield = $"Selected{item.FieldName}IDs"; + } + } + else + { + bindfield = "Entity."+ item.FieldName; + } + + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + var subtype = Type.GetType(item.RelatedField); + if (item.SubField == "`file") + { + if (item.FieldName.ToLower().Contains("photo") || item.FieldName.ToLower().Contains("pic") || item.FieldName.ToLower().Contains("icon") || item.FieldName.ToLower().Contains("zhaopian") || item.FieldName.ToLower().Contains("tupian")) + { + controltype = "WTUploadImage"; + } + else + { + controltype = "WTUploadFile"; + } + } + else + { + if (string.IsNullOrEmpty(item.SubIdField) == true) + { + controltype = "Select"; + } + else + { + controltype = "Transfer"; + } + var tempname = $"All{subtype.Name}s"; + sitems = $"Items=\"@{tempname}\""; + if (apis.ContainsKey(tempname) == false && multiapis.ContainsKey(tempname) == false) + { + if (controltype == "Select") + { + apis.Add(tempname, $"/api/{ModelName}/Get{subtype.Name}s"); + } + else + { + multiapis.Add(tempname, $"/api/{ModelName}/Get{subtype.Name}s"); + } + } + + } + } + else + { + var proType = modelType.GetSingleProperty(item.FieldName)?.PropertyType; + Type checktype = proType; + if (proType.IsNullable()) + { + checktype = proType.GetGenericArguments()[0]; + } + if (checktype == typeof(bool)) + { + controltype = "Switch"; + } + else if (checktype.IsEnum()) + { + controltype = "Select"; + + } + else if (checktype.IsNumber()) + { + controltype = "BootstrapInputNumber"; + } + else if (checktype == typeof(string)) + { + } + else if (checktype == typeof(DateTime)) + { + controltype = "DateTimePicker"; + } + } + if (controltype == "Select" || controltype == "MultiSelect") + { + ph = "PlaceHolder=\"@WtmBlazor.Localizer[\"Sys.PleaseSelect\"]\""; + } + if (controltype == "Transfer") + { + fieldstr.Append($@" + + <{controltype} @bind-Value=""@Model.{bindfield}"" {sitems} {ph}/> + "); + } + else + { + fieldstr.Append($@" + <{controltype} @bind-Value=""@Model.{bindfield}"" {sitems} {ph}/>"); + } + } + + StringBuilder apiinit = new StringBuilder(); + StringBuilder fieldinit = new StringBuilder(); + foreach (var item in apis) + { + apiinit.Append(@$" + {item.Key} = await WtmBlazor.Api.CallItemsApi(""{item.Value}"", placeholder: WtmBlazor.Localizer[""Sys.PleaseSelect""]); +"); + fieldinit.Append($@" + private List {item.Key} = new List(); +"); + } + foreach (var item in multiapis) + { + apiinit.Append(@$" + {item.Key} = await WtmBlazor.Api.CallItemsApi(""{item.Value}""); +"); + fieldinit.Append($@" + private List {item.Key} = new List(); +"); + } + return rv.Replace("$formfields$", fieldstr.ToString()).Replace("$fieldinit$", fieldinit.ToString()).Replace("$init$", apiinit.ToString()); + } + if (name == "Details") + { + StringBuilder fieldstr = new StringBuilder(); + var pros = FieldInfos.Where(x => x.IsFormField == true).ToList(); + + //生成表单model + Dictionary apis = new Dictionary(); + for (int i = 0; i < pros.Count; i++) + { + var item = pros[i]; + string controltype = "Display"; + string sitems = ""; + string bindfield = ""; + string disabled = ""; + var property = modelType.GetSingleProperty(item.FieldName); + + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + if (string.IsNullOrEmpty(item.SubIdField) == true) + { + var fk = DC.GetFKName2(modelType, item.FieldName); + bindfield = "Entity." + fk; + } + else + { + bindfield = $"Selected{item.FieldName}IDs"; + } + } + else + { + bindfield = "Entity." + item.FieldName; + } + if (string.IsNullOrEmpty(item.RelatedField) == false) + { + var subtype = Type.GetType(item.RelatedField); + if (item.SubField == "`file") + { + if (item.FieldName.ToLower().Contains("photo") || item.FieldName.ToLower().Contains("pic") || item.FieldName.ToLower().Contains("icon") || item.FieldName.ToLower().Contains("zhaopian") || item.FieldName.ToLower().Contains("tupian")) + { + controltype = "WTUploadImage"; + } + else + { + controltype = "WTUploadFile"; + } + disabled = "IsDisabled=\"true\""; + } + else + { + var tempname = $"All{subtype.Name}s"; + sitems = $"Lookup=\"@{tempname}\""; + if (apis.ContainsKey(tempname) == false) + { + apis.Add(tempname, $"/api/{ModelName}/Get{subtype.Name}s"); + } + } + } + else + { + var proType = modelType.GetSingleProperty(item.FieldName)?.PropertyType; + Type checktype = proType; + if (proType.IsNullable()) + { + checktype = proType.GetGenericArguments()[0]; + } + if (checktype == typeof(bool)) + { + controltype = "Switch"; + disabled = "IsDisabled=\"true\""; + } + } + if (controltype == "WTUploadFile") + { + string label = property.GetPropertyDisplayName(); + fieldstr.Append($@" + @if (Model.{bindfield}.HasValue){{ +
+ +
+
+ }} +"); + } + else + { + fieldstr.Append($@" + <{controltype} @bind-Value=""@Model.{bindfield}"" {sitems} {disabled} ShowLabel=""true""/>"); + } + } + + StringBuilder apiinit = new StringBuilder(); + StringBuilder fieldinit = new StringBuilder(); + foreach (var item in apis) + { + apiinit.Append(@$" + {item.Key} = await WtmBlazor.Api.CallItemsApi(""{item.Value}"", placeholder: WtmBlazor.Localizer[""Sys.All""]); +"); + fieldinit.Append($@" + private List {item.Key} = new List(); +"); + } + + return rv.Replace("$formfields$", fieldstr.ToString()).Replace("$fieldinit$", fieldinit.ToString()).Replace("$init$", apiinit.ToString()); + } + + + return rv; + } + + public string GetResource(string fileName, string subdir = "") + { + //获取编译在程序中的Controller原始代码文本 + Assembly assembly = Assembly.GetExecutingAssembly(); + string loc = ""; + if (string.IsNullOrEmpty(subdir)) + { + loc = $"WalkingTec.Mvvm.Mvc.GeneratorFiles.{fileName}"; + } + else + { + loc = $"WalkingTec.Mvvm.Mvc.GeneratorFiles.{subdir}.{fileName}"; + } + var textStreamReader = new StreamReader(assembly.GetManifestResourceStream(loc)); + string content = textStreamReader.ReadToEnd(); + textStreamReader.Close(); + return content; + } + + private string GetRelatedNamespace(List pros, string s) + { + string otherns = @""; + Type modelType = Type.GetType(SelectedModel); + foreach (var pro in pros) + { + Type proType = null; + + if (string.IsNullOrEmpty(pro.RelatedField)) + { + proType = modelType.GetSingleProperty(pro.FieldName)?.PropertyType; + } + else + { + proType = Type.GetType(pro.RelatedField); + } + string prons = proType.Namespace; + if (proType.IsNullable()) + { + prons = proType.GetGenericArguments()[0].Namespace; + } + if (s.Contains($"using {prons};") == false && otherns.Contains($"using {prons};") == false) + { + otherns += $@"using {prons}; +"; + } + + } + + return s.Replace("$othernamespace$", otherns); + } + + } + + public enum FieldInfoType { Normal, One2Many, Many2Many } + + public class FieldInfo + { + public string FieldName { get; set; } + public string RelatedField { get; set; } + + public bool IsSearcherField { get; set; } + + public bool IsListField { get; set; } + + public bool IsFormField { get; set; } + + public bool IsImportField { get; set; } + public bool IsBatchField { get; set; } + + public FieldInfoType InfoType + { + get + { + if (string.IsNullOrEmpty(RelatedField)) + { + return FieldInfoType.Normal; + } + else + { + if (string.IsNullOrEmpty(SubIdField)) + { + return FieldInfoType.One2Many; + } + else + { + return FieldInfoType.Many2Many; + } + } + } + } + + /// + /// 字段关联的类名 + /// + public string SubField { get; set; } + /// + /// 多对多关系时,记录中间表关联到主表的字段名称 + /// + public string SubIdField { get; set; } + + public string GetField(IDataContext DC, Type modelType) + { + if (this.InfoType == FieldInfoType.One2Many) + { + var fk = DC.GetFKName2(modelType, this.FieldName); + return fk; + } + else + { + return this.FieldName; + } + } + + public string GetFKType(IDataContext DC, Type modelType) + { + Type fktype = null; + if (this.InfoType == FieldInfoType.One2Many) + { + var fk = this.GetField(DC, modelType); + fktype = modelType.GetSingleProperty(fk)?.PropertyType; + } + if (this.InfoType == FieldInfoType.Many2Many) + { + var middletype = modelType.GetSingleProperty(this.FieldName)?.PropertyType; + fktype = middletype.GetGenericArguments()[0].GetSingleProperty(this.SubIdField)?.PropertyType; + } + var typename = "string"; + + if (fktype == typeof(short) || fktype == typeof(short?)) + { + typename = "short"; + } + if (fktype == typeof(int) || fktype == typeof(int?)) + { + typename = "int"; + } + if (fktype == typeof(long) || fktype == typeof(long?)) + { + typename = "long"; + } + if (fktype == typeof(Guid) || fktype == typeof(Guid?)) + { + typename = "Guid"; + } + + return typename; + + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Filters/DataContextFilter.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Filters/DataContextFilter.cs new file mode 100644 index 0000000..e292c7a --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Filters/DataContextFilter.cs @@ -0,0 +1,78 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Filters; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using WalkingTec.Mvvm.Core; + +namespace WalkingTec.Mvvm.Mvc.Filters +{ + public class DataContextFilter : ActionFilterAttribute + { + public static Func _csfunc; + + public DataContextFilter() + { + + } + + public override void OnActionExecuting(ActionExecutingContext context) + { + var controller = context.Controller as IBaseController; + if (controller == null) + { + base.OnActionExecuting(context); + return; + } + context.SetWtmContext(); + string cs = ""; + DBTypeEnum? dbtype = null; + ControllerActionDescriptor ad = context.ActionDescriptor as ControllerActionDescriptor; + var fixcontroller = ad.ControllerTypeInfo.GetCustomAttributes(typeof(FixConnectionAttribute), false).Cast().FirstOrDefault(); + var fixaction = ad.MethodInfo.GetCustomAttributes(typeof(FixConnectionAttribute), false).Cast().FirstOrDefault(); + var ispost = ad.MethodInfo.GetCustomAttributes(typeof(HttpPostAttribute), false).Cast().FirstOrDefault(); + string mode = "Read"; + + if (fixcontroller != null || fixaction != null) + { + cs = fixaction?.CsName ?? fixcontroller?.CsName; + var op = fixcontroller?.Operation ?? fixaction?.Operation; + if (op != null) + { + switch (op.Value) + { + case DBOperationEnum.Read: + mode = "Read"; + break; + case DBOperationEnum.Write: + mode = "Write"; + break; + default: + break; + } + } + dbtype = fixcontroller?.DbType ?? fixaction?.DbType; + cs = Utils.GetCS(cs, mode, controller.Wtm.ConfigInfo); + } + else + { + cs = _csfunc?.Invoke(context); + if (string.IsNullOrEmpty(cs)) + { + if(ispost != null) + { + mode = "Write"; + } + cs = context.HttpContext.Request.Query["DONOTUSECSName"]; + cs = Utils.GetCS(cs, mode, controller.Wtm.ConfigInfo); + } + } + + controller.Wtm.CurrentCS = cs; + controller.Wtm.CurrentDbType = dbtype; + base.OnActionExecuting(context); + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Filters/FrameworkFilter.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Filters/FrameworkFilter.cs new file mode 100644 index 0000000..d85688a --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Filters/FrameworkFilter.cs @@ -0,0 +1,433 @@ +using System; +using System.Linq; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Filters; +using WalkingTec.Mvvm.Core; +using System.Collections.Generic; +using System.Reflection; +using WalkingTec.Mvvm.Core.Implement; +using System.IO; +using System.Text.RegularExpressions; +using System.Text; +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Logging; +using WalkingTec.Mvvm.Core.Support.Json; +using System.Text.Json; +using WalkingTec.Mvvm.Core.Json; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.AspNetCore.Mvc.ViewEngines; + +namespace WalkingTec.Mvvm.Mvc.Filters +{ + public class FrameworkFilter : ActionFilterAttribute + { + public override void OnActionExecuting(ActionExecutingContext context) + { + var ctrl = context.Controller as IBaseController; + if (ctrl == null) + { + base.OnActionExecuting(context); + return; + } + context.SetWtmContext(); + if (context.HttpContext.Items.ContainsKey("actionstarttime") == false) + { + context.HttpContext.Items.Add("actionstarttime", DateTime.Now); + } + var ctrlActDesc = context.ActionDescriptor as ControllerActionDescriptor; + var log = new SimpleLog();// 初始化log备用 + var ctrlDes = ctrlActDesc.ControllerTypeInfo.GetCustomAttributes(typeof(ActionDescriptionAttribute), false).Cast().FirstOrDefault(); + var actDes = ctrlActDesc.MethodInfo.GetCustomAttributes(typeof(ActionDescriptionAttribute), false).Cast().FirstOrDefault(); + var postDes = ctrlActDesc.MethodInfo.GetCustomAttributes(typeof(HttpPostAttribute), false).Cast().FirstOrDefault(); + var validpostonly = ctrlActDesc.MethodInfo.GetCustomAttributes(typeof(ValidateFormItemOnlyAttribute), false).Cast().FirstOrDefault(); + + log.ITCode = ctrl.Wtm.LoginUserInfo?.ITCode ?? string.Empty; + //给日志的多语言属性赋值 + log.ModuleName = ctrlDes?.GetDescription(ctrl) ?? ctrlActDesc.ControllerName; + log.ActionName = actDes?.GetDescription(ctrl) ?? ctrlActDesc.ActionName + (postDes == null ? string.Empty : "[P]"); + log.ActionUrl = ctrl.BaseUrl; + log.IP = context.HttpContext.Connection.RemoteIpAddress.ToString(); + + ctrl.Wtm.Log = log; + foreach (var item in context.ActionArguments) + { + if (item.Value is BaseVM) + { + var model = item.Value as BaseVM; + model.Wtm = ctrl.Wtm; + model.FC = new Dictionary(); + model.CreatorAssembly = this.GetType().Assembly.FullName; + model.ControllerName = context.HttpContext.Request.Path; + //if (ctrl is BaseController c) + //{ + // model.WtmContext.WindowIds = c.WindowIds; + // model.UIService = c.UIService; + //} + //else + //{ + // model.WindowIds = ""; + // model.UIService = new DefaultUIService(); + //} + try + { + var f = context.HttpContext.Request.Form; + foreach (var key in f.Keys) + { + if (model.FC.Keys.Contains(key) == false) + { + model.FC.Add(key, f[key]); + } + } + if (context.HttpContext.Request.QueryString != QueryString.Empty) + { + foreach (var key in context.HttpContext.Request.Query.Keys) + { + if (model.FC.Keys.Contains(key) == false) + { + model.FC.Add(key, context.HttpContext.Request.Query[key]); + } + } + } + } + catch { } + + if (ctrl is BaseApiController apictrl) + { + //apictrl.TryValidateModel(model); + if (context.HttpContext.Items.ContainsKey("DONOTUSE_REQUESTBODY")) + { + string body = context.HttpContext.Items["DONOTUSE_REQUESTBODY"].ToString(); + var joption = new JsonSerializerOptions(); + joption.Converters.Add(new BodyConverter()); + try + { + var obj = JsonSerializer.Deserialize(body, joption); + foreach (var field in obj.ProNames) + { + + model.FC.Add(field, ""); + } + } + catch { } + } + } + //if (model is IBaseCRUDVM crud) + //{ + // var pros = crud.Entity.GetType().GetProperties(); + // foreach (var pro in pros) + // { + // if (model.FC.ContainsKey("Entity." + pro.Name)) + // { + // //找到类型为List的字段 + // if (pro.PropertyType.GenericTypeArguments.Count() > 0) + // { + // //获取xxx的类型 + // var ftype = pro.PropertyType.GenericTypeArguments.First(); + // //如果xxx继承自TopBasePoco + // if (ftype.IsSubclassOf(typeof(TopBasePoco))) + // { + // //界面传过来的子表数据 + + // if (pro.GetValue(crud.Entity) is IEnumerable list && list.Count() == 0) + // { + // pro.SetValue(crud.Entity, null); + // } + // } + // } + // } + // } + //} + //如果ViewModel T继承自IBaseBatchVM,则自动为其中的ListVM和EditModel初始化数据 + if (model is IBaseBatchVM temp) + { + if (temp.ListVM != null) + { + temp.ListVM.CopyContext(model); + temp.ListVM.Ids = temp.Ids == null ? new List() : temp.Ids.ToList(); + temp.ListVM.SearcherMode = ListVMSearchModeEnum.Batch; + temp.ListVM.NeedPage = false; + } + if (temp.LinkedVM != null) + { + temp.LinkedVM.CopyContext(model); + } + if (temp.ListVM != null) + { + //绑定ListVM的OnAfterInitList事件,当ListVM的InitList完成时,自动将操作列移除 + temp.ListVM.OnAfterInitList += (self) => + { + self.RemoveActionColumn(); + self.RemoveAction(); + self.AddErrorColumn(); + }; + if (temp.ListVM.Searcher != null) + { + var searcher = temp.ListVM.Searcher; + searcher.CopyContext(model); + } + temp.ListVM.DoInitListVM(); + } + temp.LinkedVM?.DoInit(); + } + if (model is IBaseImport tvm) + { + var template = tvm.Template; + template.CopyContext(model); + template.DoReInit(); + var errorlist = tvm.ErrorListVM; + errorlist.CopyContext(model); + } + if (model is IBasePagedListVM lvm) + { + var searcher = lvm.Searcher; + searcher.CopyContext(lvm); + if (ctrl is BaseController) + { + searcher.DoInit(); + } + } + model.Validate(); + var invalid = ctrl.ModelState.Where(x => x.Value.ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid).Select(x => x.Key).ToList(); + if ((ctrl as ControllerBase).Request.Method.ToLower() == "put" || validpostonly != null) + { + foreach (var v in invalid) + { + if (v?.StartsWith("Entity.") == true) + { + Regex r = new Regex("(.*?)\\[.*?\\](.*?$)"); + var m = r.Match(v); + var check = v; + if (m.Success) + { + check = m.Groups[1] + "[0]" + m.Groups[2]; + } + if (model.FC.ContainsKey(check) == false) + { + ctrl.ModelState.Remove(v); + } + } + } + } + if (ctrl is BaseController) + { + var reinit = model.GetType().GetTypeInfo().GetCustomAttributes(typeof(ReInitAttribute), false).Cast().SingleOrDefault(); + if (ctrl.ModelState.IsValid) + { + if (reinit != null && (reinit.ReInitMode == ReInitModes.SUCCESSONLY || reinit.ReInitMode == ReInitModes.ALWAYS)) + { + model.DoReInit(); + } + } + else + { + if (reinit == null || (reinit.ReInitMode == ReInitModes.FAILEDONLY || reinit.ReInitMode == ReInitModes.ALWAYS)) + { + model.DoReInit(); + } + } + } + + //如果是子表外键验证错误,例如Entity.Majors[0].SchoolId为空这种错误,则忽略。因为框架会在添加修改的时候自动给外键赋值 + var toremove = ctrl.ModelState.Select(x => x.Key).Where(x => Regex.IsMatch(x, ".*?\\[.*?\\]\\..*?id", RegexOptions.IgnoreCase)); + foreach (var r in toremove) + { + ctrl.ModelState.Remove(r); + } + } + + if(item.Value is BaseSearcher se) + { + se.FC = new Dictionary(); + se.Wtm = ctrl.Wtm; + se.Validate(); + } + } + + //忽略绑定List由于前台传递空字符串造成的错误 + base.OnActionExecuting(context); + } + + + + public override void OnActionExecuted(ActionExecutedContext context) + { + var ctrl = context.Controller as BaseController; + if (ctrl == null) + { + base.OnActionExecuted(context); + return; + } + ctrl.ViewData["DONOTUSE_COOKIEPRE"] = ctrl.Wtm.ConfigInfo.CookiePre; + var ctrlActDesc = context.ActionDescriptor as ControllerActionDescriptor; + //get viewname + string viewName = ""; + if(context.Result is PartialViewResult pvr) + { + viewName = pvr.ViewName??""; + if (viewName?.StartsWith("/") == false) + { + var viewEngine = context.HttpContext.RequestServices.GetRequiredService(); + viewName = viewEngine.FindView(context, string.IsNullOrEmpty(viewName) ? ctrlActDesc.ActionName : viewName, false)?.View?.Path; + } + } + if (context.Result is ViewResult vr) + { + viewName = vr.ViewName??""; + if (viewName?.StartsWith("/") == false) + { + var viewEngine = context.HttpContext.RequestServices.GetRequiredService(); + viewName = viewEngine.FindView(context, string.IsNullOrEmpty(viewName) ? ctrlActDesc.ActionName : viewName, false)?.View?.Path; + } + } + if (context.Result is PartialViewResult) + { + var model = (context.Result as PartialViewResult).ViewData?.Model as BaseVM; + if (model == null && (context.Result as PartialViewResult).Model == null && (context.Result as PartialViewResult).ViewData != null) + { + model = ctrl.Wtm.CreateVM(); + model.CurrentView = viewName; + (context.Result as PartialViewResult).ViewData.Model = model; + } + // 为所有 PartialView 加上最外层的 Div + if (model != null) + { + model.CurrentView = viewName; + string pagetitle = string.Empty; + var menu = Utils.FindMenu(context.HttpContext.Request.Path,ctrl.GlobaInfo.AllMenus); + if (menu == null) + { + var ctrlDes = ctrlActDesc.ControllerTypeInfo.GetCustomAttributes(typeof(ActionDescriptionAttribute), false).Cast().FirstOrDefault(); + var actDes = ctrlActDesc.MethodInfo.GetCustomAttributes(typeof(ActionDescriptionAttribute), false).Cast().FirstOrDefault(); + if (actDes != null) + { + if (ctrlDes != null) + { + pagetitle = ctrlDes.GetDescription(ctrl) + " - "; + } + pagetitle += actDes.GetDescription(ctrl); + } + } + else + { + if (menu.ParentId != null) + { + var pmenu = ctrl.GlobaInfo.AllMenus.Where(x => x.ID == menu.ParentId).FirstOrDefault(); + if (pmenu != null) + { + pmenu.PageName = Core.CoreProgram._localizer?[pmenu.PageName]; + + pagetitle = pmenu.PageName + " - "; + } + } + menu.PageName = Core.CoreProgram._localizer?[menu.PageName]; + pagetitle += menu.PageName; + } + if (string.IsNullOrEmpty(pagetitle) == false) + { + context.HttpContext.Response.Headers.Add("X-wtm-PageTitle", Convert.ToBase64String(Encoding.UTF8.GetBytes(pagetitle))); + } + context.HttpContext.Response.Cookies.Append("divid", model.ViewDivId); + } + } + if (context.Result is ViewResult) + { + var model = (context.Result as ViewResult).ViewData?.Model as BaseVM; + if (model == null && (context.Result as ViewResult).Model == null && (context.Result as ViewResult).ViewData != null) + { + model = ctrl.Wtm.CreateVM(); + model.CurrentView = viewName; + (context.Result as ViewResult).ViewData.Model = model; + } + if (model != null) + { + model.CurrentView = viewName; + context.HttpContext.Response.Cookies.Append("divid", model?.ViewDivId); + } + } + base.OnActionExecuted(context); + } + + public override void OnResultExecuted(ResultExecutedContext context) + { + var ctrl = context.Controller as IBaseController; + if (ctrl == null) + { + base.OnResultExecuted(context); + return; + } + var ctrlActDesc = context.ActionDescriptor as ControllerActionDescriptor; + var nolog = ctrlActDesc.MethodInfo.IsDefined(typeof(NoLogAttribute), false) || ctrlActDesc.ControllerTypeInfo.IsDefined(typeof(NoLogAttribute), false); + + BaseVM model = null; + if (context.Result is ViewResult vr) + { + model = vr.Model as BaseVM; + } + if (context.Result is PartialViewResult pvr) + { + model = pvr.Model as BaseVM; + context.HttpContext.Response.WriteAsync($""); + } + + //如果是来自Error,则已经记录过日志,跳过 + if (ctrlActDesc.ControllerName == "_Framework" && ctrlActDesc.ActionName == "Error") + { + return; + } + if ( nolog == false) + { + var log = new ActionLog(); + var ctrlDes = ctrlActDesc.ControllerTypeInfo.GetCustomAttributes(typeof(ActionDescriptionAttribute), false).Cast().FirstOrDefault(); + var actDes = ctrlActDesc.MethodInfo.GetCustomAttributes(typeof(ActionDescriptionAttribute), false).Cast().FirstOrDefault(); + var postDes = ctrlActDesc.MethodInfo.GetCustomAttributes(typeof(HttpPostAttribute), false).Cast().FirstOrDefault(); + + log.LogType = context.Exception == null ? ActionLogTypesEnum.Normal : ActionLogTypesEnum.Exception; + log.ActionTime = DateTime.Now; + log.ITCode = ctrl.Wtm?.LoginUserInfo?.ITCode ?? string.Empty; + // 给日志的多语言属性赋值 + log.ModuleName = ctrlDes?.GetDescription(ctrl) ?? ctrlActDesc.ControllerName; + log.ActionName = actDes?.GetDescription(ctrl) ?? ctrlActDesc.ActionName + (postDes == null ? string.Empty : "[P]"); + log.ActionUrl = context.HttpContext.Request.Path; + log.IP = context.HttpContext.GetRemoteIpAddress(); + log.Remark = context.Exception?.ToString() ?? string.Empty; + if (string.IsNullOrEmpty(log.Remark) == false && log.Remark.Length > 2000) + { + log.Remark = log.Remark.Substring(0, 2000); + } + var starttime = context.HttpContext.Items["actionstarttime"] as DateTime?; + if (starttime != null) + { + log.Duration = DateTime.Now.Subtract(starttime.Value).TotalSeconds; + } + try + { + var logger = context.HttpContext.RequestServices.GetRequiredService>(); + if (logger != null) + { + logger.Log(LogLevel.Information, new EventId(), log, null, (a, b) => + { + return a.GetLogString(); + }); + } + } + catch { } + } + if (context.Exception != null) + { + context.ExceptionHandled = true; + if (ctrl.Wtm.ConfigInfo.IsQuickDebug == true) + { + context.HttpContext.Response.WriteAsync(context.Exception.ToString()); + } + else + { + context.HttpContext.Response.WriteAsync(MvcProgram._localizer["Sys.PageError"]); + } + } + base.OnResultExecuted(context); + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Filters/PrivilegeFilter.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Filters/PrivilegeFilter.cs new file mode 100644 index 0000000..d3e1507 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Filters/PrivilegeFilter.cs @@ -0,0 +1,247 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Policy; +using System.Text.RegularExpressions; +using System.Web; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Mvc.Routing; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using WalkingTec.Mvvm.Core; +using WalkingTec.Mvvm.Core.Auth; + +namespace WalkingTec.Mvvm.Mvc.Filters +{ + public class PrivilegeFilter : ActionFilterAttribute + { + public override void OnActionExecuting(ActionExecutingContext context) + { + var controller = context.Controller as IBaseController; + if (controller == null) + { + base.OnActionExecuting(context); + return; + } + context.SetWtmContext(); + + if (controller.Wtm.ConfigInfo.IsQuickDebug && controller is BaseApiController) + { + base.OnActionExecuting(context); + return; + } + ControllerActionDescriptor ad = context.ActionDescriptor as ControllerActionDescriptor; + + var lg = context.HttpContext.RequestServices.GetRequiredService(); + + string u = null; + if (ad.Parameters.Any(x=>x.Name.ToLower() == "id")) + { + u = lg.GetPathByAction(ad.ActionName, ad.ControllerName, new { area = context.RouteData.Values["area"], id = 0 }); + } + else + { + u = lg.GetPathByAction(ad.ActionName, ad.ControllerName, new { area = context.RouteData.Values["area"] }); + } + if (u != null && u.EndsWith("/0")) + { + u = u[0..^2]; + if (controller is BaseApiController) + { + u = u + "/{id}"; + } + } + if (u != null && u.EndsWith("?id=0")) + { + u = u[0..^5]; + if (controller is BaseApiController) + { + u = u + "/{id}"; + } + } + + controller.Wtm.BaseUrl = u + context.HttpContext.Request.QueryString.ToUriComponent(); + + + //如果是QuickDebug模式,或者Action或Controller上有AllRightsAttribute标记都不需要判断权限 + //如果用户登录信息为空,也不需要判断权限,BaseController中会对没有登录的用户做其他处理 + + var isPublic = ad.MethodInfo.IsDefined(typeof(PublicAttribute), false) || ad.ControllerTypeInfo.IsDefined(typeof(PublicAttribute), false); + if (!isPublic) + isPublic = ad.MethodInfo.IsDefined(typeof(AllowAnonymousAttribute), false) || ad.ControllerTypeInfo.IsDefined(typeof(AllowAnonymousAttribute), false); + + var isAllRights = ad.MethodInfo.IsDefined(typeof(AllRightsAttribute), false) || ad.ControllerTypeInfo.IsDefined(typeof(AllRightsAttribute), false); + var isDebug = ad.MethodInfo.IsDefined(typeof(DebugOnlyAttribute), false) || ad.ControllerTypeInfo.IsDefined(typeof(DebugOnlyAttribute), false); + if (controller.Wtm.ConfigInfo.IsFilePublic == true) + { + if (ad.ControllerName == "_Framework" && (ad.MethodInfo.Name == "GetFile" || ad.MethodInfo.Name == "ViewFile")) + { + isPublic = true; + } + if(ad.ControllerTypeInfo.FullName == "WalkingTec.Mvvm.Admin.Api.FileApiController" && (ad.MethodInfo.Name == "GetFileName" || ad.MethodInfo.Name == "GetFile" || ad.MethodInfo.Name == "DownloadFile")) + { + isPublic = true; + + } + } + if (isDebug) + { + if (controller.ConfigInfo.IsQuickDebug) + { + base.OnActionExecuting(context); + } + else + { + if (controller is BaseController c) + { + context.Result = c.Content(MvcProgram._localizer["Sys.DebugOnly"]); + } + else if (controller is ControllerBase c2) + { + context.Result = c2.BadRequest(MvcProgram._localizer["Sys.DebugOnly"]); + } + } + return; + } + + if(isPublic == false && controller != null && controller.Wtm != null) + { + isPublic = controller.Wtm.IsUrlPublic(u); + } + if (isPublic == true) + { + base.OnActionExecuting(context); + return; + } + + if (controller.Wtm.LoginUserInfo == null) + { + if (controller is ControllerBase ctrl) + { + //if it's a layui search request,returns a layui format message so that it can parse + if (ctrl.Request.Headers.ContainsKey("layuisearch")) + { + ContentResult cr = new ContentResult() + { + Content = "{\"Data\":[],\"Count\":0,\"Page\":1,\"PageCount\":0,\"Msg\":\"" + MvcProgram._localizer["Sys.NeedLogin"] + "\",\"Code\":401}", + ContentType = "application/json", + StatusCode = 200 + }; + context.Result = cr; + } + else + { + if (ctrl.HttpContext.Request.Headers.ContainsKey("Authorization")) + { + context.Result = ctrl.Unauthorized(JwtBearerDefaults.AuthenticationScheme); + } + else + { + if (controller is BaseApiController) + { + ContentResult cr = new ContentResult() + { + Content = MvcProgram._localizer["Sys.NeedLogin"], + ContentType = "text/html", + StatusCode = 401 + }; + context.Result = cr; + } + else + { + string lp = controller.Wtm.ConfigInfo.CookieOptions.LoginPath; + if (lp.StartsWith("/")) + { + lp = "~" + lp; + } + if (lp.StartsWith("~/")) + { + lp = ctrl.Url.Content(lp); + } + ContentResult cr = new ContentResult() + { + Content = $"", + ContentType = "text/html", + StatusCode = 200 + }; + //context.HttpContext.Response.Headers.Add("IsScript", "true"); + context.Result = cr; + //context.Result = ctrl.Redirect(GlobalServices.GetRequiredService>().Value.LoginPath); + } + } + } + } + //context.HttpContext.ChallengeAsync().Wait(); + } + else + { + if (isAllRights == false) + { + bool canAccess = controller.Wtm.IsAccessable(controller.BaseUrl); + if (canAccess == false && controller.ConfigInfo.IsQuickDebug == false) + { + if (controller is ControllerBase ctrl) + { + //if it's a layui search request,returns a layui format message so that it can parse + if (ctrl.Request.Headers.ContainsKey("layuisearch")) + { + ContentResult cr = new ContentResult() + { + Content = "{\"Data\":[],\"Count\":0,\"Page\":1,\"PageCount\":0,\"Msg\":\""+ MvcProgram._localizer["Sys.NoPrivilege"] + "\",\"Code\":403}", + ContentType = "application/json", + StatusCode = 200 + }; + context.Result = cr; + } + else + { + if (ctrl.HttpContext.Request.Headers.ContainsKey("Authorization")) + { + context.Result = ctrl.Forbid(JwtBearerDefaults.AuthenticationScheme); + } + else + { + ContentResult cr = new ContentResult() + { + Content = MvcProgram._localizer["Sys.NoPrivilege"], + ContentType = "text/html", + StatusCode = 403 + }; + context.Result = cr; + + } + } + } + } + } + } + base.OnActionExecuting(context); + } + + private List getAuthTypes(ControllerActionDescriptor ad) + { + var authenticationSchemes = new List(); + if (ad.MethodInfo.IsDefined(typeof(AuthorizeAttribute), false)) + { + var authorizeAttr = ad.MethodInfo.GetCustomAttributes(typeof(AuthorizeAttribute), false).FirstOrDefault() as AuthorizeAttribute; + if (authorizeAttr != null) + authenticationSchemes = authorizeAttr.AuthenticationSchemes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); + } + else if (ad.ControllerTypeInfo.IsDefined(typeof(AuthorizeAttribute), false)) + { + var authorizeAttr = ad.ControllerTypeInfo.GetCustomAttributes(typeof(AuthorizeAttribute), false).FirstOrDefault() as AuthorizeAttribute; + if (authorizeAttr != null) + authenticationSchemes = authorizeAttr.AuthenticationSchemes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); + } + return authenticationSchemes; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Filters/SwaggerFilter.cs b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Filters/SwaggerFilter.cs new file mode 100644 index 0000000..5a5750e --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/Filters/SwaggerFilter.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.Rendering; +using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; +using WalkingTec.Mvvm.Core; + +namespace WalkingTec.Mvvm.Mvc.Filters +{ + public class SwaggerFilter : ISchemaFilter + { + public void Apply(OpenApiSchema schema, SchemaFilterContext context) + { + var type = context.Type; + if(type == typeof(List)) + { + schema = null; + } + //if (type.IsEnum) + //{ + // schema.Extensions.Add( + // "x-ms-enum", + // new OpenApiObject + // { + // ["name"] = new OpenApiString(type.Name), + // ["modelAsString"] = new OpenApiBoolean(true) + // } + // ); + //}; + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ApiTest.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ApiTest.txt new file mode 100644 index 0000000..851f251 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ApiTest.txt @@ -0,0 +1,130 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using WalkingTec.Mvvm.Core; +using $cns$; +using $vns$; +using $mns$; +using $dns$; +$othernamespace$ + +namespace $tns$ +{ + [TestClass] + public class $model$ApiTest + { + private $classnamel$Controller _controller; + private string _seed; + + public $model$ApiTest() + { + _seed = Guid.NewGuid().ToString(); + _controller = MockController.CreateApi<$classnamel$Controller>(new DataContext(_seed, DBTypeEnum.Memory), "user"); + } + + [TestMethod] + public void SearchTest() + { + ContentResult rv = _controller.Search(new $classnamel$Searcher()) as ContentResult; + Assert.IsTrue(string.IsNullOrEmpty(rv.Content)==false); + } + + [TestMethod] + public void CreateTest() + { + $classnamel$VM vm = _controller.Wtm.CreateVM<$classnamel$VM>(); + $model$ v = new $model$(); + $cpros$ + vm.Entity = v; + var rv = _controller.Add(vm); + Assert.IsInstanceOfType(rv, typeof(OkObjectResult)); + + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + var data = context.Set<$model$>().Find(v.ID); + $assert$ + Assert.AreEqual(data.CreateBy, "user"); + Assert.IsTrue(DateTime.Now.Subtract(data.CreateTime.Value).Seconds < 10); + } + } + + [TestMethod] + public void EditTest() + { + $model$ v = new $model$(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + $pros$ + context.Set<$model$>().Add(v); + context.SaveChanges(); + } + + $classnamel$VM vm = _controller.Wtm.CreateVM<$classnamel$VM>(); + var oldID = v.ID; + v = new $model$(); + v.ID = oldID; + $epros$ + vm.Entity = v; + vm.FC = new Dictionary(); + $fc$ + var rv = _controller.Edit(vm); + Assert.IsInstanceOfType(rv, typeof(OkObjectResult)); + + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + var data = context.Set<$model$>().Find(v.ID); + $eassert$ + Assert.AreEqual(data.UpdateBy, "user"); + Assert.IsTrue(DateTime.Now.Subtract(data.UpdateTime.Value).Seconds < 10); + } + + } + + [TestMethod] + public void GetTest() + { + $model$ v = new $model$(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + $pros$ + context.Set<$model$>().Add(v); + context.SaveChanges(); + } + var rv = _controller.Get(v.ID.ToString()); + Assert.IsNotNull(rv); + } + + [TestMethod] + public void BatchDeleteTest() + { + $model$ v1 = new $model$(); + $model$ v2 = new $model$(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + $mpros$ + context.Set<$model$>().Add(v1); + context.Set<$model$>().Add(v2); + context.SaveChanges(); + } + + var rv = _controller.BatchDelete(new string[] { v1.ID.ToString(), v2.ID.ToString() }); + Assert.IsInstanceOfType(rv, typeof(OkObjectResult)); + + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + var data1 = context.Set<$model$>().Find(v1.ID); + var data2 = context.Set<$model$>().Find(v2.ID); + $mdel$ + } + + rv = _controller.BatchDelete(new string[] {}); + Assert.IsInstanceOfType(rv, typeof(OkResult)); + + } +$add$ + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ApiTestTopPoco.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ApiTestTopPoco.txt new file mode 100644 index 0000000..d0ef3ee --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ApiTestTopPoco.txt @@ -0,0 +1,126 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using WalkingTec.Mvvm.Core; +using $cns$; +using $vns$; +using $mns$; +using $dns$; +$othernamespace$ + +namespace $tns$ +{ + [TestClass] + public class $model$ApiTest + { + private $classnamel$Controller _controller; + private string _seed; + + public $model$ApiTest() + { + _seed = Guid.NewGuid().ToString(); + _controller = MockController.CreateApi<$classnamel$Controller>(new DataContext(_seed, DBTypeEnum.Memory), "user"); + } + + [TestMethod] + public void SearchTest() + { + ContentResult rv = _controller.Search(new $classnamel$Searcher()) as ContentResult; + Assert.IsTrue(string.IsNullOrEmpty(rv.Content)==false); + } + + [TestMethod] + public void CreateTest() + { + $classnamel$VM vm = _controller.Wtm.CreateVM<$classnamel$VM>(); + $model$ v = new $model$(); + $cpros$ + vm.Entity = v; + var rv = _controller.Add(vm); + Assert.IsInstanceOfType(rv, typeof(OkObjectResult)); + + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + var data = context.Set<$model$>().Find(v.ID); + $assert$ + } + } + + [TestMethod] + public void EditTest() + { + $model$ v = new $model$(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + $pros$ + context.Set<$model$>().Add(v); + context.SaveChanges(); + } + + $classnamel$VM vm = _controller.Wtm.CreateVM<$classnamel$VM>(); + var oldID = v.ID; + v = new $model$(); + v.ID = oldID; + $epros$ + vm.Entity = v; + vm.FC = new Dictionary(); + $fc$ + var rv = _controller.Edit(vm); + Assert.IsInstanceOfType(rv, typeof(OkObjectResult)); + + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + var data = context.Set<$model$>().Find(v.ID); + $eassert$ + } + + } + + [TestMethod] + public void GetTest() + { + $model$ v = new $model$(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + $pros$ + context.Set<$model$>().Add(v); + context.SaveChanges(); + } + var rv = _controller.Get(v.ID.ToString()); + Assert.IsNotNull(rv); + } + + [TestMethod] + public void BatchDeleteTest() + { + $model$ v1 = new $model$(); + $model$ v2 = new $model$(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + $mpros$ + context.Set<$model$>().Add(v1); + context.Set<$model$>().Add(v2); + context.SaveChanges(); + } + + var rv = _controller.BatchDelete(new string[] { v1.ID.ToString(), v2.ID.ToString() }); + Assert.IsInstanceOfType(rv, typeof(OkObjectResult)); + + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + var data1 = context.Set<$model$>().Find(v1.ID); + var data2 = context.Set<$model$>().Find(v2.ID); + $mdel$ + } + + rv = _controller.BatchDelete(new string[] {}); + Assert.IsInstanceOfType(rv, typeof(OkResult)); + + } +$add$ + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/BatchVM.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/BatchVM.txt new file mode 100644 index 0000000..52cc6fa --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/BatchVM.txt @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Threading.Tasks; +using WalkingTec.Mvvm.Core; +using WalkingTec.Mvvm.Core.Extensions; +using $modelnamespace$; +$othernamespace$ + +namespace $vmnamespace$ +{ + public partial class $classname$BatchVM : BaseBatchVM<$modelname$, $classname$_BatchEdit> + { + public $classname$BatchVM() + { + ListVM = new $classname$ListVM(); + LinkedVM = new $classname$_BatchEdit(); + } + + } + + /// + /// Class to define batch edit fields + /// + public class $classname$_BatchEdit : BaseVM + {$pros$ + + protected override void InitVM() + {$init$ + } + + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ControllerTest.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ControllerTest.txt new file mode 100644 index 0000000..d4c7990 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ControllerTest.txt @@ -0,0 +1,213 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using WalkingTec.Mvvm.Core; +using $cns$; +using $vns$; +using $mns$; +using $dns$; +$othernamespace$ + +namespace $tns$ +{ + [TestClass] + public class $model$ControllerTest + { + private $model$Controller _controller; + private string _seed; + + public $model$ControllerTest() + { + _seed = Guid.NewGuid().ToString(); + _controller = MockController.CreateController<$model$Controller>(new DataContext(_seed, DBTypeEnum.Memory), "user"); + } + + [TestMethod] + public void SearchTest() + { + PartialViewResult rv = (PartialViewResult)_controller.Index(); + Assert.IsInstanceOfType(rv.Model, typeof(IBasePagedListVM)); + string rv2 = _controller.Search((rv.Model as $model$ListVM).Searcher); + Assert.IsTrue(rv2.Contains("\"Code\":200")); + } + + [TestMethod] + public void CreateTest() + { + PartialViewResult rv = (PartialViewResult)_controller.Create(); + Assert.IsInstanceOfType(rv.Model, typeof($model$VM)); + + $model$VM vm = rv.Model as $model$VM; + $model$ v = new $model$(); + $cpros$ + vm.Entity = v; + _controller.Create(vm); + + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + var data = context.Set<$model$>().Find(v.ID); + $assert$ + Assert.AreEqual(data.CreateBy, "user"); + Assert.IsTrue(DateTime.Now.Subtract(data.CreateTime.Value).Seconds < 10); + } + + } + + [TestMethod] + public void EditTest() + { + $model$ v = new $model$(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + $pros$ + context.Set<$model$>().Add(v); + context.SaveChanges(); + } + + PartialViewResult rv = (PartialViewResult)_controller.Edit(v.ID.ToString()); + Assert.IsInstanceOfType(rv.Model, typeof($model$VM)); + + $model$VM vm = rv.Model as $model$VM; + vm.Wtm.DC = new DataContext(_seed, DBTypeEnum.Memory); + v = new $model$(); + v.ID = vm.Entity.ID; + $epros$ + vm.Entity = v; + vm.FC = new Dictionary(); + $fc$ + _controller.Edit(vm); + + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + var data = context.Set<$model$>().Find(v.ID); + $eassert$ + Assert.AreEqual(data.UpdateBy, "user"); + Assert.IsTrue(DateTime.Now.Subtract(data.UpdateTime.Value).Seconds < 10); + } + + } + + + [TestMethod] + public void DeleteTest() + { + $model$ v = new $model$(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + $pros$ + context.Set<$model$>().Add(v); + context.SaveChanges(); + } + + PartialViewResult rv = (PartialViewResult)_controller.Delete(v.ID.ToString()); + Assert.IsInstanceOfType(rv.Model, typeof($model$VM)); + + $model$VM vm = rv.Model as $model$VM; + v = new $model$(); + v.ID = vm.Entity.ID; + vm.Entity = v; + _controller.Delete(v.ID.ToString(),null); + + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + var data = context.Set<$model$>().Find(v.ID); + $del$ + } + + } + + + [TestMethod] + public void DetailsTest() + { + $model$ v = new $model$(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + $pros$ + context.Set<$model$>().Add(v); + context.SaveChanges(); + } + PartialViewResult rv = (PartialViewResult)_controller.Details(v.ID.ToString()); + Assert.IsInstanceOfType(rv.Model, typeof(IBaseCRUDVM)); + Assert.AreEqual(v.ID, (rv.Model as IBaseCRUDVM).Entity.GetID()); + } + + [TestMethod] + public void BatchEditTest() + { + $model$ v1 = new $model$(); + $model$ v2 = new $model$(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + $mpros$ + context.Set<$model$>().Add(v1); + context.Set<$model$>().Add(v2); + context.SaveChanges(); + } + + PartialViewResult rv = (PartialViewResult)_controller.BatchDelete(new string[] { v1.ID.ToString(), v2.ID.ToString() }); + Assert.IsInstanceOfType(rv.Model, typeof($model$BatchVM)); + + $model$BatchVM vm = rv.Model as $model$BatchVM; + vm.Ids = new string[] { v1.ID.ToString(), v2.ID.ToString() }; + $linkedpros$ + vm.FC = new Dictionary(); + $linkedfc$ + _controller.DoBatchEdit(vm, null); + + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + var data1 = context.Set<$model$>().Find(v1.ID); + var data2 = context.Set<$model$>().Find(v2.ID); + $meassert$ + Assert.AreEqual(data1.UpdateBy, "user"); + Assert.IsTrue(DateTime.Now.Subtract(data1.UpdateTime.Value).Seconds < 10); + Assert.AreEqual(data2.UpdateBy, "user"); + Assert.IsTrue(DateTime.Now.Subtract(data2.UpdateTime.Value).Seconds < 10); + } + } + + + [TestMethod] + public void BatchDeleteTest() + { + $model$ v1 = new $model$(); + $model$ v2 = new $model$(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + $mpros$ + context.Set<$model$>().Add(v1); + context.Set<$model$>().Add(v2); + context.SaveChanges(); + } + + PartialViewResult rv = (PartialViewResult)_controller.BatchDelete(new string[] { v1.ID.ToString(), v2.ID.ToString() }); + Assert.IsInstanceOfType(rv.Model, typeof($model$BatchVM)); + + $model$BatchVM vm = rv.Model as $model$BatchVM; + vm.Ids = new string[] { v1.ID.ToString(), v2.ID.ToString() }; + _controller.DoBatchDelete(vm, null); + + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + var data1 = context.Set<$model$>().Find(v1.ID); + var data2 = context.Set<$model$>().Find(v2.ID); + $mdel$ + } + } + + [TestMethod] + public void ExportTest() + { + PartialViewResult rv = (PartialViewResult)_controller.Index(); + Assert.IsInstanceOfType(rv.Model, typeof(IBasePagedListVM)); + IActionResult rv2 = _controller.ExportExcel(rv.Model as $model$ListVM); + Assert.IsTrue((rv2 as FileContentResult).FileContents.Length > 0); + } +$add$ + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ControllerTestTopPoco.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ControllerTestTopPoco.txt new file mode 100644 index 0000000..adde414 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ControllerTestTopPoco.txt @@ -0,0 +1,196 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using WalkingTec.Mvvm.Core; +using $cns$; +using $vns$; +using $mns$; +using $dns$; +$othernamespace$ + +namespace $tns$ +{ + [TestClass] + public class $model$ControllerTest + { + private $model$Controller _controller; + private string _seed; + + public $model$ControllerTest() + { + _seed = Guid.NewGuid().ToString(); + _controller = MockController.CreateController<$model$Controller>(new DataContext(_seed, DBTypeEnum.Memory), "user"); + } + + [TestMethod] + public void SearchTest() + { + PartialViewResult rv = (PartialViewResult)_controller.Index(); + Assert.IsInstanceOfType(rv.Model, typeof(IBasePagedListVM)); + string rv2 = _controller.Search((rv.Model as $model$ListVM).Searcher); + Assert.IsTrue(rv2.Contains("\"Code\":200")); + } + + [TestMethod] + public void CreateTest() + { + PartialViewResult rv = (PartialViewResult)_controller.Create(); + Assert.IsInstanceOfType(rv.Model, typeof($model$VM)); + + $model$VM vm = rv.Model as $model$VM; + $model$ v = new $model$(); + $cpros$ + vm.Entity = v; + _controller.Create(vm); + + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + var data = context.Set<$model$>().Find(v.ID); + $assert$ + } + + } + + [TestMethod] + public void EditTest() + { + $model$ v = new $model$(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + $pros$ + context.Set<$model$>().Add(v); + context.SaveChanges(); + } + + PartialViewResult rv = (PartialViewResult)_controller.Edit(v.ID.ToString()); + Assert.IsInstanceOfType(rv.Model, typeof($model$VM)); + + $model$VM vm = rv.Model as $model$VM; + vm.Wtm.DC = new DataContext(_seed, DBTypeEnum.Memory); + v = new $model$(); + v.ID = vm.Entity.ID; + $epros$ + vm.Entity = v; + vm.FC = new Dictionary(); + $fc$ + _controller.Edit(vm); + + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + var data = context.Set<$model$>().Find(v.ID); + $eassert$ + } + + } + + + [TestMethod] + public void DeleteTest() + { + $model$ v = new $model$(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + $pros$ + context.Set<$model$>().Add(v); + context.SaveChanges(); + } + + PartialViewResult rv = (PartialViewResult)_controller.Delete(v.ID.ToString()); + Assert.IsInstanceOfType(rv.Model, typeof($model$VM)); + + $model$VM vm = rv.Model as $model$VM; + v = new $model$(); + v.ID = vm.Entity.ID; + vm.Entity = v; + _controller.Delete(v.ID.ToString(),null); + + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + var data = context.Set<$model$>().Find(v.ID); + $del$ + } + + } + + + [TestMethod] + public void DetailsTest() + { + $model$ v = new $model$(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + $pros$ + context.Set<$model$>().Add(v); + context.SaveChanges(); + } + PartialViewResult rv = (PartialViewResult)_controller.Details(v.ID.ToString()); + Assert.IsInstanceOfType(rv.Model, typeof(IBaseCRUDVM)); + Assert.AreEqual(v.ID, (rv.Model as IBaseCRUDVM).Entity.GetID()); + } + + [TestMethod] + public void BatchEditTest() + { + $model$ v1 = new $model$(); + $model$ v2 = new $model$(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + $mpros$ + context.Set<$model$>().Add(v1); + context.Set<$model$>().Add(v2); + context.SaveChanges(); + } + + PartialViewResult rv = (PartialViewResult)_controller.BatchDelete(new string[] { v1.ID.ToString(), v2.ID.ToString() }); + Assert.IsInstanceOfType(rv.Model, typeof($model$BatchVM)); + + $model$BatchVM vm = rv.Model as $model$BatchVM; + vm.Ids = new string[] { v1.ID.ToString(), v2.ID.ToString() }; + $linkedpros$ + vm.FC = new Dictionary(); + $linkedfc$ + _controller.DoBatchEdit(vm, null); + + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + var data1 = context.Set<$model$>().Find(v1.ID); + var data2 = context.Set<$model$>().Find(v2.ID); + $meassert$ + } + } + + + [TestMethod] + public void BatchDeleteTest() + { + $model$ v1 = new $model$(); + $model$ v2 = new $model$(); + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + $mpros$ + context.Set<$model$>().Add(v1); + context.Set<$model$>().Add(v2); + context.SaveChanges(); + } + + PartialViewResult rv = (PartialViewResult)_controller.BatchDelete(new string[] { v1.ID.ToString(), v2.ID.ToString() }); + Assert.IsInstanceOfType(rv.Model, typeof($model$BatchVM)); + + $model$BatchVM vm = rv.Model as $model$BatchVM; + vm.Ids = new string[] { v1.ID.ToString(), v2.ID.ToString() }; + _controller.DoBatchDelete(vm, null); + + using (var context = new DataContext(_seed, DBTypeEnum.Memory)) + { + var data1 = context.Set<$model$>().Find(v1.ID); + var data2 = context.Set<$model$>().Find(v2.ID); + $mdel$ + } + } +$add$ + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/CrudVM.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/CrudVM.txt new file mode 100644 index 0000000..d598392 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/CrudVM.txt @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.ComponentModel.DataAnnotations; +using WalkingTec.Mvvm.Core; +using WalkingTec.Mvvm.Core.Extensions; +using $modelnamespace$; +$othernamespace$ + +namespace $vmnamespace$ +{ + public partial class $classname$VM : BaseCRUDVM<$modelname$> + {$pros$ + + public $classname$VM() + {$include$ + } + + protected override void InitVM() + {$init$ + } + + public override void DoAdd() + {$add$ + base.DoAdd(); + } + + public override void DoEdit(bool updateAllFields = false) + {$edit$ + base.DoEdit(updateAllFields); + } + + public override void DoDelete() + { + base.DoDelete(); + } + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/HeaderFormat.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/HeaderFormat.txt new file mode 100644 index 0000000..74399cf --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/HeaderFormat.txt @@ -0,0 +1,9 @@ + + private List $field$Format($classname$_View entity, object val) + { + return new List + { + ColumnFormatInfo.MakeDownloadButton(ButtonTypesEnum.Button,entity.$field$), + ColumnFormatInfo.MakeViewButton(ButtonTypesEnum.Button,entity.$field$,640,480), + }; + } diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ImportVM.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ImportVM.txt new file mode 100644 index 0000000..ed39299 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ImportVM.txt @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Threading.Tasks; +using WalkingTec.Mvvm.Core; +using WalkingTec.Mvvm.Core.Extensions; +using $modelnamespace$; +$othernamespace$ + +namespace $vmnamespace$ +{ + public partial class $classname$TemplateVM : BaseTemplateVM + {$pros$ + + protected override void InitVM() + {$init$ + } + + } + + public class $classname$ImportVM : BaseImportVM<$classname$TemplateVM, $modelname$> + { + + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ListVM.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ListVM.txt new file mode 100644 index 0000000..a4fd746 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/ListVM.txt @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using WalkingTec.Mvvm.Core; +using WalkingTec.Mvvm.Core.Extensions; +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using $modelnamespace$; +$othernamespace$ + +namespace $vmnamespace$ +{ + public partial class $classname$ListVM : BasePagedListVM<$classname$_View, $classname$Searcher> + {$actions$ + + protected override IEnumerable> InitGridHeader() + { + return new List>{$headers$ + this.MakeGridHeaderAction(width: 200) + }; + }$format$ + + public override IOrderedQueryable<$classname$_View> GetSearchQuery() + { + var query = DC.Set<$modelname$>()$where$ + .Select(x => new $classname$_View + { + ID = x.ID,$select$ + }) + .OrderBy(x => x.ID); + return query; + } + + } + + public class $classname$_View : $modelname${$subpros$ + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/BatchDeleteView.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/BatchDeleteView.txt new file mode 100644 index 0000000..061492a --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/BatchDeleteView.txt @@ -0,0 +1,12 @@ +@model $vmnamespace$.$modelname$BatchVM +@inject IStringLocalizer Localizer; + + + @Localizer["Sys.BatchDeleteConfirm"] + + + + + + + diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/BatchEditView.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/BatchEditView.txt new file mode 100644 index 0000000..1b95276 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/BatchEditView.txt @@ -0,0 +1,12 @@ +@model $vmnamespace$.$modelname$BatchVM +@inject IStringLocalizer Localizer; + + +
@Localizer["Sys.BatchEditConfirm"]
$fields$ + + + + + + +
diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/Controller.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/Controller.txt new file mode 100644 index 0000000..4097c99 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/Controller.txt @@ -0,0 +1,219 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using WalkingTec.Mvvm.Core; +using WalkingTec.Mvvm.Mvc; +using WalkingTec.Mvvm.Core.Extensions; +using $vmnamespace$; + +namespace $namespace$ +{ + $area$ + [ActionDescription("$des$")] + public partial class $modelname$Controller : BaseController + { + #region Search + [ActionDescription("Sys.Search")] + public ActionResult Index() + { + var vm = Wtm.CreateVM<$modelname$ListVM>(); + return PartialView(vm); + } + + [ActionDescription("Sys.Search")] + [HttpPost] + public string Search($modelname$Searcher searcher) + { + var vm = Wtm.CreateVM<$modelname$ListVM>(passInit: true); + if (ModelState.IsValid) + { + vm.Searcher = searcher; + return vm.GetJson(false); + } + else + { + return vm.GetError(); + } + } + + #endregion + + #region Create + [ActionDescription("Sys.Create")] + public ActionResult Create() + { + var vm = Wtm.CreateVM<$modelname$VM>(); + return PartialView(vm); + } + + [HttpPost] + [ActionDescription("Sys.Create")] + public ActionResult Create($modelname$VM vm) + { + if (!ModelState.IsValid) + { + return PartialView(vm); + } + else + { + vm.DoAdd(); + if (!ModelState.IsValid) + { + vm.DoReInit(); + return PartialView(vm); + } + else + { + return FFResult().CloseDialog().RefreshGrid(); + } + } + } + #endregion + + #region Edit + [ActionDescription("Sys.Edit")] + public ActionResult Edit(string id) + { + var vm = Wtm.CreateVM<$modelname$VM>(id); + return PartialView(vm); + } + + [ActionDescription("Sys.Edit")] + [HttpPost] + [ValidateFormItemOnly] + public ActionResult Edit($modelname$VM vm) + { + if (!ModelState.IsValid) + { + return PartialView(vm); + } + else + { + vm.DoEdit(); + if (!ModelState.IsValid) + { + vm.DoReInit(); + return PartialView(vm); + } + else + { + return FFResult().CloseDialog().RefreshGridRow(vm.Entity.ID); + } + } + } + #endregion + + #region Delete + [ActionDescription("Sys.Delete")] + public ActionResult Delete(string id) + { + var vm = Wtm.CreateVM<$modelname$VM>(id); + return PartialView(vm); + } + + [ActionDescription("Sys.Delete")] + [HttpPost] + public ActionResult Delete(string id, IFormCollection nouse) + { + var vm = Wtm.CreateVM<$modelname$VM>(id); + vm.DoDelete(); + if (!ModelState.IsValid) + { + return PartialView(vm); + } + else + { + return FFResult().CloseDialog().RefreshGrid(); + } + } + #endregion + + #region Details + [ActionDescription("Sys.Details")] + public ActionResult Details(string id) + { + var vm = Wtm.CreateVM<$modelname$VM>(id); + return PartialView(vm); + } + #endregion + + #region BatchEdit + [HttpPost] + [ActionDescription("Sys.BatchEdit")] + public ActionResult BatchEdit(string[] IDs) + { + var vm = Wtm.CreateVM<$modelname$BatchVM>(Ids: IDs); + return PartialView(vm); + } + + [HttpPost] + [ActionDescription("Sys.BatchEdit")] + public ActionResult DoBatchEdit($modelname$BatchVM vm, IFormCollection nouse) + { + if (!ModelState.IsValid || !vm.DoBatchEdit()) + { + return PartialView("BatchEdit",vm); + } + else + { + return FFResult().CloseDialog().RefreshGrid().Alert(Localizer["Sys.BatchEditSuccess", vm.Ids.Length]); + } + } + #endregion + + #region BatchDelete + [HttpPost] + [ActionDescription("Sys.BatchDelete")] + public ActionResult BatchDelete(string[] IDs) + { + var vm = Wtm.CreateVM<$modelname$BatchVM>(Ids: IDs); + return PartialView(vm); + } + + [HttpPost] + [ActionDescription("Sys.BatchDelete")] + public ActionResult DoBatchDelete($modelname$BatchVM vm, IFormCollection nouse) + { + if (!ModelState.IsValid || !vm.DoBatchDelete()) + { + return PartialView("BatchDelete",vm); + } + else + { + return FFResult().CloseDialog().RefreshGrid().Alert(Localizer["Sys.BatchDeleteSuccess", vm.Ids.Length]); + } + } + #endregion + + #region Import + [ActionDescription("Sys.Import")] + public ActionResult Import() + { + var vm = Wtm.CreateVM<$modelname$ImportVM>(); + return PartialView(vm); + } + + [HttpPost] + [ActionDescription("Sys.Import")] + public ActionResult Import($modelname$ImportVM vm, IFormCollection nouse) + { + if (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData()) + { + return PartialView(vm); + } + else + { + return FFResult().CloseDialog().RefreshGrid().Alert(Localizer["Sys.ImportSuccess", vm.EntityList.Count.ToString()]); + } + } + #endregion + + [ActionDescription("Sys.Export")] + [HttpPost] + public IActionResult ExportExcel($modelname$ListVM vm) + { + return vm.GetExportData(); + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/CreateView.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/CreateView.txt new file mode 100644 index 0000000..273bd2b --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/CreateView.txt @@ -0,0 +1,9 @@ +@model $vmnamespace$.$modelname$VM +@inject IStringLocalizer Localizer; + +$fields$ + + + + + diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/DeleteView.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/DeleteView.txt new file mode 100644 index 0000000..4e70c53 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/DeleteView.txt @@ -0,0 +1,11 @@ +@model $vmnamespace$.$modelname$VM +@inject IStringLocalizer Localizer; + + + @Localizer["Sys.DeleteConfirm"]$fields$ + + + + + + diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/DetailsView.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/DetailsView.txt new file mode 100644 index 0000000..0bee0df --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/DetailsView.txt @@ -0,0 +1,8 @@ +@model $vmnamespace$.$modelname$VM +@inject IStringLocalizer Localizer; + +$fields$ + + + + diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/EditView.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/EditView.txt new file mode 100644 index 0000000..68e6c7d --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/EditView.txt @@ -0,0 +1,10 @@ +@model $vmnamespace$.$modelname$VM +@inject IStringLocalizer Localizer; + +$fields$ + + + + + + diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/ImportView.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/ImportView.txt new file mode 100644 index 0000000..e68db4b --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/ImportView.txt @@ -0,0 +1,14 @@ +@model $vmnamespace$.$modelname$ImportVM +@inject IStringLocalizer Localizer; + + + + + + + + + + + + diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/ListView.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/ListView.txt new file mode 100644 index 0000000..8142cd3 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Mvc/ListView.txt @@ -0,0 +1,6 @@ +@model $vmnamespace$.$modelname$ListVM +@inject IStringLocalizer Localizer; + +$fields$ + + diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Searcher.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Searcher.txt new file mode 100644 index 0000000..dfbee55 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Searcher.txt @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Threading.Tasks; +using WalkingTec.Mvvm.Core; +using WalkingTec.Mvvm.Core.Extensions; +using $modelnamespace$; +$othernamespace$ + +namespace $vmnamespace$ +{ + public partial class $classname$Searcher : BaseSearcher + {$pros$ + + protected override void InitVM() + {$init$ + } + + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Spa/Blazor/Controller.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Spa/Blazor/Controller.txt new file mode 100644 index 0000000..8d91ca1 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Spa/Blazor/Controller.txt @@ -0,0 +1,168 @@ +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using WalkingTec.Mvvm.Core; +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Mvc; +using $vmnamespace$; +using $modelnamespace$; +$othernamespace$ + +namespace $namespace$ +{ + $area$ + $jwt$ + [ActionDescription("$des$")] + [ApiController] + [Route("api/$modelname$")] + public partial class $controllername$Controller : BaseApiController + { + [ActionDescription("Sys.Search")] + [HttpPost("Search")] + public IActionResult Search($controllername$Searcher searcher) + { + if (ModelState.IsValid) + { + var vm = Wtm.CreateVM<$controllername$ListVM>(); + vm.Searcher = searcher; + return Content(vm.GetJson(enumToString: false)); + } + else + { + return BadRequest(ModelState.GetErrorJson()); + } + } + + [ActionDescription("Sys.Get")] + [HttpGet("{id}")] + public $controllername$VM Get(string id) + { + var vm = Wtm.CreateVM<$controllername$VM>(id); + return vm; + } + + [ActionDescription("Sys.Create")] + [HttpPost("Add")] + public IActionResult Add($controllername$VM vm) + { + if (!ModelState.IsValid) + { + return BadRequest(ModelState.GetErrorJson()); + } + else + { + vm.DoAdd(); + if (!ModelState.IsValid) + { + return BadRequest(ModelState.GetErrorJson()); + } + else + { + return Ok(vm.Entity); + } + } + + } + + [ActionDescription("Sys.Edit")] + [HttpPut("Edit")] + public IActionResult Edit($controllername$VM vm) + { + if (!ModelState.IsValid) + { + return BadRequest(ModelState.GetErrorJson()); + } + else + { + vm.DoEdit(false); + if (!ModelState.IsValid) + { + return BadRequest(ModelState.GetErrorJson()); + } + else + { + return Ok(vm.Entity); + } + } + } + + [HttpPost("BatchDelete")] + [ActionDescription("Sys.Delete")] + public IActionResult BatchDelete(string[] ids) + { + var vm = Wtm.CreateVM<$controllername$BatchVM>(); + if (ids != null && ids.Count() > 0) + { + vm.Ids = ids; + } + else + { + return Ok(); + } + if (!ModelState.IsValid || !vm.DoBatchDelete()) + { + return BadRequest(ModelState.GetErrorJson()); + } + else + { + return Ok(ids.Count()); + } + } + + + [ActionDescription("Sys.Export")] + [HttpPost("ExportExcel")] + public IActionResult ExportExcel($controllername$Searcher searcher) + { + var vm = Wtm.CreateVM<$controllername$ListVM>(); + vm.Searcher = searcher; + vm.SearcherMode = ListVMSearchModeEnum.Export; + return vm.GetExportData(); + } + + [ActionDescription("Sys.CheckExport")] + [HttpPost("ExportExcelByIds")] + public IActionResult ExportExcelByIds(string[] ids) + { + var vm = Wtm.CreateVM<$controllername$ListVM>(); + if (ids != null && ids.Count() > 0) + { + vm.Ids = new List(ids); + vm.SearcherMode = ListVMSearchModeEnum.CheckExport; + } + return vm.GetExportData(); + } + + [ActionDescription("Sys.DownloadTemplate")] + [HttpGet("GetExcelTemplate")] + public IActionResult GetExcelTemplate() + { + var vm = Wtm.CreateVM<$controllername$ImportVM>(); + var qs = new Dictionary(); + foreach (var item in Request.Query.Keys) + { + qs.Add(item, Request.Query[item]); + } + vm.SetParms(qs); + var data = vm.GenerateTemplate(out string fileName); + return File(data, "application/vnd.ms-excel", fileName); + } + + [ActionDescription("Sys.Import")] + [HttpPost("Import")] + public ActionResult Import($controllername$ImportVM vm) + { + if (vm!=null && (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData())) + { + return BadRequest(vm.GetErrorJson()); + } + else + { + return Ok(vm?.EntityList?.Count ?? 0); + } + } + +$other$ + } +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Spa/Blazor/Create.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Spa/Blazor/Create.txt new file mode 100644 index 0000000..83c1a4d --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Spa/Blazor/Create.txt @@ -0,0 +1,38 @@ +@page "$pagepath$" +@using $vmnamespace$; +@inherits BasePage + + + +$formfields$ + + + + +@code { + + private $modelname$VM Model = new $modelname$VM(); + private ValidateForm vform { get; set; } +$fieldinit$ + + protected override async Task OnInitializedAsync() + { +$init$ + await base.OnInitializedAsync(); + } + + + private async Task Submit(EditContext context) + { + await PostsForm(vform, "/api/$modelname$/add", (s) => "Sys.OprationSuccess"); + } + + public void OnClose() + { + CloseDialog(); + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Spa/Blazor/Details.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Spa/Blazor/Details.txt new file mode 100644 index 0000000..1d49aea --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Spa/Blazor/Details.txt @@ -0,0 +1,34 @@ +@page "$pagepath$" +@using $vmnamespace$; +@inherits BasePage + + + +$formfields$ + + + + +@code { + + private $modelname$VM Model = null; + private ValidateForm vform { get; set; } + [Parameter] + public string id { get; set; } +$fieldinit$ + + protected override async Task OnInitializedAsync() + { +$init$ + var rv = await WtmBlazor.Api.CallAPI<$modelname$VM>($"/api/$modelname$/{id}"); + Model = rv.Data; + } + + public void OnClose() + { + CloseDialog(); + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Spa/Blazor/Edit.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Spa/Blazor/Edit.txt new file mode 100644 index 0000000..4956e2f --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Spa/Blazor/Edit.txt @@ -0,0 +1,41 @@ +@page "$pagepath$" +@using $vmnamespace$; +@inherits BasePage + + + +$formfields$ + + + + +@code { + + private $modelname$VM Model = null; + private ValidateForm vform { get; set; } + [Parameter] + public string id { get; set; } +$fieldinit$ + + protected override async Task OnInitializedAsync() + { +$init$ + var rv = await WtmBlazor.Api.CallAPI<$modelname$VM>($"/api/$modelname$/{id}"); + Model = rv.Data; + await base.OnInitializedAsync(); + } + + private async Task Submit(EditContext context) + { + await PostsForm(vform, $"/api/$modelname$/edit", (s) => "Sys.OprationSuccess", method: HttpMethodEnum.PUT); + } + + public void OnClose() + { + CloseDialog(); + } + +} diff --git a/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Spa/Blazor/Import.txt b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Spa/Blazor/Import.txt new file mode 100644 index 0000000..8785197 --- /dev/null +++ b/WalkingTec.Mvvm/WalkingTec.Mvvm.Mvc/GeneratorFiles/Spa/Blazor/Import.txt @@ -0,0 +1,66 @@ +@page "$pagepath$" +@using $vmnamespace$; +@inherits BasePage + + + + 1@WtmBlazor.Localizer["Sys.ImportStep1"] +