更新wtm

This commit is contained in:
zgf committed 2023-08-11 15:55:50 +08:00
1 parent f119665d29
commit 3467d4aa9d
60 files changed
+1932 -397

No files matched your search

View File
File renamed without changes.
+7 -15
View File
@@ -284,25 +284,15 @@ namespace WalkingTec.Mvvm.Core
vm = vmtype.GetConstructor(System.Type.EmptyTypes).Invoke(null) as IBaseCRUDVM<TModel>;
vm.CopyContext(this);
}
var entityList = DC.Set<TModel>().CheckIDs(idsData).ToList();
//循环所有数据
for (int i = 0; i < entityList.Count; i++)
for (int i = 0; i < idsData.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中同名属性赋值
TModel entity = new TModel();
entity.SetID(idsData[i]);
//循环LinkedVM中的属性,给entity中同名属性赋值
foreach (var pro in pros)
{
var proToSet = entity.GetType().GetSingleProperty(pro.Name);
@@ -322,6 +312,7 @@ namespace WalkingTec.Mvvm.Core
if (hasvalue)
{
proToSet.SetValue(entity, valuetoset);
DC.UpdateProperty(entity, proToSet.Name);
}
}
}
@@ -361,13 +352,14 @@ namespace WalkingTec.Mvvm.Core
if (ent.UpdateTime == null)
{
ent.UpdateTime = DateTime.Now;
DC.UpdateProperty(entity, nameof(ent.UpdateTime));
}
if (string.IsNullOrEmpty(ent.UpdateBy))
{
ent.UpdateBy = LoginUserInfo?.ITCode;
DC.UpdateProperty(entity, nameof(ent.UpdateBy));
}
}
DC.UpdateEntity(entity);
}
catch (Exception e)
{
+10 -1
View File
@@ -440,7 +440,7 @@ namespace WalkingTec.Mvvm.Core
if (pro.GetCustomAttribute<NotMappedAttribute>() != null)
{
fkname = pro.GetCustomAttribute<SoftFKAttribute>()?.PropertyName;
softkey = typeof(TModel).GetCustomAttribute<SoftKeyAttribute>().PropertyName;
softkey = typeof(TModel).GetCustomAttribute<SoftKeyAttribute>()?.PropertyName;
}
}
var itemPros = ftype.GetAllProperties();
@@ -1236,6 +1236,15 @@ namespace WalkingTec.Mvvm.Core
Expression exp = f.GetExpression(Entity, para);
conditions.Add(exp);
}
if (typeof(IPersistPoco).IsAssignableFrom(typeof(TModel)) && props.Any(x => x.Name.ToLower() == "isvalid") == false)
{
IPersistPoco ent = Entity as IPersistPoco;
ent.IsValid = true;
var f = new DuplicatedField<TModel>(x => (x as IPersistPoco).IsValid);
Expression exp = f.GetExpression(Entity, para);
conditions.Add(exp);
}
//如果要求判断id不重复,则去掉id不相等的判断,加入id相等的判断
//if (props.Any(x => x.Name.ToLower() == "id"))
//{
+10 -3
View File
@@ -212,7 +212,7 @@ namespace WalkingTec.Mvvm.Core
{
var fp = Wtm.ServiceProvider.GetRequiredService<WtmFileProvider>();
// var tempdc = Wtm.DC;
file = fp.GetFile(UploadFileId, true,Wtm.CreateDC(false,"default"));
file = fp.GetFile(UploadFileId, true,Wtm.CreateDC(false));
//Wtm.DC = tempdc;
}
if (file == null)
@@ -908,7 +908,7 @@ namespace WalkingTec.Mvvm.Core
foreach (var item in DeletedFileIds)
{
fp.DeleteFile(item.ToString(), Wtm.CreateDC(false, "default"));
fp.DeleteFile(item.ToString(), Wtm.CreateDC(false));
}
}
@@ -1275,7 +1275,14 @@ namespace WalkingTec.Mvvm.Core
//将字段名保存,为后面生成错误信息作准备
props.AddRange(field.GetProperties());
}
if (typeof(ITenant).IsAssignableFrom(modelType) && props.Any(x => x.Name.ToLower() == "tenantcode") == false && Wtm?.ConfigInfo.EnableTenant == true && group.UseTenant == true)
{
ITenant ent = Entity as ITenant;
ent.TenantCode = LoginUserInfo.CurrentTenant;
var f = new DuplicatedField<P>(x => (x as ITenant).TenantCode);
Expression exp = f.GetExpression(Entity, para);
conditions.Add(exp);
}
if (conditions.Count > 0)
{
//循环添加条件并生成Where语句
+1 -1
View File
@@ -233,7 +233,7 @@ namespace WalkingTec.Mvvm.Core
#endregion
#region 添加模版数据
if (TemplateDataTable.Rows.Count > 0)
if (TemplateDataTable?.Rows.Count > 0)
{
for (int i = 0; i < TemplateDataTable.Rows.Count; i++)
{
+47 -100
View File
@@ -17,6 +17,7 @@ using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core.Extensions;
@@ -33,10 +34,10 @@ namespace WalkingTec.Mvvm.Core
public DbSet<FunctionPrivilege> BaseFunctionPrivileges { get; set; }
public DbSet<DataPrivilege> BaseDataPrivileges { get; set; }
public DbSet<FileAttachment> BaseFileAttachments { get; set; }
public DbSet<FrameworkGroup> BaseFrameworkGroups { get; set; }
public DbSet<FrameworkRole> BaseFrameworkRoles { get; set; }
public DbSet<FrameworkUserRole> BaseFrameworkUserRoles { get; set; }
public DbSet<FrameworkUserGroup> BaseFrameworkUserGroups { get; set; }
public DbSet<FrameworkGroup> BaseFrameworkGroups { get; set; }
public DbSet<ActionLog> BaseActionLogs { get; set; }
public DbSet<FrameworkTenant> FrameworkTenants { get; set; }
@@ -75,70 +76,8 @@ namespace WalkingTec.Mvvm.Core
//wtmtodo: 删除菜单同步删除页面权限
//modelBuilder.Entity<FunctionPrivilege>().HasOne(x => x.MenuItem).WithMany(x => x.Privileges).HasForeignKey(x => x.MenuItemId).OnDelete(DeleteBehavior.Cascade);
var modelAsms = Utils.GetAllAssembly();
var allTypes = Utils.GetAllModels();
var allTypes = new List<Type>();// 所有 DbSet<> 的泛型类型
#region 获取所有 DbSet<T> 的泛型类型 T 及其 List<T> 类型属性对应的类型 T
// 获取所有 DbSet<T> 的泛型类型 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,且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)
@@ -153,25 +92,28 @@ namespace WalkingTec.Mvvm.Core
}
List<Expression> list = new List<Expression>();
ParameterExpression pe = Expression.Parameter(item);
if (typeof(IPersistPoco).IsAssignableFrom(item))
if (item.BaseType == null || item.BaseType.IsAbstract == true || (item.BaseType == typeof(TopBasePoco) || item.BaseType == typeof(BasePoco) || item.BaseType?.BaseType == typeof(TreePoco)))
{
var exp = Expression.Equal(Expression.Property(pe, "IsValid"), Expression.Constant(true));
list.Add(exp);
}
if (typeof(ITenant).IsAssignableFrom(item))
{
var exp= Expression.Equal(Expression.Property(pe, "TenantCode"), Expression.PropertyOrField(Expression.Constant(this),"TenantCode"));
list.Add(exp);
}
if(list.Count > 0)
{
var finalexp = list[0];
for (int i = 1; i < list.Count; i++)
if (typeof(IPersistPoco).IsAssignableFrom(item))
{
finalexp = Expression.AndAlso(finalexp, list[i]);
var exp = Expression.Equal(Expression.Property(pe, "IsValid"), Expression.Constant(true));
list.Add(exp);
}
if (typeof(ITenant).IsAssignableFrom(item))
{
var exp = Expression.Equal(Expression.Property(pe, "TenantCode"), Expression.PropertyOrField(Expression.Constant(this), "TenantCode"));
list.Add(exp);
}
if (list.Count > 0)
{
var finalexp = list[0];
for (int i = 1; i < list.Count; i++)
{
finalexp = Expression.AndAlso(finalexp, list[i]);
}
var builder = typeof(ModelBuilder).GetMethod("Entity", Type.EmptyTypes).MakeGenericMethod(item).Invoke(modelBuilder, null) as EntityTypeBuilder;
builder.HasQueryFilter(Expression.Lambda(finalexp, pe));
}
var builder = typeof(ModelBuilder).GetMethod("Entity", Type.EmptyTypes).MakeGenericMethod(item).Invoke(modelBuilder, null) as EntityTypeBuilder;
builder.HasQueryFilter(Expression.Lambda(finalexp,pe));
}
}
}
@@ -207,12 +149,12 @@ namespace WalkingTec.Mvvm.Core
if (Set<FrameworkMenu>().Any() == false && TenantCode == null)
{
var systemManagement = GetFolderMenu("SystemManagement");
var logList = IsSpa ? GetMenu2(AllModules, "ActionLog", "MenuKey.ActionLog", 1) : GetMenu(AllModules, "_Admin", "ActionLog", "Index", "MenuKey.ActionLog", 1);
var userList = IsSpa ? GetMenu2(AllModules, "FrameworkUser", "MenuKey.UserManagement", 2) : GetMenu(AllModules, "_Admin", "FrameworkUser", "Index", "MenuKey.UserManagement", 2);
var roleList = IsSpa ? GetMenu2(AllModules, "FrameworkRole", "MenuKey.RoleManagement", 3) : GetMenu(AllModules, "_Admin", "FrameworkRole", "Index", "MenuKey.RoleManagement", 3);
var groupList = IsSpa ? GetMenu2(AllModules, "FrameworkGroup", "MenuKey.GroupManagement", 4) : GetMenu(AllModules, "_Admin", "FrameworkGroup", "Index", "MenuKey.GroupManagement", 4);
var menuList = IsSpa ? GetMenu2(AllModules, "FrameworkMenu", "MenuKey.MenuMangement", 5) : GetMenu(AllModules, "_Admin", "FrameworkMenu", "Index", "MenuKey.MenuMangement", 5);
var dpList = IsSpa ? GetMenu2(AllModules, "DataPrivilege", "MenuKey.DataPrivilege", 6) : GetMenu(AllModules, "_Admin", "DataPrivilege", "Index", "MenuKey.DataPrivilege", 6);
var logList = IsSpa ? GetMenu2(AllModules, "ActionLog", "MenuKey.ActionLog", 1) : GetMenu(AllModules, "_Admin", "ActionLog", "Index", "MenuKey.ActionLog", 1);
var userList = IsSpa ? GetMenu2(AllModules, "FrameworkUser", "MenuKey.UserManagement", 2) : GetMenu(AllModules, "_Admin", "FrameworkUser", "Index", "MenuKey.UserManagement", 2);
var roleList = IsSpa ? GetMenu2(AllModules, "FrameworkRole", "MenuKey.RoleManagement", 3) : GetMenu(AllModules, "_Admin", "FrameworkRole", "Index", "MenuKey.RoleManagement", 3);
var groupList = IsSpa ? GetMenu2(AllModules, "FrameworkGroup", "MenuKey.GroupManagement", 4) : GetMenu(AllModules, "_Admin", "FrameworkGroup", "Index", "MenuKey.GroupManagement", 4);
var menuList = IsSpa ? GetMenu2(AllModules, "FrameworkMenu", "MenuKey.MenuMangement", 5) : GetMenu(AllModules, "_Admin", "FrameworkMenu", "Index", "MenuKey.MenuMangement", 5);
var dpList = IsSpa ? GetMenu2(AllModules, "DataPrivilege", "MenuKey.DataPrivilege", 6) : GetMenu(AllModules, "_Admin", "DataPrivilege", "Index", "MenuKey.DataPrivilege", 6);
var tenantList = IsSpa ? GetMenu2(AllModules, "FrameworkTenant", "MenuKey.FrameworkTenant", 6) : GetMenu(AllModules, "_Admin", "FrameworkTenant", "Index", "MenuKey.FrameworkTenant", 7);
if (logList != null)
{
@@ -241,10 +183,10 @@ namespace WalkingTec.Mvvm.Core
var apifolder = GetFolderMenu("Api");
apifolder.ShowOnMenu = false;
apifolder.DisplayOrder = 100;
var logList2 = GetMenu2(AllModules, "ActionLog", "MenuKey.ActionLog", 1);
var userList2 = GetMenu2(AllModules, "FrameworkUser", "MenuKey.UserManagement", 2);
var roleList2 = GetMenu2(AllModules, "FrameworkRole", "MenuKey.RoleManagement", 3);
var groupList2 = GetMenu2(AllModules, "FrameworkGroup", "MenuKey.GroupManagement", 4);
var logList2 = GetMenu2(AllModules, "ActionLog", "MenuKey.ActionLog", 1);
var userList2 = GetMenu2(AllModules, "FrameworkUser", "MenuKey.UserManagement", 2);
var roleList2 = GetMenu2(AllModules, "FrameworkRole", "MenuKey.RoleManagement", 3);
var groupList2 = GetMenu2(AllModules, "FrameworkGroup", "MenuKey.GroupManagement", 4);
var menuList2 = GetMenu2(AllModules, "FrameworkMenu", "MenuKey.MenuMangement", 5);
var dpList2 = GetMenu2(AllModules, "DataPrivilege", "MenuKey.DataPrivilege", 6);
var tenantList2 = GetMenu2(AllModules, "FrameworkTenant", "MenuKey.FrameworkTenant", 7);
@@ -255,6 +197,7 @@ namespace WalkingTec.Mvvm.Core
if (item != null)
{
item.ModuleName += "Api";
item.ShowOnMenu = false;
apifolder.Children.Add(item);
}
@@ -276,14 +219,13 @@ namespace WalkingTec.Mvvm.Core
}
}
Set<FrameworkRole>().AddRange(roles);
await SaveChangesAsync();
}
return rv;
}
private FrameworkMenu GetFolderMenu(string FolderText,bool isShowOnMenu = true, bool isInherite = false)
private FrameworkMenu GetFolderMenu(string FolderText, bool isShowOnMenu = true, bool isInherite = false)
{
FrameworkMenu menu = new FrameworkMenu
{
@@ -299,14 +241,14 @@ namespace WalkingTec.Mvvm.Core
return menu;
}
private FrameworkMenu GetMenu(List<SimpleModule> allModules, string areaName, string controllerName, string actionName, string pageKey,int displayOrder)
private FrameworkMenu GetMenu(List<SimpleModule> allModules, string areaName, string controllerName, string actionName, string pageKey, 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();
bool allowtenant = controllerName != "FrameworkMenu";
FrameworkMenu menu = GetMenuFromAction(act, true, displayOrder, allowtenant);
if(act?.Module?.IsApi == true)
if (act?.Module?.IsApi == true)
{
menu.ModuleName += "Api";
}
@@ -333,7 +275,7 @@ namespace WalkingTec.Mvvm.Core
private FrameworkMenu GetMenu2(List<SimpleModule> allModules, string controllerName, string pageKey, int displayOrder)
{
bool allowtenant = controllerName != "FrameworkMenu";
var acts = allModules.Where(x => (x.FullName == $"WalkingTec.Mvvm.Admin.Api,{controllerName}")&& x.IsApi == true).SelectMany(x => x.Actions).ToList();
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)
@@ -352,7 +294,7 @@ namespace WalkingTec.Mvvm.Core
{
if (rest[i] != null)
{
var sub = GetMenuFromAction(rest[i], false, (i + 1), allowtenant);
var sub = GetMenuFromAction(rest[i], false, (i + 1), allowtenant);
sub.PageName = pageKey;
menu.Children.Add(sub);
}
@@ -361,7 +303,7 @@ namespace WalkingTec.Mvvm.Core
return menu;
}
private FrameworkMenu GetMenuFromAction(SimpleAction act, bool isMainLink, int displayOrder = 1, bool allowtenant = true)
private FrameworkMenu GetMenuFromAction(SimpleAction act, bool isMainLink, int displayOrder = 1, bool allowtenant = true)
{
if (act == null)
{
@@ -485,14 +427,17 @@ namespace WalkingTec.Mvvm.Core
}
else
{
IDataContext rv = null;
if (ConnectionString != null)
{
return (IDataContext)this.GetType().GetConstructor(new Type[] { typeof(CS) }).Invoke(new object[] { ConnectionString }); ;
rv = (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 });
rv =(IDataContext)this.GetType().GetConstructor(new Type[] { typeof(string), typeof(DBTypeEnum) }).Invoke(new object[] { CSName, DBType });
}
rv.SetTenantCode(this.TenantCode);
return rv;
}
}
/// <summary>
@@ -665,8 +610,10 @@ namespace WalkingTec.Mvvm.Core
case DBTypeEnum.SQLite:
optionsBuilder.UseSqlite(CSName);
break;
//case DBTypeEnum.DaMeng:
// optionsBuilder.UseDm(CSName);
// break;
case DBTypeEnum.Oracle:
optionsBuilder.UseOracle(CSName, option =>
{
if (string.IsNullOrEmpty(Version) == false)
+2 -2
View File
@@ -28,7 +28,7 @@ namespace WalkingTec.Mvvm.Core
/// <summary>
/// 数据库类型
/// </summary>
public enum DBTypeEnum { SqlServer, MySql, PgSql, Memory, SQLite, Oracle }
public enum DBTypeEnum { SqlServer, MySql, PgSql, Memory, SQLite, Oracle,DaMeng }
/// <summary>
/// 页面显示方式
@@ -131,7 +131,7 @@ namespace WalkingTec.Mvvm.Core
}
public enum UIEnum
{ LayUI, React, VUE,Blazor }
{ LayUI, React, VUE,Blazor,VUE3 }
@@ -285,17 +285,17 @@ namespace WalkingTec.Mvvm.Core.Extensions
switch (col.EditType)
{
case EditTypeEnum.TextBox:
html = (self as BaseVM).UIService.MakeTextBox(name, val);
html = (self as BaseVM).UIService.MakeTextBox(name, val,null,col.IsReadOnly);
break;
case EditTypeEnum.CheckBox:
_ = bool.TryParse(val, out bool nb);
html = (self as BaseVM).UIService.MakeCheckBox(nb, null, name, "true");
html = (self as BaseVM).UIService.MakeCheckBox(nb, null, name, "true",col.IsReadOnly);
break;
case EditTypeEnum.ComboBox:
html = (self as BaseVM).UIService.MakeCombo(name, col.ListItems, val);
html = (self as BaseVM).UIService.MakeCombo(name, col.ListItems, val,null,col.IsReadOnly);
break;
case EditTypeEnum.Datetime:
html = (self as BaseVM).UIService.MakeDateTime(name, val);
html = (self as BaseVM).UIService.MakeDateTime(name, val,null, col.IsReadOnly,col.DateType);
break;
default:
break;
@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace WalkingTec.Mvvm.Core.Extensions
{
public static class DictionaryExtension
{
public static T GetValue<T>(this Dictionary<string,object> self, string key)
{
if (self.ContainsKey(key))
{
object v = self[key];
if(v is JsonElement j)
{
v = j.ToString();
}
var cv = v.ConvertValue(typeof(T));
if (cv == null)
{
return default(T);
}
else
{
return (T)cv;
}
}
else
{
return default(T);
}
}
}
}
@@ -488,7 +488,11 @@ namespace WalkingTec.Mvvm.Core.Extensions
if (_propertyCache.ContainsKey(self.FullName) == false)
{
var properties = self.GetProperties().ToList();
_propertyCache = _propertyCache.Add(self.FullName, properties);
try
{
_propertyCache = _propertyCache.Add(self.FullName, properties);
}
catch { }
return properties.Where(x => x.Name == name).FirstOrDefault();
}
else
@@ -502,7 +506,11 @@ namespace WalkingTec.Mvvm.Core.Extensions
if (_propertyCache.ContainsKey(self.FullName) == false)
{
var properties = self.GetProperties().ToList();
_propertyCache = _propertyCache.Add(self.FullName, properties);
try
{
_propertyCache = _propertyCache.Add(self.FullName, properties);
}
catch { }
return properties.Where(where).FirstOrDefault();
}
else
@@ -516,7 +524,17 @@ namespace WalkingTec.Mvvm.Core.Extensions
if (_propertyCache.ContainsKey(self.FullName) == false)
{
var properties = self.GetProperties().ToList();
_propertyCache = _propertyCache.Add(self.FullName, properties);
try
{
_propertyCache = _propertyCache.Add(self.FullName, properties);
}
catch
{
if (_propertyCache.ContainsKey(self.FullName) == true)
{
return _propertyCache[self.FullName];
}
}
return properties;
}
else
+9 -1
View File
@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Core.Support.Json;
namespace WalkingTec.Mvvm.Core
@@ -34,7 +35,7 @@ namespace WalkingTec.Mvvm.Core
_customUserProperties = new List<PropertyInfo>();
if(CustomUserType != null)
{
_customUserProperties = CustomUserType.GetProperties( BindingFlags.Public| BindingFlags.Instance | BindingFlags.DeclaredOnly).ToList();
_customUserProperties = CustomUserType.GetProperties( BindingFlags.Public| BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(x=>x.PropertyType.IsListOf<TopBasePoco>() == false && typeof(TopBasePoco).IsAssignableFrom(x.PropertyType) == false).ToList();
}
}
return _customUserProperties;
@@ -57,6 +58,13 @@ namespace WalkingTec.Mvvm.Core
public void SetMenuGetFunc(Func<List<SimpleMenu>> func) => MenuGetFunc = func;
public void SetTenantGetFunc(Func<List<FrameworkTenant>> func) => TenantGetFunc = func;
public List<Type> GetPocoTypesAssignableFrom<T>()
{
var rv = new List<Type>();
var allType = Utils.GetAllModels();
rv.AddRange(allType.Where(x => typeof(T).IsAssignableFrom(x) && x != typeof(T) && x.IsAbstract == false).ToList());
return rv;
}
public List<Type> GetTypesAssignableFrom<T>()
{
var rv = new List<Type>();
@@ -141,6 +141,10 @@ namespace WalkingTec.Mvvm.Core
public List<ComboSelectListItem> ListItems { get; set; }
public DateTimeTypeEnum? DateType { get; set; }
public bool IsReadOnly { get; set; }
#region 只读属性 生成 Excel 及其 表头用
/// <summary>
@@ -296,12 +296,16 @@ namespace WalkingTec.Mvvm.Core
/// <param name="self"></param>
/// <param name="editType">单元格编辑类型</param>
/// <param name="listitems">listitems</param>
/// <param name="dateType"></param>
/// <param name="readOnly"></param>
/// <returns></returns>
public static GridColumn<T> SetEditType<T>(this GridColumn<T> self, EditTypeEnum editType = EditTypeEnum.Text, List<ComboSelectListItem> listitems = null)
public static GridColumn<T> SetEditType<T>(this GridColumn<T> self, EditTypeEnum editType = EditTypeEnum.Text, List<ComboSelectListItem> listitems = null, DateTimeTypeEnum dateType = DateTimeTypeEnum.DateTime, bool readOnly = false)
where T : TopBasePoco
{
self.EditType = editType;
self.ListItems = listitems;
self.DateType = dateType;
self.IsReadOnly = readOnly;
return self;
}
@@ -147,6 +147,10 @@ namespace WalkingTec.Mvvm.Core
List<ComboSelectListItem> ListItems { get; set; }
DateTimeTypeEnum? DateType { get; set; }
bool IsReadOnly { get; set; }
#region 只读属性 生成 Excel 及其 表头用
/// <summary>
@@ -747,6 +747,10 @@ namespace WalkingTec.Mvvm.Core
if (propertyType.IsGeneric(typeof(Nullable<>)) == true)
{
var gs = propertyType.GenericTypeArguments;
if(value == null)
{
return null;
}
try
{
val = ConvertValue(value, gs[0]);
+1 -1
View File
@@ -22,7 +22,7 @@ namespace WalkingTec.Mvvm.Core
string MakeCombo(string name = null, List<ComboSelectListItem> 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);
string MakeDateTime(string name = null, string value = null, string emptyText = null, bool isReadOnly = false, DateTimeTypeEnum? dateType = DateTimeTypeEnum.DateTime);
}
}
@@ -51,7 +51,7 @@ namespace WalkingTec.Mvvm.Core.Implement
return "";
}
public string MakeDateTime(string name = null, string value = null, string emptyText = null, bool isReadOnly = false)
public string MakeDateTime(string name = null, string value = null, string emptyText = null, bool isReadOnly = false, DateTimeTypeEnum? dateType = DateTimeTypeEnum.DateTime)
{
return "";
}
@@ -0,0 +1,37 @@
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 NullableConverter<T> : JsonConverter<Nullable<T>> where T : struct
{
public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
{
if (string.IsNullOrEmpty(reader.GetString()) || string.IsNullOrWhiteSpace(reader.GetString()))
{
return null;
}
else
{
return JsonSerializer.Deserialize<T>(ref reader, options);
}
}
return JsonSerializer.Deserialize<T>(ref reader, options);
}
public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, value!.Value, options);
}
}
}
@@ -0,0 +1,105 @@
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 NullableEnumConverter : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert)
{
return typeToConvert.IsGenericType && typeToConvert.GetGenericTypeDefinition() == typeof(Nullable<>) && typeToConvert.GetGenericArguments()[0].IsEnum;
}
public override JsonConverter CreateConverter(
Type type,
JsonSerializerOptions options)
{
var temp = CloneOptions(options);
foreach (var item in options.Converters)
{
if(item.GetType() != typeof(PocoConverter) && item.GetType() != typeof(NullableEnumConverter))
{
temp.Converters.Add(item);
}
}
JsonConverter converter = (JsonConverter)Activator.CreateInstance(
typeof(NullableEnumConverterInner<>).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 NullableEnumConverterInner<T> :
JsonConverter<T>
{
protected readonly JsonSerializerOptions _options;
public NullableEnumConverterInner(JsonSerializerOptions options)
{
_options = options;
}
public override T Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
{
if (string.IsNullOrEmpty(reader.GetString()) || string.IsNullOrWhiteSpace(reader.GetString()))
{
return default(T);
}
}
return JsonSerializer.Deserialize<T>(ref reader, _options);
}
public override void Write(
Utf8JsonWriter writer,
T data,
JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, data, typeof(T), _options);
}
}
}
}
+4 -4
View File
@@ -215,10 +215,10 @@ namespace WalkingTec.Mvvm.Core
}
}
var topdata = context.GlobaInfo.AllMenus.Where(x => x.ShowOnMenu && (x.IsInside == false || x.FolderOnly == true || string.IsNullOrEmpty(x.MethodName))).ToList();
var allowedids = context.LoginUserInfo.FunctionPrivileges.Select(x => x.MenuItemId).ToList();
var allowedids = context.LoginUserInfo?.FunctionPrivileges?.Select(x => x.MenuItemId).ToList();
foreach (var item in topdata)
{
if (allowedids.Contains(item.ID) && item.IsParentShowOnMenu(topdata))
if (allowedids?.Contains(item.ID) == true && item.IsParentShowOnMenu(topdata))
{
ms.Add(new SimpleMenuApi
{
@@ -269,13 +269,13 @@ namespace WalkingTec.Mvvm.Core
public IDataContext GetUserDC(WTMContext context)
{
if (context?.LoginUserInfo?.TenantCode == null)
if (context?.LoginUserInfo?.CurrentTenant == null)
{
return context.CreateDC(cskey: "default");
}
else
{
var item = context.GlobaInfo.AllTenant.Where(x => x.TCode == context?.LoginUserInfo?.TenantCode).FirstOrDefault();
var item = context.GlobaInfo.AllTenant.Where(x => x.TCode == context?.LoginUserInfo?.CurrentTenant).FirstOrDefault();
if (item != null)
{
return item.CreateDC(context);
+1 -1
View File
@@ -16,7 +16,7 @@ namespace WalkingTec.Mvvm.Core
/// <summary>
/// Model层的基类,所有的model都应该继承这个类。这会使所有的model层对应的数据库表都有一个自增主键
/// </summary>
public class BasePoco : TopBasePoco, IBasePoco
public abstract class BasePoco : TopBasePoco, IBasePoco
{
/// <summary>
/// CreateTime
@@ -67,6 +67,10 @@ namespace WalkingTec.Mvvm.Core
}
}
[NotMapped]
public Dictionary<string, object> Attributes { get; set; }
public IDataContext CreateDC(WTMContext wtm)
{
if (IsUsingDB == false)
@@ -11,7 +11,7 @@ namespace WalkingTec.Mvvm.Core
/// <summary>
/// TopBasePoco
/// </summary>
public class TopBasePoco
public class TopBasePoco
{
/// <summary>
/// Id
+1 -1
View File
@@ -9,7 +9,7 @@ using System.Threading.Tasks;
namespace WalkingTec.Mvvm.Core
{
public abstract class TreePoco : TopBasePoco
public class TreePoco : TopBasePoco
{
[Display(Name = "_Admin.Parent")]
public Guid? ParentId { get; set; }
@@ -20,7 +20,7 @@ namespace WalkingTec.Mvvm.Core.Support.FileHandlers
public override Stream GetFileData(IWtmFile file)
{
var rv = _wtm.DC.Set<FileAttachment>().CheckID(file.GetID()).FirstOrDefault();
var rv = wtm.DC.Set<FileAttachment>().CheckID(file.GetID()).FirstOrDefault();
if (rv != null)
{
return new MemoryStream((rv as FileAttachment).FileData);
@@ -37,7 +37,7 @@ namespace WalkingTec.Mvvm.Core.Support.FileHandlers
file.UploadTime = DateTime.Now;
file.SaveMode = _modeName;
file.ExtraInfo = extra;
file.TenantCode = _wtm.LoginUserInfo?.CurrentTenant;
file.TenantCode = wtm.LoginUserInfo?.CurrentTenant;
var ext = string.Empty;
if (string.IsNullOrEmpty(fileName) == false)
{
@@ -50,8 +50,8 @@ namespace WalkingTec.Mvvm.Core.Support.FileHandlers
data.CopyTo(dataStream);
file.FileData = dataStream.ToArray();
}
_wtm.DC.AddEntity(file);
_wtm.DC.SaveChanges();
wtm.DC.AddEntity(file);
wtm.DC.SaveChanges();
return file;
}
}
@@ -11,10 +11,10 @@ namespace WalkingTec.Mvvm.Core.Support.FileHandlers
{
public abstract class WtmFileHandlerBase : IWtmFileHandler
{
protected WTMContext _wtm;
public WTMContext wtm;
public WtmFileHandlerBase(WTMContext wtm)
{
_wtm = wtm;
this.wtm = wtm;
}
@@ -60,10 +60,10 @@ namespace WalkingTec.Mvvm.Core.Support.FileHandlers
public IWtmFileHandler CreateFileHandler(string saveMode = null, IDataContext dc = null)
{
ConstructorInfo ci = null;
//if(dc != null)
//{
// _wtm.DC = dc;
//}
if (dc != null)
{
_wtm.DC = dc;
}
if (string.IsNullOrEmpty(saveMode))
{
ci = _defaultHandler;
@@ -154,8 +154,14 @@ namespace WalkingTec.Mvvm.Core.Support.FileHandlers
}).FirstOrDefault();
if (rv != null && withData == true)
{
var fh = CreateFileHandler(rv.SaveMode, dc);
rv.DataStream = fh.GetFileData(rv);
try
{
var fh = CreateFileHandler(rv.SaveMode, dc);
rv.DataStream = fh.GetFileData(rv);
}
catch {
rv = null;
}
}
return rv;
@@ -26,7 +26,7 @@ namespace WalkingTec.Mvvm.Core.Support.FileHandlers
public override (string path, string handlerInfo) Upload(string fileName, long fileLength, Stream data, string group = null, string subdir = null, string extra = null)
{
var localSettings = _wtm.ConfigInfo.FileUploadOptions.Settings.Where(x => x.Key.ToLower() == "local").Select(x => x.Value).FirstOrDefault();
var localSettings = wtm.ConfigInfo.FileUploadOptions.Settings.Where(x => x.Key.ToLower() == "local").Select(x => x.Value).FirstOrDefault();
var groupdir = "";
if (string.IsNullOrEmpty(group))
@@ -91,7 +91,7 @@ namespace WalkingTec.Mvvm.Core.Support.FileHandlers
string rv = "";
if (path.StartsWith("."))
{
rv = Path.Combine(_wtm.ConfigInfo.HostRoot, path);
rv = Path.Combine(wtm.ConfigInfo.HostRoot, path);
}
else
{
@@ -23,7 +23,7 @@ namespace WalkingTec.Mvvm.Core.Support.FileHandlers
public override Stream GetFileData(IWtmFile file)
{
var ossSettings = _wtm.ConfigInfo.FileUploadOptions.Settings.Where(x => x.Key.ToLower() == "oss").Select(x => x.Value).FirstOrDefault();
var ossSettings = wtm.ConfigInfo.FileUploadOptions.Settings.Where(x => x.Key.ToLower() == "oss").Select(x => x.Value).FirstOrDefault();
FileHandlerOptions groupInfo = null;
if (string.IsNullOrEmpty(file.HandlerInfo))
{
@@ -60,7 +60,7 @@ namespace WalkingTec.Mvvm.Core.Support.FileHandlers
ext = fileName.Substring(dotPos + 1);
}
var ossSettings = _wtm.ConfigInfo.FileUploadOptions.Settings.Where(x => x.Key.ToLower() == "oss").Select(x => x.Value).FirstOrDefault();
var ossSettings = wtm.ConfigInfo.FileUploadOptions.Settings.Where(x => x.Key.ToLower() == "oss").Select(x => x.Value).FirstOrDefault();
FileHandlerOptions groupInfo = null;
if (string.IsNullOrEmpty(group))
{
@@ -95,8 +95,15 @@ namespace WalkingTec.Mvvm.Core.Support.FileHandlers
}
var fullPath = Path.Combine(pathHeader, $"{Guid.NewGuid().ToNoSplitString()}.{ext}");
fullPath = fullPath.Replace("\\", "/");
var imagetypes = new string[]{ "jpg","jpeg","bmp","tif","gif","png"};
ObjectMetadata md = new ObjectMetadata();
ext = ext.ToLower();
if (imagetypes.Contains(ext))
{
md.ContentType = "image/jpg";
}
OssClient client = new OssClient(groupInfo.ServerUrl, groupInfo.Key, groupInfo.Secret);
var result = client.PutObject(groupInfo.GroupLocation, fullPath, data);
var result = client.PutObject(groupInfo.GroupLocation, fullPath, data,md);
if (result.HttpStatusCode == System.Net.HttpStatusCode.OK)
{
return (fullPath, groupInfo.GroupName);
@@ -109,7 +116,7 @@ namespace WalkingTec.Mvvm.Core.Support.FileHandlers
public override void DeleteFile(IWtmFile file)
{
var ossSettings = _wtm.ConfigInfo.FileUploadOptions.Settings.Where(x => x.Key.ToLower() == "oss").Select(x => x.Value).FirstOrDefault();
var ossSettings = wtm.ConfigInfo.FileUploadOptions.Settings.Where(x => x.Key.ToLower() == "oss").Select(x => x.Value).FirstOrDefault();
FileHandlerOptions groupInfo = null;
if (string.IsNullOrEmpty(file.HandlerInfo))
{
@@ -22,6 +22,7 @@ namespace WalkingTec.Mvvm.Core
}
}
[ProviderAlias("WTM")]
public class WTMLoggerProvider : ILoggerProvider
{
private IServiceProvider sp = null;
+39 -1
View File
@@ -1,3 +1,4 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using NPOI.HSSF.Util;
using System;
@@ -21,7 +22,7 @@ namespace WalkingTec.Mvvm.Core
{
private static List<Assembly> _allAssemblies;
private static List<Type> _allModels;
public static string GetCurrentComma()
{
if (CultureInfo.CurrentUICulture.Name == "zh-cn")
@@ -96,6 +97,43 @@ namespace WalkingTec.Mvvm.Core
return _allAssemblies;
}
private static List<Type> _allModelTypes= new List<Type>();
public static List<Type> GetAllModels()
{
if (_allModels == null)
{
var modelAsms = Utils.GetAllAssembly();
var allTypes = new List<Type>();// 所有 DbSet<> 的泛型类型
// 获取所有 DbSet<T> 的泛型类型 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 { }
}
_allModels = allTypes;
}
return _allModels;
}
public static SimpleMenu FindMenu(string url, List<SimpleMenu> menus)
{
if (url == null)
+2 -3
View File
@@ -4,9 +4,7 @@ using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http;
using System.Net.Http.Json;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
@@ -435,7 +433,7 @@ namespace WalkingTec.Mvvm.Core
}
else
{
exist = BaseUserQuery.IgnoreQueryFilters().Any(x => x.ITCode.ToLower() == username && x.Password == Utils.GetMD5String(password) && x.TenantCode == tenant && x.IsValid==true);
exist = BaseUserQuery.IgnoreQueryFilters().Any(x => x.ITCode.ToLower() == username.ToLower() && x.Password == Utils.GetMD5String(password) && x.TenantCode == tenant && x.IsValid==true);
}
if (exist == false)
{
@@ -839,6 +837,7 @@ params string[] groupcode)
log.Duration = duration;
log.ModuleName = moduleName;
log.ActionName = actionName;
log.ITCode = LoginUserInfo?.ITCode;
log.Request = request;
log.Result = result;
log.IP = ip;
@@ -1,7 +1,9 @@
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using System;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Web;
@@ -48,8 +50,9 @@ namespace WalkingTec.Mvvm.Mvc.Binders
.MethodInfo
.CustomAttributes
.Where(x => x.AttributeType == typeof(StringNeedLTGTAttribute)).Count();
if (count == 0)
var count2 = (bindingContext.ModelMetadata as DefaultModelMetadata)?.Attributes?.PropertyAttributes?
.Where(x => x.GetType() == typeof(JsonConverterAttribute)).Count();
if (count == 0 && (count2==null || count2 == 0))
{
value = HttpUtility.HtmlEncode(value);
}
+471 -28
View File
@@ -134,21 +134,21 @@ namespace WalkingTec.Mvvm.Mvc
{
get
{
/*if (_sharedir == null)
if (_sharedir == null)
{
var up = Directory.GetParent(MainDir);
var sharedir = up.GetDirectories().Where(x => x.Name.ToLower().EndsWith(".shared")).FirstOrDefault();
if (string.IsNullOrEmpty(Area))
{
if (string.IsNullOrEmpty(Area))
{
sharedir = Directory.CreateDirectory(sharedir.FullName + $"{Path.DirectorySeparatorChar}Pages{Path.DirectorySeparatorChar}{ModelName}");
}
else
{
}
else
{
sharedir = Directory.CreateDirectory(sharedir.FullName + $"{Path.DirectorySeparatorChar}Pages{Path.DirectorySeparatorChar}{Area}{Path.DirectorySeparatorChar}{ModelName}");
}
_sharedir = sharedir.FullName;
}*/
}
return _sharedir;
}
}
@@ -433,6 +433,7 @@ namespace WalkingTec.Mvvm.Mvc
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);
}
#region 设置react和vue的默认页面和默认菜单,vue3不需要这部分
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)
{
@@ -499,9 +500,10 @@ namespace WalkingTec.Mvvm.Mvc
}
}
#endregion
}
if(UI == UIEnum.Blazor)
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);
@@ -509,8 +511,29 @@ namespace WalkingTec.Mvvm.Mvc
File.WriteAllText($"{ShareDir}{Path.DirectorySeparatorChar}Details.razor", GenerateBlazorView("Details"), Encoding.UTF8);
File.WriteAllText($"{ShareDir}{Path.DirectorySeparatorChar}Import.razor", GenerateBlazorView("Import"), Encoding.UTF8);
}
if (UI == UIEnum.VUE3)
{
//Todo 生成vue3页面
var pathvue3 = $"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}views{Path.DirectorySeparatorChar}{Area.ToLower()}{Path.DirectorySeparatorChar}{ModelName.ToLower()}{Path.DirectorySeparatorChar}";
if (Directory.Exists(pathvue3) == false)
{
Directory.CreateDirectory(pathvue3);
}
var pathapi = $"{MainDir}{Path.DirectorySeparatorChar}ClientApp{Path.DirectorySeparatorChar}src{Path.DirectorySeparatorChar}api{Path.DirectorySeparatorChar}{Area.ToLower()}{Path.DirectorySeparatorChar}{ModelName}{Path.DirectorySeparatorChar}";
if (Directory.Exists(pathapi) == false)
{
Directory.CreateDirectory(pathapi);
}
File.WriteAllText($"{pathvue3}index.vue", GenerateVue3View("Index"), Encoding.UTF8);
File.WriteAllText($"{pathvue3}create.vue", GenerateVue3View("Create"), Encoding.UTF8);
File.WriteAllText($"{pathvue3}edit.vue", GenerateVue3View("Edit"), Encoding.UTF8);
File.WriteAllText($"{pathvue3}details.vue", GenerateVue3View("Details"), Encoding.UTF8);
File.WriteAllText($"{pathvue3}import.vue", GenerateVue3View("Import"), Encoding.UTF8);
File.WriteAllText($"{pathapi}index.ts", GenerateVue3View("indexapi"), Encoding.UTF8);
}
}
/*var test = GenerateTest();
var test = GenerateTest();
if (test != "")
{
if (UI == UIEnum.LayUI && IsApi == false)
@@ -521,7 +544,7 @@ namespace WalkingTec.Mvvm.Mvc
{
File.WriteAllText($"{TestDir}{Path.DirectorySeparatorChar}{ModelName}ApiTest.cs", test, Encoding.UTF8);
}
}*/
}
}
public string GenerateController()
@@ -535,7 +558,7 @@ namespace WalkingTec.Mvvm.Mvc
else
{
dir = "Spa";
if(UI == UIEnum.Blazor)
if (UI == UIEnum.Blazor)
{
dir = "Spa.Blazor";
}
@@ -766,7 +789,7 @@ namespace WalkingTec.Mvvm.Mvc
{
var middleType = modelType.GetSingleProperty(pro.FieldName).PropertyType.GenericTypeArguments[0];
var middlename = DC.GetPropertyNameByFk(middleType, pro.SubIdField);
if(typeof(IPersistPoco).IsAssignableFrom(Type.GetType(pro.RelatedField)))
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,"",""), ";
@@ -1043,7 +1066,7 @@ namespace WalkingTec.Mvvm.Mvc
{
checktype = proType.GetGenericArguments()[0];
}
if(checktype == typeof(bool) && proType.IsNullable() == false)
if (checktype == typeof(bool) && proType.IsNullable() == false)
{
fieldstr.Append($@"<wt:switch field=""{pre}.{item.FieldName}"" />");
@@ -1141,7 +1164,7 @@ namespace WalkingTec.Mvvm.Mvc
Type modelType = Type.GetType(SelectedModel);
if (UI == UIEnum.LayUI && IsApi == false)
{
if (typeof(IBasePoco).IsAssignableFrom( modelType) || typeof(IPersistPoco).IsAssignableFrom(modelType))
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);
}
@@ -1223,7 +1246,7 @@ namespace WalkingTec.Mvvm.Mvc
if (pro.Value == "$fk$")
{
mpros += $@"
v2.{ pro.Key} = v1.{pro.Key}; ";
v2.{pro.Key} = v1.{pro.Key}; ";
}
else
@@ -1260,29 +1283,29 @@ namespace WalkingTec.Mvvm.Mvc
string del = $"Assert.AreEqual(data, null);";
string mdel = @"Assert.AreEqual(data1, null);
Assert.AreEqual(data2, null);";
if (typeof(IPersistPoco).IsAssignableFrom( modelType))
if (typeof(IPersistPoco).IsAssignableFrom(modelType))
{
del = $"Assert.AreEqual(data.IsValid, false);";
mdel = @"Assert.AreEqual(data1.IsValid, false);
Assert.AreEqual(data2.IsValid, false);";
del = $"Assert.AreEqual(data, null);";
mdel = @"Assert.AreEqual(data1, null);
Assert.AreEqual(data2, null);";
}
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);
rv = GetRelatedNamespace(FieldInfos.Where(x => string.IsNullOrEmpty(x.RelatedField) == false).ToList(), rv);
}
return rv;
}
private string GenerateAddFKModel(string keyname, Type t, List<Type> exist)
{
if(exist == null)
if (exist == null)
{
exist = new List<Type>();
}
if(exist.Contains(t) == true)
if (exist.Contains(t) == true)
{
return "";
}
@@ -1666,7 +1689,7 @@ namespace WalkingTec.Mvvm.Mvc
}
else
{
fieldstr.AppendLine($@" <Col span={{24}}>
fieldstr.AppendLine($@" <Col span={{24}}>
<FormItem {{...props}} fieId=""Entity.{item.FieldName}"" layout=""row"" />
</Col>");
}
@@ -2127,7 +2150,7 @@ namespace WalkingTec.Mvvm.Mvc
public string GenerateBlazorView(string name)
{
string pagepath = string.IsNullOrEmpty(Area) ? $"/{ModelName}" : $"/{Area}/{ModelName}";
if(name != "Index")
if (name != "Index")
{
pagepath += $"/{name}";
}
@@ -2307,7 +2330,7 @@ namespace WalkingTec.Mvvm.Mvc
controltype = "WTDateRange";
}
}
if(controltype == "Select" || controltype == "MultiSelect")
if (controltype == "Select" || controltype == "MultiSelect")
{
ph = "PlaceHolder=\"@WtmBlazor.Localizer[\"Sys.All\"]\"";
}
@@ -2336,7 +2359,7 @@ namespace WalkingTec.Mvvm.Mvc
");
}
return rv.Replace("$columns$", fieldstr.ToString()).Replace("$searchfields$",fieldstr2.ToString()).Replace("$init$", apiinit.ToString()).Replace("$fieldinit$", fieldinit.ToString());
return rv.Replace("$columns$", fieldstr.ToString()).Replace("$searchfields$", fieldstr2.ToString()).Replace("$init$", apiinit.ToString()).Replace("$fieldinit$", fieldinit.ToString());
}
@@ -2371,7 +2394,7 @@ namespace WalkingTec.Mvvm.Mvc
}
else
{
bindfield = "Entity."+ item.FieldName;
bindfield = "Entity." + item.FieldName;
}
if (string.IsNullOrEmpty(item.RelatedField) == false)
@@ -2488,7 +2511,7 @@ namespace WalkingTec.Mvvm.Mvc
private List<SelectedItem> {item.Key} = new List<SelectedItem>();
");
}
return rv.Replace("$formfields$", fieldstr.ToString()).Replace("$fieldinit$", fieldinit.ToString()).Replace("$init$", apiinit.ToString());
return rv.Replace("$formfields$", fieldstr.ToString()).Replace("$fieldinit$", fieldinit.ToString()).Replace("$init$", apiinit.ToString());
}
if (name == "Details")
{
@@ -2606,6 +2629,426 @@ namespace WalkingTec.Mvvm.Mvc
return rv;
}
public string GenerateVue3View(string name)
{
string pagepath = string.IsNullOrEmpty(Area) ? $"/{ModelName}" : $"/{Area.ToLower()}/{ModelName}";
var rv = GetResource($"{name}.txt", "Spa.Vue3")
.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();
StringBuilder searchentity = new StringBuilder();
var pros = FieldInfos.Where(x => x.IsListField == true).ToList();
var pros2 = FieldInfos.Where(x => x.IsSearcherField == true).ToList();
List<PropertyInfo> existSubPro = new List<PropertyInfo>();
Dictionary<string, string> apis = new Dictionary<string, string>();
Dictionary<string, string> multiapis = new Dictionary<string, string>();
for (int i = 0; i < pros.Count; i++)
{
var item = pros[i];
var mpro = modelType.GetSingleProperty(item.FieldName);
string render = "";
string template = "text";
string newname = item.FieldName;
var property = modelType.GetSingleProperty(item.FieldName);
string label = property.GetPropertyDisplayName();
if (mpro.PropertyType.IsBoolOrNullableBool())
{
template = "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 = "image";
}
else
{
}
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($@"
{{title:'{label}',key: '{newname}',type: '{template}',isCheck: true}},");
}
for (int i = 0; i < pros2.Count; i++)
{
string controltype = "input";
string sitems = "";
string bindfield = "";
string ph = "";
var item = pros2[i];
var property = modelType.GetSingleProperty(item.FieldName);
string label = property.GetPropertyDisplayName();
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;
}
searchentity.AppendLine($@" {bindfield}: null,");
if (string.IsNullOrEmpty(item.RelatedField) == false)
{
var subtype = Type.GetType(item.RelatedField);
var tempname = $"All{subtype.Name}s";
if (string.IsNullOrEmpty(item.SubIdField) == true)
{
controltype = "select";
sitems += $@"
<el-option v-for=""item in state{ModelName}.{tempname}"" :key=""item.Value"" :value=""item.Value"" :label=""item.Text""></el-option>";
}
else
{
ph += " multiple";
}
ph += $" :data=\"state{ModelName}.{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 = $@"
<el-option :key=""1"" :value=true :label=""$t('message._system.common.vm.tips_bool_true')""></el-option>
<el-option :key=""0"" :value=false :label=""$t('message._system.common.vm.tips_bool_false')""></el-option>
";
}
else if (checktype.IsEnum())
{
controltype = "select";
var es = checktype.ToListItems();
for (int a = 0; a < es.Count; a++)
{
var e = es[a];
sitems += $@"
<el-option key=""{e.Value}"" value=""{e.Value}"" label=""{e.Text}""></el-option>";
}
}
else if (checktype.IsNumber())
{
controltype = "input-number";
}
else if (checktype == typeof(string))
{
}
else if (checktype == typeof(DateTime))
{
controltype = "date-picker";
}
}
if (controltype == "Select" || controltype == "MultiSelect")
{
ph = "PlaceHolder=\"@WtmBlazor.Localizer[\"Sys.All\"]\"";
}
//<{controltype} @bind-Value=""@SearchModel.{bindfield}"" {sitems} {ph}/>
fieldstr2.Append($@"
<el-col :xs=""24"" :lg=""12"" class=""mb20"">
<el-form-item ref=""{bindfield}_FormItem"" prop=""{bindfield}"" label=""{label}"">
<el-{controltype} v-model=""searchData{ModelName}.{bindfield}""{ph} clearable>{sitems}</el-{controltype}>
</el-form-item>
</el-col>");
}
StringBuilder apiinit = new StringBuilder();
StringBuilder fieldinit = new StringBuilder();
foreach (var item in apis)
{
apiinit.Append(@$"
other.getSelectList('{item.Value}',[],false).then(x=>{{state{ModelName}.{item.Key} = x}});
");
fieldinit.Append($@"
{item.Key}: [] as any[],");
}
foreach (var item in multiapis)
{
apiinit.Append(@$"
other.getSelectList('{item.Value}',[],false).then(x=>{{state{ModelName}.{item.Key} = x}});
");
fieldinit.Append($@"
{item.Key}: [] as any[],");
}
return rv.Replace("$columns$", fieldstr.ToString()).Replace("$searchentity$", searchentity.ToString()).Replace("$searchfields$", fieldstr2.ToString()).Replace("$init$", apiinit.ToString()).Replace("$fieldinit$", fieldinit.ToString());
}
if (name == "Create" || name == "Edit" || name == "Details")
{
StringBuilder fieldstr = new StringBuilder();
StringBuilder fieldentityinit = new StringBuilder();
StringBuilder selectfieldinit = new StringBuilder();
var pros = FieldInfos.Where(x => x.IsFormField == true).ToList();
if (name != "Create")
{
fieldentityinit.AppendLine($@" ID: null,");
}
//生成表单model
Dictionary<string, string> apis = new Dictionary<string, string>();
Dictionary<string, string> multiapis = new Dictionary<string, string>();
for (int i = 0; i < pros.Count; i++)
{
var item = pros[i];
string controltype = "el-input";
string sitems = "";
string bindfield = "";
string ph = "";
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 = "";
if (isrequired == true)
{
rules = $@" :rules=""[{{ required: true, message:'{label}为必填项',trigger:'blur'}}]""";
}
if (string.IsNullOrEmpty(item.RelatedField) == false && string.IsNullOrEmpty(item.SubIdField) == true)
{
var fk = DC.GetFKName2(modelType, item.FieldName);
fieldentityinit.AppendLine($@" {fk}: null,");
}
else
{
fieldentityinit.AppendLine($@" {item.FieldName}: null,");
}
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";
selectfieldinit.AppendLine($@" {bindfield}: [],");
}
}
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 = "wtm-upload-image";
}
else
{
controltype = "wtm-upload-file";
}
}
else
{
var tempname = $"All{subtype.Name}s";
if (string.IsNullOrEmpty(item.SubIdField) == true)
{
controltype = "el-select";
sitems = $@"
<el-option v-for=""item in state{ModelName}.{tempname}"" :key=""item.Value"" :value=""item.Value"" :label=""item.Text""></el-option>";
}
else
{
controltype = "el-transfer";
ph += $@" :data=""state{ModelName}.{tempname}""";
}
//sitems = $"Items=\"@{tempname}\"";
if (apis.ContainsKey(tempname) == false && multiapis.ContainsKey(tempname) == false)
{
if (controltype == "el-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 = "el-select";
sitems = $@"
<el-option :key=""1"" :value=true :label=""$t('message._system.common.vm.tips_bool_true')""></el-option>
<el-option :key=""0"" :value=false :label=""$t('message._system.common.vm.tips_bool_false')""></el-option>
";
}
else if (checktype.IsEnum())
{
controltype = "el-select";
var es = checktype.ToListItems();
for (int a = 0; a < es.Count; a++)
{
var e = es[a];
sitems += $@"
<el-option key=""{e.Value}"" value=""{e.Value}"" label=""{e.Text}""></el-option>";
}
}
else if (checktype.IsNumber())
{
controltype = "el-input-number";
}
else if (checktype == typeof(string))
{
}
else if (checktype == typeof(DateTime))
{
controltype = "el-date-picker";
}
}
if (name == "Details")
{
ph += " disabled";
}
if (controltype == "el-transfer")
{
fieldstr.Append($@"
<el-col :xs=""24"" :lg=""24"" class=""mb20"">
<el-form-item ref=""{bindfield.Replace(".", "_")}_FormItem"" prop=""{bindfield}"" label=""{label}""{rules}>
<{controltype} v-model=""state{ModelName}.vmModel.{bindfield}""{ph} clearable>{sitems}</{controltype}>
</el-form-item>
</el-col>");
}
else
{
fieldstr.Append($@"
<el-col :xs=""24"" :lg=""12"" class=""mb20"">
<el-form-item ref=""{bindfield.Replace(".", "_")}_FormItem"" prop=""{bindfield}"" label=""{label}""{rules}>
<{controltype} v-model=""state{ModelName}.vmModel.{bindfield}""{ph} clearable>{sitems}</{controltype}>
</el-form-item>
</el-col>");
}
}
StringBuilder apiinit = new StringBuilder();
StringBuilder fieldinit = new StringBuilder();
foreach (var item in apis)
{
apiinit.Append(@$"
other.getSelectList('{item.Value}',[],false).then(x=>{{state{ModelName}.{item.Key} = x}});
");
fieldinit.Append($@"
{item.Key}: [] as any[],");
}
foreach (var item in multiapis)
{
apiinit.Append(@$"
other.getSelectList('{item.Value}',[],false).then(x=>{{state{ModelName}.{item.Key} = x}});
");
fieldinit.Append($@"
{item.Key}: [] as any[],");
}
return rv.Replace("$formfields$", fieldstr.ToString()).Replace("$fieldinit$", fieldinit.ToString()).Replace("$selectfieldinit$", selectfieldinit.ToString())
.Replace("$fieldentityinit$", fieldentityinit.ToString()).Replace("$init$", apiinit.ToString());
}
if (name == "indexapi")
{
return rv;
}
return rv;
}
public string GetResource(string fileName, string subdir = "")
{
//获取编译在程序中的Controller原始代码文本
@@ -19,9 +19,6 @@ using WalkingTec.Mvvm.Core.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using WalkingTec.Mvvm.Core.Extensions;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Dynamic;
using NPOI.SS.Formula.Functions;
namespace WalkingTec.Mvvm.Mvc.Filters
{
@@ -98,7 +95,7 @@ namespace WalkingTec.Mvvm.Mvc.Filters
if (context.HttpContext.Items.ContainsKey("DONOTUSE_REQUESTBODY"))
{
string body = context.HttpContext.Items["DONOTUSE_REQUESTBODY"].ToString();
var joption = new JsonSerializerOptions();
var joption = new JsonSerializerOptions(Core.CoreProgram.DefaultJsonOption);
joption.Converters.Add(new BodyConverter());
try
{
@@ -366,7 +363,7 @@ namespace WalkingTec.Mvvm.Mvc.Filters
if (context.Result is PartialViewResult pvr)
{
model = pvr.Model as BaseVM;
context.HttpContext.Response.WriteAsync($"<script>ff.ResizeChart('{model?.ViewDivId}')</script>");
context.HttpContext.Response.WriteAsync($"<script>try{{ff.ResizeChart('{model?.ViewDivId}')}}catch{{}}</script>");
}
//如果是来自Error,则已经记录过日志,跳过
@@ -194,6 +194,10 @@ namespace WalkingTec.Mvvm.Mvc.Filters
{
context.Result = ctrl.Forbid(JwtBearerDefaults.AuthenticationScheme);
}
else if(controller is BaseApiController bac)
{
context.Result = bac.Forbid();
}
else
{
ContentResult cr = new ContentResult()
@@ -234,8 +238,12 @@ namespace WalkingTec.Mvvm.Mvc.Filters
{
context.Result = ctrl.Forbid(JwtBearerDefaults.AuthenticationScheme);
}
else
{
else if (controller is BaseApiController bac)
{
context.Result = bac.Forbid();
}
else
{
ContentResult cr = new ContentResult()
{
Content = MvcProgram._localizer["Sys.NoPrivilege"],
@@ -0,0 +1,83 @@
<template>
<div class="card-fill layout-padding">
<el-card shadow="hover" class="layout-padding-auto" >
<el-form ref="formRef$modelname$" :model="state$modelname$.vmModel" label-width="100px">
<el-row>
$formfields$
</el-row>
<div style="text-align:right;">
<WtmButton @click="onSubmit$modelname$" type="primary" :button-text="$t('message._system.common.vm.submit')" style="margin-top:15px;"/>
<WtmButton @click="onClose$modelname$" type="primary" :button-text="$t('message._system.common.vm.cancel')" style="margin-top:15px;"/>
</div>
</el-form>
</el-card>
</div>
</template>
<script setup lang="ts" name="message._system.common.vm.add;false">
import { ElMessageBox, ElMessage } from 'element-plus';
import { defineAsyncComponent,reactive, ref, getCurrentInstance, onMounted, nextTick } from 'vue';
import { $modelname$Api } from '/@/api$pagepath$';
import other from '/@/utils/other';
import fileApi from '/@/api/file';
import { useRouter } from "vue-router";
const ci = getCurrentInstance() as any;
// 定义变量内容
const formRef$modelname$ = ref();
const state$modelname$ = reactive({
vmModel: {
Entity:{
$fieldentityinit$
},
$selectfieldinit$
},
$fieldinit$
});
// 取消
const onClose$modelname$ = () => {
closeDialog();
};
// 提交
const onSubmit$modelname$ = () => {
formRef$modelname$.value?.validate((valid: boolean, fields: any) => {
if (valid) {
$modelname$Api().add(state$modelname$.vmModel).then(() => {
ElMessage.success(ci.proxy.$t('message._system.common.vm.submittip'));
emit('refresh');
closeDialog();
}).catch((error) => {
other.setFormError(ci, error);
})
}
})
};
// 页面加载时
onMounted(() => {
$init$
});
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh','closeDialog']);
// 关闭弹窗
const closeDialog = () => {
emit('closeDialog');
};
// 暴露变量
defineExpose({
});
</script>
<style scoped lang="scss">
</style>
@@ -0,0 +1,75 @@
<template>
<div class="card-fill layout-padding">
<el-card shadow="hover" class="layout-padding-auto" >
<el-form ref="formRef$modelname$" :model="state$modelname$.vmModel" label-width="100px">
<el-row>
$formfields$
</el-row>
<div style="text-align:right;">
<WtmButton @click="onClose$modelname$" type="primary" :button-text="$t('message._system.common.vm.cancel')" style="margin-top:15px;"/>
</div>
</el-form>
</el-card>
</div>
</template>
<script setup lang="ts" name="message._system.common.vm.detail;false">
import { ElMessageBox, ElMessage } from 'element-plus';
import { defineAsyncComponent,reactive, ref, getCurrentInstance, onMounted, nextTick } from 'vue';
import { $modelname$Api } from '/@/api$pagepath$';
import other from '/@/utils/other';
import fileApi from '/@/api/file';
import { useRouter } from "vue-router";
const ci = getCurrentInstance() as any;
// 定义变量内容
const formRef$modelname$ = ref();
const state$modelname$ = reactive({
vmModel: {
Entity:{
$fieldentityinit$
},
$selectfieldinit$
},
$fieldinit$
});
// 取消
const onClose$modelname$ = () => {
closeDialog();
};
// 页面加载时
onMounted(() => {
$init$
if (ci.attrs["wtmdata"]) {
state$modelname$.vmModel.Entity.ID = ci.attrs["wtmdata"].ID;
}
else if (useRouter().currentRoute.value.query.id) {
state$modelname$.vmModel.Entity.ID = useRouter().currentRoute.value.query.id as any;
}
$modelname$Api().get(state$modelname$.vmModel.Entity.ID ?? "").then((data: any) => other.setValue(state$modelname$.vmModel, data));
});
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh','closeDialog']);
// 关闭弹窗
const closeDialog = () => {
emit('closeDialog');
};
// 暴露变量
defineExpose({
});
</script>
<style scoped lang="scss">
</style>
@@ -0,0 +1,90 @@
<template>
<div class="card-fill layout-padding">
<el-card shadow="hover" class="layout-padding-auto" >
<el-form ref="formRef$modelname$" :model="state$modelname$.vmModel" label-width="100px">
<el-row>
$formfields$
</el-row>
<div style="text-align:right;">
<WtmButton @click="onSubmit$modelname$" type="primary" :button-text="$t('message._system.common.vm.submit')" style="margin-top:15px;"/>
<WtmButton @click="onClose$modelname$" type="primary" :button-text="$t('message._system.common.vm.cancel')" style="margin-top:15px;"/>
</div>
</el-form>
</el-card>
</div>
</template>
<script setup lang="ts" name="message._system.common.vm.edit;false">
import { ElMessageBox, ElMessage } from 'element-plus';
import { defineAsyncComponent,reactive, ref, getCurrentInstance, onMounted, nextTick } from 'vue';
import { $modelname$Api } from '/@/api$pagepath$';
import other from '/@/utils/other';
import fileApi from '/@/api/file';
import { useRouter } from "vue-router";
const ci = getCurrentInstance() as any;
// 定义变量内容
const formRef$modelname$ = ref();
const state$modelname$ = reactive({
vmModel: {
Entity:{
$fieldentityinit$
},
$selectfieldinit$
},
$fieldinit$
});
// 取消
const onClose$modelname$ = () => {
closeDialog();
};
// 提交
const onSubmit$modelname$ = () => {
formRef$modelname$.value?.validate((valid: boolean, fields: any) => {
if (valid) {
$modelname$Api().edit(state$modelname$.vmModel).then(() => {
ElMessage.success(ci.proxy.$t('message._system.common.vm.submittip'));
emit('refresh');
closeDialog();
}).catch((error) => {
other.setFormError(ci, error);
})
}
})
};
// 页面加载时
onMounted(() => {
$init$
if (ci.attrs["wtmdata"]) {
state$modelname$.vmModel.Entity.ID = ci.attrs["wtmdata"].ID;
}
else if (useRouter().currentRoute.value.query.id) {
state$modelname$.vmModel.Entity.ID = useRouter().currentRoute.value.query.id as any;
}
$modelname$Api().get(state$modelname$.vmModel.Entity.ID ?? "").then((data: any) => other.setValue(state$modelname$.vmModel, data));
});
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh','closeDialog']);
// 关闭弹窗
const closeDialog = () => {
emit('closeDialog');
};
// 暴露变量
defineExpose({
});
</script>
<style scoped lang="scss">
</style>
@@ -0,0 +1,84 @@
<template>
<div class="card-fill layout-padding">
<el-card shadow="hover" class="layout-padding-auto" >
<el-form ref="formRef" :model="state.vmModel" label-width="90px" >
<WtmImportor url="/api/$modelname$/GetExcelTemplate" v-model="state.vmModel.UploadFileId" :files="state.vmModel.files"/>
<div v-if="state.errorFileId" style="margin-top: 10px;vertical-align: bottom;">
<el-button @click="onErrorFile" size="small" type="danger">{{ $t('message._system.common.vm.importtip') }}</el-button>
</div>
</el-form>
<footer class="el-dialog__footer" style="padding: unset;padding-top: 10px;">
<span class="dialog-footer">
<el-button @click="onCancel" >{{$t('message._system.common.vm.cancel')}}</el-button>
<el-button :disabled="state.vmModel.UploadFileId===null" type="primary" @click="onSubmit" >{{$t('message._system.common.vm.submit')}}</el-button>
</span>
</footer>
</el-card>
</div>
</template>
<script setup lang="ts" name="message._system.common.vm.import;false">
import { ElMessageBox, ElMessage } from 'element-plus';
import { defineAsyncComponent,reactive, ref, getCurrentInstance, onMounted, nextTick } from 'vue';
import { $modelname$Api } from '/@/api$pagepath$';
import other from '/@/utils/other';
import fileApi from '/@/api/file';
import { useRouter } from "vue-router";
const ci = getCurrentInstance() as any;
// 定义变量内容
const formRef = ref();
const state = reactive({
vmModel: {
UploadFileId: null,
files: []
},
errorFileId: null
});
// 取消
const onCancel = () => {
closeDialog();
};
const onSubmit = () => {
$modelname$Api().import(state.vmModel)
.then((res) => {
ElMessage.success(ci.proxy.$t('message._system.common.vm.importsuc',{count:res}));
emit('refresh');
closeDialog();
})
.catch((error) => {
state.errorFileId = error.FormError['Entity.ErrorFileId']
ElMessage.error(error.FormError['Entity.Import']);
});
}
const onErrorFile = () => {
fileApi().downloadFile(state.errorFileId);
}
// 页面加载时
onMounted(() => {
});
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh','closeDialog']);
// 关闭弹窗
const closeDialog = () => {
emit('closeDialog');
};
// 暴露变量
defineExpose({
});
</script>
<style scoped lang="scss">
</style>
@@ -0,0 +1,143 @@
<template>
<div class="card-fill layout-padding">
<el-card shadow="hover" class="layout-padding-auto" >
<WtmSearcher v-model="searchData$modelname$" @search="getTableData$modelname$">
<el-row>
$searchfields$
</el-row>
</WtmSearcher>
<div style="text-align: right;">
<WtmButton v-auth="'/api/$modelname$/Add'" icon='fa fa-plus' type='primary' :button-text="$t('message._system.common.vm.add')" @click="OnCreateClick()"/>
<WtmButton v-auth="'/api/$modelname$/BatchDelete'" icon='fa fa-trash' type='danger' :button-text="$t('message._system.common.vm.batchdelete')" :confirm="$t('message._system.common.vm.deletetip')" @click="onBatchDelete()"/>
<WtmButton v-auth="'/api/$modelname$/Import'" icon='fa fa-tasks' type='primary' :button-text="$t('message._system.common.vm.import')" @click="OnImportClick()"/>
<WtmButton v-auth="'/api/$modelname$/$modelname$ExportExcel'" icon='fa fa-arrow-circle-down' type='primary' :button-text="$t('message._system.common.vm.export')" @click="onExport()"/>
</div>
<WtmTable ref="tableRef$modelname$" v-bind="tableData$modelname$">
<template #operation>
<el-table-column :label="$t('message._system.common.vm.operate')" width="180">
<template v-slot="scope">
<el-button text type="primary" @click="OnEditrowClick(scope.row)" v-auth="'/api/$modelname$/Edit'">{{ $t('message._system.common.vm.edit') }}</el-button>
<el-button text type="primary" @click="OnDetailsrowClick(scope.row)" v-auth="'/api/$modelname$/{id}'">{{ $t('message._system.common.vm.detail') }}</el-button>
<el-popconfirm :title="$t('message._system.common.vm.deletetip')" @confirm="onDelete(scope.row)">
<template #reference>
<el-button text type="danger" v-auth="'/api/$modelname$/BatchDelete'">{{ $t('message._system.common.vm.delete') }}</el-button>
</template>
</el-popconfirm>
</template>
</el-table-column>
</template>
</WtmTable>
</el-card>
</div>
</template>
<script setup lang="ts" name="$des$;true;$controllername$">
import { ElMessageBox, ElMessage } from 'element-plus';
import { defineAsyncComponent,reactive, ref, getCurrentInstance, onMounted, nextTick } from 'vue';
import { $modelname$Api } from '/@/api$pagepath$';
import other from '/@/utils/other';
import fileApi from '/@/api/file';
import { useRouter } from "vue-router";
const ci = getCurrentInstance() as any;
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));
const state$modelname$ = reactive({
$fieldinit$
});
const searchData$modelname$ = ref({
$searchentity$
});
// 定义变量内容
const tableRef$modelname$ = ref();
const tableData$modelname$ = ref({
// 列表数据(必传)
data: [],
// 表头内容(必传,注意格式)
header: [
$columns$
],
// 配置项(必传)
config: {
total: 0, // 列表总数
loading: true, // loading 加载
isSerialNo: true, // 是否显示表格序号
isSelection: true, // 是否显示表格多选
isOperate: true, // 是否显示表格操作栏
}
});
// 初始化表格数据
const getTableData$modelname$ = () => {
tableRef$modelname$.value.doSearch($modelname$Api().search, searchData$modelname$.value)
.catch((error: any) => {
other.setFormError(ci, error);
});
};
const OnCreateClick = () => {
other.openDialog(ci.proxy.$t('message._system.common.vm.add'), CreateDialog, null, getTableData$modelname$)
};
const OnEditrowClick = (row: any) => {
other.openDialog(ci.proxy.$t('message._system.common.vm.edit'), EditDialog, row, getTableData$modelname$)
};
const OnDetailsrowClick = (row: any) => {
other.openDialog(ci.proxy.$t('message._system.common.vm.detail'), DetailsDialog, row, getTableData$modelname$)
};
// 删除
const onDelete = (row: any) => {
$modelname$Api().delete([row.ID]).then(() => { getTableData$modelname$()})
};
const onBatchDelete = () => {
const selectedrows = tableRef$modelname$.value.getSelectedRows();
const selectedids = selectedrows.map((x: any) => x.ID);
if (selectedids.length > 0)
$modelname$Api().delete(selectedids).then(() => { getTableData$modelname$()})
else
ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
};
const OnImportClick = () => {
other.openDialog(ci.proxy.$t('message._system.common.vm.import'), ImportDialog, null, getTableData$modelname$)
};
const onExport = () => {
const selected = tableRef$modelname$.value.getSelectedRows();
if (selected.length > 0) {
$modelname$Api().exportById(selected.map((x: any) => x.ID));
}
else {
$modelname$Api().export({});
}
};
// 页面加载时
onMounted(() => {
$init$
getTableData$modelname$();
});
// 暴露变量
defineExpose({
});
</script>
<style scoped lang="scss">
</style>
@@ -0,0 +1,72 @@
import request from '/@/utils/request';
import other from '/@/utils/other';
function $modelname$Api() {
return {
search: (data: object) => {
return request({
url: '/api/$modelname$/Search',
method: 'post',
data,
});
},
get: (data: number|string) => {
return request({
url: '/api/$modelname$/'+data,
method: 'get'
});
},
add:(data: object)=>{
return request({
url:'/api/$modelname$/Add',
method:'post',
data
});
},
edit:(data: object)=>{
return request({
url:'/api/$modelname$/edit',
method:'put',
data
});
},
batchedit:(data: object)=>{
return request({
url:'/api/$modelname$/batchedit',
method:'post',
data
});
},
delete:(data: Array<number>|Array<string>)=>{
return request({
url:'/api/$modelname$/BatchDelete',
method:'post',
data
});
},
export: (data: object) => {
return request<any,Blob>({
responseType: "blob",
url: '/api/$modelname$/ExportExcel',
method: 'post',
data,
}).then((data)=>{other.downloadFile(data)});;
},
exportById: (data: Array<number>|Array<string>) => {
return request<any,Blob>({
url: '/api/$modelname$/ExportExcelByIds',
method: 'post',
data,
}).then((data)=>{other.downloadFile(data)});
},
import: (data: object) => {
return request({
url: '/api/$modelname$/Import',
method: 'post',
data,
});
},
};
}
export {$modelname$Api}
@@ -47,6 +47,7 @@ using Microsoft.AspNetCore.SpaServices.Extensions;
using Microsoft.Extensions.FileProviders;
using WalkingTec.Mvvm.Core.Support.Quartz;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace WalkingTec.Mvvm.Mvc
{
@@ -602,7 +603,7 @@ namespace WalkingTec.Mvvm.Mvc
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.SecurityKey)),
LifetimeValidator = (DateTime? notBefore, DateTime? expires, SecurityToken securityToken, TokenValidationParameters validationParameters) =>
{
if(expires == null)
if (expires == null)
{
return true;
}
@@ -610,7 +611,7 @@ namespace WalkingTec.Mvvm.Mvc
{
return expires.Value > DateTime.UtcNow;
}
},
},
ValidateLifetime = true
};
})
@@ -766,7 +767,7 @@ namespace WalkingTec.Mvvm.Mvc
gd.IsSpa = isspa == true || test != null;
gd.AllModule = GetAllModules(controllers);
var modules = Utils.ResetModule(gd.AllModule, false);
gd.CustomUserType = gd.GetTypesAssignableFrom<FrameworkUserBase>().Where(x => x.Name.ToLower() == "frameworkuser").FirstOrDefault();
gd.CustomUserType = gd.GetPocoTypesAssignableFrom<FrameworkUserBase>().Where(x => x.Name.ToLower() == "frameworkuser").FirstOrDefault();
gd.SetMenuGetFunc(() =>
{
var menus = new List<SimpleMenu>();
@@ -793,14 +794,30 @@ namespace WalkingTec.Mvvm.Mvc
var tenantsCacheKey = nameof(GlobalData.AllTenant);
if (cache.TryGetValue(tenantsCacheKey, out tenants) == false)
{
tenants = new List<FrameworkTenant>();
if (configs?.EnableTenant == true)
{
using (var dc = configs.Connections.Where(x => x.Key.ToLower() == "default").FirstOrDefault().CreateDC())
{
tenants = dc.Set<FrameworkTenant>().IgnoreQueryFilters().Where(x => x.Enabled).ToList();
var cusTenantType = gd.GetPocoTypesAssignableFrom<FrameworkTenant>().FirstOrDefault();
if (cusTenantType != null)
{
var set = dc.GetType().GetMethod("Set", Type.EmptyTypes).MakeGenericMethod(cusTenantType);
var q = set.Invoke(dc, null) as IQueryable<FrameworkTenant>;
tenants = q.IgnoreQueryFilters().Where(x => x.Enabled).ToList();
}
var _all = dc.Set<FrameworkTenant>().IgnoreQueryFilters().Where(x => x.Enabled).ToList();
foreach (var item in _all)
{
if(tenants.Any(x=>x.ID == item.ID) == false)
{
tenants.Add(item);
}
}
tenants = tenants.OrderBy(x => x.CreateTime).ToList();
foreach (var item in tenants)
{
if (string.IsNullOrEmpty(item.TDomain)==false)
if (string.IsNullOrEmpty(item.TDomain) == false)
{
Regex r = new Regex("(http://|https://)?(.+)(/)?");
var m = r.Match(item.TDomain);
@@ -809,10 +826,28 @@ namespace WalkingTec.Mvvm.Mvc
item.TDomain = m.Groups[2].Value;
}
}
item.Attributes = new Dictionary<string, object>();
if (cusTenantType != null)
{
var cuspros = cusTenantType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(x => x.PropertyType.IsListOf<TopBasePoco>() == false && typeof(TopBasePoco).IsAssignableFrom(x.PropertyType) == false).ToList();
foreach (var pro in cuspros)
{
if (item.Attributes.ContainsKey(pro.Name) == false)
{
try
{
item.Attributes.Add(pro.Name, pro.GetValue(item));
}
catch { }
}
}
}
}
}
}
if(tenants == null)
if (tenants == null)
{
tenants = new List<FrameworkTenant>();
}
@@ -50,19 +50,39 @@ namespace WalkingTec.Mvvm.Mvc
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString;
options.JsonSerializerOptions.AllowTrailingCommas = true;
options.JsonSerializerOptions.Converters.Add(new NullableConverter<int>());
options.JsonSerializerOptions.Converters.Add(new NullableConverter<long>());
options.JsonSerializerOptions.Converters.Add(new NullableConverter<decimal>());
options.JsonSerializerOptions.Converters.Add(new NullableConverter<short>());
options.JsonSerializerOptions.Converters.Add(new NullableConverter<float>());
options.JsonSerializerOptions.Converters.Add(new NullableConverter<double>());
options.JsonSerializerOptions.Converters.Add(new NullableConverter<bool>());
options.JsonSerializerOptions.Converters.Add(new NullableConverter<DateTime>());
options.JsonSerializerOptions.Converters.Add(new NullableConverter<Guid>());
options.JsonSerializerOptions.Converters.Add(new NullableEnumConverter());
options.JsonSerializerOptions.Converters.Add(new BoolStringConverter());
options.JsonSerializerOptions.Converters.Add(new DateRangeConverter());
options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
options.JsonSerializerOptions.Converters.Add(new StringIgnoreLTGTConverter());
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
options.JsonSerializerOptions.Converters.Add(new BoolStringConverter());
options.JsonSerializerOptions.Converters.Add(new DateRangeConverter());
options.JsonSerializerOptions.Converters.Add(new PocoConverter());
options.JsonSerializerOptions.Converters.Add(new TypeConverter());
options.JsonSerializerOptions.Converters.Add(new DynamicDataConverter());
Core.CoreProgram.DefaultJsonOption = options.JsonSerializerOptions;
JsonSerializerOptions jsonOptions2 = new JsonSerializerOptions();
jsonOptions2.PropertyNamingPolicy = null;
jsonOptions2.NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString;
options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString;
jsonOptions2.AllowTrailingCommas = true;
jsonOptions2.Converters.Add(new NullableConverter<int>());
jsonOptions2.Converters.Add(new NullableConverter<long>());
jsonOptions2.Converters.Add(new NullableConverter<decimal>());
jsonOptions2.Converters.Add(new NullableConverter<short>());
jsonOptions2.Converters.Add(new NullableConverter<float>());
jsonOptions2.Converters.Add(new NullableConverter<double>());
jsonOptions2.Converters.Add(new NullableConverter<bool>());
jsonOptions2.Converters.Add(new NullableConverter<DateTime>());
jsonOptions2.Converters.Add(new NullableConverter<Guid>());
jsonOptions2.Converters.Add(new NullableEnumConverter());
jsonOptions2.Converters.Add(new DateTimeConverter());
jsonOptions2.Converters.Add(new JsonStringEnumConverter());
jsonOptions2.Converters.Add(new BoolStringConverter());
@@ -145,6 +145,32 @@ Layout = null;
</wt:fieldset>
}
else if (Model.UI == WalkingTec.Mvvm.Core.UIEnum.VUE3)
{
var viewdir = Model.MainDir + $"\\ClientApp\\src\\views\\{(string.IsNullOrEmpty(Model.Area)?"":$"{Model.Area}\\")}" + Model.ModelName.ToLower();
var apidir = Model.MainDir + $"\\ClientApp\\src\\api\\{(string.IsNullOrEmpty(Model.Area) ? "" : $"{Model.Area}\\")}" + Model.ModelName.ToLower();
<wt:fieldset title="VUE Views">
<wt:linkbutton text="@preview" window-width="600" post-current-form="true" size=" ButtonSizeEnum.Mini"
target=" ButtonTargetEnum.Layer" url="/_CodeGen/Preview?PreviewFile=Index&ui=vue3" />
@viewdir\index.vue<br />
<wt:linkbutton text="@preview" window-width="600" post-current-form="true" size=" ButtonSizeEnum.Mini"
target=" ButtonTargetEnum.Layer" url="/_CodeGen/Preview?PreviewFile=Create&ui=vue3" />
@viewdir\create.vue<br />
<wt:linkbutton text="@preview" window-width="600" post-current-form="true" size=" ButtonSizeEnum.Mini"
target=" ButtonTargetEnum.Layer" url="/_CodeGen/Preview?PreviewFile=Edit&ui=vue3" />
@viewdir\edit.vue<br />
<wt:linkbutton text="@preview" window-width="600" post-current-form="true" size=" ButtonSizeEnum.Mini"
target=" ButtonTargetEnum.Layer" url="/_CodeGen/Preview?PreviewFile=Details&ui=vue3" />
@viewdir\details.vue<br />
<wt:linkbutton text="@preview" window-width="600" post-current-form="true" size=" ButtonSizeEnum.Mini"
target=" ButtonTargetEnum.Layer" url="/_CodeGen/Preview?PreviewFile=Import&ui=vue3" />
@viewdir\import.vue <br />
<wt:linkbutton text="@preview" window-width="600" post-current-form="true" size=" ButtonSizeEnum.Mini"
target=" ButtonTargetEnum.Layer" url="/_CodeGen/Preview?PreviewFile=indexapi&ui=vue3" />
@apidir\index.vue <br />
</wt:fieldset>
}
else if (Model.UI == WalkingTec.Mvvm.Core.UIEnum.Blazor)
{
var viewdir = Model.ShareDir;
@@ -21,6 +21,17 @@
<None Remove="GeneratorFiles\Spa\Blazor\Edit.txt" />
<None Remove="GeneratorFiles\Spa\Blazor\Import.txt" />
<None Remove="GeneratorFiles\Spa\Blazor\Index.txt" />
<None Remove="GeneratorFiles\Spa\Vue3\Create.txt" />
<None Remove="GeneratorFiles\Spa\Vue3\Details.txt" />
<None Remove="GeneratorFiles\Spa\Vue3\Edit.txt" />
<None Remove="GeneratorFiles\Spa\Vue3\Import.txt" />
<None Remove="GeneratorFiles\Spa\Vue3\Index.txt" />
<None Remove="GeneratorFiles\Spa\Vue3\indexapi.txt" />
<None Remove="GeneratorFiles\Spa\Vue\Create.txt" />
<None Remove="GeneratorFiles\Spa\Vue\Details.txt" />
<None Remove="GeneratorFiles\Spa\Vue\Edit.txt" />
<None Remove="GeneratorFiles\Spa\Vue\Import.txt" />
<None Remove="GeneratorFiles\Spa\Vue\index.txt" />
<EmbeddedResource Include="framework_layui.js" />
<EmbeddedResource Include="GeneratorFiles\ApiTest.txt" />
<EmbeddedResource Include="GeneratorFiles\ApiTestTopPoco.txt" />
@@ -57,6 +68,12 @@
<EmbeddedResource Include="GeneratorFiles\Mvc\CreateView.txt" />
<EmbeddedResource Include="GeneratorFiles\Mvc\DeleteView.txt" />
<EmbeddedResource Include="GeneratorFiles\Mvc\DetailsView.txt" />
<EmbeddedResource Include="GeneratorFiles\Spa\Vue3\Create.txt" />
<EmbeddedResource Include="GeneratorFiles\Spa\Vue3\Details.txt" />
<EmbeddedResource Include="GeneratorFiles\Spa\Vue3\Edit.txt" />
<EmbeddedResource Include="GeneratorFiles\Spa\Vue3\Import.txt" />
<EmbeddedResource Include="GeneratorFiles\Spa\Vue3\Index.txt" />
<EmbeddedResource Include="GeneratorFiles\Spa\Vue3\indexapi.txt" />
</ItemGroup>
<ItemGroup>
@@ -65,7 +82,9 @@
<PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="6.0.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="2.1.0" />
<PackageReference Include="SixLabors.ImageSharp.Drawing" Version="1.0.0-beta14" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="6.4.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="6.4.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.4.0" />
<PackageReference Include="VueCliMiddleware" Version="6.0.0" />
</ItemGroup>
@@ -101,7 +101,12 @@ namespace WalkingTec.Mvvm.Mvc
List<string> apineeded = new List<string>();
ViewData["code"] = vm.GenerateVUEView(vm.PreviewFile,apineeded);
}
else if(vm.UI == UIEnum.Blazor)
else if (vm.UI == UIEnum.VUE3)
{
List<string> apineeded = new List<string>();
ViewData["code"] = vm.GenerateVue3View(vm.PreviewFile);
}
else if (vm.UI == UIEnum.Blazor)
{
ViewData["code"] = vm.GenerateBlazorView(vm.PreviewFile);
}
+12 -12
View File
@@ -48,7 +48,7 @@ namespace WalkingTec.Mvvm.Mvc
, string _DONOT_USE_CURRENTCS
)
{
string cs = string.IsNullOrEmpty(_DONOT_USE_CURRENTCS) ? "default" : _DONOT_USE_CURRENTCS;
string cs =_DONOT_USE_CURRENTCS;
Wtm.CurrentCS = cs;
var listVM = Wtm.CreateVM(_DONOT_USE_VMNAME, null, null, true) as IBasePagedListVM<TopBasePoco, ISearcher>;
@@ -129,7 +129,7 @@ namespace WalkingTec.Mvvm.Mvc
//var vmType = Type.GetType(_DONOT_USE_VMNAME);
//var vmCreater = vmType.GetConstructor(Type.EmptyTypes);
//var listVM = vmCreater.Invoke(null) as BaseVM;
Wtm.CurrentCS = (string.IsNullOrEmpty(_DONOT_USE_CS) == true) ? "default" : _DONOT_USE_CS;
Wtm.CurrentCS = _DONOT_USE_CS;
var listVM = Wtm.CreateVM(_DONOT_USE_VMNAME, null, null, true) as IBasePagedListVM<TopBasePoco, BaseSearcher>;
listVM.FC = qs;
if (listVM is IBasePagedListVM<TopBasePoco, ISearcher>)
@@ -210,7 +210,7 @@ namespace WalkingTec.Mvvm.Mvc
/// <returns></returns>
[HttpPost]
[ActionDescription("Export")]
public IActionResult GetExportExcel(string _DONOT_USE_VMNAME, string _DONOT_USE_CS = "default")
public IActionResult GetExportExcel(string _DONOT_USE_VMNAME, string _DONOT_USE_CS)
{
var qs = new Dictionary<string, object>();
foreach (var item in Request.Query.Keys)
@@ -226,7 +226,7 @@ namespace WalkingTec.Mvvm.Mvc
}
var instanceType = Type.GetType(_DONOT_USE_VMNAME);
Wtm.CurrentCS = (string.IsNullOrEmpty(_DONOT_USE_CS) == true) ? "default" : _DONOT_USE_CS;
Wtm.CurrentCS = _DONOT_USE_CS;
var listVM = Wtm.CreateVM(_DONOT_USE_VMNAME) as IBasePagedListVM<TopBasePoco, ISearcher>;
listVM.FC = qs;
@@ -253,9 +253,9 @@ namespace WalkingTec.Mvvm.Mvc
/// <returns></returns>
[HttpGet]
[ActionDescription("DownloadTemplate")]
public IActionResult GetExcelTemplate(string _DONOT_USE_VMNAME, string _DONOT_USE_CS = "default")
public IActionResult GetExcelTemplate(string _DONOT_USE_VMNAME, string _DONOT_USE_CS)
{
Wtm.CurrentCS = _DONOT_USE_CS ?? "default";
//Wtm.CurrentCS = _DONOT_USE_CS ?? "default";
var importVM = Wtm.CreateVM(_DONOT_USE_VMNAME) as IBaseImport<BaseTemplateVM>;
var qs = new Dictionary<string, string>();
foreach (var item in Request.Query.Keys)
@@ -325,7 +325,7 @@ namespace WalkingTec.Mvvm.Mvc
[HttpPost]
[ActionDescription("UploadFileRoute")]
public IActionResult Upload([FromServices] WtmFileProvider fp, string sm = null, string groupName = null, string subdir = null, string extra = null, bool IsTemprory = true, string _DONOT_USE_CS = "default")
public IActionResult Upload([FromServices] WtmFileProvider fp, string sm = null, string groupName = null, string subdir = null, string extra = null, bool IsTemprory = true, string _DONOT_USE_CS=null)
{
var FileData = Request.Form.Files[0];
var file = fp.Upload(FileData.FileName, FileData.Length, FileData.OpenReadStream(), groupName, subdir, extra, sm, Wtm.CreateDC(cskey: _DONOT_USE_CS));
@@ -334,7 +334,7 @@ namespace WalkingTec.Mvvm.Mvc
[HttpPost]
[ActionDescription("UploadFileRoute")]
public IActionResult UploadImage([FromServices] WtmFileProvider fp, string sm = null, string groupName = null, string subdir = null, string extra = null, bool IsTemprory = true, string _DONOT_USE_CS = "default", int? width = null, int? height = null)
public IActionResult UploadImage([FromServices] WtmFileProvider fp, string sm = null, string groupName = null, string subdir = null, string extra = null, bool IsTemprory = true, string _DONOT_USE_CS = null, int? width = null, int? height = null)
{
if (width == null && height == null)
{
@@ -368,7 +368,7 @@ namespace WalkingTec.Mvvm.Mvc
[HttpPost]
[ActionDescription("UploadForLayUIRichTextBox")]
public IActionResult UploadForLayUIRichTextBox([FromServices] WtmFileProvider fp, string _DONOT_USE_CS = "default", string groupName = null, string subdir = null)
public IActionResult UploadForLayUIRichTextBox([FromServices] WtmFileProvider fp, string _DONOT_USE_CS = null, string groupName = null, string subdir = null)
{
var FileData = Request.Form.Files[0];
var file = fp.Upload(FileData.FileName, FileData.Length, FileData.OpenReadStream(), groupName, subdir, dc: Wtm.CreateDC(cskey: _DONOT_USE_CS));
@@ -387,13 +387,13 @@ namespace WalkingTec.Mvvm.Mvc
}
[ActionDescription("GetFileName")]
public IActionResult GetFileName([FromServices] WtmFileProvider fp, Guid id, string _DONOT_USE_CS = "default")
public IActionResult GetFileName([FromServices] WtmFileProvider fp, Guid id, string _DONOT_USE_CS)
{
return Ok(fp.GetFileName(id.ToString(), Wtm.CreateDC(cskey: _DONOT_USE_CS)));
}
[ActionDescription("GetFile")]
public async Task<IActionResult> GetFile([FromServices] WtmFileProvider fp, string id, bool stream = false, string _DONOT_USE_CS = "default", int? width = null, int? height = null)
public async Task<IActionResult> GetFile([FromServices] WtmFileProvider fp, string id, bool stream = false, string _DONOT_USE_CS = null, int? width = null, int? height = null)
{
var file = fp.GetFile(id, true, Wtm.CreateDC(cskey: _DONOT_USE_CS));
if (file == null)
@@ -463,7 +463,7 @@ namespace WalkingTec.Mvvm.Mvc
}
[ActionDescription("ViewFile")]
public IActionResult ViewFile([FromServices] WtmFileProvider fp, string id, string width, string _DONOT_USE_CS = "default")
public IActionResult ViewFile([FromServices] WtmFileProvider fp, string id, string width, string _DONOT_USE_CS = null)
{
var file = fp.GetFile(id, false, Wtm.CreateDC(cskey: _DONOT_USE_CS));
string html = string.Empty;
+145 -72
View File
@@ -162,37 +162,45 @@ window.ff = {
if (para !== undefined) {
getpost = "Post";
}
$.ajax({
type: getpost,
url: url,
data: para,
success: function (data, textStatus, request) {
if (request.getResponseHeader('IsScript') === 'true') {
eval(data);
}
else {
data = '<div class="layui-card donotuse_pdiv"><div class="layui-card-body donotuse_pdiv" id=\"' + $.cookie("divid") + '\" >' + data + "</div></div>";
var child = window.open("/Home/PIndex#/_framework/redirect");
child.document.close();
$(child.document).ready(function () {
setTimeout(function () {
$('#LAY_app_body', child.document).html(data);
$(child.document).attr("title", title);
}, 500);
});
}
layer.close(index);
},
error: function (a, b, c) {
layer.close(index);
if (a.responseText !== undefined && a.responseText !== "") {
layer.alert(a.responseText);
}
else {
layer.alert(ff.DONOTUSE_Text_LoadFailed);
}
}
var child = window.open("/Home/PIndex/#" + url);
$(child.document).ready(function() {
setTimeout(function() {
$(child.document).attr("title", title);
}, 500);
});
layer.close(index);
// $.ajax({
// type: getpost,
// url: url,
// data: para,
// success: function (data, textStatus, request) {
// if (request.getResponseHeader('IsScript') === 'true') {
// eval(data);
// }
// else {
// data = '<div class="layui-card donotuse_pdiv"><div class="layui-card-body donotuse_pdiv" id=\"' + $.cookie("divid") + '\" >' + data + "</div></div>";
// var child = window.open("/Home/PIndex/#/_framework/redirect");
// child.document.close();
// $(child.document).ready(function () {
// setTimeout(function() {
// debugger;
// $('#LAY_app_body', child.document).html(data);
// $(child.document).attr("title", title);
// }, 500);
// });
// }
// layer.close(index);
// },
// error: function (a, b, c) {
// layer.close(index);
// if (a.responseText !== undefined && a.responseText !== "") {
// layer.alert(a.responseText);
// }
// else {
// layer.alert(ff.DONOTUSE_Text_LoadFailed);
// }
// }
// });
}
else {
layer.close(index);
@@ -264,7 +272,7 @@ window.ff = {
url = $("#" + formId).attr("action");
}
var d = null;
if (searchervm !== undefined && searchervm !== null && searchervm !== "") {
if ($("#" + formId).find("a[IsSearchButton]").length>0) {
d = ff.GetSearchFormData(formId, searchervm);
}
else {
@@ -553,7 +561,7 @@ window.ff = {
this.SetCookie("windowids", wids.join());
}
else {
if (layui.setter == undefined || layui.setter.pageTabs == undefined) {
if (layui.setter == undefined || layui.setter.pageTabs == undefined || window.location.href.toLocaleLowerCase().indexOf("/home/pindex/")>-1) {
window.close();
}
else if (layui.setter.pageTabs === false || $('.layadmin-tabsbody-item').length === 0) {
@@ -599,7 +607,7 @@ window.ff = {
}
},
ChainChange: function (url, self) {
ChainChange: function (url, self, usedefaultvalue) {
var form = layui.form;
var linkto = self.attributes["wtm-linkto"];
if (linkto == undefined) {
@@ -653,7 +661,11 @@ window.ff = {
var item = null;
if (controltype === "tree") {
window[comboid].update({ data: ff.getTreeItems(data.Data) });
var df = [];
if (usedefaultvalue == true) {
df = eval(comboid + "defaultvalues");
}
window[comboid].update({ data: ff.getTreeItems(data.Data,df) });
}
if (controltype === "transfer") {
layui.transfer.reload(targetid, {
@@ -662,16 +674,32 @@ window.ff = {
}
if (controltype === "combo") {
window[comboid].update({ data: ff.getComboItems(data.Data) });
var df = [];
if (usedefaultvalue == true) {
df = eval(comboid + "defaultvalues");
}
window[comboid].update({ data: ff.getComboItems(data.Data, df, usedefaultvalue) });
}
if (controltype === "checkbox") {
for (i = 0; i < data.Data.length; i++) {
item = data.Data[i];
if (item.Selected === true) {
target.append("<input type='checkbox' name = '" + targetname + "' value = '" + item.Value + "' title = '" + item.Text + "' checked />");
}
if (usedefaultvalue == true) {
var df = [];
df = eval(comboid + "defaultvalues");
if (df.indexOf(item.Value) > -1) {
target.append("<input type='checkbox' name = '" + targetname + "' value = '" + item.Value + "' title = '" + item.Text + "' checked />");
}
else {
target.append("<input type='checkbox' name = '" + targetname + "' value = '" + item.Value + "' title = '" + item.Text + "' />");
}
}
else {
target.append("<input type='checkbox' name = '" + targetname + "' value = '" + item.Value + "' title = '" + item.Text + "' />");
if (item.Selected === true) {
target.append("<input type='checkbox' name = '" + targetname + "' value = '" + item.Value + "' title = '" + item.Text + "' checked />");
}
else {
target.append("<input type='checkbox' name = '" + targetname + "' value = '" + item.Value + "' title = '" + item.Text + "' />");
}
}
}
form.render('checkbox', targetfilter);
@@ -679,11 +707,23 @@ window.ff = {
if (controltype === "radio") {
for (i = 0; i < data.Data.length; i++) {
item = data.Data[i];
if (item.Selected === true) {
target.append("<input type='radio' name = '" + targetname + "' value = '" + item.Value + "' title = '" + item.Text + "' checked />");
}
if (usedefaultvalue == true) {
var df = [];
df = eval(comboid + "defaultvalues");
if (df.indexOf(item.Value) > -1) {
target.append("<input type='radio' name = '" + targetname + "' value = '" + item.Value + "' title = '" + item.Text + "' checked />");
}
else {
target.append("<input type='radio' name = '" + targetname + "' value = '" + item.Value + "' title = '" + item.Text + "' />");
}
}
else {
target.append("<input type='radio' name = '" + targetname + "' value = '" + item.Value + "' title = '" + item.Text + "' />");
if (item.Selected === true) {
target.append("<input type='radio' name = '" + targetname + "' value = '" + item.Value + "' title = '" + item.Text + "' checked />");
}
else {
target.append("<input type='radio' name = '" + targetname + "' value = '" + item.Value + "' title = '" + item.Text + "' />");
}
}
}
form.render('radio', targetfilter);
@@ -727,6 +767,7 @@ window.ff = {
window[controlid].update({ data: da });
}
if (controltype === "checkbox") {
target[0].innerHTML = "";
for (i = 0; i < data.Data.length; i++) {
item = data.Data[i];
if (item.Selected === true || svals.indexOf(item.Value) > -1) {
@@ -787,10 +828,13 @@ window.ff = {
var tableid = tables[i].id;
var loaddata = layui.table.cache[tableid];
if (loaddata == undefined || loaddata.length == 0) {
var subpro = tables[i].attributes["subpro"].value;
if (subpro != undefined && subpro != "") {
filter[subpro + ".length"] = "0";
try {
var subpro = tables[i].attributes["subpro"].value;
if (subpro != undefined && subpro != "") {
filter[subpro + ".length"] = "0";
}
}
catch { }
}
}
@@ -823,7 +867,7 @@ window.ff = {
return;
}
var itemname = item.name;
if (/_DONOTUSE_(.*?)\[(\d?)\]\.(.*?)$/.test(itemname)) {
if (/_DONOTUSE_(.*?)\[(.*?)\]\.(.*?)$/.test(itemname)) {
var name1 = RegExp.$1;
var number = RegExp.$2;
var name2 = RegExp.$3;
@@ -840,7 +884,7 @@ window.ff = {
return;
}
var issub = false;
if (/(.*?)\[(\-?\d?)\]\.(.*?)$/.test(itemname)) {
if (/(.*?)\[(.*?)\]\.(.*?)$/.test(itemname)) {
var name1 = RegExp.$1;
var number = RegExp.$2;
var name2 = RegExp.$3;
@@ -889,13 +933,27 @@ window.ff = {
},
GetSearchFormData: function (formId, listvm) {
var data = ff.GetFormData(formId);
var data = ff.GetFormData(formId, listvm);
for (var attr in data) {
if (attr.startsWith(listvm + ".")) {
data[attr.replace(listvm + ".", "")] = data[attr];
delete data[attr];
}
}
var tc = $("#" + formId).closest("div[wtm-ctype='tc']")
if (tc.length > 0) {
var obj = eval(tc[0].id + "selected");
if (obj !== undefined && obj !== null) {
for (var item in obj) {
if (listvm == "") {
data["Searcher."+item] = obj[item];
}
else {
data[item] = obj[item];
}
}
}
}
return data;
},
@@ -906,8 +964,13 @@ window.ff = {
}
var tempwhere = {};
$.extend(tempwhere, defaultcondition);
$.extend(tempwhere, formData);
for (let item in tempwhere) {
if (item.startsWith("Searcher.") == false) {
tempwhere["Searcher." + item] = tempwhere[item];
}
}
var form = $('<form method="POST" action="' + url + '">');
for (var attr in tempwhere) {
if (tempwhere[attr] != null) {
@@ -948,7 +1011,7 @@ window.ff = {
var searcher = $('form[chartlink*="' + chartid + '"]');
if (searcher !== undefined && searcher.length > 0) {
postdata = ff.GetFormData(searcher[0].id);
postdata = ff.GetSearchFormData(searcher[0].id,"Searcher");
}
$.ajax({
cache: false,
@@ -1012,8 +1075,8 @@ window.ff = {
var re3 = /(.*?)<input hidden name='(.*?)\.id' .*?\/>(.*?)/ig;
for (val in data) {
if (typeof (data[val]) == 'string') {
data[val] = data[val].replace(/\[\d?\]/ig, "[" + loaddata.length + "]");
data[val] = data[val].replace(/_\d?_/ig, "_" + loaddata.length + "_");
data[val] = data[val].replace(/\[\d+\]/ig, "[" + loaddata.length + "]");
data[val] = data[val].replace(/_\d+_/ig, "_" + loaddata.length + "_");
data[val] = data[val].replace(re, "$1 onchange=\"ff.gridcellchange(this,'" + gridid + "'," + loaddata.length + ",'" + val + "',0)\" />$2");
data[val] = data[val].replace(re2, "$1 onchange=\"ff.gridcellchange(this,'" + gridid + "'," + loaddata.length + ",'" + val + "',1)\" >$2");
data[val] = data[val].replace(re3, "$1 <input hidden name=\"$2.id\" value='" + data["ID"] + "'/> $3");
@@ -1026,14 +1089,16 @@ window.ff = {
layui.table.render(option);
},
SetGridCellDate: function (id) {
SetGridCellDate: function (id,dt) {
layui.use('laydate', function () {
var laydate = layui.laydate;
laydate.render({
elem: '#' + id
, type: dt
, show: true
, closeStop: '#' + id
, done: function (value, date, endDate) {
document.getElementById(id).value = value;
document.getElementById(id).onchange();
}
});
@@ -1067,9 +1132,14 @@ window.ff = {
for (var i = 0; i < loaddata.length; i++) {
for (val in loaddata[i]) {
if (typeof (loaddata[i][val]) == 'string') {
loaddata[i][val] = loaddata[i][val].replace(/\[\d?\]/ig, "[" + i + "]");
loaddata[i][val] = loaddata[i][val].replace(/_\d?_/ig, "_" + i + "_");
loaddata[i][val] = loaddata[i][val].replace("/onchange=\".*?\"/", "onchange=\"ff.gridcellchange(this,'" + gridid + "'," + i + ",'" + val + "')\"");
loaddata[i][val] = loaddata[i][val].replace(/\[\d+\]/ig, "[" + i + "]");
loaddata[i][val] = loaddata[i][val].replace(/_\d+_/ig, "_" + i + "_");
if (/<input .*?\s*\/>.*?/.test(loaddata[i][val])) {
loaddata[i][val] = loaddata[i][val].replace(/onchange=\".*?\"/ig, "onchange=\"ff.gridcellchange(this,'" + gridid + "'," + i + ",'" + val + "',0)\"");
}
if (/<select .*?\s*>.*?<\/select>/.test(loaddata[i][val])) {
loaddata[i][val] = loaddata[i][val].replace(/onchange=\".*?\"/ig, "onchange=\"ff.gridcellchange(this,'" + gridid + "'," + i + ",'" + val + "',1)\"");
}
}
}
}
@@ -1178,22 +1248,24 @@ window.ff = {
return rv;
},
getComboItems: function (data, svals) {
getComboItems: function (data, svals, useDefaultvalue) {
var rv = [];
if (svals == undefined || svals == null) {
svals = [];
}
for (var i = 0; i < data.length; i++) {
var item = {};
item.value = data[i].Value;
item.name = data[i].Text;
item.disabled = data[i].Disabled;
item.selected = data[i].Selected || svals.indexOf(data[i].Value) > -1;
item.icon = data[i].Icon;
if (data[i].Children != null && data[i].Children.length > 0) {
item.children = this.getTreeItems(data[i].Children, svals);
if (data != null) {
for (var i = 0; i < data.length; i++) {
var item = {};
item.value = data[i].Value;
item.name = data[i].Text;
item.disabled = data[i].Disabled;
item.selected = useDefaultvalue == true ? svals.indexOf(data[i].Value) > -1 : data[i].Selected;
item.icon = data[i].Icon;
if (data[i].Children != null && data[i].Children.length > 0) {
item.children = this.getTreeItems(data[i].Children, svals);
}
rv.push(item);
}
rv.push(item);
}
return rv;
},
@@ -1247,12 +1319,13 @@ window.ff = {
var hidAreas = [' input[wtm-tag=wtmselector]'];
// 多选下拉框
var multiCombos = $('#' + formId + ' select[wtm-combo=MULTI_COMBO]');
var multiCombos = $('#' + formId + ' div[wtm-ctype=combo]').add($('#' + formId + ' div[wtm-ctype=tree]'));
if (multiCombos && multiCombos.length > 0) {
for (i = 0; i < multiCombos.length; i++) {
var name = multiCombos.attr('lay-filter');
hidAreas.push(" input[name='" + name + "']");
multiCombos.each(function () {
let name = $(this).attr('id');
window[name].setValue([]);
}
);
}
for (var i = 0; i < hidAreas.length; i++) {
var hiddenAreas = $('#' + formId + hidAreas[i]);
@@ -70,7 +70,7 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI.Common
public string MakeCombo(string name = null, List<ComboSelectListItem> value = null, string selectedValue = null, string emptyText = null, bool isReadOnly = false)
{
var disable = isReadOnly ? " disabled='' class='layui-disabled'" : " ";
string rv = $"<select name='{name}' id='{(name == null ? "" : Utils.GetIdByName(name))}' class='layui-input' style='height:28px' lay-ignore>";
string rv = $"<select name='{name}' id='{(name == null ? "" : Utils.GetIdByName(name))}' class='layui-input' style='height:28px' {disable} lay-ignore>";
if (string.IsNullOrEmpty(emptyText) == false)
{
rv += $@"
@@ -105,7 +105,7 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI.Common
return $@"<input class='layui-input' style='height:28px' name='{name ?? ""}' id='{(name == null ? "" : Utils.GetIdByName(name))}' value='{value ?? ""}' {disable} />";
}
public string MakeDateTime(string name = null, string value = null, string emptyText = null, bool isReadOnly = false)
public string MakeDateTime(string name = null, string value = null, string emptyText = null, bool isReadOnly = false, DateTimeTypeEnum? dateType = DateTimeTypeEnum.DateTime)
{
var id = (name == null ? "" : Utils.GetIdByName(name));
var disable = isReadOnly ? " disabled='' class='layui-disabled'" : " ";
@@ -118,7 +118,7 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI.Common
value = "";
}
}
return $@"<input class='layui-input' style='height:28px' name='{name ?? ""}' id='{id}' value='{value ?? ""}' {disable} onclick='ff.SetGridCellDate(""{id}"")'/>";
return $@"<input class='layui-input' style='height:28px' name='{name ?? ""}' id='{id}' value='{value ?? ""}' {disable} onclick='ff.SetGridCellDate(""{id}"",""{dateType.ToString().ToLower()}"")'/>";
}
@@ -82,6 +82,16 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
if (string.IsNullOrEmpty(ItemUrl) == false)
{
foreach (var item in values)
{
listItems.Add(new ComboSelectListItem
{
Text = "",
Value = item?.ToString(),
Selected = true
});
}
output.PostElement.AppendHtml($"<script>ff.LoadComboItems('checkbox','{ItemUrl}','{Id}','{Field.Name}',{JsonSerializer.Serialize(values)})</script>");
}
else
@@ -127,29 +137,6 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
});
}
}
try
{
List<string> checkvalue = null;
//如果是Entity.xxList[0].xxxid的格式,使用GetPropertySiblingValues方法获取Entity.xxxList.Select(x=>x.xxxid).ToList()的结果
if (Field.Name.Contains("["))
{
//默认多对多不必填
if (Required == null)
{
Required = false;
}
}
else if (Field.Model is IList == false && Field.Model != null)
{
checkvalue = new List<string> { Field.Model.ToString() };
}
else
{
}
}
catch
{
}
}
SetSelected(listItems, values);
}
@@ -171,7 +158,12 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
output.PostContent.AppendHtml($@"
<input type=""checkbox"" name=""{Field.Name}"" value=""{item.Value}"" title=""{item.Text}"" {selected} {(Disabled ? "disabled=\"\"" : string.Empty)}/>");
}
output.PostElement.AppendHtml($@"<input type=""hidden"" name=""_DONOTUSE_{Field.Name}"" value=""1"" />");
output.PostElement.AppendHtml($@"
<input type=""hidden"" name=""_DONOTUSE_{Field.Name}"" value=""1"" />
<script>
{Id}defaultvalues = {JsonSerializer.Serialize(values)};
</script>
");
base.Process(context, output);
}
@@ -165,6 +165,16 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
//{
// ItemUrl = _wtm.HttpContext.Request.IsHttps ? "https://" : "http://" + _wtm.HttpContext?.Request?.Host.ToString() + ItemUrl;
//}
foreach (var item in selectVal)
{
listItems.Add(new ComboSelectListItem
{
Text = "",
Value = item?.ToString(),
Selected = true
});
}
output.PostElement.AppendHtml($"<script>ff.LoadComboItems('combo','{ItemUrl}','{Id}','{Field.Name}',{JsonSerializer.Serialize(selectVal)})</script>");
}
@@ -302,7 +312,21 @@ var {Id} = xmSelect.render({{
}}" : FormatFuncName(ChangeFunc))}
}},
data: {JsonSerializer.Serialize(GetLayuiTree(listItems,selectVal))}
}})
}});
{Id}defaultvalues = {JsonSerializer.Serialize(selectVal)};
{(selectVal?.Count>0 && (LinkField != null || string.IsNullOrEmpty(LinkId) == false) ? @$"
var {Id}u = ""{(TriggerUrl ?? "")}"";
if ({Id}u.indexOf(""?"") == -1) {{
{Id}u += ""?t="" + new Date().getTime();
}}
var {Id}data = {JsonSerializer.Serialize(selectVal)};
for (var i = 0; i < {Id}data.length; i++) {{
{Id}u += ""&id="" + {Id}data[i];
}};
setTimeout(function(){{
ff.ChainChange({Id}u, $('#{Id}')[0], true);
}},100);
" : "")}
</script>
";
output.PostElement.AppendHtml(script);
@@ -4,6 +4,7 @@ using System.Text.Json;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.Options;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
namespace WalkingTec.Mvvm.TagHelpers.LayUI
{
@@ -18,34 +19,6 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
/// </summary>
EN
}
public enum DateTimeTypeEnum
{
/// <summary>
/// 日期选择器
/// 可选择:年、月、日
/// </summary>
Date,
/// <summary>
/// 日期时间选择器
/// 可选择:年、月、日、时、分、秒
/// </summary>
DateTime,
/// <summary>
/// 年选择器
/// 只提供年列表选择
/// </summary>
Year,
/// <summary>
/// 年月选择器
/// 只提供年、月选择
/// </summary>
Month,
/// <summary>
/// 时间选择器
/// 只提供时、分、秒选择
/// </summary>
Time
}
[HtmlTargetElement("wt:datetime", Attributes = REQUIRED_ATTR_NAME, TagStructure = TagStructure.WithoutEndTag)]
public class DateTimeTagHelper : BaseFieldTag
@@ -187,7 +160,7 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
RangeSplit = "~";
}
if (Field.ModelExplorer.ModelType == typeof(string))
if (Field.ModelExplorer.ModelType == typeof(string) || Field.ModelExplorer.ModelType.IsNumber())
{
Value = Field.Model?.ToString() ?? Value;
}
@@ -177,6 +177,15 @@ layui.use(['form'],function(){{
//如果是 SearchPanel,并且指定了 OldPost,则提交整个表单,而不是只刷新 Grid 数据
if (OldPost == true && this is SearchPanelTagHelper search)
{
// string addhidden = $"var form = $('#{search.Id}');";
// foreach (var item in search.GridId.Split(','))
// {
// addhidden += $@"
// for(let f in {item}defaultfilter.where){{
// form.append(""<input type='hidden' name='Searcher.""+f+""' value='""+{item}defaultfilter.where[f]+""'/>"");
// }}
//";
// }
output.PostElement.AppendHtml($@"
$('#{search.SearchBtnId}').on('click', function () {{
if({BeforeSubmit ?? "true"} == false){{return false;}}
@@ -131,7 +131,11 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
var item = listItems[i];
var selected = item.Selected ? " checked" : " ";
output.PostContent.AppendHtml($@"
<input type=""radio"" name=""{Field.Name}"" value=""{item.Value}"" title=""{item.Text}"" {selected} />");
<input type=""radio"" name=""{Field.Name}"" value=""{item.Value}"" title=""{item.Text}"" {selected} />
<script>
{Id}defaultvalues = {JsonSerializer.Serialize(values)};
</script>
");
}
base.Process(context, output);
@@ -63,7 +63,7 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
{
if (string.IsNullOrEmpty(_gridId))
{
if (string.IsNullOrEmpty(_gridIdUserSet))
if (_gridIdUserSet==null)
{
if (ListVM != null)
{
@@ -112,7 +112,7 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
/// <summary>
/// Reset button Id
/// </summary>
private string ResetBtnId => $"{RESET_BTN_ID_PREFIX}{SearcherVM.UniqueId}";
private string ResetBtnId => $"{RESET_BTN_ID_PREFIX}{SearcherVM?.UniqueId}";
/// <summary>
/// 重置按钮
@@ -17,15 +17,19 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
/// <summary>
/// 改变选择时触发的js函数,func(data)格式;
/// 文本时触发的js函数,func(data)格式;
/// <para>
/// data.Text得到选中文本;
/// </para>
/// <para>
/// data.Value得到被选中的值;
/// data得到文本;
/// </para>
/// </summary>
public string ChangeFunc { get; set; }
/// <summary>
/// 文本修改后焦点离开时触发的js函数,func(data)格式;
/// <para>
/// data得到文本;
/// </para>
/// </summary>
public string DoneFunc { get; set; }
public bool IsPassword { get; set; }
@@ -38,6 +42,15 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
output.Attributes.Add("type", type);
output.Attributes.Add("name", Field.Name);
output.Attributes.Add("wtm-name", Field.Name);
if(string.IsNullOrEmpty(ChangeFunc) == false)
{
output.Attributes.Add("oninput", $"{FormatFuncName(ChangeFunc, false)}(this.value)");
}
if (string.IsNullOrEmpty(DoneFunc) == false)
{
output.Attributes.Add("onchange", $"{FormatFuncName(DoneFunc, false)}(this.value)");
}
if (string.IsNullOrEmpty(Field?.Model?.ToString()) == false)
{
DefaultValue = null;
@@ -156,6 +156,29 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
DefaultValue = $"[{string.Join(",", DefaultValue.Split(",").Select(x => "'" + x + "'"))}]";
}
}
if (string.IsNullOrEmpty(ItemUrl) == false)
{
foreach (var item in selectVal)
{
listItems.Add(new ComboSelectListItem
{
Text = "",
Value = item?.ToString(),
Selected = true
});
}
data = listItems.Select(x => new
{
x.Value,
Title = x.Text,
x.Disabled,
Checked = x.Selected
}).ToArray();
output.PostElement.AppendHtml($"<script>ff.LoadComboItems('transfer','{ItemUrl}','{Id}','{Field.Name}',{JsonSerializer.Serialize(selectVal)})</script>");
}
var title = $"['{(string.IsNullOrEmpty(LeftTitle) ? THProgram._localizer["Sys.ForSelect"] : LeftTitle)}','{(string.IsNullOrEmpty(RightTitle) ? THProgram._localizer["Sys.Selected"] : RightTitle)}']";
var content = $@"
<script>
@@ -210,10 +233,6 @@ layui.use(['transfer'],function(){{
output.PostElement.AppendHtml(content);
output.PostElement.AppendHtml($"<div id=\"{Id}div\"></div>");
output.PostElement.AppendHtml($@"<input type=""hidden"" name=""_DONOTUSE_{Field.Name}"" value=""1"" />");
if (string.IsNullOrEmpty(ItemUrl) == false)
{
output.PostElement.AppendHtml($"<script>ff.LoadComboItems('transfer','{ItemUrl}','{Id}','{Field.Name}',{JsonSerializer.Serialize(selectVal)})</script>");
}
base.Process(context, output);
}
@@ -68,6 +68,7 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
output.TagMode = TagMode.StartTagAndEndTag;
Id = string.IsNullOrEmpty(Id) ? Guid.NewGuid().ToNoSplitString() : Id;
output.Attributes.Add("id", "top" + Id);
output.Attributes.Add("wtm-ctype", "tc");
output.Attributes.Add("class", "layui-row donotuse_fill");
if (Items.Model is List<TreeSelectListItem> mm)
{
@@ -77,32 +78,47 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
}
var inside = await output.GetChildContentAsync();
var insideContent = inside.GetContent();
string cusmtomclick = "";
var idfieldname = IdField?.Name ?? "notsetid";
idfieldname = Regex.Replace(idfieldname, ".*?Searcher\\.", "");
var levelfieldname = LevelField?.Name ?? "notsetlevel";
levelfieldname = Regex.Replace(levelfieldname, ".*?Searcher\\.", "");
string cusmtomclick = $"top{Id}selected.{idfieldname}=data.data.id;top{Id}selected.{levelfieldname}=data.data.level;";
if (string.IsNullOrEmpty(ClickFunc))
{
Regex r = new Regex("(.*?)option = {");
var m = r.Match(insideContent);
if (m.Success)
Regex r3 = new Regex("id=\"(.*?)\" IsSearchButton");
var m3 = r3.Match(insideContent);
if (m3.Success)
{
var gridid = m.Groups[1].Value.Trim();
Regex r2 = new Regex($"(.*?) = table.render\\({gridid}option\\);");
var m2 = r2.Match(insideContent);
if (m2.Success)
cusmtomclick += $@"
$('#{m3.Groups[1].Value.Trim()}').click();
";
}
else
{
Regex r = new Regex("(.*?)option = {");
var m = r.Match(insideContent);
if (m.Success)
{
var gridvar = m2.Groups[1].Value.Trim();
var idfieldname = IdField?.Name ?? "notsetid";
idfieldname = Regex.Replace(idfieldname, ".*?Searcher\\.","");
var levelfieldname = LevelField?.Name ?? "notsetlevel";
levelfieldname = Regex.Replace(levelfieldname, ".*?Searcher\\.", "");
cusmtomclick = $@"
var gridid = m.Groups[1].Value.Trim();
Regex r2 = new Regex($"(.*?) = table.render\\({gridid}option\\);");
var m2 = r2.Match(insideContent);
if (m2.Success)
{
var gridvar = m2.Groups[1].Value.Trim();
cusmtomclick = $@"
$.extend({gridid}defaultfilter.where,{{'{idfieldname}':data.data.id, '{levelfieldname}':data.data.level }});
";
}
cusmtomclick += $@"
layui.table.reload('{gridid}',{{url:{gridid}url, where: {gridid}defaultfilter.where}});
";
}
else if (string.IsNullOrEmpty(insideContent))
{
cusmtomclick = $"if(data.data.href!=null && data.data.href!=''){{ff.LoadPage1(data.data.href,'div_{Id}');}}";
}
}
else if (string.IsNullOrEmpty(insideContent))
{
cusmtomclick = $"if(data.data.href!=null && data.data.href!=''){{ff.LoadPage1(data.data.href,'div_{Id}');}}";
}
}
else
@@ -132,6 +148,27 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
last{Id} = ele;
}}
{cusmtomclick}
}}
,setSelected: function(data){{
var ele = null;
if(data.elem != undefined){{
ele = data.elem.find('.layui-tree-main:first');
}}
else{{
ele = $('#div{Id}').find(""div[data-id='""+data.data.id+""']"").find('.layui-tree-main:first');
}}
if(last{Id} != null){{
last{Id}.css('background-color','');
last{Id}.find('.layui-tree-txt').css('color','');
}}
if(last{Id} === ele){{
last{Id} = null;
}}
else{{
ele.css('background-color','#5fb878');
ele.find('.layui-tree-txt').css('color','#fff');
last{Id} = ele;
}}
}}";
var selecteditem = GetSelectedItem(treeitems);
@@ -144,6 +181,13 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
</div>
<div id=""div_{Id}"" style=""box-sizing:border-box"" class=""layui-col-md10 donotuse_pdiv"">{insideContent}</div>
<script>
var top{Id}selected = {{}};
{
(selecteditem==null?"": @$"
top{Id}selected.{idfieldname} = '{selecteditem.Id}';
top{Id}selected.{levelfieldname} = {selecteditem.Level};
")
}
layui.use(['tree'],function(){{
var last{Id} = null;
var treecontainer{Id} = layui.tree.render({{
@@ -151,7 +195,7 @@ layui.use(['tree'],function(){{
{onclick}
,data: {JsonSerializer.Serialize(treeitems)}
}});
{(selecteditem == null ? string.Empty : $@"treecontainer{Id}.config.click({{
{(selecteditem == null ? string.Empty : $@"treecontainer{Id}.config.setSelected({{
data: {JsonSerializer.Serialize(selecteditem)}
}});")}
{(string.IsNullOrEmpty(AutoLoadUrl) || selecteditem != null ? string.Empty : $"ff.LoadPage1('{AutoLoadUrl}','div_{Id}');")}
@@ -199,7 +243,7 @@ layui.use(['tree'],function(){{
{
foreach (var item in tree)
{
if (item.Checked == true)
if (item.Id == IdField.Model?.ToString())
{
return item;
}
@@ -68,8 +68,21 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
output.Attributes.Add("wtm-name", Field.Name);
output.Attributes.Add("wtm-multi", MultiSelect.ToString().ToLower());
Id = string.IsNullOrEmpty(Id) ? Guid.NewGuid().ToNoSplitString() : Id;
if (LinkField != null || string.IsNullOrEmpty(LinkId) == false)
{
var linkto = "";
if (string.IsNullOrEmpty(LinkId))
{
linkto = Core.Utils.GetIdByName(LinkField.ModelExplorer.Container.ModelType.Name + "." + LinkField.Name);
}
else
{
linkto = LinkId;
}
output.Attributes.Add("wtm-linkto", $"{linkto}");
}
List<object> vals = new List<object>();
List<object> vals = new List<object>();
if (Field?.Model != null)
{
if (MultiSelect == true)
@@ -84,13 +97,41 @@ namespace WalkingTec.Mvvm.TagHelpers.LayUI
vals.Add(Field.Model.ToString());
}
}
List<LayuiTreeItem> treeitems = new List<LayuiTreeItem>();
if (vals.Count == 0)
{
if (string.IsNullOrEmpty(DefaultValue) == false)
{
vals.AddRange(DefaultValue.Split(','));
}
}
List<LayuiTreeItem> treeitems = new List<LayuiTreeItem>();
if (string.IsNullOrEmpty(ItemUrl) == true && Items?.Model is List<TreeSelectListItem> mm)
{
treeitems = GetLayuiTree(mm, vals);
}
var script = $@"
if (string.IsNullOrEmpty(ItemUrl) == false)
{
foreach (var item in vals)
{
treeitems.Add(new LayuiTreeItem
{
Title = "",
Id = item?.ToString(),
Checked = true
});
}
output.PostElement.AppendHtml($@"<script>
ff.LoadComboItems('tree','{ItemUrl}','{Id}','{Field.Name}',{JsonSerializer.Serialize(vals)},function(){{
}})
</script>");
}
var script = $@"
<script>
var {Id} = xmSelect.render({{
el: '#{Id}',
@@ -143,8 +184,8 @@ var {Id} = xmSelect.render({{
}},
}},
}}
}},
")} tree: {{
}},")}
tree: {{
strict: false,
show: true,
showFolderIcon: true,
@@ -166,18 +207,25 @@ var {Id} = xmSelect.render({{
}}" : FormatFuncName(ChangeFunc))}
}},
data: {JsonSerializer.Serialize(treeitems)}
}})
}});
{Id}defaultvalues = {JsonSerializer.Serialize(vals)};
{(vals?.Count > 0 && (LinkField != null || string.IsNullOrEmpty(LinkId) == false) ? @$"
var {Id}u = ""{(TriggerUrl ?? "")}"";
if ({Id}u.indexOf(""?"") == -1) {{
{Id}u += ""?t="" + new Date().getTime();
}}
var {Id}data = {JsonSerializer.Serialize(vals)};
for (var i = 0; i < {Id}data.length; i++) {{
{Id}u += ""&id="" + {Id}data[i];
}};
setTimeout(function(){{
ff.ChainChange({Id}u, $('#{Id}')[0], true);
}},100);
" : "")}
</script>
";
output.PostElement.AppendHtml(script);
if (string.IsNullOrEmpty(ItemUrl) == false)
{
output.PostElement.AppendHtml($@"<script>
ff.LoadComboItems('tree','{ItemUrl}','{Id}','{Field.Name}',{JsonSerializer.Serialize(vals)},function(){{
}})
</script>");
}
string hidden = $"<p id='tree{Id}hidden'>";
if (Field?.Model != null)
{