增加Prism 框架
This commit is contained in:
1 parent
2cd6b8db86
commit
726eb6de16
99 files changed
+12527
No files matched your search
@@ -0,0 +1,35 @@
|
||||
using System.Text;
|
||||
|
||||
namespace MAX.Framework.Commons
|
||||
{
|
||||
public struct KeyValue
|
||||
{
|
||||
public KeyValue(string key, string value)
|
||||
{
|
||||
Key = key;
|
||||
Value = value;
|
||||
}
|
||||
|
||||
public string Key { get; set; }
|
||||
public string Value { get; set; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
stringBuilder.Append('[');
|
||||
if (Key != null)
|
||||
{
|
||||
stringBuilder.Append(Key.ToString());
|
||||
}
|
||||
|
||||
stringBuilder.Append(", ");
|
||||
if (Value != null)
|
||||
{
|
||||
stringBuilder.Append(Value.ToString());
|
||||
}
|
||||
|
||||
stringBuilder.Append(']');
|
||||
return stringBuilder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using Newtonsoft.Json;
|
||||
using ConfigHelper = MAX.Framework.Helpers.ConfigHelper;
|
||||
|
||||
namespace MAX.Framework.Configs
|
||||
{
|
||||
public abstract class ConfigBase
|
||||
{
|
||||
[JsonIgnore]
|
||||
public abstract string ConfigName { get; }
|
||||
}
|
||||
/// <summary>
|
||||
/// 设置
|
||||
/// </summary>
|
||||
public abstract class ConfigBase<TConfig> : ConfigBase where TConfig : ConfigBase, new()
|
||||
{
|
||||
private static TConfig mySelf;//= default(T);
|
||||
public static TConfig Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (mySelf == null)
|
||||
{
|
||||
mySelf = new TConfig();
|
||||
}
|
||||
|
||||
return mySelf;
|
||||
}
|
||||
}
|
||||
|
||||
public static TConfig LoadConfig()
|
||||
{
|
||||
try
|
||||
{
|
||||
TConfig config = ConfigHelper.LoadConfig<TConfig>();
|
||||
mySelf = config;
|
||||
return mySelf;
|
||||
}
|
||||
catch { }
|
||||
return default;
|
||||
}
|
||||
public void SaveConfig()
|
||||
{
|
||||
ConfigHelper.SaveConfig(ConfigName, this);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace MAX.Framework
|
||||
{
|
||||
/// <summary>
|
||||
/// 全局配置
|
||||
/// </summary>
|
||||
public class GlobalConfig
|
||||
{
|
||||
/// <summary>
|
||||
/// 数据库名
|
||||
/// </summary>
|
||||
public const string DbName = "db.db";
|
||||
|
||||
/// <summary>
|
||||
/// app启动路径
|
||||
/// </summary>
|
||||
public static string AppDirectory
|
||||
{
|
||||
get
|
||||
{
|
||||
return AppDomain.CurrentDomain.BaseDirectory;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
using MAX.Framework.Commons;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
namespace MAX.Framework.Helpers
|
||||
{
|
||||
/// <summary>
|
||||
/// App 配置
|
||||
/// </summary>
|
||||
public class AppConfigHelper
|
||||
{
|
||||
public static string exeConfigPath = Assembly.GetEntryAssembly()?.Location ?? "";
|
||||
|
||||
public static string GetConnectionString(string name)
|
||||
{
|
||||
Configuration config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
|
||||
string connection = config.ConnectionStrings.ConnectionStrings[name].ConnectionString ?? "";
|
||||
//string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
|
||||
return connection;
|
||||
}
|
||||
///<summary>
|
||||
///返回*.exe.config文件中appSettings配置节的value项
|
||||
///</summary>
|
||||
///<param name="strKey"></param>
|
||||
///<returns></returns>
|
||||
public static TValue GetAppConfig<TValue>(string strKey, TValue def = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
string value = GetAppConfig(strKey);
|
||||
return MAX.Core.Helpers.Convert.To<TValue>(value);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return def;
|
||||
}
|
||||
}
|
||||
///<summary>
|
||||
///返回*.exe.config文件中appSettings配置节的value项
|
||||
///</summary>
|
||||
///<param name="strKey"></param>
|
||||
///<returns></returns>
|
||||
public static string GetAppConfig(string strKey)
|
||||
{
|
||||
Configuration config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
|
||||
foreach (string key in config.AppSettings.Settings.AllKeys)
|
||||
{
|
||||
if (key == strKey)
|
||||
{
|
||||
return config.AppSettings.Settings[strKey].Value.ToString();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public static List<KeyValue> GetAppSettings()
|
||||
{
|
||||
Configuration config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
|
||||
List<KeyValue> settings = new List<KeyValue>();
|
||||
foreach (string key in config.AppSettings.Settings.AllKeys)
|
||||
{
|
||||
settings.Add(new KeyValue(key, config.AppSettings.Settings[key].Value));
|
||||
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
///<summary>
|
||||
///在*.exe.config文件中appSettings配置节增加一对键值对
|
||||
///</summary>
|
||||
///<param name="newKey"></param>
|
||||
///<param name="newValue"></param>
|
||||
public static void UpdateAppConfig(string newKey, string newValue)
|
||||
{
|
||||
Configuration config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
|
||||
bool exist = false;
|
||||
foreach (string key in config.AppSettings.Settings.AllKeys)
|
||||
{
|
||||
if (key == newKey)
|
||||
{
|
||||
exist = true;
|
||||
}
|
||||
}
|
||||
if (exist)
|
||||
{
|
||||
config.AppSettings.Settings.Remove(newKey);
|
||||
}
|
||||
config.AppSettings.Settings.Add(newKey, newValue);
|
||||
config.Save(ConfigurationSaveMode.Modified);
|
||||
ConfigurationManager.RefreshSection("appSettings");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 静态类型写入配置文件信息
|
||||
/// 名称相同
|
||||
/// </summary>
|
||||
/// <param name="appType"></param>
|
||||
public static void SetAppConfig(Type appType)
|
||||
{
|
||||
PropertyInfo[] props = appType.GetProperties(BindingFlags.Static | BindingFlags.Public);
|
||||
List<KeyValue> settings = GetAppSettings();
|
||||
foreach (KeyValue item in settings)
|
||||
{
|
||||
try
|
||||
{
|
||||
PropertyInfo prop = props.FirstOrDefault(a => a.Name.ToLower() == item.Key.ToLower());
|
||||
if (prop != null)
|
||||
{
|
||||
object value = Core.Helpers.Convert.To(prop.PropertyType, item.Value);
|
||||
prop.SetValue(null, value);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 静态配置文件信息写入到配置文件中
|
||||
/// 只写入配置文件中存在的配置项中
|
||||
/// </summary>
|
||||
/// <param name="appType"></param>
|
||||
public static void UpdateAppConfig(Type appType)
|
||||
{
|
||||
PropertyInfo[] props = appType.GetProperties(BindingFlags.Static | BindingFlags.Public);
|
||||
List<KeyValue> settings = GetAppSettings();
|
||||
foreach (KeyValue item in settings)
|
||||
{
|
||||
try
|
||||
{
|
||||
PropertyInfo prop = props.FirstOrDefault(a => a.Name.ToLower() == item.Key.ToLower());
|
||||
if (prop != null)
|
||||
{
|
||||
object value = prop.GetValue(null);
|
||||
if (value?.ToString().ToLower() == item.Value.ToLower())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
UpdateAppConfig(item.Key, value?.ToString());
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
using MAX.Core.DependencyInjection;
|
||||
using MAX.Framework.Configs;
|
||||
using MAX.Framework.Interfaces;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace MAX.Framework.Helpers
|
||||
{
|
||||
/// <summary>
|
||||
/// 配置
|
||||
/// </summary>
|
||||
public class ConfigHelper
|
||||
{
|
||||
private static IFolderConfig _folderConfig = LazyServiceProvider.Instance.LazyGetService<IFolderConfig>();
|
||||
public static string prvategp = "4Z-zy_VP";//pIuEFX-0-OZm%tP2qtKw
|
||||
public static T LoadConfig<T>() where T : ConfigBase
|
||||
{
|
||||
string filename = Activator.CreateInstance<T>().ConfigName;
|
||||
return LoadConfig<T>(filename);
|
||||
}
|
||||
|
||||
public static T LoadConfig<T>(string fileName) where T : ConfigBase
|
||||
{
|
||||
try
|
||||
{
|
||||
string filePath = GetConfigUserPath(fileName);
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
string content = File.ReadAllText(filePath, Encoding.UTF8);
|
||||
return JsonConvert.DeserializeObject<T>(content);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return default;
|
||||
}
|
||||
|
||||
public static void SaveConfig<T>(T config) where T : ConfigBase
|
||||
{
|
||||
string filename = Activator.CreateInstance<T>().ConfigName;
|
||||
SaveConfig(filename, config);
|
||||
}
|
||||
|
||||
public static void SaveConfig<T>(string fileName, T config) where T : ConfigBase
|
||||
{
|
||||
try
|
||||
{
|
||||
string filePath = GetConfigUserPath(fileName);
|
||||
FileHelper.CreateDirectory(filePath);
|
||||
string content = JsonConvert.SerializeObject(config);
|
||||
File.WriteAllText(filePath, content, Encoding.UTF8);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
public static void SaveConfig(string fileName, string content)
|
||||
{
|
||||
try
|
||||
{
|
||||
string filePath = GetConfigUserPath(fileName);
|
||||
FileHelper.CreateDirectory(filePath);
|
||||
File.WriteAllText(filePath, content, Encoding.UTF8);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
public static string GetConfigUserPath(string fileName)
|
||||
{
|
||||
string filePath = Path.Combine(_folderConfig.LocalAppFolder, "config", fileName);
|
||||
return filePath;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace MAX.Framework.Helpers
|
||||
{
|
||||
/// <summary>
|
||||
/// 文件操作帮助类
|
||||
/// </summary>
|
||||
public class FileHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取文件MD5值
|
||||
/// </summary>
|
||||
/// <param name="FilePath"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetFileMd5(string FilePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
FileStream get_file = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||||
System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
|
||||
byte[] hash_byte = get_md5.ComputeHash(get_file);
|
||||
string resule = BitConverter.ToString(hash_byte);
|
||||
resule = resule.Replace("-", "");
|
||||
get_file.Close();
|
||||
return resule;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return e.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取所有内容 相对路径Or绝对路径
|
||||
/// </summary>
|
||||
/// <param name="file"></param>
|
||||
/// <returns></returns>
|
||||
public static string ReadAllText(string file)
|
||||
{
|
||||
if (!Path.IsPathRooted(file))
|
||||
{
|
||||
file = Path.Combine(GlobalConfig.AppDirectory, file);
|
||||
}
|
||||
if (File.Exists(file))
|
||||
{
|
||||
return _ReadAllText(file, Encoding.UTF8);
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
/// <summary>
|
||||
/// 读取所有内容 绝对路径
|
||||
/// </summary>
|
||||
/// <param name="file"></param>
|
||||
/// <returns></returns>
|
||||
public static string ReadAbsAllText(string file)
|
||||
{
|
||||
return _ReadAllText(file, Encoding.UTF8);
|
||||
}
|
||||
/// <summary>
|
||||
/// 读取所有内容 相对路径
|
||||
/// </summary>
|
||||
/// <param name="file"></param>
|
||||
/// <returns></returns>
|
||||
public static string ReadPartialAllText(string file)
|
||||
{
|
||||
string _file = Path.Combine(GlobalConfig.AppDirectory, file);
|
||||
return _ReadAllText(_file, Encoding.UTF8);
|
||||
}
|
||||
|
||||
private static string _ReadAllText(string file, Encoding encoding)
|
||||
{
|
||||
if (File.Exists(file))
|
||||
{
|
||||
return File.ReadAllText(file, encoding);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception($"缺失文件{file}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建目录
|
||||
/// </summary>
|
||||
/// <param name="dir"></param>
|
||||
public static void CreateDirectory(string dir)
|
||||
{
|
||||
if (Path.HasExtension(dir))
|
||||
{
|
||||
dir = Path.GetDirectoryName(dir);
|
||||
}
|
||||
if (!Directory.Exists(dir))
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
}
|
||||
}
|
||||
|
||||
public static bool DeleteDirectory(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(path, true);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void CopyDirectory(string sourceDir, string destinationDir, bool recursive = true)
|
||||
{
|
||||
// Get information about the source directory
|
||||
DirectoryInfo dir = new DirectoryInfo(sourceDir);
|
||||
|
||||
// Check if the source directory exists
|
||||
if (!dir.Exists)
|
||||
{
|
||||
throw new DirectoryNotFoundException($"Source directory not found: {dir.FullName}");
|
||||
}
|
||||
|
||||
// Cache directories before we start copying
|
||||
DirectoryInfo[] dirs = dir.GetDirectories();
|
||||
|
||||
// Create the destination directory
|
||||
Directory.CreateDirectory(destinationDir);
|
||||
|
||||
// Get the files in the source directory and copy to the destination directory
|
||||
foreach (FileInfo file in dir.GetFiles())
|
||||
{
|
||||
string targetFilePath = Path.Combine(destinationDir, file.Name);
|
||||
file.CopyTo(targetFilePath);
|
||||
}
|
||||
|
||||
// If recursive and copying subdirectories, recursively call this method
|
||||
if (recursive)
|
||||
{
|
||||
foreach (DirectoryInfo subDir in dirs)
|
||||
{
|
||||
string newDestinationDir = Path.Combine(destinationDir, subDir.Name);
|
||||
CopyDirectory(subDir.FullName, newDestinationDir, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取文件夹大小
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <returns></returns>
|
||||
public static long GetDirectorySize(string path)
|
||||
{
|
||||
long result = 0;
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(path))
|
||||
{
|
||||
dynamic fso = Activator.CreateInstance(Type.GetTypeFromProgID("Scripting.FileSystemObject"));
|
||||
dynamic fldr = fso.GetFolder(path);
|
||||
result = (long)fldr.size;
|
||||
}
|
||||
else
|
||||
{
|
||||
result = 0;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
result = 0;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,77 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
|
||||
namespace MAX.Framework.Helpers
|
||||
{
|
||||
public static class ObjectHelper
|
||||
{
|
||||
private static readonly ConcurrentDictionary<string, PropertyInfo> CachedObjectProperties =
|
||||
new ConcurrentDictionary<string, PropertyInfo>();
|
||||
|
||||
public static void TrySetProperty<TObject, TValue>(
|
||||
TObject obj,
|
||||
Expression<Func<TObject, TValue>> propertySelector,
|
||||
Func<TValue> valueFactory,
|
||||
params Type[] ignoreAttributeTypes
|
||||
)
|
||||
{
|
||||
TrySetProperty(obj, propertySelector, x => valueFactory(), ignoreAttributeTypes);
|
||||
}
|
||||
|
||||
public static void TrySetProperty<TObject, TValue>(
|
||||
TObject obj,
|
||||
Expression<Func<TObject, TValue>> propertySelector,
|
||||
Func<TObject, TValue> valueFactory,
|
||||
params Type[] ignoreAttributeTypes
|
||||
)
|
||||
{
|
||||
string cacheKey =
|
||||
$"{obj?.GetType().FullName}-"
|
||||
+ $"{propertySelector}-"
|
||||
+ $"{(ignoreAttributeTypes != null ? "-" + string.Join("-", ignoreAttributeTypes.Select(x => x.FullName)) : "")}";
|
||||
|
||||
PropertyInfo property = CachedObjectProperties.GetOrAdd(
|
||||
cacheKey,
|
||||
(name) =>
|
||||
{
|
||||
if (propertySelector.Body.NodeType != ExpressionType.MemberAccess)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
MemberExpression memberExpression = (MemberExpression)propertySelector.Body;
|
||||
|
||||
PropertyInfo propertyInfo = obj?.GetType()
|
||||
.GetProperties()
|
||||
.FirstOrDefault(
|
||||
x =>
|
||||
x.Name == memberExpression.Member.Name
|
||||
&& x.GetSetMethod(true) != null
|
||||
);
|
||||
|
||||
if (propertyInfo == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
ignoreAttributeTypes != null
|
||||
&& ignoreAttributeTypes.Any(
|
||||
ignoreAttribute => propertyInfo.IsDefined(ignoreAttribute, true)
|
||||
)
|
||||
)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return propertyInfo;
|
||||
}
|
||||
);
|
||||
|
||||
property?.SetValue(obj, valueFactory(obj));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MAX.Framework.Helpers;
|
||||
public class StringTypeHelper
|
||||
{
|
||||
public static object ConvertToObject(string input, out Type type)
|
||||
{
|
||||
type = typeof(string);
|
||||
object value = input;
|
||||
|
||||
// 1. 检查布尔值(支持多种表示形式)
|
||||
if (IsBoolean(input, out bool boolValue))
|
||||
{
|
||||
type = typeof(bool);
|
||||
value = boolValue;
|
||||
return value;
|
||||
}
|
||||
|
||||
// 2. 检查整数
|
||||
if (int.TryParse(input, NumberStyles.Integer, CultureInfo.InvariantCulture, out int intValue))
|
||||
{
|
||||
type = typeof(int);
|
||||
value = intValue;
|
||||
return value;
|
||||
}
|
||||
|
||||
// 3. 检查无符号整数
|
||||
if (ulong.TryParse(input, NumberStyles.Integer, CultureInfo.InvariantCulture, out ulong ulongValue))
|
||||
{
|
||||
type = typeof(ulong);
|
||||
value = ulongValue;
|
||||
return value;
|
||||
}
|
||||
|
||||
// 4. 检查双精度浮点数
|
||||
if (double.TryParse(input, NumberStyles.Number | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent,
|
||||
CultureInfo.InvariantCulture, out double doubleValue))
|
||||
{
|
||||
type = typeof(double);
|
||||
value = doubleValue;
|
||||
return value;
|
||||
}
|
||||
|
||||
// 5. 检查十进制数
|
||||
if (decimal.TryParse(input, NumberStyles.Number | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent,
|
||||
CultureInfo.InvariantCulture, out decimal decimalValue))
|
||||
{
|
||||
type = typeof(decimal);
|
||||
value = decimalValue;
|
||||
return value;
|
||||
}
|
||||
|
||||
// 6. 检查日期时间
|
||||
if (IsDateTime(input, out DateTime dateTimeValue))
|
||||
{
|
||||
type = typeof(DateTime);
|
||||
value = dateTimeValue;
|
||||
return value;
|
||||
}
|
||||
|
||||
// 7. 检查null
|
||||
if (input == null)
|
||||
{
|
||||
type = typeof(string);
|
||||
value = null;
|
||||
return value;
|
||||
}
|
||||
|
||||
// 8. 默认返回字符串类型
|
||||
type = typeof(string);
|
||||
return value;
|
||||
}
|
||||
|
||||
|
||||
private static bool IsBoolean(string input, out bool boolValue)
|
||||
{
|
||||
boolValue = false;
|
||||
// 支持多种布尔值表示形式
|
||||
if (input.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase) ||
|
||||
input.Equals(bool.FalseString, StringComparison.OrdinalIgnoreCase) ||
|
||||
input.Equals("t", StringComparison.OrdinalIgnoreCase) ||
|
||||
input.Equals("f", StringComparison.OrdinalIgnoreCase) ||
|
||||
input.Equals("1", StringComparison.Ordinal) ||
|
||||
input.Equals("0", StringComparison.Ordinal) ||
|
||||
input.Equals("yes", StringComparison.OrdinalIgnoreCase) ||
|
||||
input.Equals("no", StringComparison.OrdinalIgnoreCase) ||
|
||||
input.Equals("真", StringComparison.Ordinal) ||
|
||||
input.Equals("假", StringComparison.Ordinal))
|
||||
{
|
||||
boolValue = input.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase) ||
|
||||
input.Equals("t", StringComparison.OrdinalIgnoreCase) ||
|
||||
input.Equals("1", StringComparison.Ordinal) ||
|
||||
input.Equals("yes", StringComparison.OrdinalIgnoreCase) ||
|
||||
input.Equals("真", StringComparison.Ordinal);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsDateTime(string input, out DateTime dateTimeValue)
|
||||
{
|
||||
dateTimeValue = default;
|
||||
// 首先尝试使用默认的DateTime.TryParse进行解析
|
||||
if (DateTime.TryParse(input, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dateTime))
|
||||
{
|
||||
dateTimeValue = dateTime;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 如果解析失败,尝试使用不同的格式字符串进行解析
|
||||
string[] formats = {
|
||||
"yyyy-MM-dd",
|
||||
"yyyy/MM/dd",
|
||||
"yyyy.MM.dd",
|
||||
"yyyyMMdd",
|
||||
"yyyy-MM-dd HH:mm",
|
||||
"yyyy/MM/dd HH:mm",
|
||||
"yyyy.MM.dd HH:mm",
|
||||
"yyyy-MM-dd HH:mm:ss",
|
||||
"yyyy/MM/dd HH:mm:ss",
|
||||
"yyyy.MM.dd HH:mm:ss",
|
||||
"yyyy-MM-dd HH:mm:ss.fff",
|
||||
"yyyy-MM-ddTHH:mm:ss.fffK" // 支持ISO 8601格式带时区
|
||||
};
|
||||
|
||||
// 使用TryParseExact尝试解析,提供多种格式字符串
|
||||
foreach (string format in formats)
|
||||
{
|
||||
if (DateTime.TryParseExact(input, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
|
||||
{
|
||||
dateTimeValue = dateTime;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using MAX.Core.Commons;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
namespace MAX.Framework.Helpers
|
||||
{
|
||||
public class WinCmdHelper
|
||||
{
|
||||
#region 执行Dos命令
|
||||
|
||||
/// <summary>
|
||||
/// 执行Dos命令
|
||||
/// </summary>
|
||||
/// <param name="cmd">Dos命令及参数</param>
|
||||
/// <param name="isShowCmdWindow">是否显示cmd窗口</param>
|
||||
/// <param name="isCloseCmdProcess">执行完毕后是否关闭cmd进程</param>
|
||||
/// <returns>成功返回true,失败返回false</returns>
|
||||
public static Result ExcuteDosCommand(string cmd, string workdir, bool isShowCmdWindow = false, bool isWaitForExit = false, bool isCloseCmdProcess = true)
|
||||
{
|
||||
Result result = new Result();
|
||||
try
|
||||
{
|
||||
StringBuilder errString = new StringBuilder();
|
||||
StringBuilder outString = new StringBuilder();
|
||||
Process p = new Process();
|
||||
p.StartInfo.FileName = "cmd";
|
||||
p.StartInfo.WorkingDirectory = workdir;
|
||||
p.StartInfo.Arguments = "/c " + cmd;
|
||||
p.StartInfo.StandardOutputEncoding = Encoding.UTF8;
|
||||
p.StartInfo.StandardErrorEncoding = Encoding.UTF8;
|
||||
p.StartInfo.UseShellExecute = false;
|
||||
p.StartInfo.RedirectStandardOutput = true;
|
||||
p.StartInfo.RedirectStandardError = true;
|
||||
p.StartInfo.CreateNoWindow = !isShowCmdWindow;
|
||||
p.OutputDataReceived += new DataReceivedEventHandler(delegate (object sender, DataReceivedEventArgs e)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(e.Data))
|
||||
{
|
||||
outString.AppendLine(e.Data);
|
||||
Debug.WriteLine(e.Data);
|
||||
}
|
||||
});
|
||||
p.ErrorDataReceived += new DataReceivedEventHandler(delegate (object sender, DataReceivedEventArgs e)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(e.Data))
|
||||
{
|
||||
errString.AppendLine(e.Data);
|
||||
}
|
||||
});
|
||||
p.Start();
|
||||
p.BeginOutputReadLine();
|
||||
p.BeginErrorReadLine();
|
||||
if (isWaitForExit)
|
||||
{
|
||||
p.WaitForExit();
|
||||
}
|
||||
|
||||
if (isCloseCmdProcess)
|
||||
{
|
||||
p.Close();
|
||||
}
|
||||
if (errString.Length <= 0)
|
||||
{
|
||||
result.Success = true;
|
||||
result.Data = outString.ToString();
|
||||
}
|
||||
Console.WriteLine(string.Format("成功执行Dos命令[{0}]!", cmd));
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("执行命令失败,请检查输入的命令是否正确:" + ex.Message, ex);
|
||||
result.Msg = ex.Message;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void P_ErrorDataReceived(object sender, DataReceivedEventArgs e)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 判断指定的进程是否在运行中
|
||||
|
||||
/// <summary>
|
||||
/// 判断指定的进程是否在运行中
|
||||
/// </summary>
|
||||
/// <param name="processName">要判断的进程名称,不包括扩展名exe</param>
|
||||
/// <param name="processFileName">进程文件的完整路径</param>
|
||||
/// <returns>存在返回true,否则返回false</returns>
|
||||
public static bool CheckProcessExists(string processName, string processFileName)
|
||||
{
|
||||
Process[] processes = Process.GetProcessesByName(processName);
|
||||
foreach (Process p in processes)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(processFileName))
|
||||
{
|
||||
if (processFileName == p?.MainModule?.FileName)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 结束指定的windows进程
|
||||
|
||||
/// <summary>
|
||||
/// 结束指定的windows进程,如果进程存在
|
||||
/// </summary>
|
||||
/// <param name="processName">进程名称,不包含扩展名</param>
|
||||
/// <param name="processFileName">进程文件完整路径,如果为空则删除所有进程名为processName参数值的进程</param>
|
||||
public static bool KillProcessExists(string processName, string processFileName)
|
||||
{
|
||||
try
|
||||
{
|
||||
Process[] processes = Process.GetProcessesByName(processName);
|
||||
foreach (Process p in processes)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(processFileName))
|
||||
{
|
||||
if (processFileName == p.MainModule.FileName)
|
||||
{
|
||||
p.Kill();
|
||||
p.Close();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
p.Kill();
|
||||
p.Close();
|
||||
}
|
||||
}
|
||||
Console.WriteLine(string.Format("成功结束[{0}]进程!", processes));
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("结束指定的Widnows进程异常:" + ex.Message, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
|
||||
using System.Xml;
|
||||
using System.Data;
|
||||
using System.IO;
|
||||
using System;
|
||||
|
||||
namespace MAX.Framework.Helpers
|
||||
{
|
||||
/// <summary>
|
||||
/// Xml的操作公共类
|
||||
/// </summary>
|
||||
public class XmlHelper
|
||||
{
|
||||
#region 字段定义
|
||||
/// <summary>
|
||||
/// /// XML文件的物理路径
|
||||
/// </summary>
|
||||
private string _filePath = string.Empty;
|
||||
/// <summary>
|
||||
/// Xml文档
|
||||
/// </summary>
|
||||
private XmlDocument _xml;
|
||||
/// <summary>
|
||||
/// XML的根节点
|
||||
/// </summary>
|
||||
private XmlElement _element;
|
||||
#endregion
|
||||
|
||||
#region 构造方法
|
||||
/// <summary>
|
||||
/// 实例化XmlHelper对象
|
||||
/// </summary>
|
||||
/// <param name="xmlFilePath">Xml文件的相对路径</param>
|
||||
public XmlHelper(string xmlFilePath)
|
||||
{
|
||||
//获取XML文件的绝对路径
|
||||
_filePath = xmlFilePath;
|
||||
//创建一个XML对象
|
||||
_xml = new XmlDocument();
|
||||
if (File.Exists(xmlFilePath))
|
||||
{
|
||||
//加载XML文件
|
||||
_xml.Load(xmlFilePath);
|
||||
}
|
||||
_element = _xml.DocumentElement;
|
||||
}
|
||||
public XmlHelper(Stream stream)
|
||||
{
|
||||
//创建一个XML对象
|
||||
_xml = new XmlDocument();
|
||||
if (stream != null)
|
||||
{
|
||||
//加载XML
|
||||
_xml.Load(stream);
|
||||
}
|
||||
_element = _xml.DocumentElement;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
|
||||
#region 获取指定XPath表达式的节点对象
|
||||
/// <summary>
|
||||
/// 获取指定XPath表达式的节点对象
|
||||
/// </summary>
|
||||
/// <param name="xPath">XPath表达式,
|
||||
/// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
|
||||
/// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
|
||||
/// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
|
||||
/// </param>
|
||||
public XmlNode GetNode(string xPath)
|
||||
{
|
||||
//返回XPath节点
|
||||
return _element.SelectSingleNode(xPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定XPath表达式的节点对象
|
||||
/// </summary>
|
||||
/// <param name="xPath">XPath表达式,
|
||||
/// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
|
||||
/// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
|
||||
/// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
|
||||
/// </param>
|
||||
public XmlNodeList GetNodes(string xPath)
|
||||
{
|
||||
//返回XPath节点
|
||||
return _element.SelectNodes(xPath);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 获取指定XPath表达式节点的值
|
||||
/// <summary>
|
||||
/// 获取指定XPath表达式节点的值
|
||||
/// </summary>
|
||||
/// <param name="xPath">XPath表达式,
|
||||
/// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
|
||||
/// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
|
||||
/// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
|
||||
/// </param>
|
||||
public string GetValue(string xPath)
|
||||
{
|
||||
//返回XPath节点的值
|
||||
string value = _element.SelectSingleNode(xPath)?.InnerText ?? "";
|
||||
return value;
|
||||
}
|
||||
public T GetValue<T>(string xPath, T? def = default)
|
||||
{
|
||||
string value = GetValue(xPath);
|
||||
if (value == null)
|
||||
return def;
|
||||
else
|
||||
return (T)Convert.ChangeType(value, typeof(T));
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 获取指定XPath表达式节点的属性值
|
||||
/// <summary>
|
||||
/// 获取指定XPath表达式节点的属性值
|
||||
/// </summary>
|
||||
/// <param name="xPath">XPath表达式,
|
||||
/// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
|
||||
/// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
|
||||
/// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
|
||||
/// </param>
|
||||
/// <param name="attributeName">属性名</param>
|
||||
public string GetAttributeValue(string xPath, string attributeName)
|
||||
{
|
||||
//返回XPath节点的属性值
|
||||
return _element.SelectSingleNode(xPath).Attributes[attributeName].Value;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 新增节点
|
||||
/// <summary>
|
||||
/// 1. 功能:新增节点。
|
||||
/// 2. 使用条件:将任意节点插入到当前Xml文件中。
|
||||
/// </summary>
|
||||
/// <param name="xmlNode">要插入的Xml节点</param>
|
||||
public void AppendNode(XmlNode xmlNode)
|
||||
{
|
||||
//导入节点
|
||||
XmlNode node = _xml.ImportNode(xmlNode, true);
|
||||
|
||||
//将节点插入到根节点下
|
||||
_element.AppendChild(node);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 1. 功能:新增节点。
|
||||
/// 2. 使用条件:将DataSet中的第一条记录插入Xml文件中。
|
||||
/// </summary>
|
||||
/// <param name="ds">DataSet的实例,该DataSet中应该只有一条记录</param>
|
||||
public void AppendNode(DataSet ds)
|
||||
{
|
||||
//创建XmlDataDocument对象
|
||||
XmlDataDocument xmlDataDocument = new XmlDataDocument(ds);
|
||||
|
||||
//导入节点
|
||||
XmlNode node = xmlDataDocument.DocumentElement.FirstChild;
|
||||
|
||||
//将节点插入到根节点下
|
||||
AppendNode(node);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 删除节点
|
||||
/// <summary>
|
||||
/// 删除指定XPath表达式的节点
|
||||
/// </summary>
|
||||
/// <param name="xPath">XPath表达式,
|
||||
/// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
|
||||
/// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
|
||||
/// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
|
||||
/// </param>
|
||||
public void RemoveNode(string xPath)
|
||||
{
|
||||
//获取要删除的节点
|
||||
XmlNode node = _xml.SelectSingleNode(xPath);
|
||||
|
||||
//删除节点
|
||||
_element.RemoveChild(node);
|
||||
}
|
||||
#endregion //删除节点
|
||||
|
||||
#region 保存XML文件
|
||||
/// <summary>
|
||||
/// 保存XML文件
|
||||
/// </summary>
|
||||
public void Save()
|
||||
{
|
||||
if (string.IsNullOrEmpty(_filePath))
|
||||
{
|
||||
throw new Exception("Xml文件路径不能为空!");
|
||||
}
|
||||
//保存XML文件
|
||||
_xml.Save(_filePath);
|
||||
}
|
||||
public void Save(string filePath)
|
||||
{
|
||||
//保存XML文件
|
||||
_xml.Save(filePath);
|
||||
}
|
||||
#endregion //保存XML文件
|
||||
|
||||
#region 静态方法
|
||||
|
||||
#region 创建根节点对象
|
||||
/// <summary>
|
||||
/// 创建根节点对象
|
||||
/// </summary>
|
||||
/// <param name="xmlFilePath">Xml文件的相对路径</param>
|
||||
private static XmlElement CreateRootElement(string xmlFilePath)
|
||||
{
|
||||
//定义变量,表示XML文件的绝对路径
|
||||
string filePath = "";
|
||||
|
||||
//获取XML文件的绝对路径
|
||||
filePath = xmlFilePath;
|
||||
|
||||
//创建XmlDocument对象
|
||||
XmlDocument xmlDocument = new XmlDocument();
|
||||
//加载XML文件
|
||||
xmlDocument.Load(filePath);
|
||||
|
||||
//返回根节点
|
||||
return xmlDocument.DocumentElement;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 获取指定XPath表达式节点的值
|
||||
/// <summary>
|
||||
/// 获取指定XPath表达式节点的值
|
||||
/// </summary>
|
||||
/// <param name="xmlFilePath">Xml文件的相对路径</param>
|
||||
/// <param name="xPath">XPath表达式,
|
||||
/// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
|
||||
/// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
|
||||
/// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
|
||||
/// </param>
|
||||
public static string GetValue(string xmlFilePath, string xPath)
|
||||
{
|
||||
//创建根对象
|
||||
XmlElement rootElement = CreateRootElement(xmlFilePath);
|
||||
|
||||
//返回XPath节点的值
|
||||
return rootElement.SelectSingleNode(xPath).InnerText;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 获取指定XPath表达式节点的属性值
|
||||
/// <summary>
|
||||
/// 获取指定XPath表达式节点的属性值
|
||||
/// </summary>
|
||||
/// <param name="xmlFilePath">Xml文件的相对路径</param>
|
||||
/// <param name="xPath">XPath表达式,
|
||||
/// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
|
||||
/// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
|
||||
/// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
|
||||
/// </param>
|
||||
/// <param name="attributeName">属性名</param>
|
||||
public static string GetAttributeValue(string xmlFilePath, string xPath, string attributeName)
|
||||
{
|
||||
//创建根对象
|
||||
XmlElement rootElement = CreateRootElement(xmlFilePath);
|
||||
|
||||
//返回XPath节点的属性值
|
||||
return rootElement.SelectSingleNode(xPath).Attributes[attributeName].Value;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
}
|
||||
|
||||
public static class XmlHelExtension
|
||||
{
|
||||
public static string GetAttributeValue(this XmlNode node, string attributeName)
|
||||
{
|
||||
return node.Attributes[attributeName].Value;
|
||||
}
|
||||
public static T GetAttributeValue<T>(this XmlNode node, string attributeName)
|
||||
{
|
||||
var value = node.Attributes[attributeName].Value;
|
||||
if (string.IsNullOrEmpty(value))
|
||||
return default(T);
|
||||
return (T)Convert.ChangeType(value, typeof(T));
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using MAX.Core.DependencyInjection;
|
||||
|
||||
namespace MAX.Framework.Interfaces
|
||||
{
|
||||
public interface IAppConfig : ISingletonDependency
|
||||
{
|
||||
/// <summary>
|
||||
/// 公司名称
|
||||
/// </summary>
|
||||
string CompanyName { get; }
|
||||
/// <summary>
|
||||
/// 软件名称
|
||||
/// </summary>
|
||||
string AppName { get; }
|
||||
T GetValue<T>(string key, T defaultValue = default);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using MAX.Core;
|
||||
using MAX.Core.DependencyInjection;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MAX.Framework.Interfaces
|
||||
{
|
||||
/// <summary>
|
||||
/// 初始化接口
|
||||
/// </summary>
|
||||
public interface IAppInitialize : ISingletonDependency, IPriority
|
||||
{
|
||||
/// <summary>
|
||||
/// 描述
|
||||
/// </summary>
|
||||
string Description { get; }
|
||||
|
||||
/// <summary>
|
||||
/// App 初始化数据
|
||||
/// </summary>
|
||||
void AppInitialize();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 初始化接口(异步)
|
||||
/// </summary>
|
||||
public interface IAppInitializeAsync : ISingletonDependency, IPriority
|
||||
{
|
||||
/// <summary>
|
||||
/// 描述
|
||||
/// </summary>
|
||||
string Description { get; }
|
||||
|
||||
/// <summary>
|
||||
/// App 初始化数据
|
||||
/// </summary>
|
||||
Task AppInitializeAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using MAX.Core.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MAX.Framework.Interfaces
|
||||
{
|
||||
public interface IFolderConfig: ISingletonDependency
|
||||
{
|
||||
/// <summary>
|
||||
/// 执行目录
|
||||
/// </summary>
|
||||
string LocalFolder { get; }
|
||||
string LocalAppFolder { get; }
|
||||
string TargetFolder { get; }
|
||||
string LoggingFolder { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
using MAX.Core.DependencyInjection;
|
||||
using MAX.Core.Infrastructure;
|
||||
using MAX.Core.Logger;
|
||||
using MAX.Framework.Interfaces;
|
||||
using NLog;
|
||||
using NLog.Targets;
|
||||
using System;
|
||||
using LLogLevel = MAX.Core.Logger.LogLevel;
|
||||
using NLogLevel = NLog.LogLevel;
|
||||
|
||||
namespace MAX.Framework.Logger
|
||||
{
|
||||
public class NLogger : ILoggerFacade, ISingletonDependency
|
||||
{
|
||||
private readonly ILogger _log;
|
||||
public static ILoggerFacade Instance => LazyServiceProvider.Instance.LazyGetService<ILoggerFacade>();
|
||||
public NLogger(IFolderConfig folderConfig = null)
|
||||
{
|
||||
if (folderConfig != null)
|
||||
{
|
||||
Target target = new FileTarget("log1")
|
||||
{
|
||||
FileName = $"{folderConfig.LoggingFolder}\\{DateTime.Now:yyyy-MM-dd}.txt",
|
||||
};
|
||||
var config = new NLog.Config.LoggingConfiguration();
|
||||
config.AddRule(NLogLevel.Debug, NLogLevel.Fatal, target);
|
||||
|
||||
LogManager.Configuration = config;
|
||||
}
|
||||
_log = LogManager.GetLogger("GlobalLogger");
|
||||
}
|
||||
|
||||
public bool IsDebugEnabled { get; private set; } = false;
|
||||
|
||||
public void Debug(Exception ex, string message)
|
||||
{
|
||||
Execute(NLogLevel.Debug, ex, message);
|
||||
}
|
||||
|
||||
public void Debug(string message)
|
||||
{
|
||||
Execute(NLogLevel.Debug, message);
|
||||
}
|
||||
public void Error(Exception ex)
|
||||
{
|
||||
Execute(NLogLevel.Error, ex);
|
||||
}
|
||||
public void Error(Exception ex, string message)
|
||||
{
|
||||
Execute(NLogLevel.Error, ex, message);
|
||||
}
|
||||
|
||||
public void Error(string message)
|
||||
{
|
||||
Execute(NLogLevel.Error, message);
|
||||
}
|
||||
|
||||
public void Fatal(Exception ex, string message)
|
||||
{
|
||||
Execute(NLogLevel.Fatal, ex, message);
|
||||
}
|
||||
|
||||
public void Fatal(string message)
|
||||
{
|
||||
Execute(NLogLevel.Fatal, message);
|
||||
}
|
||||
|
||||
public void Info(Exception ex, string message)
|
||||
{
|
||||
Execute(NLogLevel.Info, ex, message);
|
||||
}
|
||||
|
||||
public void Info(string message)
|
||||
{
|
||||
Execute(NLogLevel.Info, message);
|
||||
}
|
||||
|
||||
public void Warn(Exception ex, string message)
|
||||
{
|
||||
Execute(NLogLevel.Warn, ex, message);
|
||||
}
|
||||
|
||||
public void Warn(string message)
|
||||
{
|
||||
Execute(NLogLevel.Warn, message);
|
||||
}
|
||||
public void Log(string message, LLogLevel level)
|
||||
{
|
||||
NLogLevel lv = NLogLevel.Info;
|
||||
switch (level)
|
||||
{
|
||||
case LLogLevel.Trace:
|
||||
lv = NLogLevel.Trace;
|
||||
break;
|
||||
case LLogLevel.Debug:
|
||||
lv = NLogLevel.Debug;
|
||||
break;
|
||||
case LLogLevel.Info:
|
||||
lv = NLogLevel.Info;
|
||||
break;
|
||||
case LLogLevel.Warn:
|
||||
lv = NLogLevel.Warn;
|
||||
break;
|
||||
case LLogLevel.Error:
|
||||
lv = NLogLevel.Error;
|
||||
break;
|
||||
case LLogLevel.Fatal:
|
||||
lv = NLogLevel.Fatal;
|
||||
break;
|
||||
case LLogLevel.None:
|
||||
lv = NLogLevel.Off;
|
||||
break;
|
||||
}
|
||||
Execute(lv, message);
|
||||
}
|
||||
/// <summary>
|
||||
/// 是否启用
|
||||
/// </summary>
|
||||
private bool Enabled(NLogLevel level)
|
||||
{
|
||||
if (level > NLogLevel.Debug)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return IsDebugEnabled;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行
|
||||
/// </summary>
|
||||
private void Execute(NLogLevel level, Exception ex, string message = "")
|
||||
{
|
||||
if (Enabled(level))
|
||||
{
|
||||
_log.Log(level, ex, message, null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 执行
|
||||
/// </summary>
|
||||
private void Execute(NLogLevel level, string message)
|
||||
{
|
||||
if (Enabled(level))
|
||||
{
|
||||
_log.Log(level, message);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>$(DefaultTargetFramework)-windows</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Autofac" Version="9.3.2" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
|
||||
<PackageReference Include="NLog" Version="6.2.0" />
|
||||
<PackageReference Include="Prism.Wpf" Version="8.1.97" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\MAX.Core\MAX.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,243 @@
|
||||
using System.Linq.Expressions;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
using Prism.Properties;
|
||||
|
||||
|
||||
namespace Prism.Commands
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Provides an implementation of the <see cref="IAsyncCommand"/>
|
||||
/// </summary>
|
||||
public class AsyncDelegateCommand : DelegateCommandBase, IAsyncCommand
|
||||
{
|
||||
private bool _enableParallelExecution = false;
|
||||
private bool _isExecuting = false;
|
||||
private readonly Func<CancellationToken, Task> _executeMethod;
|
||||
private Func<bool> _canExecuteMethod;
|
||||
private Func<CancellationToken> _getCancellationToken = () => CancellationToken.None;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="AsyncDelegateCommand"/> with the <see cref="Func{Task}"/> to invoke on execution.
|
||||
/// </summary>
|
||||
/// <param name="executeMethod">The <see cref="Func{Task}"/> to invoke when <see cref="ICommand.Execute(object)"/> is called.</param>
|
||||
public AsyncDelegateCommand(Func<Task> executeMethod)
|
||||
#if NET6_0_OR_GREATER
|
||||
: this (c => executeMethod().WaitAsync(c), () => true)
|
||||
#else
|
||||
: this(c => executeMethod(), () => true)
|
||||
#endif
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="AsyncDelegateCommand"/> with the <see cref="Func{Task}"/> to invoke on execution.
|
||||
/// </summary>
|
||||
/// <param name="executeMethod">The <see cref="Func{CancellationToken, Task}"/> to invoke when <see cref="ICommand.Execute(object)"/> is called.</param>
|
||||
public AsyncDelegateCommand(Func<CancellationToken, Task> executeMethod)
|
||||
: this(executeMethod, () => true)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="DelegateCommand"/> with the <see cref="Func{Task}"/> to invoke on execution
|
||||
/// and a <see langword="Func" /> to query for determining if the command can execute.
|
||||
/// </summary>
|
||||
/// <param name="executeMethod">The <see cref="Func{Task}"/> to invoke when <see cref="ICommand.Execute"/> is called.</param>
|
||||
/// <param name="canExecuteMethod">The delegate to invoke when <see cref="ICommand.CanExecute"/> is called</param>
|
||||
public AsyncDelegateCommand(Func<Task> executeMethod, Func<bool> canExecuteMethod)
|
||||
#if NET6_0_OR_GREATER
|
||||
: this(c => executeMethod().WaitAsync(c), canExecuteMethod)
|
||||
#else
|
||||
: this(c => executeMethod(), canExecuteMethod)
|
||||
#endif
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="DelegateCommand"/> with the <see cref="Func{Task}"/> to invoke on execution
|
||||
/// and a <see langword="Func" /> to query for determining if the command can execute.
|
||||
/// </summary>
|
||||
/// <param name="executeMethod">The <see cref="Func{CancellationToken, Task}"/> to invoke when <see cref="ICommand.Execute"/> is called.</param>
|
||||
/// <param name="canExecuteMethod">The delegate to invoke when <see cref="ICommand.CanExecute"/> is called</param>
|
||||
public AsyncDelegateCommand(Func<CancellationToken, Task> executeMethod, Func<bool> canExecuteMethod)
|
||||
: base()
|
||||
{
|
||||
if (executeMethod == null || canExecuteMethod == null)
|
||||
throw new ArgumentNullException(nameof(executeMethod), "Neither the executeMethod nor the canExecuteMethod delegates can be null");
|
||||
|
||||
_executeMethod = executeMethod;
|
||||
_canExecuteMethod = canExecuteMethod;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current state of the AsyncDelegateCommand
|
||||
/// </summary>
|
||||
public bool IsExecuting
|
||||
{
|
||||
get => _isExecuting;
|
||||
private set
|
||||
{
|
||||
_isExecuting = value;
|
||||
OnCanExecuteChanged();
|
||||
}
|
||||
}
|
||||
|
||||
///<summary>
|
||||
/// Executes the command.
|
||||
///</summary>
|
||||
public async Task Execute(CancellationToken? cancellationToken = null)
|
||||
{
|
||||
var token = cancellationToken ?? _getCancellationToken();
|
||||
try
|
||||
{
|
||||
if (!_enableParallelExecution && IsExecuting)
|
||||
return;
|
||||
|
||||
IsExecuting = true;
|
||||
await _executeMethod(token)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
throw;
|
||||
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsExecuting = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines if the command can be executed.
|
||||
/// </summary>
|
||||
/// <returns>Returns <see langword="true"/> if the command can execute,otherwise returns <see langword="false"/>.</returns>
|
||||
public bool CanExecute()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!_enableParallelExecution && IsExecuting)
|
||||
return false;
|
||||
|
||||
return _canExecuteMethod?.Invoke() ?? true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle the internal invocation of <see cref="ICommand.Execute(object)"/>
|
||||
/// </summary>
|
||||
/// <param name="parameter">Command Parameter</param>
|
||||
protected override async void Execute(object parameter)
|
||||
{
|
||||
// We don't want to wrap this in a try/catch because we already handle
|
||||
// or mean to rethrow the exception in the call with the CancellationToken.
|
||||
var cancellationToken = _getCancellationToken();
|
||||
await Execute(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle the internal invocation of <see cref="ICommand.CanExecute(object)"/>
|
||||
/// </summary>
|
||||
/// <param name="parameter"></param>
|
||||
/// <returns><see langword="true"/> if the Command Can Execute, otherwise <see langword="false" /></returns>
|
||||
protected override bool CanExecute(object parameter)
|
||||
{
|
||||
return CanExecute();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enables Parallel Execution of Async Tasks
|
||||
/// </summary>
|
||||
/// <returns>The current instance of <see cref="AsyncDelegateCommand"/>.</returns>
|
||||
public AsyncDelegateCommand EnableParallelExecution()
|
||||
{
|
||||
_enableParallelExecution = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <see cref="CancellationTokenSourceFactory(Func{CancellationToken})"/> based on the specified timeout.
|
||||
/// </summary>
|
||||
/// <param name="timeout">A specified timeout.</param>
|
||||
/// <returns>The current instance of <see cref="AsyncDelegateCommand{T}"/>.</returns>
|
||||
public AsyncDelegateCommand CancelAfter(TimeSpan timeout) =>
|
||||
CancellationTokenSourceFactory(() => new CancellationTokenSource(timeout).Token);
|
||||
|
||||
/// <summary>
|
||||
/// Provides a delegate callback to provide a default CancellationToken when the Command is invoked.
|
||||
/// </summary>
|
||||
/// <param name="factory">The default <see cref="CancellationToken"/> Factory.</param>
|
||||
/// <returns>The current instance of <see cref="AsyncDelegateCommand"/>.</returns>
|
||||
public AsyncDelegateCommand CancellationTokenSourceFactory(Func<CancellationToken> factory)
|
||||
{
|
||||
_getCancellationToken = factory;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Observes a property that implements INotifyPropertyChanged, and automatically calls DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The object type containing the property specified in the expression.</typeparam>
|
||||
/// <param name="propertyExpression">The property expression. Example: ObservesProperty(() => PropertyName).</param>
|
||||
/// <returns>The current instance of <see cref="AsyncDelegateCommand"/>.</returns>
|
||||
public AsyncDelegateCommand ObservesProperty<T>(Expression<Func<T>> propertyExpression)
|
||||
{
|
||||
ObservesPropertyInternal(propertyExpression);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Observes a property that is used to determine if this command can execute, and if it implements INotifyPropertyChanged it will automatically call DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications.
|
||||
/// </summary>
|
||||
/// <param name="canExecuteExpression">The property expression. Example: ObservesCanExecute(() => PropertyName).</param>
|
||||
/// <returns>The current instance of <see cref="AsyncDelegateCommand"/>.</returns>
|
||||
public AsyncDelegateCommand ObservesCanExecute(Expression<Func<bool>> canExecuteExpression)
|
||||
{
|
||||
_canExecuteMethod = canExecuteExpression.Compile();
|
||||
ObservesPropertyInternal(canExecuteExpression);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provides the ability to connect a delegate to catch exceptions encountered by CanExecute or the Execute methods of the DelegateCommand
|
||||
/// </summary>
|
||||
/// <param name="catch">TThe callback when a specific exception is encountered</param>
|
||||
/// <returns>The current instance of <see cref="AsyncDelegateCommand"/>.</returns>
|
||||
public AsyncDelegateCommand Catch<TException>(Action<TException> @catch)
|
||||
where TException : Exception
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provides the ability to connect a delegate to catch exceptions encountered by CanExecute or the Execute methods of the DelegateCommand
|
||||
/// </summary>
|
||||
/// <param name="catch">The generic / default callback when an exception is encountered</param>
|
||||
/// <returns>The current instance of <see cref="AsyncDelegateCommand"/>.</returns>
|
||||
public AsyncDelegateCommand Catch(Action<Exception> @catch)
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
Task IAsyncCommand.ExecuteAsync(object parameter)
|
||||
{
|
||||
return Execute(_getCancellationToken());
|
||||
}
|
||||
|
||||
Task IAsyncCommand.ExecuteAsync(object parameter, CancellationToken cancellationToken)
|
||||
{
|
||||
return Execute(cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
using System.Linq.Expressions;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
using System.Reflection.Emit;
|
||||
using System.Resources;
|
||||
|
||||
namespace Prism.Commands
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides an implementation of the <see cref="IAsyncCommand"/> with a generic parameter type.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class AsyncDelegateCommand<T> : DelegateCommandBase, IAsyncCommand
|
||||
{
|
||||
private bool _enableParallelExecution = false;
|
||||
private bool _isExecuting = false;
|
||||
private readonly Func<T, CancellationToken, Task> _executeMethod;
|
||||
private Func<T, bool> _canExecuteMethod;
|
||||
private Func<CancellationToken> _getCancellationToken = () => CancellationToken.None;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="AsyncDelegateCommand{T}"/> with the <see cref="Func{Task}"/> to invoke on execution.
|
||||
/// </summary>
|
||||
/// <param name="executeMethod">The <see cref="Func{T, Task}"/> to invoke when <see cref="ICommand.Execute(object)"/> is called.</param>
|
||||
public AsyncDelegateCommand(Func<T, Task> executeMethod)
|
||||
#if NET6_0_OR_GREATER
|
||||
: this((p,t) => executeMethod(p).WaitAsync(t), _ => true)
|
||||
#else
|
||||
: this((p, t) => executeMethod(p), _ => true)
|
||||
#endif
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="AsyncDelegateCommand{T}"/> with the <see cref="Func{Task}"/> to invoke on execution.
|
||||
/// </summary>
|
||||
/// <param name="executeMethod">The <see cref="Func{T, CancellationToken, Task}"/> to invoke when <see cref="ICommand.Execute(object)"/> is called.</param>
|
||||
public AsyncDelegateCommand(Func<T, CancellationToken, Task> executeMethod)
|
||||
: this(executeMethod, _ => true)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="DelegateCommand"/> with the <see cref="Func{Task}"/> to invoke on execution
|
||||
/// and a <see langword="Func" /> to query for determining if the command can execute.
|
||||
/// </summary>
|
||||
/// <param name="executeMethod">The <see cref="Func{T, Task}"/> to invoke when <see cref="ICommand.Execute"/> is called.</param>
|
||||
/// <param name="canExecuteMethod">The delegate to invoke when <see cref="ICommand.CanExecute"/> is called</param>
|
||||
public AsyncDelegateCommand(Func<T, Task> executeMethod, Func<T, bool> canExecuteMethod)
|
||||
#if NET6_0_OR_GREATER
|
||||
: this((p, c) => executeMethod(p).WaitAsync(c), canExecuteMethod)
|
||||
#else
|
||||
: this((p, c) => executeMethod(p), canExecuteMethod)
|
||||
#endif
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="DelegateCommand"/> with the <see cref="Func{Task}"/> to invoke on execution
|
||||
/// and a <see langword="Func" /> to query for determining if the command can execute.
|
||||
/// </summary>
|
||||
/// <param name="executeMethod">The <see cref="Func{T, CancellationToken, Task}"/> to invoke when <see cref="ICommand.Execute"/> is called.</param>
|
||||
/// <param name="canExecuteMethod">The delegate to invoke when <see cref="ICommand.CanExecute"/> is called</param>
|
||||
public AsyncDelegateCommand(Func<T, CancellationToken, Task> executeMethod, Func<T, bool> canExecuteMethod)
|
||||
: base()
|
||||
{
|
||||
if (executeMethod == null || canExecuteMethod == null)
|
||||
throw new ArgumentNullException(nameof(executeMethod), "Neither the executeMethod nor the canExecuteMethod delegates can be null");
|
||||
|
||||
|
||||
_executeMethod = executeMethod;
|
||||
_canExecuteMethod = canExecuteMethod;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current state of the AsyncDelegateCommand
|
||||
/// </summary>
|
||||
public bool IsExecuting
|
||||
{
|
||||
get => _isExecuting;
|
||||
private set
|
||||
{
|
||||
_isExecuting = value;
|
||||
OnCanExecuteChanged();
|
||||
}
|
||||
}
|
||||
|
||||
///<summary>
|
||||
/// Executes the command.
|
||||
///</summary>
|
||||
public async Task Execute(T parameter, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
var token = cancellationToken ?? _getCancellationToken();
|
||||
|
||||
try
|
||||
{
|
||||
if (!_enableParallelExecution && IsExecuting)
|
||||
return;
|
||||
|
||||
IsExecuting = true;
|
||||
await _executeMethod(parameter, token)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsExecuting = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines if the command can be executed.
|
||||
/// </summary>
|
||||
/// <returns>Returns <see langword="true"/> if the command can execute,otherwise returns <see langword="false"/>.</returns>
|
||||
public bool CanExecute(T parameter)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!_enableParallelExecution && IsExecuting)
|
||||
return false;
|
||||
|
||||
return _canExecuteMethod?.Invoke(parameter) ?? true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
throw;
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle the internal invocation of <see cref="ICommand.Execute(object)"/>
|
||||
/// </summary>
|
||||
/// <param name="parameter">Command Parameter</param>
|
||||
protected override async void Execute(object parameter)
|
||||
{
|
||||
var cancellationToken = _getCancellationToken();
|
||||
T parameterAsT;
|
||||
try
|
||||
{
|
||||
parameterAsT = (T)parameter;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
|
||||
// If we had an exception casting the parameter to T ,
|
||||
// we would have already returned. We want to surface any
|
||||
// exceptions thrown by the Execute method.
|
||||
await Execute(parameterAsT, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle the internal invocation of <see cref="ICommand.CanExecute(object)"/>
|
||||
/// </summary>
|
||||
/// <param name="parameter"></param>
|
||||
/// <returns><see langword="true"/> if the Command Can Execute, otherwise <see langword="false" /></returns>
|
||||
protected override bool CanExecute(object parameter)
|
||||
{
|
||||
try
|
||||
{
|
||||
return CanExecute((T)parameter);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enables Parallel Execution of Async Tasks
|
||||
/// </summary>
|
||||
/// <returns>The current instance of <see cref="AsyncDelegateCommand{T}"/>.</returns>
|
||||
public AsyncDelegateCommand<T> EnableParallelExecution()
|
||||
{
|
||||
_enableParallelExecution = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <see cref="CancellationTokenSourceFactory(Func{CancellationToken})"/> based on the specified timeout.
|
||||
/// </summary>
|
||||
/// <param name="timeout">A specified timeout.</param>
|
||||
/// <returns>The current instance of <see cref="AsyncDelegateCommand{T}"/>.</returns>
|
||||
public AsyncDelegateCommand<T> CancelAfter(TimeSpan timeout) =>
|
||||
CancellationTokenSourceFactory(() => new CancellationTokenSource(timeout).Token);
|
||||
|
||||
/// <summary>
|
||||
/// Provides a delegate callback to provide a default CancellationToken when the Command is invoked.
|
||||
/// </summary>
|
||||
/// <param name="factory">The default <see cref="CancellationToken"/> Factory.</param>
|
||||
/// <returns>The current instance of <see cref="AsyncDelegateCommand{T}"/>.</returns>
|
||||
public AsyncDelegateCommand<T> CancellationTokenSourceFactory(Func<CancellationToken> factory)
|
||||
{
|
||||
_getCancellationToken = factory;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Observes a property that implements INotifyPropertyChanged, and automatically calls DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications.
|
||||
/// </summary>
|
||||
/// <typeparam name="TType">The type of the return value of the method that this delegate encapsulates</typeparam>
|
||||
/// <param name="propertyExpression">The property expression. Example: ObservesProperty(() => PropertyName).</param>
|
||||
/// <returns>The current instance of <see cref="AsyncDelegateCommand{T}"/>.</returns>
|
||||
public AsyncDelegateCommand<T> ObservesProperty<TType>(Expression<Func<TType>> propertyExpression)
|
||||
{
|
||||
ObservesPropertyInternal(propertyExpression);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Observes a property that is used to determine if this command can execute, and if it implements INotifyPropertyChanged it will automatically call DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications.
|
||||
/// </summary>
|
||||
/// <param name="canExecuteExpression">The property expression. Example: ObservesCanExecute(() => PropertyName).</param>
|
||||
/// <returns>The current instance of <see cref="AsyncDelegateCommand{T}"/>.</returns>
|
||||
public AsyncDelegateCommand<T> ObservesCanExecute(Expression<Func<bool>> canExecuteExpression)
|
||||
{
|
||||
Expression<Func<T, bool>> expression = Expression.Lambda<Func<T, bool>>(canExecuteExpression.Body, Expression.Parameter(typeof(T), "o"));
|
||||
_canExecuteMethod = expression.Compile();
|
||||
ObservesPropertyInternal(canExecuteExpression);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provides the ability to connect a delegate to catch exceptions encountered by CanExecute or the Execute methods of the DelegateCommand
|
||||
/// </summary>
|
||||
/// <param name="catch">TThe callback when a specific exception is encountered</param>
|
||||
/// <returns>The current instance of <see cref="AsyncDelegateCommand{T}"/>.</returns>
|
||||
public AsyncDelegateCommand<T> Catch<TException>(Action<TException> @catch)
|
||||
where TException : Exception
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provides the ability to connect a delegate to catch exceptions encountered by CanExecute or the Execute methods of the DelegateCommand
|
||||
/// </summary>
|
||||
/// <param name="catch">The generic / default callback when an exception is encountered</param>
|
||||
/// <returns>The current instance of <see cref="AsyncDelegateCommand{T}"/>.</returns>
|
||||
public AsyncDelegateCommand<T> Catch(Action<Exception> @catch)
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
async Task IAsyncCommand.ExecuteAsync(object parameter)
|
||||
{
|
||||
try
|
||||
{
|
||||
// If T is not nullable this may throw an exception
|
||||
await Execute((T)parameter, _getCancellationToken());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
async Task IAsyncCommand.ExecuteAsync(object parameter, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
// If T is not nullable this may throw an exception
|
||||
await Execute((T)parameter, cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace Prism.Commands
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Provides an abstraction layer for custom controls which want to make use of Async Commands
|
||||
/// </summary>
|
||||
public interface IAsyncCommand : ICommand
|
||||
{
|
||||
/// <summary>
|
||||
/// Executes the Command with a specified parameter and the Default <see cref="CancellationToken"/>.
|
||||
/// </summary>
|
||||
/// <param name="parameter">The Command Parameter</param>
|
||||
/// <returns>An Asynchronous Task</returns>
|
||||
Task ExecuteAsync(object parameter);
|
||||
|
||||
/// <summary>
|
||||
/// Executes the Command with a specified parameter and using a <see cref="CancellationToken"/>
|
||||
/// </summary>
|
||||
/// <param name="parameter">The Command Parameter</param>
|
||||
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
|
||||
/// <returns>An Asynchronous Task</returns>
|
||||
Task ExecuteAsync(object parameter, CancellationToken cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
using Autofac;
|
||||
using Autofac.Core;
|
||||
using Autofac.Features.ResolveAnything;
|
||||
using MAX.Core;
|
||||
using MAX.Core.Autofac;
|
||||
using MAX.Core.DependencyInjection;
|
||||
using MAX.Core.Helpers;
|
||||
using MAX.Core.Infrastructure;
|
||||
using MAX.Core.Reflections;
|
||||
using MAX.Framework.Interfaces;
|
||||
using MAX.Framework.Prism.Autofac;
|
||||
using Prism.Ioc;
|
||||
using Prism.Ioc.Internals;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Prism.Autofac
|
||||
{
|
||||
public class AutofacContainerExtension : IContainerExtension<IContainer>, IContainerInfo
|
||||
{
|
||||
private AutofacScopedProvider _currentScope;
|
||||
public readonly ContainerBuilder Builder;
|
||||
|
||||
public IContainer Instance { get; private set; }
|
||||
|
||||
public IScopedProvider CurrentScope => _currentScope;
|
||||
public AutofacContainerExtension()
|
||||
{
|
||||
Builder = new ContainerBuilder();
|
||||
string currentContainer = "CurrentContainer";
|
||||
Builder.RegisterInstance(this).Named(currentContainer, typeof(AutofacContainerExtension));
|
||||
Builder.RegisterInstance(this).As<IContainerExtension>();
|
||||
Builder.RegisterInstance(this).As<IContainerProvider>();
|
||||
//设置过滤AOP
|
||||
//IAspectConfiguration configuration = new AspectConfiguration();
|
||||
//foreach (var item in AppTypeFinder.Assemblies)
|
||||
//{
|
||||
// string _namespace = item.FullName;
|
||||
// if (!Regex.IsMatch(_namespace, "^MAX", RegexOptions.IgnoreCase | RegexOptions.Compiled))
|
||||
// {
|
||||
// configuration.NonAspectPredicates.AddNamespace(_namespace);
|
||||
// }
|
||||
//}
|
||||
//Builder.RegisterDynamicProxy(configuration);
|
||||
}
|
||||
public AutofacContainerExtension(ContainerBuilder builder)
|
||||
{
|
||||
Builder = builder;
|
||||
string currentContainer = "CurrentContainer";
|
||||
//Builder.RegisterDynamicProxy();
|
||||
Builder.RegisterInstance(this).Named(currentContainer, typeof(AutofacContainerExtension));
|
||||
Builder.RegisterInstance(this).As<IContainerExtension>();
|
||||
Builder.RegisterInstance(this).As<IContainerProvider>();
|
||||
}
|
||||
public IScopedProvider CreateScope()
|
||||
{
|
||||
return CreateScopeInternal();
|
||||
}
|
||||
protected IScopedProvider CreateScopeInternal()
|
||||
{
|
||||
_currentScope = new AutofacScopedProvider(Instance);
|
||||
return _currentScope;
|
||||
}
|
||||
public void FinalizeExtension()
|
||||
{
|
||||
if (Instance != null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Assembly[] assemblies = AppTypeFinder.Assemblies.ToArray();
|
||||
|
||||
// Make sure any not specifically registered concrete type can resolve.
|
||||
IEnumerable<IStartup> startupList = ReflectionHelper.GetInstancesByInterface<IStartup>(assemblies);
|
||||
int index = 1;
|
||||
foreach (IStartup item in startupList.OrderByDescending(a => a.Priority))
|
||||
{
|
||||
Debug.WriteLine($"Startup - {index++} : {item.GetType()}");
|
||||
item.Initialize();
|
||||
}
|
||||
|
||||
// Make sure any not specifically registered concrete type can resolve.
|
||||
IEnumerable<IDependencyRegistrar> ListDependency = ReflectionHelper.GetInstancesByInterface<IDependencyRegistrar>(assemblies);
|
||||
foreach (IDependencyRegistrar item in ListDependency)
|
||||
{
|
||||
item.Register(Builder);
|
||||
}
|
||||
|
||||
IEnumerable<IPreRegisterTypes> PreRegisterTypes = ReflectionHelper.GetInstancesByInterface<IPreRegisterTypes>(assemblies);
|
||||
foreach (IPreRegisterTypes item in PreRegisterTypes)
|
||||
{
|
||||
item.RegisterTypes(this);
|
||||
}
|
||||
|
||||
Builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
|
||||
Instance = Builder.Build();
|
||||
IocManager.SetContainer(Instance);
|
||||
|
||||
}
|
||||
|
||||
public bool IsRegistered(Type type)
|
||||
{
|
||||
return Instance.IsRegistered(type);
|
||||
}
|
||||
|
||||
public bool IsRegistered(Type type, string name)
|
||||
{
|
||||
return Instance.IsRegisteredWithName(name, type);
|
||||
}
|
||||
|
||||
public IContainerRegistry Register(Type from, Type to)
|
||||
{
|
||||
Builder.RegisterType(to).As(from);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IContainerRegistry Register(Type from, Type to, string name)
|
||||
{
|
||||
Builder.RegisterType(to).Named(name, from);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public IContainerRegistry RegisterInstance(Type type, object instance)
|
||||
{
|
||||
Builder.RegisterInstance(instance).As(type);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IContainerRegistry RegisterInstance(Type type, object instance, string name)
|
||||
{
|
||||
Builder.RegisterInstance(instance).Named(name, type);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IContainerRegistry RegisterSingleton(Type from, Type to)
|
||||
{
|
||||
Builder.RegisterType(to).As(from).SingleInstance();
|
||||
return this;
|
||||
}
|
||||
|
||||
public IContainerRegistry RegisterSingleton(Type from, Type to, string name)
|
||||
{
|
||||
Builder.RegisterType(to).Named(name, from).SingleInstance();
|
||||
return this;
|
||||
}
|
||||
|
||||
public IContainerRegistry RegisterSingleton(Type type, Func<object> factoryMethod)
|
||||
{
|
||||
Debugger.Break();
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IContainerRegistry RegisterSingleton(Type type, Func<IContainerProvider, object> factoryMethod)
|
||||
{
|
||||
Debugger.Break();
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public object Resolve(Type type)
|
||||
{
|
||||
return Instance.Resolve(type);
|
||||
}
|
||||
|
||||
public object Resolve(Type type, params (Type Type, object Instance)[] parameters)
|
||||
{
|
||||
List<TypedParameter> listps = new List<TypedParameter>();
|
||||
foreach ((Type Type, object Instance) item in parameters)
|
||||
{
|
||||
TypedParameter ps = new TypedParameter(item.Type, item.Instance);
|
||||
listps.Add(ps);
|
||||
}
|
||||
return Instance.Resolve(type, listps);
|
||||
}
|
||||
|
||||
public object Resolve(Type type, string name)
|
||||
{
|
||||
return Instance.ResolveNamed(name, type);
|
||||
}
|
||||
|
||||
public object Resolve(Type type, string name, params (Type Type, object Instance)[] parameters)
|
||||
{
|
||||
List<TypedParameter> listps = new List<TypedParameter>();
|
||||
foreach ((Type Type, object Instance) item in parameters)
|
||||
{
|
||||
TypedParameter ps = new TypedParameter(item.Type, item.Instance);
|
||||
listps.Add(ps);
|
||||
}
|
||||
return Instance.ResolveNamed(name, type, listps);
|
||||
}
|
||||
|
||||
public IContainerRegistry Register(Type type, Func<object> factoryMethod)
|
||||
{
|
||||
Debugger.Break();
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IContainerRegistry Register(Type type, Func<IContainerProvider, object> factoryMethod)
|
||||
{
|
||||
Debugger.Break();
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
public IContainerRegistry RegisterMany(Type type, params Type[] serviceTypes)
|
||||
{
|
||||
Debugger.Break();
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IContainerRegistry RegisterManySingleton(Type type, params Type[] serviceTypes)
|
||||
{
|
||||
Debugger.Break();
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IContainerRegistry RegisterScoped(Type from, Type to)
|
||||
{
|
||||
Debugger.Break();
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IContainerRegistry RegisterScoped(Type type, Func<object> factoryMethod)
|
||||
{
|
||||
Debugger.Break();
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IContainerRegistry RegisterScoped(Type type, Func<IContainerProvider, object> factoryMethod)
|
||||
{
|
||||
Debugger.Break();
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Type GetRegistrationType(string key)
|
||||
{
|
||||
Type retType = null;
|
||||
//First try friendly name registration. If not found, try type registration
|
||||
foreach (IComponentRegistration registration in Instance.ComponentRegistry.Registrations)
|
||||
{
|
||||
//System.Diagnostics.Debug.WriteLine(registration.ToString());
|
||||
foreach (Service service in registration.Services)
|
||||
{
|
||||
//System.Diagnostics.Debug.WriteLine(service.ToString());
|
||||
if (service is KeyedService ks)
|
||||
{
|
||||
if (key.Equals(ks.ServiceKey.ToString(), StringComparison.Ordinal))
|
||||
{
|
||||
if (Instance.ComponentRegistry.TryGetServiceRegistration(service, out ServiceRegistration serviceRegistration))
|
||||
{
|
||||
retType = serviceRegistration.Registration.Target.Activator.LimitType;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Instance.TryResolveService
|
||||
//retType = Instance.ResolveNamed<object>(key).GetType();
|
||||
if (retType == null)
|
||||
{
|
||||
retType = Instance.ResolveNamed<object>(key).GetType();
|
||||
if (retType == null)
|
||||
{
|
||||
retType = typeof(System.Object);
|
||||
}
|
||||
}
|
||||
return retType;
|
||||
}
|
||||
|
||||
public Type GetRegistrationType(Type serviceType)
|
||||
{
|
||||
Debugger.Break();
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
private class AutofacScopedProvider : IScopedProvider
|
||||
{
|
||||
private readonly IContainer _container;
|
||||
|
||||
public bool IsAttached { get; set; }
|
||||
|
||||
public IScopedProvider CurrentScope => this;
|
||||
|
||||
public IScopedProvider CreateScope()
|
||||
{
|
||||
return this;
|
||||
}
|
||||
public AutofacScopedProvider(IContainer container)
|
||||
{
|
||||
_container = container;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_container.Dispose();
|
||||
}
|
||||
|
||||
public object Resolve(Type type)
|
||||
{
|
||||
return _container.Resolve(type);
|
||||
}
|
||||
|
||||
public object Resolve(Type type, params (Type Type, object Instance)[] parameters)
|
||||
{
|
||||
List<TypedParameter> listps = new List<TypedParameter>();
|
||||
foreach ((Type Type, object Instance) item in parameters)
|
||||
{
|
||||
TypedParameter ps = new TypedParameter(item.Type, item.Instance);
|
||||
listps.Add(ps);
|
||||
}
|
||||
return _container.Resolve(type, listps);
|
||||
}
|
||||
|
||||
public object Resolve(Type type, string name)
|
||||
{
|
||||
return _container.ResolveNamed(name, type);
|
||||
}
|
||||
|
||||
public object Resolve(Type type, string name, params (Type Type, object Instance)[] parameters)
|
||||
{
|
||||
List<TypedParameter> list = new List<TypedParameter>();
|
||||
foreach ((Type Type, object Instance) item in parameters)
|
||||
{
|
||||
TypedParameter ps = new TypedParameter(item.Type, item.Instance);
|
||||
list.Add(ps);
|
||||
}
|
||||
return _container.ResolveNamed(name, type, list);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Autofac;
|
||||
using Prism.Ioc;
|
||||
|
||||
namespace Prism.Autofac
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides customization extensions for Autofac Applications
|
||||
/// </summary>
|
||||
public interface IAutofacContainerExtension : IContainerExtension<IContainer>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the <see cref="ContainerBuilder"/> used to register the services for the application
|
||||
/// </summary>
|
||||
ContainerBuilder Builder { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using Prism.Ioc;
|
||||
|
||||
namespace MAX.Framework.Prism.Autofac
|
||||
{
|
||||
public interface IPreRegisterTypes
|
||||
{
|
||||
void RegisterTypes(IContainerRegistry containerRegistry);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using Prism.Ioc;
|
||||
using System;
|
||||
using System.Windows;
|
||||
using AutofacCore = Autofac.Core;
|
||||
|
||||
namespace Prism.Autofac
|
||||
{
|
||||
/// <summary>
|
||||
/// Base application class that uses <see cref="UnityContainerExtension"/> as it's container.
|
||||
/// </summary>
|
||||
public abstract class PrismApplication : PrismApplicationBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Create a new <see cref="UnityContainerExtension"/> used by Prism.
|
||||
/// </summary>
|
||||
/// <returns>A new <see cref="UnityContainerExtension"/>.</returns>
|
||||
protected override IContainerExtension CreateContainerExtension()
|
||||
{
|
||||
return new AutofacContainerExtension();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the <see cref="Type"/>s of the Exceptions that are not considered
|
||||
/// root exceptions by the <see cref="ExceptionExtensions"/>.
|
||||
/// </summary>
|
||||
protected override void RegisterFrameworkExceptionTypes()
|
||||
{
|
||||
ExceptionExtensions.RegisterFrameworkExceptionType(typeof(AutofacCore.DependencyResolutionException));
|
||||
ExceptionExtensions.RegisterFrameworkExceptionType(typeof(AutofacCore.Registration.ComponentNotRegisteredException));
|
||||
|
||||
}
|
||||
|
||||
protected override void Initialize()
|
||||
{
|
||||
base.Initialize();
|
||||
}
|
||||
|
||||
|
||||
protected override Window CreateShell()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using Prism.Ioc;
|
||||
using System;
|
||||
using AutofacCore = Autofac.Core;
|
||||
|
||||
namespace Prism.Autofac
|
||||
{
|
||||
/// <summary>
|
||||
/// Base bootstrapper class that uses <see cref="UnityContainerExtension"/> as it's container.
|
||||
/// </summary>
|
||||
public abstract class PrismBootstrapper : PrismBootstrapperBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Create a new <see cref="UnityContainerExtension"/> used by Prism.
|
||||
/// </summary>
|
||||
/// <returns>A new <see cref="UnityContainerExtension"/>.</returns>
|
||||
protected override IContainerExtension CreateContainerExtension()
|
||||
{
|
||||
return new AutofacContainerExtension();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the <see cref="Type"/>s of the Exceptions that are not considered
|
||||
/// root exceptions by the <see cref="ExceptionExtensions"/>.
|
||||
/// </summary>
|
||||
protected override void RegisterFrameworkExceptionTypes()
|
||||
{
|
||||
ExceptionExtensions.RegisterFrameworkExceptionType(typeof(AutofacCore.DependencyResolutionException));
|
||||
ExceptionExtensions.RegisterFrameworkExceptionType(typeof(AutofacCore.Registration.ComponentNotRegisteredException));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using Autofac;
|
||||
using Prism.Ioc;
|
||||
|
||||
namespace Prism.Autofac
|
||||
{
|
||||
/// <summary>
|
||||
/// Extensions help get the underlying <see cref="IUnityContainer" />
|
||||
/// </summary>
|
||||
public static class PrismIocExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the <see cref="IUnityContainer" /> from the <see cref="IContainerProvider" />
|
||||
/// </summary>
|
||||
/// <param name="containerProvider">The current <see cref="IContainerProvider" /></param>
|
||||
/// <returns>The underlying <see cref="IUnityContainer" /></returns>
|
||||
public static IContainer GetContainer(this IContainerProvider containerProvider)
|
||||
{
|
||||
return ((IContainerExtension<IContainer>)containerProvider).Instance;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="IUnityContainer" /> from the <see cref="IContainerProvider" />
|
||||
/// </summary>
|
||||
/// <param name="containerRegistry">The current <see cref="IContainerRegistry" /></param>
|
||||
/// <returns>The underlying <see cref="IUnityContainer" /></returns>
|
||||
public static IContainer GetContainer(this IContainerRegistry containerRegistry)
|
||||
{
|
||||
return ((IContainerExtension<IContainer>)containerRegistry).Instance;
|
||||
}
|
||||
/// <summary>
|
||||
/// Gets the <see cref="ContainerBuilder"/> used to register services.
|
||||
/// </summary>
|
||||
/// <param name="registry"></param>
|
||||
/// <returns>The current <see cref="ContainerBuilder"/></returns>
|
||||
public static ContainerBuilder GetBuilder(this IContainerRegistry registry)
|
||||
{
|
||||
return ((IAutofacContainerExtension)registry).Builder;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Prism.Regions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using Autofac;
|
||||
using Autofac.Core;
|
||||
using System.Windows.Input;
|
||||
using MAX.Core.DependencyInjection;
|
||||
namespace MAX.Framework.PrismExtension;
|
||||
public static class RegionManagerExtension
|
||||
{
|
||||
public static FrameworkElement GetView(this IRegionManager regionManager, string regionName, string target)
|
||||
{
|
||||
var region = regionManager.Regions[regionName];
|
||||
if (region != null)
|
||||
{
|
||||
|
||||
var viewType = IocManager.GetRegistrationType(target);
|
||||
foreach (var viewItem in region.Views)
|
||||
{
|
||||
if (viewItem.GetType() == viewType)
|
||||
{
|
||||
if (viewItem is FrameworkElement fk)
|
||||
{
|
||||
return fk;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using Autofac;
|
||||
using MAX.Core;
|
||||
using MAX.Core.Autofac;
|
||||
using MAX.Core.DependencyInjection;
|
||||
using MAX.Core.Infrastructure;
|
||||
using MAX.Core.Logger;
|
||||
using MAX.Core.Reflections;
|
||||
using MAX.Framework.Logger;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
namespace MAX.Framework;
|
||||
|
||||
public class Startup : IStartup
|
||||
{
|
||||
public int Priority => int.MaxValue - 1;
|
||||
|
||||
public void Initialize()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public void Register(ContainerBuilder builder)
|
||||
{
|
||||
#region 注册所有IOC接口
|
||||
|
||||
Assembly[] assemblies = AppTypeFinder.Assemblies.ToArray();
|
||||
|
||||
Type typeSingleton = typeof(ISingletonDependency);
|
||||
builder.RegisterAssemblyTypes(assemblies)
|
||||
.Where(a =>
|
||||
typeSingleton.IsAssignableFrom(a)
|
||||
&& a.IsClass
|
||||
&& !a.IsAbstract
|
||||
)
|
||||
.AsImplementedInterfaces()
|
||||
.AsSelf()
|
||||
.PropertiesAutowired(new CustomPropertySelector())
|
||||
.SingleInstance();
|
||||
|
||||
|
||||
Type typeTransient = typeof(ITransientDependency);
|
||||
builder.RegisterAssemblyTypes(assemblies)
|
||||
.Where(a =>
|
||||
typeTransient.IsAssignableFrom(a)
|
||||
&& a.IsClass
|
||||
&& !a.IsAbstract
|
||||
)
|
||||
.AsImplementedInterfaces()
|
||||
.AsSelf()
|
||||
.PropertiesAutowired(new CustomPropertySelector())
|
||||
.InstancePerDependency();
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user