懒得勤快 hace 5 años
padre
commit
f6370f5cdc
Se han modificado 80 ficheros con 283 adiciones y 12733 borrados
  1. 1 2
      Masuit.Tools.Core.UnitTest/ExtensionTest.cs
  2. 0 33
      Masuit.Tools.Core/Hardware/CPU_INFO.cs
  3. 0 59
      Masuit.Tools.Core/Hardware/CpuInfo.cs
  4. 0 23
      Masuit.Tools.Core/Hardware/DiskData.cs
  5. 0 23
      Masuit.Tools.Core/Hardware/MemoryInfo.cs
  6. 0 23
      Masuit.Tools.Core/Hardware/NetData.cs
  7. 0 43
      Masuit.Tools.Core/Hardware/RamInfo.cs
  8. 0 853
      Masuit.Tools.Core/Hardware/SystemInfo.cs
  9. 0 22
      Masuit.Tools.Core/Hardware/SystemtimeInfo.cs
  10. 0 15
      Masuit.Tools.Core/Hardware/Unit.cs
  11. 0 209
      Masuit.Tools.Core/Html/HtmlTools.cs
  12. 0 70
      Masuit.Tools.Core/Linq/LinqExtension.cs
  13. 0 55
      Masuit.Tools.Core/Logging/LogInfo.cs
  14. 0 28
      Masuit.Tools.Core/Logging/LogLevel.cs
  15. 0 452
      Masuit.Tools.Core/Logging/LogManager.cs
  16. 0 74
      Masuit.Tools.Core/Mapping/Copier.cs
  17. 0 12
      Masuit.Tools.Core/Mapping/Core/CreateConfig.cs
  18. 0 193
      Masuit.Tools.Core/Mapping/Core/MapperConfiguration.cs
  19. 0 679
      Masuit.Tools.Core/Mapping/Core/MapperConfigurationBase.cs
  20. 0 134
      Masuit.Tools.Core/Mapping/Core/MapperConfigurationCollectionContainer.cs
  21. 0 35
      Masuit.Tools.Core/Mapping/Core/PropertiesNotMapped.cs
  22. 0 59
      Masuit.Tools.Core/Mapping/Core/TypePairMapper.cs
  23. 0 56
      Masuit.Tools.Core/Mapping/Exceptions/MapperExceptionBase.cs
  24. 0 55
      Masuit.Tools.Core/Mapping/Exceptions/MapperExistException.cs
  25. 0 54
      Masuit.Tools.Core/Mapping/Exceptions/MapperNotInitializedException.cs
  26. 0 46
      Masuit.Tools.Core/Mapping/Exceptions/NoActionAfterMappingException.cs
  27. 0 54
      Masuit.Tools.Core/Mapping/Exceptions/NoFoundMapperException.cs
  28. 0 53
      Masuit.Tools.Core/Mapping/Exceptions/NotSameTypePropertyException.cs
  29. 0 54
      Masuit.Tools.Core/Mapping/Exceptions/PropertyNoExistException.cs
  30. 0 59
      Masuit.Tools.Core/Mapping/Exceptions/ReadOnlyPropertyException.cs
  31. 0 19
      Masuit.Tools.Core/Mapping/ExpressionCpoier.cs
  32. 0 176
      Masuit.Tools.Core/Mapping/ExpressionMapper.cs
  33. 0 77
      Masuit.Tools.Core/Mapping/Extensions/ExpressionExtentions.cs
  34. 0 124
      Masuit.Tools.Core/Mapping/Extensions/QueryableExtentions.cs
  35. 0 34
      Masuit.Tools.Core/Mapping/Helper/MapperHelper.cs
  36. 0 64
      Masuit.Tools.Core/Mapping/Helper/TypeSystem.cs
  37. 0 26
      Masuit.Tools.Core/Mapping/Visitor/ChangParameterExpressionVisitor.cs
  38. 0 113
      Masuit.Tools.Core/Mapping/Visitor/ConverterExpressionVisitor.cs
  39. 0 210
      Masuit.Tools.Core/Mapping/Visitor/MapperExpressionVisitor.cs
  40. 0 35
      Masuit.Tools.Core/Mapping/Visitor/PropertiesVisitor.cs
  41. 87 0
      Masuit.Tools.Core/Masuit.Tools.Core.csproj
  42. 0 1132
      Masuit.Tools.Core/Media/ImageUtilities.cs
  43. 0 28
      Masuit.Tools.Core/Media/ThumbnailCutMode.cs
  44. 0 64
      Masuit.Tools.Core/Models/BaiduIP.cs
  45. 0 142
      Masuit.Tools.Core/Models/Email.cs
  46. 0 16
      Masuit.Tools.Core/Models/IspInfo.cs
  47. 0 191
      Masuit.Tools.Core/Models/PhysicsAddress.cs
  48. 0 52
      Masuit.Tools.Core/Models/TaobaoIP.cs
  49. 0 634
      Masuit.Tools.Core/Net/FtpClient.cs
  50. 0 413
      Masuit.Tools.Core/Net/MultiThreadDownloader.cs
  51. 0 319
      Masuit.Tools.Core/Net/PartialDownloader.cs
  52. 0 566
      Masuit.Tools.Core/Net/SocketClient.cs
  53. 0 450
      Masuit.Tools.Core/Reflection/ClassHelper.cs
  54. 0 233
      Masuit.Tools.Core/Reflection/ReflectHelper.cs
  55. 0 542
      Masuit.Tools.Core/Reflection/ReflectionUtil.cs
  56. 0 1536
      Masuit.Tools.Core/Security/Encrypt.cs
  57. 0 39
      Masuit.Tools.Core/Security/HashEncode.cs
  58. 0 397
      Masuit.Tools.Core/Security/RSACrypt.cs
  59. 0 50
      Masuit.Tools.Core/Systems/ConcurrentLimitedQueue.cs
  60. 0 41
      Masuit.Tools.Core/Systems/Disposable.cs
  61. 0 209
      Masuit.Tools.Core/Systems/EnumExt.cs
  62. 0 86
      Masuit.Tools.Core/Systems/HiPerfTimer.cs
  63. 0 39
      Masuit.Tools.Core/Systems/LimitedQueue.cs
  64. 0 173
      Masuit.Tools.Core/Systems/SnowFlake.cs
  65. 0 15
      Masuit.Tools.Core/Systems/StopwatchHelper.cs
  66. 0 37
      Masuit.Tools.Core/Validator/ComplexPassword.cs
  67. 0 43
      Masuit.Tools.Core/Validator/IsEmailAttribute.cs
  68. 0 31
      Masuit.Tools.Core/Validator/IsIPAddressAttribute.cs
  69. 0 31
      Masuit.Tools.Core/Validator/IsPhoneAttribute.cs
  70. 0 46
      Masuit.Tools.Core/Validator/MaxValueAttribute.cs
  71. 0 46
      Masuit.Tools.Core/Validator/MinValueAttribute.cs
  72. 0 431
      Masuit.Tools.Core/Win32/Windows.cs
  73. 0 57
      Masuit.Tools.Core/Win32/WindowsCommand.cs
  74. 0 20
      Masuit.Tools.UnitTest/Mapping/Extentions/QueryableExtentionsTest.cs
  75. 26 2
      Masuit.Tools/Hardware/RamInfo.cs
  76. 5 5
      Masuit.Tools/Mapping/Extensions/QueryableExtentions.cs
  77. 142 195
      Masuit.Tools/Net/PartialDownloader.cs
  78. 2 3
      Masuit.Tools/Security/Encrypt.cs
  79. 19 5
      Masuit.Tools/Systems/HiPerfTimer.cs
  80. 1 9
      NetCoreTest/Program.cs

+ 1 - 2
Masuit.Tools.Core.UnitTest/ExtensionTest.cs

@@ -19,7 +19,6 @@ namespace Masuit.Tools.Core.UnitTest
         }
 
         [Theory]
-        [InlineData("www.baidu.com")]
         [InlineData("//www.baidu.com")]
         [InlineData("http://www.baidu.com")]
         [InlineData("https://www.baidu.com")]
@@ -30,7 +29,7 @@ namespace Masuit.Tools.Core.UnitTest
         [InlineData("https://baidu.com:8080/abc/def/hi_jk-mn%ADF%AA?s=www&x=yyy#top/aaa/bbb/ccc")]
         [InlineData("http://music.163.com/def/hhh.html?s=www&x=yyy#/my/m/music/empty")]
         [InlineData("http://music.163.com/#/search/m/?%23%2Fmy%2Fm%2Fmusic%2Fempty=&s=fade&type=1!k")]
-        public void MatchUrl_Valid_ReturnFalse(string s)
+        public void MatchUrl_Valid_ReturnTrue(string s)
         {
             var isip = s.MatchUrl();
             Assert.True(isip);

+ 0 - 33
Masuit.Tools.Core/Hardware/CPU_INFO.cs

@@ -1,33 +0,0 @@
-using System.Runtime.InteropServices;
-
-namespace Masuit.Tools.Hardware
-{
-
-    public static partial class SystemInfo
-    {
-        #region 定义CPU的信息结构
-
-        /// <summary>
-        /// 定义CPU的信息结构
-        /// </summary>
-        [StructLayout(LayoutKind.Sequential)]
-        public struct CPU_INFO
-        {
-#pragma warning disable 1591
-            public uint dwOemId;
-            public uint dwPageSize;
-            public uint lpMinimumApplicationAddress;
-            public uint lpMaximumApplicationAddress;
-            public uint dwActiveProcessorMask;
-            public uint dwNumberOfProcessors;
-            public uint dwProcessorType;
-            public uint dwAllocationGranularity;
-            public uint dwProcessorLevel;
-            public uint dwProcessorRevision;
-#pragma warning restore 1591
-        }
-#pragma warning restore 1591
-
-        #endregion
-    }
-}

+ 0 - 59
Masuit.Tools.Core/Hardware/CpuInfo.cs

@@ -1,59 +0,0 @@
-namespace Masuit.Tools.Hardware
-{
-    /// <summary>
-    /// CPU模型
-    /// </summary>
-    public class CpuInfo
-    {
-        /// <summary>
-        /// 设备ID端口
-        /// </summary>
-        public string DeviceID { get; set; }
-
-        /// <summary>
-        /// CPU型号 
-        /// </summary>
-        public string Type { get; set; }
-
-        /// <summary>
-        /// CPU厂商
-        /// </summary>
-        public string Manufacturer { get; set; }
-
-        /// <summary>
-        /// CPU最大睿频
-        /// </summary>
-        public string MaxClockSpeed { get; set; }
-
-        /// <summary>
-        /// CPU的时钟频率
-        /// </summary>
-        public string CurrentClockSpeed { get; set; }
-
-        /// <summary>
-        /// CPU核心数
-        /// </summary>
-        public int NumberOfCores { get; set; }
-
-        /// <summary>
-        /// 逻辑处理器核心数
-        /// </summary>
-        public int NumberOfLogicalProcessors { get; set; }
-
-        /// <summary>
-        /// CPU使用率
-        /// </summary>
-        public double CpuLoad { get; set; }
-
-        /// <summary>
-        /// CPU位宽
-        /// </summary>
-        public string DataWidth { get; set; }
-
-        /// <summary>
-        /// 核心温度
-        /// </summary>
-        public double Temperature { get; set; }
-    }
-#pragma warning restore 1591
-}

+ 0 - 23
Masuit.Tools.Core/Hardware/DiskData.cs

@@ -1,23 +0,0 @@
-namespace Masuit.Tools.Hardware
-{
-    /// <summary>
-    /// 磁盘数据
-    /// </summary>
-    public enum DiskData
-    {
-        /// <summary>
-        /// 读写
-        /// </summary>
-        ReadAndWrite,
-
-        /// <summary>
-        /// 读
-        /// </summary>
-        Read,
-
-        /// <summary>
-        /// 写
-        /// </summary>
-        Write
-    }
-}

+ 0 - 23
Masuit.Tools.Core/Hardware/MemoryInfo.cs

@@ -1,23 +0,0 @@
-using System.Runtime.InteropServices;
-
-namespace Masuit.Tools.Hardware
-{
-
-    /// <summary>
-    /// 定义内存的信息结构
-    /// </summary>
-    [StructLayout(LayoutKind.Sequential)]
-    public struct MemoryInfo
-    {
-#pragma warning disable 1591
-        public uint dwLength;
-        public uint dwMemoryLoad;
-        public uint dwTotalPhys;
-        public uint dwAvailPhys;
-        public uint dwTotalPageFile;
-        public uint dwAvailPageFile;
-        public uint dwTotalVirtual;
-        public uint dwAvailVirtual;
-#pragma warning restore 1591
-    }
-}

+ 0 - 23
Masuit.Tools.Core/Hardware/NetData.cs

@@ -1,23 +0,0 @@
-namespace Masuit.Tools.Hardware
-{
-    /// <summary>
-    /// 网络数据
-    /// </summary>
-    public enum NetData
-    {
-        /// <summary>
-        /// 收发
-        /// </summary>
-        ReceivedAndSent,
-
-        /// <summary>
-        /// 收
-        /// </summary>
-        Received,
-
-        /// <summary>
-        /// 发
-        /// </summary>
-        Sent
-    }
-}

+ 0 - 43
Masuit.Tools.Core/Hardware/RamInfo.cs

@@ -1,43 +0,0 @@
-namespace Masuit.Tools.Hardware
-{
-    /// <summary>
-    /// 内存条模型
-    /// </summary>
-    public class RamInfo
-    {
-        /// <summary>
-        /// 可用物理内存
-        /// </summary>
-        public double MemoryAvailable { get; set; }
-
-        /// <summary>
-        /// 物理总内存
-        /// </summary>
-        public double PhysicalMemory { get; set; }
-
-        /// <summary>
-        /// 分页内存总数
-        /// </summary>
-        public double TotalPageFile { get; set; }
-
-        /// <summary>
-        /// 分页内存可用
-        /// </summary>
-        public double AvailablePageFile { get; set; }
-
-        /// <summary>
-        /// 虚拟内存总数
-        /// </summary>
-        public double TotalVirtual { get; set; }
-
-        /// <summary>
-        /// 虚拟内存可用
-        /// </summary>
-        public double AvailableVirtual { get; set; }
-
-        /// <summary>
-        /// 内存使用率
-        /// </summary>
-        public double MemoryUsage => (1 - MemoryAvailable / PhysicalMemory) * 100;
-    }
-}

+ 0 - 853
Masuit.Tools.Core/Hardware/SystemInfo.cs

@@ -1,853 +0,0 @@
-using Masuit.Tools.Logging;
-using Microsoft.Win32;
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Management;
-using System.Runtime.InteropServices;
-using System.Text;
-using System.Threading;
-
-namespace Masuit.Tools.Hardware
-{
-    /// <summary>
-    /// 硬件信息,部分功能需要C++支持
-    /// </summary>
-    public static partial class SystemInfo
-    {
-        #region 字段
-
-        private const int GwHwndfirst = 0;
-        private const int GwHwndnext = 2;
-        private const int GwlStyle = -16;
-        private const int WsVisible = 268435456;
-        private const int WsBorder = 8388608;
-        private static readonly PerformanceCounter PcCpuLoad; //CPU计数器 
-
-        private static readonly PerformanceCounter MemoryCounter = new PerformanceCounter();
-        private static readonly PerformanceCounter CpuCounter = new PerformanceCounter();
-        private static readonly PerformanceCounter DiskReadCounter = new PerformanceCounter();
-        private static readonly PerformanceCounter DiskWriteCounter = new PerformanceCounter();
-
-        private static readonly string[] InstanceNames;
-        private static readonly PerformanceCounter[] NetRecvCounters;
-        private static readonly PerformanceCounter[] NetSentCounters;
-
-        #endregion
-
-        #region 构造函数 
-
-        /// <summary>
-        /// 静态构造函数
-        /// </summary>
-        static SystemInfo()
-        {
-            //初始化CPU计数器 
-            PcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total")
-            {
-                MachineName = "."
-            };
-            PcCpuLoad.NextValue();
-
-            //CPU个数 
-            ProcessorCount = Environment.ProcessorCount;
-
-            //获得物理内存 
-            try
-            {
-                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
-                ManagementObjectCollection moc = mc.GetInstances();
-                foreach (ManagementBaseObject mo in moc)
-                {
-                    if (mo["TotalPhysicalMemory"] != null)
-                    {
-                        PhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString());
-                    }
-                }
-
-                PerformanceCounterCategory cat = new PerformanceCounterCategory("Network Interface");
-                InstanceNames = cat.GetInstanceNames();
-                NetRecvCounters = new PerformanceCounter[InstanceNames.Length];
-                NetSentCounters = new PerformanceCounter[InstanceNames.Length];
-                for (int i = 0; i < InstanceNames.Length; i++)
-                {
-                    NetRecvCounters[i] = new PerformanceCounter();
-                    NetSentCounters[i] = new PerformanceCounter();
-                }
-
-                CompactFormat = false;
-            }
-            catch (Exception e)
-            {
-                LogManager.Error(e);
-            }
-        }
-
-        #endregion
-
-        private static bool CompactFormat { get; set; }
-
-        #region CPU核心 
-
-        /// <summary>
-        /// 获取CPU核心数 
-        /// </summary>
-        public static int ProcessorCount { get; }
-
-        #endregion
-
-        #region CPU占用率 
-
-        /// <summary>
-        /// 获取CPU占用率 %
-        /// </summary>
-        public static float CpuLoad => PcCpuLoad.NextValue();
-
-        #endregion
-
-        #region 可用内存 
-
-        /// <summary>
-        /// 获取可用内存
-        /// </summary>
-        public static long MemoryAvailable
-        {
-            get
-            {
-                try
-                {
-                    long availablebytes = 0;
-                    ManagementClass mos = new ManagementClass("Win32_OperatingSystem");
-                    foreach (var o in mos.GetInstances())
-                    {
-                        var mo = (ManagementObject)o;
-                        if (mo["FreePhysicalMemory"] != null)
-                        {
-                            availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());
-                        }
-                    }
-
-                    return availablebytes;
-                }
-                catch (Exception)
-                {
-                    return 0;
-                }
-            }
-        }
-
-        #endregion
-
-        #region 物理内存 
-
-        /// <summary>
-        /// 获取物理内存
-        /// </summary>
-        public static long PhysicalMemory { get; }
-
-        #endregion
-
-        #region 查找所有应用程序标题 
-
-        /// <summary>
-        /// 查找所有应用程序标题 
-        /// </summary>
-        /// <param name="handle">应用程序标题范型</param>
-        /// <returns>所有应用程序集合</returns>
-        public static ArrayList FindAllApps(int handle)
-        {
-            ArrayList apps = new ArrayList();
-            int hwCurr = GetWindow(handle, GwHwndfirst);
-
-            while (hwCurr > 0)
-            {
-                int IsTask = WsVisible | WsBorder;
-                int lngStyle = GetWindowLongA(hwCurr, GwlStyle);
-                bool taskWindow = (lngStyle & IsTask) == IsTask;
-                if (taskWindow)
-                {
-                    int length = GetWindowTextLength(new IntPtr(hwCurr));
-                    StringBuilder sb = new StringBuilder(2 * length + 1);
-                    GetWindowText(hwCurr, sb, sb.Capacity);
-                    string strTitle = sb.ToString();
-                    if (!string.IsNullOrEmpty(strTitle))
-                    {
-                        apps.Add(strTitle);
-                    }
-                }
-
-                hwCurr = GetWindow(hwCurr, GwHwndnext);
-            }
-
-            return apps;
-        }
-
-        #endregion
-
-        #region 获取CPU的数量
-
-        /// <summary>
-        /// 获取CPU的数量
-        /// </summary>
-        /// <returns>CPU的数量</returns>
-        public static int GetCpuCount()
-        {
-            try
-            {
-                ManagementClass m = new ManagementClass("Win32_Processor");
-                ManagementObjectCollection mn = m.GetInstances();
-                return mn.Count;
-            }
-            catch (Exception)
-            {
-                return 0;
-            }
-        }
-
-        #endregion
-
-        #region 获取CPU信息
-
-        /// <summary>
-        /// 获取CPU信息
-        /// </summary>
-        /// <returns>CPU信息</returns>
-        public static List<CpuInfo> GetCpuInfo()
-        {
-            try
-            {
-                List<CpuInfo> list = new List<CpuInfo>();
-                ManagementObjectSearcher mySearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
-                foreach (var o in mySearcher.Get())
-                {
-                    var myObject = (ManagementObject)o;
-                    list.Add(new CpuInfo
-                    {
-                        CpuLoad = CpuLoad,
-                        NumberOfLogicalProcessors = ProcessorCount,
-                        CurrentClockSpeed = myObject.Properties["CurrentClockSpeed"].Value.ToString(),
-                        Manufacturer = myObject.Properties["Manufacturer"].Value.ToString(),
-                        MaxClockSpeed = myObject.Properties["MaxClockSpeed"].Value.ToString(),
-                        Type = myObject.Properties["Name"].Value.ToString(),
-                        DataWidth = myObject.Properties["DataWidth"].Value.ToString(),
-                        DeviceID = myObject.Properties["DeviceID"].Value.ToString(),
-                        NumberOfCores = Convert.ToInt32(myObject.Properties["NumberOfCores"].Value),
-                        Temperature = GetCPUTemperature()
-                    });
-                }
-
-                return list;
-            }
-            catch (Exception)
-            {
-                return new List<CpuInfo>();
-            }
-        }
-
-        #endregion
-
-        #region 获取内存信息
-
-        /// <summary>
-        /// 获取内存信息
-        /// </summary>
-        /// <returns>内存信息</returns>
-        public static RamInfo GetRamInfo()
-        {
-            var info = new RamInfo();
-            info.MemoryAvailable = GetFreePhysicalMemory();
-            info.PhysicalMemory = GetTotalPhysicalMemory();
-            info.TotalPageFile = GetTotalVirtualMemory();
-            info.AvailablePageFile = GetTotalVirtualMemory() - GetUsedVirtualMemory();
-            info.AvailableVirtual = 1 - GetUsageVirtualMemory();
-            info.TotalVirtual = 1 - GetUsedPhysicalMemory();
-            return info;
-        }
-
-        #endregion
-
-        #region 获取CPU温度
-
-        /// <summary>
-        /// 获取CPU温度
-        /// </summary>
-        /// <returns>CPU温度</returns>
-        public static double GetCPUTemperature()
-        {
-            try
-            {
-                string str = "";
-                ManagementObjectSearcher vManagementObjectSearcher = new ManagementObjectSearcher(@"root\WMI", @"select * from MSAcpi_ThermalZoneTemperature");
-                foreach (ManagementObject managementObject in vManagementObjectSearcher.Get())
-                {
-                    str += managementObject.Properties["CurrentTemperature"].Value.ToString();
-                }
-
-                //这就是CPU的温度了
-                double temp = (double.Parse(str) - 2732) / 10;
-                return Math.Round(temp, 2);
-            }
-            catch (Exception)
-            {
-                return 0;
-            }
-        }
-
-        #endregion
-
-        #region WMI接口获取CPU使用率
-
-        /// <summary>
-        /// WMI接口获取CPU使用率
-        /// </summary>
-        /// <returns></returns>
-        public static string GetProcessorData()
-        {
-            double d = GetCounterValue(CpuCounter, "Processor", "% Processor Time", "_Total");
-            return CompactFormat ? (int)d + "%" : d.ToString("F") + "%";
-        }
-
-        #endregion
-
-        #region 获取虚拟内存使用率详情
-
-        /// <summary>
-        /// 获取虚拟内存使用率详情
-        /// </summary>
-        /// <returns></returns>
-        public static string GetMemoryVData()
-        {
-            double d = GetCounterValue(MemoryCounter, "Memory", "% Committed Bytes In Use", null);
-            var str = d.ToString("F") + "% (";
-
-            d = GetCounterValue(MemoryCounter, "Memory", "Committed Bytes", null);
-            str += FormatBytes(d) + " / ";
-
-            d = GetCounterValue(MemoryCounter, "Memory", "Commit Limit", null);
-            return str + FormatBytes(d) + ") ";
-        }
-
-        /// <summary>
-        /// 获取虚拟内存使用率
-        /// </summary>
-        /// <returns></returns>
-        public static double GetUsageVirtualMemory()
-        {
-            return GetCounterValue(MemoryCounter, "Memory", "% Committed Bytes In Use", null);
-        }
-
-        /// <summary>
-        /// 获取虚拟内存已用大小
-        /// </summary>
-        /// <returns></returns>
-        public static double GetUsedVirtualMemory()
-        {
-            return GetCounterValue(MemoryCounter, "Memory", "Committed Bytes", null);
-        }
-
-        /// <summary>
-        /// 获取虚拟内存总大小
-        /// </summary>
-        /// <returns></returns>
-        public static double GetTotalVirtualMemory()
-        {
-            return GetCounterValue(MemoryCounter, "Memory", "Commit Limit", null);
-        }
-
-        #endregion
-
-        #region 获取物理内存使用率详情
-
-        /// <summary>
-        /// 获取物理内存使用率详情描述
-        /// </summary>
-        /// <returns></returns>
-        public static string GetMemoryPData()
-        {
-            string s = QueryComputerSystem("totalphysicalmemory");
-            double totalphysicalmemory = Convert.ToDouble(s);
-
-            double d = GetCounterValue(MemoryCounter, "Memory", "Available Bytes", null);
-            d = totalphysicalmemory - d;
-
-            s = CompactFormat ? "%" : "% (" + FormatBytes(d) + " / " + FormatBytes(totalphysicalmemory) + ")";
-            d /= totalphysicalmemory;
-            d *= 100;
-            return CompactFormat ? (int)d + s : d.ToString("F") + s;
-        }
-
-        /// <summary>
-        /// 获取物理内存总数,单位B
-        /// </summary>
-        /// <returns></returns>
-        public static double GetTotalPhysicalMemory()
-        {
-            string s = QueryComputerSystem("totalphysicalmemory");
-            return s.ToDouble();
-        }
-
-        /// <summary>
-        /// 获取空闲的物理内存数,单位B
-        /// </summary>
-        /// <returns></returns>
-        public static double GetFreePhysicalMemory()
-        {
-            return GetCounterValue(MemoryCounter, "Memory", "Available Bytes", null);
-        }
-
-        /// <summary>
-        /// 获取已经使用了的物理内存数,单位B
-        /// </summary>
-        /// <returns></returns>
-        public static double GetUsedPhysicalMemory()
-        {
-            return GetTotalPhysicalMemory() - GetFreePhysicalMemory();
-        }
-
-        #endregion
-
-        #region 获取硬盘的读写速率
-
-        /// <summary>
-        /// 获取硬盘的读写速率
-        /// </summary>
-        /// <param name="dd">读或写</param>
-        /// <returns></returns>
-        public static double GetDiskData(DiskData dd) => dd == DiskData.Read ? GetCounterValue(DiskReadCounter, "PhysicalDisk", "Disk Read Bytes/sec", "_Total") : dd == DiskData.Write ? GetCounterValue(DiskWriteCounter, "PhysicalDisk", "Disk Write Bytes/sec", "_Total") : dd == DiskData.ReadAndWrite ? GetCounterValue(DiskReadCounter, "PhysicalDisk", "Disk Read Bytes/sec", "_Total") + GetCounterValue(DiskWriteCounter, "PhysicalDisk", "Disk Write Bytes/sec", "_Total") : 0;
-
-        #endregion
-
-        #region 获取网络的传输速率
-
-        /// <summary>
-        /// 获取网络的传输速率
-        /// </summary>
-        /// <param name="nd">上传或下载</param>
-        /// <returns></returns>
-        public static double GetNetData(NetData nd)
-        {
-            if (InstanceNames.Length == 0)
-            {
-                return 0;
-            }
-
-            double d = 0;
-            for (int i = 0; i < InstanceNames.Length; i++)
-            {
-                double receied = GetCounterValue(NetRecvCounters[i], "Network Interface", "Bytes Received/sec", InstanceNames[i]);
-                double send = GetCounterValue(NetSentCounters[i], "Network Interface", "Bytes Sent/sec", InstanceNames[i]);
-                switch (nd)
-                {
-                    case NetData.Received:
-                        d += receied;
-                        break;
-                    case NetData.Sent:
-                        d += send;
-                        break;
-                    case NetData.ReceivedAndSent:
-                        d += receied + send;
-                        break;
-                    default:
-                        d += 0;
-                        break;
-                }
-            }
-
-            return d;
-        }
-
-        #endregion
-
-        /// <summary>
-        /// 获取网卡硬件地址
-        /// </summary>
-        /// <returns></returns>
-        public static IList<string> GetMacAddress()
-        {
-            //获取网卡硬件地址       
-            try
-            {
-                IList<string> list = new List<string>();
-                using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
-                using var moc = mc.GetInstances();
-                foreach (ManagementObject mo in moc)
-                {
-                    if ((bool)mo["IPEnabled"])
-                    {
-                        list.Add(mo["MacAddress"].ToString());
-                    }
-                }
-
-                return list;
-            }
-            catch (Exception)
-            {
-                return new List<string>();
-            }
-        }
-
-        /// <summary>
-        /// 获取IP地址 
-        /// </summary>
-        /// <returns></returns>
-        public static IList<string> GetIPAddress()
-        {
-            //获取IP地址        
-            try
-            {
-                IList<string> list = new List<string>();
-                using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
-                using var moc = mc.GetInstances();
-                foreach (ManagementObject mo in moc)
-                {
-                    if ((bool)mo["IPEnabled"])
-                    {
-                        var ar = (Array)(mo.Properties["IpAddress"].Value);
-                        var st = ar.GetValue(0).ToString();
-                        list.Add(st);
-                    }
-                }
-
-                return list;
-            }
-            catch (Exception)
-            {
-                return new List<string>()
-                {
-                    "未能获取到当前计算机的IP地址,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。"
-                };
-            }
-        }
-
-        /// <summary>  
-        /// 运行一个控制台程序并返回其输出参数。  
-        /// </summary>  
-        /// <param name="filename">程序名</param>  
-        /// <param name="arguments">输入参数</param>
-        /// <param name="recordLog">是否记录日志</param>
-        /// <returns></returns>  
-        public static string RunApp(string filename, string arguments, bool recordLog)
-        {
-            try
-            {
-                if (recordLog)
-                {
-                    Trace.WriteLine(filename + " " + arguments);
-                }
-
-                Process proc = new Process
-                {
-                    StartInfo =
-                    {
-                        FileName = filename,
-                        CreateNoWindow = true,
-                        Arguments = arguments,
-                        RedirectStandardOutput = true,
-                        UseShellExecute = false
-                    }
-                };
-                proc.Start();
-
-                using var sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default);
-                Thread.Sleep(100); //貌似调用系统的nslookup还未返回数据或者数据未编码完成,程序就已经跳过直接执行  
-                //txt = sr.ReadToEnd()了,导致返回的数据为空,故睡眠令硬件反应  
-                if (!proc.HasExited) //在无参数调用nslookup后,可以继续输入命令继续操作,如果进程未停止就直接执行  
-                {
-                    //txt = sr.ReadToEnd()程序就在等待输入,而且又无法输入,直接掐住无法继续运行  
-                    proc.Kill();
-                }
-
-                string txt = sr.ReadToEnd();
-                sr.Close();
-                if (recordLog)
-                {
-                    Trace.WriteLine(txt);
-                }
-                return txt;
-            }
-            catch (Exception ex)
-            {
-                Trace.WriteLine(ex);
-                return ex.Message;
-            }
-        }
-
-        /// <summary>
-        /// 获取操作系统版本
-        /// </summary>
-        /// <returns></returns>
-        public static string GetOsVersion()
-        {
-            try
-            {
-                return Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion")?.GetValue("ProductName").ToString();
-            }
-            catch (Exception)
-            {
-                return "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。";
-            }
-        }
-
-        #region 将速度值格式化成字节单位
-
-        /// <summary>
-        /// 将速度值格式化成字节单位
-        /// </summary>
-        /// <param name="bytes"></param>
-        /// <returns></returns>
-        public static string FormatBytes(this double bytes)
-        {
-            int unit = 0;
-            while (bytes > 1024)
-            {
-                bytes /= 1024;
-                ++unit;
-            }
-
-            string s = CompactFormat ? ((int)bytes).ToString() : bytes.ToString("F") + " ";
-            return s + (Unit)unit;
-        }
-
-        #endregion
-
-        #region 查询计算机系统信息
-
-        /// <summary>
-        /// 获取计算机开机时间
-        /// </summary>
-        /// <returns>datetime</returns>
-        public static DateTime BootTime()
-        {
-            var query = new SelectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem WHERE Primary='true'");
-            var searcher = new ManagementObjectSearcher(query);
-
-            foreach (ManagementObject mo in searcher.Get())
-            {
-                return ManagementDateTimeConverter.ToDateTime(mo.Properties["LastBootUpTime"].Value.ToString());
-            }
-
-            return DateTime.Now - TimeSpan.FromMilliseconds(Environment.TickCount & Int32.MaxValue);
-        }
-
-        /// <summary>
-        /// 查询计算机系统信息
-        /// </summary>
-        /// <param name="type">类型名</param>
-        /// <returns></returns>
-        public static string QueryComputerSystem(string type)
-        {
-            try
-            {
-                string str = null;
-                ManagementObjectSearcher objCS = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem");
-                foreach (ManagementObject objMgmt in objCS.Get())
-                {
-                    str = objMgmt[type].ToString();
-                }
-                return str;
-            }
-            catch (Exception e)
-            {
-                return "未能获取到当前计算机系统信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。异常信息:" + e.Message;
-            }
-        }
-
-        #endregion
-
-        #region 获取环境变量
-
-        /// <summary>
-        /// 获取环境变量
-        /// </summary>
-        /// <param name="type">环境变量名</param>
-        /// <returns></returns>
-        public static string QueryEnvironment(string type) => Environment.ExpandEnvironmentVariables(type);
-
-        #endregion
-
-        #region 获取磁盘空间
-
-        /// <summary>
-        /// 获取磁盘可用空间
-        /// </summary>
-        /// <returns></returns>
-        public static Dictionary<string, string> DiskFree()
-        {
-            try
-            {
-                Dictionary<string, string> dic = new Dictionary<string, string>();
-                ManagementObjectSearcher objCS = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk");
-                foreach (ManagementObject objMgmt in objCS.Get())
-                {
-                    var device = objMgmt["DeviceID"];
-                    if (null != device)
-                    {
-                        var space = objMgmt["FreeSpace"];
-                        if (null != space)
-                        {
-                            dic.Add(device.ToString(), FormatBytes(double.Parse(space.ToString())));
-                        }
-                    }
-                }
-
-                return dic;
-            }
-            catch (Exception)
-            {
-                return new Dictionary<string, string>()
-                {
-                    { "null", "未能获取到当前计算机的磁盘信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。" }
-                };
-            }
-        }
-
-        /// <summary>
-        /// 获取磁盘总空间
-        /// </summary>
-        /// <returns></returns>
-        public static Dictionary<string, string> DiskTotalSpace()
-        {
-            try
-            {
-                Dictionary<string, string> dic = new Dictionary<string, string>();
-                ManagementObjectSearcher objCS = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk");
-                foreach (ManagementObject objMgmt in objCS.Get())
-                {
-                    var device = objMgmt["DeviceID"];
-                    if (null != device)
-                    {
-                        var space = objMgmt["Size"];
-                        if (null != space)
-                        {
-                            dic.Add(device.ToString(), FormatBytes(double.Parse(space.ToString())));
-                        }
-                    }
-                }
-
-                return dic;
-            }
-            catch (Exception)
-            {
-                return new Dictionary<string, string>();
-            }
-        }
-
-
-        /// <summary>
-        /// 获取磁盘已用空间
-        /// </summary>
-        /// <returns></returns>
-        public static Dictionary<string, string> DiskUsedSpace()
-        {
-            try
-            {
-                Dictionary<string, string> dic = new Dictionary<string, string>();
-                ManagementObjectSearcher objCS = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk");
-                foreach (ManagementObject objMgmt in objCS.Get())
-                {
-                    var device = objMgmt["DeviceID"];
-                    if (null != device)
-                    {
-                        var free = objMgmt["FreeSpace"];
-                        var total = objMgmt["Size"];
-                        if (null != total)
-                        {
-                            dic.Add(device.ToString(), FormatBytes(double.Parse(total.ToString()) - free.ToString().ToDouble()));
-                        }
-                    }
-                }
-
-                return dic;
-            }
-            catch (Exception)
-            {
-                return new Dictionary<string, string>()
-                {
-                    { "null", "未能获取到当前计算机的磁盘信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。" }
-                };
-            }
-        }
-
-        /// <summary>
-        /// 获取磁盘使用率
-        /// </summary>
-        /// <returns></returns>
-        public static Dictionary<string, double> DiskUsage()
-        {
-            try
-            {
-                Dictionary<string, double> dic = new Dictionary<string, double>();
-                ManagementObjectSearcher objCS = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk");
-                foreach (ManagementObject objMgmt in objCS.Get())
-                {
-                    var device = objMgmt["DeviceID"];
-                    if (null != device)
-                    {
-                        var free = objMgmt["FreeSpace"];
-                        var total = objMgmt["Size"];
-                        if (null != total && total.ToString().ToDouble() > 0)
-                        {
-                            dic.Add(device.ToString(), 1 - free.ToString().ToDouble() / total.ToString().ToDouble());
-                        }
-                    }
-                }
-
-                return dic;
-            }
-            catch (Exception)
-            {
-                return new Dictionary<string, double>()
-                {
-                    { "未能获取到当前计算机的磁盘信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。", 0 }
-                };
-            }
-        }
-
-        #endregion
-
-        private static double GetCounterValue(PerformanceCounter pc, string categoryName, string counterName, string instanceName)
-        {
-            pc.CategoryName = categoryName;
-            pc.CounterName = counterName;
-            pc.InstanceName = instanceName;
-            return pc.NextValue();
-        }
-
-        #region Win32API声明 
-
-#pragma warning disable 1591
-        [DllImport("kernel32")]
-        public static extern void GetWindowsDirectory(StringBuilder winDir, int count);
-
-        [DllImport("kernel32")]
-        public static extern void GetSystemDirectory(StringBuilder sysDir, int count);
-
-        [DllImport("kernel32")]
-        public static extern void GetSystemInfo(ref CPU_INFO cpuinfo);
-
-        [DllImport("kernel32")]
-        public static extern void GlobalMemoryStatus(ref MemoryInfo meminfo);
-
-        [DllImport("kernel32")]
-        public static extern void GetSystemTime(ref SystemtimeInfo stinfo);
-
-        [DllImport("IpHlpApi.dll")]
-        public static extern uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);
-
-        [DllImport("User32")]
-        public static extern int GetWindow(int hWnd, int wCmd);
-
-        [DllImport("User32")]
-        public static extern int GetWindowLongA(int hWnd, int wIndx);
-
-        [DllImport("user32.dll")]
-        public static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);
-
-        [DllImport("user32", CharSet = CharSet.Auto)]
-        public static extern int GetWindowTextLength(IntPtr hWnd);
-#pragma warning restore 1591
-
-        #endregion
-    }
-}

+ 0 - 22
Masuit.Tools.Core/Hardware/SystemtimeInfo.cs

@@ -1,22 +0,0 @@
-using System.Runtime.InteropServices;
-
-namespace Masuit.Tools.Hardware
-{
-    /// <summary>
-    /// 定义系统时间的信息结构
-    /// </summary>
-    [StructLayout(LayoutKind.Sequential)]
-    public struct SystemtimeInfo
-    {
-#pragma warning disable 1591
-        public ushort wYear;
-        public ushort wMonth;
-        public ushort wDayOfWeek;
-        public ushort wDay;
-        public ushort wHour;
-        public ushort wMinute;
-        public ushort wSecond;
-        public ushort wMilliseconds;
-#pragma warning restore 1591
-    }
-}

+ 0 - 15
Masuit.Tools.Core/Hardware/Unit.cs

@@ -1,15 +0,0 @@
-namespace Masuit.Tools.Hardware
-{
-
-    /// <summary>
-    /// 字节单位枚举
-    /// </summary>
-    enum Unit
-    {
-        B,
-        KB,
-        MB,
-        GB,
-        EB
-    }
-}

+ 0 - 209
Masuit.Tools.Core/Html/HtmlTools.cs

@@ -1,209 +0,0 @@
-using Ganss.XSS;
-using HtmlAgilityPack;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text.RegularExpressions;
-
-namespace Masuit.Tools.Html
-{
-    /// <summary>
-    /// html工具类
-    /// </summary>
-    public static partial class HtmlTools
-    {
-        private static readonly HtmlSanitizer Sanitizer = new HtmlSanitizer();
-
-        static HtmlTools()
-        {
-            Sanitizer.AllowedAttributes.Remove("id");
-            Sanitizer.AllowedAttributes.Remove("alt");
-            Sanitizer.AllowedCssProperties.Remove("font-family");
-            Sanitizer.AllowedCssProperties.Remove("background-color");
-            Sanitizer.KeepChildNodes = true;
-            Sanitizer.AllowedTags.Remove("input");
-            Sanitizer.AllowedTags.Remove("button");
-            Sanitizer.AllowedTags.Remove("iframe");
-            Sanitizer.AllowedTags.Remove("frame");
-            Sanitizer.AllowedTags.Remove("textarea");
-            Sanitizer.AllowedTags.Remove("select");
-            Sanitizer.AllowedTags.Remove("form");
-            Sanitizer.AllowedAttributes.Add("src");
-            Sanitizer.AllowedAttributes.Add("class");
-            Sanitizer.AllowedAttributes.Add("style");
-        }
-
-        /// <summary>
-        /// 标准的防止html的xss净化器
-        /// </summary>
-        /// <param name="html"></param>
-        /// <returns></returns>
-        public static string HtmlSantinizerStandard(this string html)
-        {
-            return Sanitizer.Sanitize(html);
-        }
-
-        /// <summary>
-        /// 自定义的防止html的xss净化器
-        /// </summary>
-        /// <param name="html">源html</param>
-        /// <param name="labels">需要移除的标签集合</param>
-        /// <param name="attributes">需要移除的属性集合</param>
-        /// <param name="styles">需要移除的样式集合</param>
-        /// <returns></returns>
-        public static string HtmlSantinizerCustom(this string html, string[] labels = null, string[] attributes = null, string[] styles = null)
-        {
-            if (labels != null)
-            {
-                foreach (string label in labels)
-                {
-                    Sanitizer.AllowedTags.Remove(label);
-                }
-            }
-
-            if (attributes != null)
-            {
-                foreach (string attr in attributes)
-                {
-                    Sanitizer.AllowedAttributes.Remove(attr);
-                }
-            }
-
-            if (styles != null)
-            {
-                foreach (string p in styles)
-                {
-                    Sanitizer.AllowedCssProperties.Remove(p);
-                }
-            }
-
-            Sanitizer.KeepChildNodes = true;
-            return Sanitizer.Sanitize(html);
-        }
-        /// <summary>
-        /// 去除html标签后并截取字符串
-        /// </summary>
-        /// <param name="html">源html</param>
-        /// <param name="length">截取长度</param>
-        /// <returns></returns>
-        public static string RemoveHtmlTag(this string html, int length = 0)
-        {
-            var doc = new HtmlDocument();
-            doc.LoadHtml(html);
-            var strText = doc.DocumentNode.InnerText;
-            if (length > 0 && strText.Length > length)
-            {
-                return strText.Substring(0, length);
-            }
-
-            return strText;
-        }
-
-        /// <summary>
-        /// 清理Word文档转html后的冗余标签属性
-        /// </summary>
-        /// <param name="html"></param>
-        /// <returns></returns>
-        public static string ClearHtml(this string html)
-        {
-            string s = Regex.Match(Regex.Replace(html, @"background-color:#?\w{3,7}|font-family:'?[\w|\(|\)]*'?;?", string.Empty), @"<body[^>]*>([\s\S]*)<\/body>").Groups[1].Value.Replace("&#xa0;", string.Empty);
-            s = Regex.Replace(s, @"\w+-?\w+:0\w+;?", string.Empty); //去除多余的零值属性
-            s = Regex.Replace(s, "alt=\"(.+?)\"", string.Empty); //除去alt属性
-            s = Regex.Replace(s, @"-aw.+?\s", string.Empty); //去除Word产生的-aw属性
-            return s;
-        }
-
-        /// <summary>
-        /// 替换html的img路径为绝对路径
-        /// </summary>
-        /// <param name="html"></param>
-        /// <param name="imgDest"></param>
-        /// <returns></returns>
-        public static string ReplaceHtmlImgSource(this string html, string imgDest) => html.Replace("<img src=\"", "<img src=\"" + imgDest + "/");
-
-        /// <summary>
-        /// 将src的绝对路径换成相对路径
-        /// </summary>
-        /// <param name="s"></param>
-        /// <returns></returns>
-        public static string ConvertImgSrcToRelativePath(this string s)
-        {
-            return Regex.Replace(s, @"<img src=""(http:\/\/.+?)/", @"<img src=""/");
-        }
-
-        /// <summary>
-        /// 匹配html的所有img标签集合
-        /// </summary>
-        /// <param name="html"></param>
-        /// <returns></returns>
-        public static IEnumerable<HtmlNode> MatchImgTags(this string html)
-        {
-            var doc = new HtmlDocument();
-            doc.LoadHtml(html);
-            var nodes = doc.DocumentNode.Descendants("img");
-            return nodes;
-        }
-
-        /// <summary>
-        /// 匹配html的所有img标签的src集合
-        /// </summary>
-        /// <param name="html"></param>
-        /// <returns></returns>
-        public static IEnumerable<string> MatchImgSrcs(this string html)
-        {
-            return MatchImgTags(html).Where(n => n.Attributes.Contains("src")).Select(n => n.Attributes["src"].Value);
-        }
-
-        /// <summary>
-        /// 获取html中第一个img标签的src
-        /// </summary>
-        /// <param name="html"></param>
-        /// <returns></returns>
-        public static string MatchFirstImgSrc(this string html)
-        {
-            return MatchImgSrcs(html).FirstOrDefault();
-        }
-
-        /// <summary>
-        /// 随机获取html代码中的img标签的src属性
-        /// </summary>
-        /// <param name="html"></param>
-        /// <returns></returns>
-        public static string MatchRandomImgSrc(this string html)
-        {
-            int count = MatchImgSrcs(html).Count();
-            var rnd = new Random();
-            return MatchImgSrcs(html).ElementAtOrDefault(rnd.Next(count));
-        }
-
-        /// <summary>
-        /// 替换回车换行符为html换行符
-        /// </summary>
-        /// <param name="str">html</param>
-        public static string StrFormat(this string str)
-        {
-            str = str.Replace("\r\n", "<br />");
-            str = str.Replace("\n", "<br />");
-            var str2 = str;
-
-            return str2;
-        }
-
-        /// <summary>
-        /// 替换html字符
-        /// </summary>
-        /// <param name="strHtml">html</param>
-        public static string EncodeHtml(this string strHtml)
-        {
-            if (strHtml != "")
-            {
-                strHtml = strHtml.Replace(",", "&def");
-                strHtml = strHtml.Replace("'", "&dot");
-                strHtml = strHtml.Replace(";", "&dec");
-                return strHtml;
-            }
-
-            return "";
-        }
-    }
-}

+ 0 - 70
Masuit.Tools.Core/Linq/LinqExtension.cs

@@ -1,70 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq.Expressions;
-
-namespace Masuit.Tools.Core.Linq
-{
-    /// <summary>
-    /// LINQ扩展方法
-    /// </summary>
-    public static class LinqExtension
-    {
-        /// <summary>
-        /// 与连接
-        /// </summary>
-        /// <typeparam name="T">类型</typeparam>
-        /// <param name="left">左条件</param>
-        /// <param name="right">右条件</param>
-        /// <returns>新表达式</returns>
-        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right)
-        {
-            return CombineLambdas(left, right, ExpressionType.AndAlso);
-        }
-
-        /// <summary>
-        /// 或连接
-        /// </summary>
-        /// <typeparam name="T">类型</typeparam>
-        /// <param name="left">左条件</param>
-        /// <param name="right">右条件</param>
-        /// <returns>新表达式</returns>
-        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right)
-        {
-            return CombineLambdas(left, right, ExpressionType.OrElse);
-        }
-
-        private static Expression<Func<T, bool>> CombineLambdas<T>(this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right, ExpressionType expressionType)
-        {
-            if (IsExpressionBodyConstant(left))
-            {
-                return right;
-            }
-
-            var visitor = new SubstituteParameterVisitor
-            {
-                Sub =
-                {
-                    [right.Parameters[0]] = left.Parameters[0]
-                }
-            };
-
-            Expression body = Expression.MakeBinary(expressionType, left.Body, visitor.Visit(right.Body));
-            return Expression.Lambda<Func<T, bool>>(body, left.Parameters[0]);
-        }
-
-        private static bool IsExpressionBodyConstant<T>(Expression<Func<T, bool>> left)
-        {
-            return left.Body.NodeType == ExpressionType.Constant;
-        }
-
-        internal class SubstituteParameterVisitor : ExpressionVisitor
-        {
-            public Dictionary<Expression, Expression> Sub = new Dictionary<Expression, Expression>();
-
-            protected override Expression VisitParameter(ParameterExpression node)
-            {
-                return Sub.TryGetValue(node, out var newValue) ? newValue : node;
-            }
-        }
-    }
-}

+ 0 - 55
Masuit.Tools.Core/Logging/LogInfo.cs

@@ -1,55 +0,0 @@
-using System;
-
-namespace Masuit.Tools.Logging
-{
-    /// <summary>
-    /// 日志信息
-    /// </summary>
-    public class LogInfo
-    {
-        /// <summary>
-        /// 时间
-        /// </summary>
-        public DateTime Time { get; set; }
-
-        /// <summary>
-        /// 线程id
-        /// </summary>
-        public int ThreadId { get; set; }
-
-        /// <summary>
-        /// 日志级别
-        /// </summary>
-        public LogLevel LogLevel { get; set; }
-
-        /// <summary>
-        /// 异常源
-        /// </summary>
-        public string Source { get; set; }
-
-        /// <summary>
-        /// 异常信息
-        /// </summary>
-        public string Message { get; set; }
-
-        /// <summary>
-        /// 异常对象
-        /// </summary>
-        public Exception Exception { get; set; }
-
-        /// <summary>
-        /// 日志类型
-        /// </summary>
-        public string ExceptionType { get; set; }
-
-        /// <summary>
-        /// 请求路径
-        /// </summary>
-        public string RequestUrl { get; set; }
-
-        /// <summary>
-        /// 客户端代理
-        /// </summary>
-        public string UserAgent { get; set; }
-    }
-}

+ 0 - 28
Masuit.Tools.Core/Logging/LogLevel.cs

@@ -1,28 +0,0 @@
-namespace Masuit.Tools.Logging
-{
-    /// <summary>
-    /// 日志级别
-    /// </summary>
-    public enum LogLevel
-    {
-        /// <summary>
-        /// 信息级别
-        /// </summary>
-        Info,
-
-        /// <summary>
-        /// debug级别
-        /// </summary>
-        Debug,
-
-        /// <summary>
-        /// 错误级别
-        /// </summary>
-        Error,
-
-        /// <summary>
-        /// 致命级别
-        /// </summary>
-        Fatal
-    }
-}

+ 0 - 452
Masuit.Tools.Core/Logging/LogManager.cs

@@ -1,452 +0,0 @@
-using System;
-using System.Collections.Concurrent;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text.RegularExpressions;
-using System.Threading;
-using System.Threading.Tasks;
-using static System.DateTime;
-
-namespace Masuit.Tools.Logging
-{
-    /// <summary>
-    /// 日志组件
-    /// </summary>
-    public class LogManager
-    {
-        static readonly ConcurrentQueue<Tuple<string, string>> LogQueue = new ConcurrentQueue<Tuple<string, string>>();
-
-        /// <summary>
-        /// 自定义事件
-        /// </summary>
-        public static event Action<LogInfo> Event;
-
-        static LogManager()
-        {
-            var writeTask = new Task(obj =>
-            {
-                while (true)
-                {
-                    Pause.WaitOne(1000, true);
-                    List<string[]> temp = new List<string[]>();
-                    foreach (var logItem in LogQueue)
-                    {
-                        string logPath = logItem.Item1;
-                        string logMergeContent = String.Concat(logItem.Item2, Environment.NewLine, "----------------------------------------------------------------------------------------------------------------------", Environment.NewLine);
-                        string[] logArr = temp.FirstOrDefault(d => d[0].Equals(logPath));
-                        if (logArr != null)
-                        {
-                            logArr[1] = string.Concat(logArr[1], logMergeContent);
-                        }
-                        else
-                        {
-                            logArr = new[]
-                            {
-                                logPath,
-                                logMergeContent
-                            };
-                            temp.Add(logArr);
-                        }
-
-                        LogQueue.TryDequeue(out Tuple<string, string> _);
-                    }
-
-                    foreach (var item in temp)
-                    {
-                        WriteText(item[0], item[1]);
-                    }
-                }
-            }, null, TaskCreationOptions.LongRunning);
-            writeTask.Start();
-        }
-
-        private static AutoResetEvent Pause => new AutoResetEvent(false);
-
-        /// <summary>
-        /// 日志存放目录,默认日志放在当前应用程序运行目录下的logs文件夹中
-        /// </summary>
-        public static string LogDirectory
-        {
-            get => Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory).Any(s => s.Contains("Web.config")) ? AppDomain.CurrentDomain.BaseDirectory + @"App_Data\Logs\" : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
-            set
-            {
-            }
-        }
-
-        /// <summary>
-        /// 写入Info级别的日志
-        /// </summary>
-        /// <param name="info"></param>
-        public static void Info(string info)
-        {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(info).ToUpper()}  {info}"));
-            LogInfo log = new LogInfo()
-            {
-                LogLevel = LogLevel.Info,
-                Message = info,
-                Time = Now,
-                ThreadId = Thread.CurrentThread.ManagedThreadId
-            };
-            Event?.Invoke(log);
-        }
-
-        /// <summary>
-        /// 写入Info级别的日志
-        /// </summary>
-        /// <param name="source"></param>
-        /// <param name="info"></param>
-        public static void Info(string source, string info)
-        {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(info).ToUpper()}   {source}  {info}"));
-            LogInfo log = new LogInfo()
-            {
-                LogLevel = LogLevel.Info,
-                Message = info,
-                Time = Now,
-                ThreadId = Thread.CurrentThread.ManagedThreadId,
-                Source = source
-            };
-            Event?.Invoke(log);
-        }
-
-        /// <summary>
-        /// 写入Info级别的日志
-        /// </summary>
-        /// <param name="source"></param>
-        /// <param name="info"></param>
-        public static void Info(Type source, string info)
-        {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(info).ToUpper()}   {source.FullName}  {info}"));
-            LogInfo log = new LogInfo()
-            {
-                LogLevel = LogLevel.Info,
-                Message = info,
-                Time = Now,
-                ThreadId = Thread.CurrentThread.ManagedThreadId,
-                Source = source.FullName
-            };
-            Event?.Invoke(log);
-        }
-
-        /// <summary>
-        /// 写入debug级别日志
-        /// </summary>
-        /// <param name="debug">异常对象</param>
-        public static void Debug(string debug)
-        {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(debug).ToUpper()}   {debug}"));
-            LogInfo log = new LogInfo()
-            {
-                LogLevel = LogLevel.Debug,
-                Message = debug,
-                Time = Now,
-                ThreadId = Thread.CurrentThread.ManagedThreadId
-            };
-            Event?.Invoke(log);
-        }
-
-        /// <summary>
-        /// 写入debug级别日志
-        /// </summary>
-        /// <param name="source">异常源的类型</param>
-        /// <param name="debug">异常对象</param>
-        public static void Debug(string source, string debug)
-        {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(debug).ToUpper()}   {source}  {debug}"));
-            LogInfo log = new LogInfo()
-            {
-                LogLevel = LogLevel.Debug,
-                Message = debug,
-                Time = Now,
-                ThreadId = Thread.CurrentThread.ManagedThreadId,
-                Source = source
-            };
-            Event?.Invoke(log);
-        }
-
-        /// <summary>
-        /// 写入debug级别日志
-        /// </summary>
-        /// <param name="source">异常源的类型</param>
-        /// <param name="debug">异常对象</param>
-        public static void Debug(Type source, string debug)
-        {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(debug).ToUpper()}   {source.FullName}  {debug}"));
-            LogInfo log = new LogInfo()
-            {
-                LogLevel = LogLevel.Debug,
-                Message = debug,
-                Time = Now,
-                ThreadId = Thread.CurrentThread.ManagedThreadId,
-                Source = source.FullName
-            };
-            Event?.Invoke(log);
-        }
-
-        /// <summary>
-        /// 写入error级别日志
-        /// </summary>
-        /// <param name="error">异常对象</param>
-        public static void Error(Exception error)
-        {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {error.Source}  {error.Message}{Environment.NewLine}{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {error.Source}  {error.StackTrace}"));
-            LogInfo log = new LogInfo()
-            {
-                LogLevel = LogLevel.Error,
-                Message = error.Message,
-                Time = Now,
-                ThreadId = Thread.CurrentThread.ManagedThreadId,
-                Source = error.Source,
-                Exception = error,
-                ExceptionType = error.GetType().Name
-            };
-            Event?.Invoke(log);
-        }
-
-        /// <summary>
-        /// 写入error级别日志
-        /// </summary>
-        /// <param name="source">异常源的类型</param>
-        /// <param name="error">异常对象</param>
-        public static void Error(Type source, Exception error)
-        {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source.FullName}  {error.Message}{Environment.NewLine}{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source.FullName}  {error.StackTrace}"));
-            LogInfo log = new LogInfo()
-            {
-                LogLevel = LogLevel.Error,
-                Message = error.Message,
-                Time = Now,
-                ThreadId = Thread.CurrentThread.ManagedThreadId,
-                Source = source.FullName,
-                Exception = error,
-                ExceptionType = error.GetType().Name
-            };
-            Event?.Invoke(log);
-        }
-
-        /// <summary>
-        /// 写入error级别日志
-        /// </summary>
-        /// <param name="source">异常源的类型</param>
-        /// <param name="error">异常信息</param>
-        public static void Error(Type source, string error)
-        {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source.FullName}  {error}"));
-            LogInfo log = new LogInfo()
-            {
-                LogLevel = LogLevel.Error,
-                Message = error,
-                Time = Now,
-                ThreadId = Thread.CurrentThread.ManagedThreadId,
-                Source = source.FullName,
-                //Exception = error,
-                ExceptionType = error.GetType().Name
-            };
-            Event?.Invoke(log);
-        }
-
-        /// <summary>
-        /// 写入error级别日志
-        /// </summary>
-        /// <param name="source">异常源的类型</param>
-        /// <param name="error">异常对象</param>
-        public static void Error(string source, Exception error)
-        {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source}  {error.Message}{Environment.NewLine}{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source}  {error.StackTrace}"));
-            LogInfo log = new LogInfo()
-            {
-                LogLevel = LogLevel.Error,
-                Message = error.Message,
-                Time = Now,
-                ThreadId = Thread.CurrentThread.ManagedThreadId,
-                Source = source,
-                Exception = error,
-                ExceptionType = error.GetType().Name
-            };
-            Event?.Invoke(log);
-        }
-
-        /// <summary>
-        /// 写入error级别日志
-        /// </summary>
-        /// <param name="source">异常源的类型</param>
-        /// <param name="error">异常信息</param>
-        public static void Error(string source, string error)
-        {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source}  {error}"));
-            LogInfo log = new LogInfo()
-            {
-                LogLevel = LogLevel.Error,
-                Message = error,
-                Time = Now,
-                ThreadId = Thread.CurrentThread.ManagedThreadId,
-                Source = source,
-                //Exception = error,
-                ExceptionType = error.GetType().Name
-            };
-            Event?.Invoke(log);
-        }
-
-        /// <summary>
-        /// 写入fatal级别日志
-        /// </summary>
-        /// <param name="fatal">异常对象</param>
-        public static void Fatal(Exception fatal)
-        {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {fatal.Source}  {fatal.Message}{Environment.NewLine}{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {fatal.Source}  {fatal.StackTrace}"));
-            LogInfo log = new LogInfo()
-            {
-                LogLevel = LogLevel.Fatal,
-                Message = fatal.Message,
-                Time = Now,
-                ThreadId = Thread.CurrentThread.ManagedThreadId,
-                Source = fatal.Source,
-                Exception = fatal,
-                ExceptionType = fatal.GetType().Name
-            };
-            Event?.Invoke(log);
-        }
-
-        /// <summary>
-        /// 写入fatal级别日志
-        /// </summary>
-        /// <param name="source">异常源的类型</param>
-        /// <param name="fatal">异常对象</param>
-        public static void Fatal(Type source, Exception fatal)
-        {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source.FullName}  {fatal.Message}{Environment.NewLine}{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source.FullName}  {fatal.StackTrace}"));
-            LogInfo log = new LogInfo()
-            {
-                LogLevel = LogLevel.Fatal,
-                Message = fatal.Message,
-                Time = Now,
-                ThreadId = Thread.CurrentThread.ManagedThreadId,
-                Source = source.FullName,
-                Exception = fatal,
-                ExceptionType = fatal.GetType().Name
-            };
-            Event?.Invoke(log);
-        }
-
-        /// <summary>
-        /// 写入fatal级别日志
-        /// </summary>
-        /// <param name="source">异常源的类型</param>
-        /// <param name="fatal">异常对象</param>
-        public static void Fatal(Type source, string fatal)
-        {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source.FullName}  {fatal}"));
-            LogInfo log = new LogInfo()
-            {
-                LogLevel = LogLevel.Fatal,
-                Message = fatal,
-                Time = Now,
-                ThreadId = Thread.CurrentThread.ManagedThreadId,
-                Source = source.FullName,
-                //Exception = fatal,
-                ExceptionType = fatal.GetType().Name
-            };
-            Event?.Invoke(log);
-        }
-
-        /// <summary>
-        /// 写入fatal级别日志
-        /// </summary>
-        /// <param name="source">异常源的类型</param>
-        /// <param name="fatal">异常对象</param>
-        public static void Fatal(string source, Exception fatal)
-        {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source}  {fatal.Message}{Environment.NewLine}{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source}  {fatal.StackTrace}"));
-            LogInfo log = new LogInfo()
-            {
-                LogLevel = LogLevel.Fatal,
-                Message = fatal.Message,
-                Time = Now,
-                ThreadId = Thread.CurrentThread.ManagedThreadId,
-                Source = source,
-                Exception = fatal,
-                ExceptionType = fatal.GetType().Name
-            };
-            Event?.Invoke(log);
-        }
-
-        /// <summary>
-        /// 写入fatal级别日志
-        /// </summary>
-        /// <param name="source">异常源的类型</param>
-        /// <param name="fatal">异常对象</param>
-        public static void Fatal(string source, string fatal)
-        {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source}  {fatal}"));
-            LogInfo log = new LogInfo()
-            {
-                LogLevel = LogLevel.Fatal,
-                Message = fatal,
-                Time = Now,
-                ThreadId = Thread.CurrentThread.ManagedThreadId,
-                Source = source,
-                ExceptionType = fatal.GetType().Name
-            };
-            Event?.Invoke(log);
-        }
-
-        private static string GetLogPath()
-        {
-            string newFilePath;
-            String logDir = string.IsNullOrEmpty(LogDirectory) ? Path.Combine(Environment.CurrentDirectory, "logs") : LogDirectory;
-            if (!Directory.Exists(logDir))
-            {
-                Directory.CreateDirectory(logDir);
-            }
-
-            string extension = ".log";
-            string fileNameNotExt = Now.ToString("yyyyMMdd");
-            string fileNamePattern = string.Concat(fileNameNotExt, "(*)", extension);
-            List<string> filePaths = Directory.GetFiles(logDir, fileNamePattern, SearchOption.TopDirectoryOnly).ToList();
-
-            if (filePaths.Count > 0)
-            {
-                int fileMaxLen = filePaths.Max(d => d.Length);
-                string lastFilePath = filePaths.Where(d => d.Length == fileMaxLen).OrderByDescending(d => d).FirstOrDefault();
-                if (new FileInfo(lastFilePath).Length > 1 * 1024 * 1024)
-                {
-                    string no = new Regex(@"(?is)(?<=\()(.*)(?=\))").Match(Path.GetFileName(lastFilePath)).Value;
-                    bool parse = int.TryParse(no, out int tempno);
-                    string formatno = $"({(parse ? (tempno + 1) : tempno)})";
-                    string newFileName = String.Concat(fileNameNotExt, formatno, extension);
-                    newFilePath = Path.Combine(logDir, newFileName);
-                }
-                else
-                {
-                    newFilePath = lastFilePath;
-                }
-            }
-            else
-            {
-                string newFileName = string.Concat(fileNameNotExt, $"({0})", extension);
-                newFilePath = Path.Combine(logDir, newFileName);
-            }
-
-            return newFilePath;
-        }
-
-        private static void WriteText(string logPath, string logContent)
-        {
-            try
-            {
-                if (!File.Exists(logPath))
-                {
-                    File.CreateText(logPath).Close();
-                }
-
-                using var sw = File.AppendText(logPath);
-                sw.Write(logContent);
-            }
-            catch (Exception)
-            {
-                // ignored
-            }
-        }
-    }
-}

+ 0 - 74
Masuit.Tools.Core/Mapping/Copier.cs

@@ -1,74 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq.Expressions;
-
-namespace Masuit.Tools.Mapping
-{
-    /// <summary>
-    /// 表达式树复制对象
-    /// </summary>
-    /// <typeparam name="T"></typeparam>
-    public static class Copier<T>
-    {
-        private static readonly ParameterExpression ParameterExpression = Expression.Parameter(typeof(T), "p");
-        private static Func<T, T> _func;
-        private static readonly Dictionary<string, Expression> DictRule = new Dictionary<string, Expression>();
-
-        /// <summary>
-        /// 深拷贝
-        /// </summary>
-        /// <param name="source"></param>
-        /// <returns></returns>
-        public static T Copy(T source)
-        {
-            if (_func == null)
-            {
-                List<MemberBinding> memberBindings = new List<MemberBinding>();
-                foreach (var item in typeof(T).GetProperties())
-                {
-                    if (DictRule.ContainsKey(item.Name))
-                    {
-                        MemberBinding memberBinding = Expression.Bind(item, DictRule[item.Name]);
-                        memberBindings.Add(memberBinding);
-                    }
-                    else
-                    {
-                        var tInProperty = typeof(T).GetProperty(item.Name);
-                        var tInField = typeof(T).GetField(item.Name);
-                        if (tInProperty != null || tInField != null)
-                        {
-                            MemberExpression property = Expression.PropertyOrField(ParameterExpression, item.Name);
-                            MemberBinding memberBinding = Expression.Bind(item, property);
-                            memberBindings.Add(memberBinding);
-                        }
-                    }
-                }
-
-                foreach (var item in typeof(T).GetFields())
-                {
-                    if (DictRule.ContainsKey(item.Name))
-                    {
-                        MemberBinding memberBinding = Expression.Bind(item, DictRule[item.Name]);
-                        memberBindings.Add(memberBinding);
-                    }
-                    else
-                    {
-                        var tInProperty = typeof(T).GetProperty(item.Name);
-                        var tInField = typeof(T).GetField(item.Name);
-                        if (tInProperty != null || tInField != null)
-                        {
-                            MemberExpression property = Expression.PropertyOrField(ParameterExpression, item.Name);
-                            MemberBinding memberBinding = Expression.Bind(item, property);
-                            memberBindings.Add(memberBinding);
-                        }
-                    }
-                }
-
-                MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(T)), memberBindings.ToArray());
-                Expression<Func<T, T>> lambda = Expression.Lambda<Func<T, T>>(memberInitExpression, ParameterExpression);
-                _func = lambda.Compile();
-            }
-            return _func.Invoke(source);
-        }
-    }
-}

+ 0 - 12
Masuit.Tools.Core/Mapping/Core/CreateConfig.cs

@@ -1,12 +0,0 @@
-namespace Masuit.Tools.Mapping.Core
-{
-    /// <summary>
-    /// 映射配置对象
-    /// </summary>
-    internal class CreateConfig
-    {
-        public bool CanCreate { get; set; }
-
-        public string MapperName { get; set; }
-    }
-}

+ 0 - 193
Masuit.Tools.Core/Mapping/Core/MapperConfiguration.cs

@@ -1,193 +0,0 @@
-using Masuit.Tools.Mapping.Exceptions;
-using System;
-using System.Collections.Generic;
-using System.Linq.Expressions;
-using System.Reflection;
-
-namespace Masuit.Tools.Mapping.Core
-{
-    /// <summary>
-    /// 主映射器
-    /// </summary>
-    /// <typeparam name="TSource">源类型</typeparam>
-    /// <typeparam name="TDest">目标类型</typeparam>
-    public class MapperConfiguration<TSource, TDest> : MapperConfigurationBase
-    {
-        /// <summary>
-        /// 
-        /// </summary>
-        protected readonly IList<Action<TSource, TDest>> actionsAfterMap;
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        public MapperConfiguration(string paramName, string mapperName = null) : base(typeof(TSource), typeof(TDest), paramName, mapperName)
-        {
-            actionsAfterMap = new List<Action<TSource, TDest>>();
-        }
-
-        /// <summary>
-        /// 获取Lambda表达式树
-        /// </summary>
-        /// <returns></returns>
-        public Expression<Func<TSource, TDest>> GetLambdaExpression()
-        {
-            MemberInitExpression exp = GetMemberInitExpression();
-            return Expression.Lambda<Func<TSource, TDest>>(exp, paramClassSource);
-        }
-
-        /// <summary>
-        /// 获取委托
-        /// </summary>
-        /// <returns></returns>
-        public Func<TSource, TDest> GetFuncDelegate()
-        {
-            return (Func<TSource, TDest>)GetDelegate();
-        }
-
-        /// <summary>
-        /// 映射成员
-        /// </summary>
-        /// <param name="getPropertySource">源类型</param>
-        /// <param name="getPropertyDest">目标类型</param>
-        /// <returns></returns>
-        public MapperConfiguration<TSource, TDest> ForMember<TPropertySource, TPropertyDest>(Expression<Func<TSource, TPropertySource>> getPropertySource, Expression<Func<TDest, TPropertyDest>> getPropertyDest)
-        {
-            // 添加到映射列表并且可以继续操作
-            ForMemberBase(getPropertySource.Body, getPropertyDest.Body, false);
-            return this;
-        }
-
-        /// <summary>
-        /// 映射成员
-        /// </summary>
-        /// <typeparam name="TPropertySource">属性源类型</typeparam>
-        /// <typeparam name="TPropertyDest">属性目标类型</typeparam>
-        /// <param name="getPropertySource">源类型</param>
-        /// <param name="getPropertyDest">目标类型</param>
-        /// <param name="checkIfNull">是否检查null值</param>
-        /// <returns></returns>
-        public MapperConfiguration<TSource, TDest> ForMember<TPropertySource, TPropertyDest>(Expression<Func<TSource, TPropertySource>> getPropertySource, Expression<Func<TDest, TPropertyDest>> getPropertyDest, bool checkIfNull)
-        {
-            // 添加到映射列表并且可以继续操作
-            ForMemberBase(getPropertySource.Body, getPropertyDest.Body, checkIfNull);
-            return this;
-        }
-
-        /// <summary>
-        /// 映射成员
-        /// </summary>
-        /// <typeparam name="TPropertySource">属性源类型</typeparam>
-        /// <typeparam name="TPropertyDest">属性目标类型</typeparam>
-        /// <param name="getPropertySource">源类型</param>
-        /// <param name="getPropertyDest">目标类型</param>
-        /// <param name="mapperName">mapper别名</param>
-        /// <returns></returns>
-        public MapperConfiguration<TSource, TDest> ForMember<TPropertySource, TPropertyDest>(Expression<Func<TSource, TPropertySource>> getPropertySource, Expression<Func<TDest, TPropertyDest>> getPropertyDest, string mapperName)
-        {
-            // 添加到映射列表并且可以继续操作
-            ForMemberBase(getPropertySource.Body, getPropertyDest.Body, true, mapperName);
-            return this;
-        }
-
-        /// <summary>
-        /// 忽略一些不需要映射的成员
-        /// </summary>
-        /// <param name="propertyDest">属性名</param>
-        /// <returns></returns>
-        public MapperConfiguration<TSource, TDest> Ignore<TProperty>(Expression<Func<TDest, TProperty>> propertyDest)
-        {
-            return IgnoreBase(propertyDest) as MapperConfiguration<TSource, TDest>;
-        }
-
-        /// <summary>
-        /// 映射后要执行的操作
-        /// </summary>
-        /// <param name="actionAfterMap">映射后要执行的操作</param>
-        /// <returns></returns>
-        public MapperConfiguration<TSource, TDest> AfterMap(Action<TSource, TDest> actionAfterMap)
-        {
-            // 添加到映射列表并且可以继续操作
-            actionsAfterMap.Add(actionAfterMap);
-            return this;
-        }
-
-        /// <summary>
-        /// 执行后续操作。
-        /// </summary>
-        /// <param name="source">源类型</param>
-        /// <param name="dest">目标类型</param>
-        public void ExecuteAfterActions(TSource source, TDest dest)
-        {
-            if (actionsAfterMap.Count > 0)
-            {
-                foreach (var action in actionsAfterMap)
-                {
-                    if (action == null)
-                    {
-                        throw new NoActionAfterMappingException();
-                    }
-                    action(source, dest);
-                }
-            }
-        }
-
-        /// <summary>
-        /// 反向映射
-        /// </summary>
-        /// <param name="name">mapper别名</param>
-        /// <returns>
-        /// 新的mapper对象
-        /// </returns>
-        /// <exception cref="MapperExistException"></exception>
-        public MapperConfiguration<TDest, TSource> ReverseMap(string name = null)
-        {
-            MapperConfigurationBase map = GetMapper(typeof(TDest), typeof(TSource), false, name);
-
-            if (map != null)
-            {
-                throw new MapperExistException(typeof(TDest), typeof(TSource));
-            }
-            string finalName = string.IsNullOrEmpty(name) ? "s" + (MapperConfigurationCollectionContainer.Instance.Count).ToString() : name;
-            map = new MapperConfiguration<TDest, TSource>(finalName);
-            MapperConfigurationCollectionContainer.Instance.Add(map);
-            CreateCommonMember();
-
-            // 现有属性的映射,并且创建反向关系
-            foreach (var item in PropertiesMapping)
-            {
-                PropertyInfo propertyDest = GetPropertyInfo(item.Item1);
-                if (propertyDest.CanWrite)
-                {
-                    if (!string.IsNullOrEmpty(item.Item4))
-                    {
-                        //找到反向关系的mapper
-                        var reverseMapper = GetMapper(item.Item2.Type, item.Item1.Type, false);
-                        if (reverseMapper != null)
-                        {
-                            map.ForMemberBase(item.Item2, item.Item1, item.Item3, reverseMapper.Name);
-                        }
-                    }
-                    else
-                    {
-                        if (item.Item1.NodeType == ExpressionType.MemberAccess)
-                        {
-                            map.ForMemberBase(item.Item2, item.Item1, item.Item3, item.Item4);
-                        }
-                    }
-                }
-            }
-
-            return (MapperConfiguration<TDest, TSource>)map;
-        }
-
-        /// <summary>
-        /// 是否使用服务注入
-        /// </summary>
-        public MapperConfiguration<TSource, TDest> ConstructUsingServiceLocator()
-        {
-            UseServiceLocator = true;
-            return this;
-        }
-    }
-}

+ 0 - 679
Masuit.Tools.Core/Mapping/Core/MapperConfigurationBase.cs

@@ -1,679 +0,0 @@
-using Masuit.Tools.Mapping.Exceptions;
-using Masuit.Tools.Mapping.Helper;
-using Masuit.Tools.Mapping.Visitor;
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Linq;
-using System.Linq.Expressions;
-using System.Reflection;
-
-namespace Masuit.Tools.Mapping.Core
-{
-    /// <summary>
-    /// mapper配置基类
-    /// </summary>
-    public abstract class MapperConfigurationBase
-    {
-        private Delegate _delegateCallForNew;
-
-        private Delegate _delegateCallForExisting;
-
-        private Func<Type, object> _constructorFunc;
-
-        private bool _isInitialized;
-        private readonly MethodInfo _selectMethod;
-
-        private readonly MethodInfo _toListMethod;
-
-        private readonly List<PropertyInfo> _propertiesToIgnore;
-
-        internal ParameterExpression paramClassSource;
-        internal MapperExpressionVisitor visitorMapper;
-        internal List<MemberAssignment> memberForNew;
-        internal LambdaExpression expressionForExisting;
-
-        /// <summary>
-        /// 属性映射对应关系<br/>
-        /// Item1 : 源表达式<br/>
-        /// Item2 : 目标表达式<br/>
-        /// Item3 : 检查null值<br/>
-        /// Item4 : mapper别名<br/>
-        /// </summary>
-        protected List<Tuple<Expression, Expression, bool, string>> PropertiesMapping { get; private set; }
-
-
-        /// <summary>
-        /// 需要被忽略映射的属性
-        /// </summary>
-        protected ReadOnlyCollection<PropertyInfo> PropertiesToIgnore => _propertiesToIgnore.AsReadOnly();
-
-        /// <summary>
-        /// 是否使用服务依赖注入
-        /// </summary>
-        public bool UseServiceLocator { get; protected set; }
-
-        /// <summary>
-        /// 对象源类型
-        /// </summary>
-        public Type SourceType { get; private set; }
-
-        /// <summary>
-        /// 对象目标类型
-        /// </summary>
-        public Type TargetType { get; private set; }
-
-        /// <summary>
-        /// 获取mapper映射成员
-        /// </summary>
-        public ReadOnlyCollection<MemberAssignment> MemberToMapForNew => new ReadOnlyCollection<MemberAssignment>(memberForNew);
-
-
-        /// <summary>
-        /// mapper别名
-        /// </summary>
-        public string Name { get; protected set; }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="source">源类型</param>
-        /// <param name="destination">目标类型</param>
-        /// <param name="paramName">属性名</param>
-        /// <param name="name">别名</param>
-        protected MapperConfigurationBase(Type source, Type destination, string paramName, string name = null)
-        {
-            TargetType = destination;
-            SourceType = source;
-            paramClassSource = Expression.Parameter(source, paramName);
-            Name = string.IsNullOrEmpty(name) ? paramName : name;
-            _propertiesToIgnore = new List<PropertyInfo>();
-            PropertiesMapping = new List<Tuple<Expression, Expression, bool, string>>();
-            visitorMapper = new MapperExpressionVisitor(paramClassSource);
-            memberForNew = new List<MemberAssignment>();
-            _selectMethod = typeof(Enumerable).GetMethods().Where(m => m.Name == "Select").Select(x => x.GetParameters().First(p => p.Name.Equals("selector") && p.ParameterType.GetGenericArguments().Length == 2)).First().Member as MethodInfo;
-            _toListMethod = typeof(Enumerable).GetMethod("ToList");
-        }
-
-        /// <summary>
-        /// 获取mapper委托
-        /// </summary>
-        /// <returns></returns>
-        public Delegate GetDelegate()
-        {
-            if (!_isInitialized)
-            {
-                throw new MapperNotInitializedException(SourceType, TargetType);
-            }
-
-            // 因为在这里有映射器的性能问题,而缓存委托会显着缩短处理时间,如果没有表达式编译每次编译会很慢
-            if (_delegateCallForNew == null)
-            {
-                MemberInitExpression exp = GetMemberInitExpression();
-
-                _delegateCallForNew = Expression.Lambda(exp, paramClassSource).Compile();
-            }
-
-            return _delegateCallForNew;
-        }
-
-        /// <summary>
-        /// 获取现有目标类型的委托。
-        /// </summary>
-        /// <exception cref="MapperNotInitializedException"></exception>
-        public Delegate GetDelegateForExistingTarget()
-        {
-            if (!_isInitialized)
-            {
-                throw new MapperNotInitializedException(SourceType, TargetType);
-            }
-
-            // 因为在这里有映射器的性能问题,而缓存委托会显着缩短处理时间,如果没有表达式编译每次编译会很慢
-            if (_delegateCallForExisting == null)
-            {
-                CreateMemberAssignementForExistingTarget();
-            }
-
-            return _delegateCallForExisting;
-        }
-
-        /// <summary>
-        /// 获取泛型的Lambda表达式
-        /// </summary>
-        public LambdaExpression GetGenericLambdaExpression()
-        {
-            MemberInitExpression exp = GetMemberInitExpression();
-            return Expression.Lambda(exp, paramClassSource);
-        }
-
-        /// <summary>
-        /// 获取目标类型的实际类型
-        /// </summary>
-        public Type GetDestinationType()
-        {
-            return GetRealType(TargetType);
-        }
-
-        /// <summary>
-        /// 忽略目标类型的属性
-        /// </summary>
-        /// <typeparam name="TDest">对象源类型</typeparam>
-        /// <typeparam name="TProperty">对象目标类型</typeparam>
-        /// <param name="propertyDest">目标对象的属性</param>
-        /// <returns></returns>
-        protected MapperConfigurationBase IgnoreBase<TDest, TProperty>(Expression<Func<TDest, TProperty>> propertyDest)
-        {
-            // 添加到映射列表并且可以继续操作
-            _propertiesToIgnore.Add(GetPropertyInfo(propertyDest));
-            return this;
-        }
-
-        /// <summary>
-        /// 获取映射器实例
-        /// </summary>
-        /// <param name="typeOfSource">源类型</param>
-        /// <param name="typeOfTarget">目标类型</param>
-        /// <param name="throwExceptionOnNoFound">如果没找到是否需要抛出异常</param>
-        /// <param name="name">mapper别名</param>
-        /// <returns></returns>
-        /// <exception cref="NoFoundMapperException"></exception>
-        protected static MapperConfigurationBase GetMapper(Type typeOfSource, Type typeOfTarget, bool throwExceptionOnNoFound, string name = null)
-        {
-            var mapperExterne = MapperConfigurationCollectionContainer.Instance.Find(typeOfSource, typeOfTarget, name);
-            // 如果没有任何配置,手动抛出异常
-            if (mapperExterne == null && throwExceptionOnNoFound)
-            {
-                throw new NoFoundMapperException(typeOfSource, typeOfTarget);
-            }
-
-            return mapperExterne;
-        }
-
-        /// <summary>
-        /// 创建公共成员
-        /// </summary>
-        protected void CreateCommonMember()
-        {
-            PropertyInfo[] propertiesSource = SourceType.GetProperties();
-            foreach (PropertyInfo propSource in propertiesSource)
-            {
-                PropertyInfo propDest = TargetType.GetProperty(propSource.Name);
-                if (propDest != null)
-                {
-                    // 检查是否已存在或被忽略。
-                    bool ignorePropDest = _propertiesToIgnore.Exists(x => x.Name == propDest.Name) || PropertiesMapping.Exists(x => GetPropertyInfo(x.Item2).Name == propDest.Name);
-
-                    if (propDest.CanWrite && !ignorePropDest)
-                    {
-                        Type sourceType = propSource.PropertyType;
-                        Type destType = propDest.PropertyType;
-                        bool isList = IsListOf(destType);
-                        if (isList)
-                        {
-                            sourceType = TypeSystem.GetElementType(propSource.PropertyType);
-                            destType = TypeSystem.GetElementType(propDest.PropertyType);
-                        }
-
-                        var canCreateConfig = CanCreateConfig(sourceType, destType);
-                        if (canCreateConfig.CanCreate)
-                        {
-                            // 只创造现有的关系
-                            Expression expSource = Expression.MakeMemberAccess(paramClassSource, propSource);
-                            ParameterExpression paramDest = Expression.Parameter(TargetType, "t");
-                            Expression expDest = Expression.MakeMemberAccess(paramDest, propDest);
-                            PropertiesMapping.Add(Tuple.Create(expSource, expDest, false, canCreateConfig.MapperName));
-                        }
-                    }
-                }
-            }
-        }
-
-        private static CreateConfig CanCreateConfig(Type typeSource, Type typeTarget)
-        {
-            CreateConfig result = new CreateConfig
-            {
-                CanCreate = typeSource == typeTarget
-            };
-            //不是同一类型
-            if (!result.CanCreate)
-            {
-                //查找是否存在映射器
-                var mapper = MapperConfigurationCollectionContainer.Instance.Find(typeSource, typeTarget);
-                if (mapper != null)
-                {
-                    result.MapperName = mapper.Name;
-                    result.CanCreate = true;
-                }
-            }
-
-            return result;
-        }
-
-        /// <summary>
-        /// 检查并配置mapper
-        /// </summary>
-        /// <param name="configExpression">配置表达式树</param>
-        /// <exception cref="NotSameTypePropertyException">
-        /// </exception>
-        /// <exception cref="ReadOnlyPropertyException"></exception>
-        protected void CheckAndConfigureMapping(ref Tuple<Expression, Expression, bool, string> configExpression)
-        {
-            Type typeSource = configExpression.Item1.Type;
-            Type typeTarget = configExpression.Item2.Type;
-
-            // 正常情况下,目标表达式是一个成员表达式树
-            PropertyInfo propTarget = GetPropertyInfo(configExpression.Item2);
-
-            if (propTarget.CanWrite)
-            {
-                CheckAndRemoveMemberDest(propTarget.Name);
-                if (!IsListOf(typeTarget))
-                {
-                    CreatBindingFromSimple(ref configExpression, typeSource, typeTarget, propTarget);
-                }
-                else
-                {
-                    CreateBindingFromList(ref configExpression, typeSource, typeTarget, propTarget);
-                }
-            }
-            else
-            {
-                throw new ReadOnlyPropertyException(propTarget);
-            }
-        }
-
-        /// <summary>
-        /// 检查并移除目标成员
-        /// </summary>
-        /// <param name="properyName">属性名</param>
-        protected void CheckAndRemoveMemberDest(string properyName)
-        {
-            Predicate<MemberAssignment> exp = m => m.Member.Name == properyName;
-            if (memberForNew.Exists(exp))
-            {
-                memberForNew.RemoveAll(exp);
-            }
-        }
-
-        /// <summary>
-        /// 获取成员初始化表达式。
-        /// </summary>
-        /// <returns></returns>
-        protected MemberInitExpression GetMemberInitExpression()
-        {
-            Type typeDest = GetDestinationType();
-            NewExpression newClassDest = Expression.New(typeDest);
-            MemberInitExpression exp = Expression.MemberInit(newClassDest, MemberToMapForNew);
-            return exp;
-        }
-
-        /// <summary>
-        /// 创建成员绑定。
-        /// </summary>
-        /// <param name="propertyExpression">属性表达式</param>
-        /// <param name="propertyTarget">目标属性</param>
-        /// <param name="checkIfNull">是否检查null值</param>
-        protected void CreateMemberBinding(Expression propertyExpression, MemberInfo propertyTarget, bool checkIfNull)
-        {
-            // 访问表达式进行转换
-            Expression result = visitorMapper.Visit(propertyExpression, checkIfNull);
-            MemberAssignment bind = Expression.Bind(propertyTarget, result);
-            memberForNew.Add(bind);
-        }
-
-        /// <summary>
-        /// 将表达式源的映射分配给属性目标。
-        /// </summary>
-        /// <param name="getPropertySource">属性源类型</param>
-        /// <param name="getPropertyDest">属性目标类型</param>
-        /// <param name="checkIfNull">是否检查null值</param>
-        /// <param name="name">要使用的映射器的别名</param>
-        internal MapperConfigurationBase ForMemberBase(Expression getPropertySource, Expression getPropertyDest, bool checkIfNull, string name = null)
-        {
-            // 添加到映射列表并且可以继续操作
-            PropertiesMapping.Add(Tuple.Create(getPropertySource, getPropertyDest, checkIfNull, name));
-            return this;
-        }
-
-        /// <summary>
-        /// 获取属性信息。
-        /// </summary>
-        /// <param name="propertyExpression">属性表达式树</param>
-        /// <returns></returns>
-        /// <exception cref="System.NotImplementedException">
-        /// 这种表达方式不承担职责,或者这种类型的表达式是无效的
-        /// </exception>
-        protected static PropertyInfo GetPropertyInfo(Expression propertyExpression)
-        {
-            var expressionToAnalyse = propertyExpression.NodeType == ExpressionType.Lambda ? (propertyExpression as LambdaExpression).Body : propertyExpression;
-            switch (expressionToAnalyse.NodeType)
-            {
-                case ExpressionType.Convert:
-                    Expression operand = (expressionToAnalyse as UnaryExpression).Operand;
-                    switch (operand.NodeType)
-                    {
-                        case ExpressionType.MemberAccess:
-                            return (operand as MemberExpression).Member as PropertyInfo;
-                        default:
-                            throw new NotImplementedException("这种表达方式目前尚未支持");
-                    }
-                case ExpressionType.MemberAccess:
-                    return (expressionToAnalyse as MemberExpression).Member as PropertyInfo;
-                default:
-                    throw new NotImplementedException("这种表达方式目前尚未支持");
-            }
-        }
-
-        internal void Initialize(Func<Type, object> constructor)
-        {
-            CreateMappingExpression(constructor);
-            CreateMemberAssignementForExistingTarget();
-        }
-
-        /// <summary>
-        /// 为现有目标对象创建成员
-        /// </summary>
-        public virtual void CreateMemberAssignementForExistingTarget()
-        {
-            if (PropertiesMapping.Count > 0)
-            {
-                // 用于更改原始表达式的参数。
-                var paramTarget = Expression.Parameter(TargetType, paramClassSource.Name.Replace("s", "t"));
-                ChangParameterExpressionVisitor visitSource = new ChangParameterExpressionVisitor(paramClassSource);
-                ChangParameterExpressionVisitor visitTarget = new ChangParameterExpressionVisitor(paramTarget);
-
-                List<Expression> finalAssign = new List<Expression>();
-
-                foreach (var item in PropertiesMapping)
-                {
-                    var propToAssign = visitTarget.Visit(item.Item2);
-                    var assignExpression = visitSource.Visit(item.Item1);
-                    Type sourceType = TypeSystem.GetElementType(item.Item2.Type);
-                    Type targetType = TypeSystem.GetElementType(item.Item1.Type);
-                    if (string.IsNullOrEmpty(item.Item4))
-                    {
-                        object defaultValue = MapperHelper.GetDefaultValue(item.Item2.Type);
-                        Expression defaultExpression = Expression.Constant(defaultValue, item.Item2.Type);
-                        Expression checkIfNull = Expression.NotEqual(assignExpression, defaultExpression);
-                        if (item.Item3)
-                        {
-                            Expression setIf = Expression.IfThen(checkIfNull, Expression.Assign(propToAssign, assignExpression));
-                            finalAssign.Add(setIf);
-                        }
-                        else
-                        {
-                            if (!IsListOf(propToAssign.Type))
-                            {
-                                finalAssign.Add(Expression.Assign(propToAssign, assignExpression));
-                            }
-                            else
-                            {
-                                if (sourceType == targetType)
-                                {
-                                    Expression toListExp = Expression.Call(_toListMethod.MakeGenericMethod(sourceType), assignExpression);
-                                    Expression setIf = Expression.IfThen(checkIfNull, Expression.Assign(propToAssign, assignExpression));
-                                    finalAssign.Add(setIf);
-                                    finalAssign.Add(toListExp);
-                                }
-                            }
-                        }
-                    }
-                    else // 来自其他映射器。
-                    {
-                        var mapper = GetMapper(sourceType, targetType, false, item.Item4);
-                        if (mapper != null)
-                        {
-                            mapper.Initialize(_constructorFunc);
-
-                            Expression defaultExpression = Expression.Constant(MapperHelper.GetDefaultValue(item.Item2.Type), item.Item2.Type);
-                            if (!IsListOf(propToAssign.Type))
-                            {
-                                ChangParameterExpressionVisitor changeVisitor = new ChangParameterExpressionVisitor(propToAssign, assignExpression);
-
-                                Expression modifiedExpression = changeVisitor.Visit(mapper.expressionForExisting.Body);
-                                Expression checkIfNull = Expression.NotEqual(propToAssign, defaultExpression);
-                                Expression setIf = Expression.IfThen(checkIfNull, modifiedExpression);
-                                assignExpression = setIf;
-                            }
-                            else
-                            {
-                                //Expression selectExp = Expression.Call(_selectMethod.MakeGenericMethod(sourceType), Expression.Constant(mapper.GetDelegate()));
-                                Expression checkIfNull = Expression.NotEqual(propToAssign, defaultExpression);
-                                Expression setIf = Expression.IfThen(checkIfNull, Expression.Assign(propToAssign, assignExpression));
-                                assignExpression = setIf;
-                            }
-
-                            finalAssign.Add(assignExpression);
-                        }
-                    }
-                }
-
-                if (finalAssign.Count > 0 && _delegateCallForExisting == null)
-                {
-                    expressionForExisting = Expression.Lambda(Expression.Block(typeof(void), finalAssign), paramClassSource, paramTarget);
-                    // 编译
-                    _delegateCallForExisting = expressionForExisting.Compile();
-                }
-            }
-        }
-
-        internal Expression GetLambdaDest(string propertyName)
-        {
-            var exp = PropertiesMapping.Find(x => GetPropertyInfo(x.Item1).Name == propertyName);
-            if (exp != null)
-            {
-                var final = exp.Item2;
-                if (final.NodeType == ExpressionType.Convert)
-                {
-                    final = (final as UnaryExpression).Operand;
-                }
-
-                return final;
-            }
-
-            return null;
-        }
-
-        /// <summary>
-        /// 创建映射表达式树
-        /// </summary>
-        /// <param name="constructor"></param>
-        public virtual void CreateMappingExpression(Func<Type, object> constructor)
-        {
-            if (!_isInitialized)
-            {
-                // 它是在处理前放置以避免递归循环。
-                _isInitialized = true;
-                _constructorFunc = constructor;
-                CreateCommonMember();
-                var propsToAnalyse = PropertiesMapping.ToList(); // 克隆列表以便于更改。
-                for (int i = 0; i < propsToAnalyse.Count; i++)
-                {
-                    var propToAnalyse = propsToAnalyse[i];
-                    CheckAndConfigureMapping(ref propToAnalyse);
-                    propsToAnalyse[i] = propToAnalyse;
-                }
-
-                PropertiesMapping = propsToAnalyse;
-                // 编译
-                GetDelegate();
-            }
-        }
-
-        internal Type GetRealType(Type typeToFind)
-        {
-            if (UseServiceLocator)
-                return _constructorFunc(typeToFind).GetType();
-            return typeToFind;
-        }
-
-        internal PropertiesNotMapped GetPropertiesNotMapped()
-        {
-            PropertiesNotMapped result = new PropertiesNotMapped();
-            // 克隆属性信息
-            List<PropertyInfo> sourceProperties = SourceType.GetProperties().ToList();
-            List<PropertyInfo> targetProperties = TargetType.GetProperties().ToList();
-
-            PropertiesVisitor visitor = new PropertiesVisitor(TargetType);
-            foreach (var members in memberForNew)
-            {
-                var members1 = members;
-                sourceProperties.RemoveAll((p) => members1.Member.Name == p.Name);
-                targetProperties.RemoveAll((p) => visitor.GetProperties(members.Expression).Contains(p));
-            }
-
-            // 检查被忽略映射的成员
-            sourceProperties.RemoveAll((p) => _propertiesToIgnore.Contains(p));
-            result.sourceProperties = sourceProperties;
-            result.targetProperties = targetProperties;
-
-            return result;
-        }
-
-        /// <summary>
-        /// 获取排序表达式树
-        /// </summary>
-        /// <param name="propertySource">属性名</param>
-        /// <returns></returns>
-        public LambdaExpression GetSortedExpression(string propertySource)
-        {
-            var exp = PropertiesMapping.Find(x => GetPropertyInfo(x.Item2).Name == propertySource);
-            if (exp == null)
-            {
-                throw new PropertyNoExistException(propertySource, TargetType);
-            }
-
-            // 更改参数
-            var visitor = new MapperExpressionVisitor(paramClassSource);
-            var result = visitor.Visit(exp.Item1);
-            return Expression.Lambda(result, paramClassSource);
-        }
-
-        private static bool IsListOf(Type typeTarget)
-        {
-            // 特殊情况字符串是char数组。
-            if (typeTarget == typeof(string))
-            {
-                return false;
-            }
-
-            Func<Type, bool> test = t => t.IsAssignableFrom(typeof(IEnumerable));
-            return test(typeTarget) || typeTarget.GetInterfaces().Any(test);
-        }
-
-        private MapperConfigurationBase GetAndCheckMapper(Type typeOfSource, Type typeOfTarget, string name)
-        {
-            var externalMapper = GetMapper(typeOfSource, typeOfTarget, false, name);
-            if (externalMapper != null)
-            {
-                return externalMapper;
-            }
-
-            //如果找不到具有别名的映射器
-            if (!string.IsNullOrEmpty(name))
-            {
-                throw new NoFoundMapperException(name);
-            }
-
-            throw new NotSameTypePropertyException(typeOfSource, typeOfTarget);
-        }
-
-        private void CreatBindingFromSimple(ref Tuple<Expression, Expression, bool, string> configExpression, Type typeSource, Type typeTarget, PropertyInfo propTarget)
-        {
-            // 没有特殊的操作
-            if (typeSource == typeTarget)
-            {
-                // 创建成员绑定
-                CreateMemberBinding(configExpression.Item1, propTarget, configExpression.Item3);
-            }
-            else
-            {
-                // 尝试查找mapper
-                MapperConfigurationBase externalMapper = GetAndCheckMapper(typeSource, typeTarget, configExpression.Item4);
-                // 如果此时未初始化映射器
-                externalMapper.CreateMappingExpression(_constructorFunc);
-                // 默认情况下,检查对象的null
-                Expression mapExpression = externalMapper.GetMemberInitExpression();
-                Expression defaultExpression = Expression.Constant(MapperHelper.GetDefaultValue(configExpression.Item1.Type), configExpression.Item1.Type);
-                // 修改成员
-                Expression expSource = visitorMapper.Visit(configExpression.Item1);
-                ChangParameterExpressionVisitor changeParamaterVisitor = new ChangParameterExpressionVisitor(expSource);
-                mapExpression = changeParamaterVisitor.Visit(mapExpression);
-                // 现在可以创建正确的参数。
-                Expression checkIfNull = Expression.NotEqual(expSource, defaultExpression);
-                // 创建条件
-                var checkExpression = Expression.Condition(checkIfNull, mapExpression, Expression.Constant(MapperHelper.GetDefaultValue(mapExpression.Type), mapExpression.Type), mapExpression.Type);
-                MemberAssignment bindExpression = Expression.Bind(propTarget, checkExpression);
-                // 找到了映射器但没有配置
-                if (string.IsNullOrEmpty(configExpression.Item4))
-                {
-                    configExpression = Tuple.Create(configExpression.Item1, configExpression.Item2, configExpression.Item3, externalMapper.Name);
-                }
-
-                memberForNew.Add(bindExpression);
-            }
-        }
-
-        private void CreateBindingFromList(ref Tuple<Expression, Expression, bool, string> configExpression, Type typeSource, Type typeTarget, PropertyInfo propTarget)
-        {
-            Type sourceTypeList = TypeSystem.GetElementType(typeSource);
-            Type destTypeList = TypeSystem.GetElementType(typeTarget);
-            if (sourceTypeList == destTypeList)
-            {
-                if (configExpression.Item2.NodeType == ExpressionType.MemberAccess)
-                {
-                    CreateMemberBinding(configExpression.Item1, propTarget, configExpression.Item3);
-                }
-            }
-            // 使用Enumerable类的select方法来更改类型
-            else
-            {
-                var externalMapper = GetAndCheckMapper(sourceTypeList, destTypeList, configExpression.Item4);
-                externalMapper.CreateMappingExpression(_constructorFunc);
-                MemberAssignment expBind;
-                Expression expSource = configExpression.Item1;
-
-                ChangParameterExpressionVisitor visitor = new ChangParameterExpressionVisitor(paramClassSource);
-                expSource = visitor.Visit(expSource);
-
-                // 为了与EF / LINQ2SQL兼容。
-                LambdaExpression expMappeur = externalMapper.GetGenericLambdaExpression();
-                // 创建对Select方法的调用,在Enumerable的Select中插入一个lambda表达式(参数是一个委托),通常情况下,这是不可能的,但(个人认为)编译器就像这样创建并且LINQ2SQL / EF是可以进行sql查询的
-                Expression select = Expression.Call(_selectMethod.MakeGenericMethod(sourceTypeList, destTypeList), new[]
-                {
-                    expSource,
-                    expMappeur
-                });
-                // 创建对ToList方法的调用
-                Expression toList = Expression.Call(_toListMethod.MakeGenericMethod(destTypeList), select);
-
-                if (configExpression.Item3) // 如果要检查无效(使用EF / LinqTosql,则不需要)。
-                {
-                    // 测试source的属性是否为null。
-                    Expression checkIfNull = Expression.NotEqual(expSource, Expression.Constant(MapperHelper.GetDefaultValue(expSource.Type), expSource.Type));
-                    // 有时候ToList方法不起作用,则使用实现ToList不起作用的类
-                    Expression asExp = Expression.TypeAs(toList, propTarget.PropertyType);
-                    // 创建条件表达式
-                    Expression expCondition = Expression.Condition(checkIfNull, asExp, Expression.Constant(MapperHelper.GetDefaultValue(typeTarget), typeTarget));
-
-                    // 分配给目标属性。
-                    expBind = Expression.Bind(propTarget, expCondition);
-                }
-                else
-                {
-                    // 分配给目标属性。
-                    expBind = Expression.Bind(propTarget, toList);
-                }
-
-                // 查找mapper
-                if (string.IsNullOrEmpty(configExpression.Item4))
-                {
-                    configExpression = Tuple.Create(configExpression.Item1, configExpression.Item2, configExpression.Item3, externalMapper.Name);
-                }
-
-                memberForNew.Add(expBind);
-            }
-        }
-    }
-}

+ 0 - 134
Masuit.Tools.Core/Mapping/Core/MapperConfigurationCollectionContainer.cs

@@ -1,134 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Linq;
-
-namespace Masuit.Tools.Mapping.Core
-{
-    /// <summary>
-    /// 单例存储映射器。
-    /// </summary>
-    /// <remarks>不需要单例,因为适用于所有线程。</remarks>
-    public class MapperConfigurationCollectionContainer : IEnumerable<MapperConfigurationBase>
-    {
-        private readonly HashSet<MapperConfigurationBase> _items;
-        private static MapperConfigurationCollectionContainer currentInstance;
-
-        private MapperConfigurationCollectionContainer()
-        {
-            _items = new HashSet<MapperConfigurationBase>();
-        }
-
-        /// <summary>
-        /// mapper映射容器
-        /// </summary>
-        public static MapperConfigurationCollectionContainer Instance => currentInstance ??= new MapperConfigurationCollectionContainer();
-
-        /// <summary>
-        /// count
-        /// </summary>
-        public int Count => _items.Count;
-
-        /// <summary>
-        /// 索引器
-        /// </summary>
-        /// <param name="index"></param>
-        /// <returns></returns>
-        internal MapperConfigurationBase this[int index]
-        {
-            get
-            {
-                if (index > _items.Count)
-                    throw new IndexOutOfRangeException();
-                var enumerator = GetEnumerator();
-                int i = 0;
-                while (enumerator.MoveNext())
-                {
-                    if (i == index)
-                    {
-                        return enumerator.Current;
-                    }
-                    i++;
-                }
-
-                return null;
-            }
-        }
-
-        /// <summary>
-        /// 查找指定的源。
-        /// </summary>
-        /// <param name="source">源类型</param>
-        /// <param name="target">目标对象</param>
-        /// <param name="name">别名</param>
-        internal MapperConfigurationBase Find(Type source, Type target, string name = null)
-        {
-            foreach (var current in this)
-            {
-                string nameMapper = string.IsNullOrEmpty(name) ? current.paramClassSource.Name : name;
-                if (current.SourceType == source && current.TargetType == target && current.Name == nameMapper)
-                {
-                    return current;
-                }
-            }
-            return null;
-        }
-
-        /// <summary>
-        /// 是否存在谓词的映射。
-        /// </summary>
-        /// <param name="match">条件表达式</param>
-        public bool Exists(Func<MapperConfigurationBase, bool> match)
-        {
-            return this.Any(match);
-        }
-
-        /// <summary>
-        /// 移除指定的元素
-        /// </summary>
-        /// <param name="index"></param>
-        public void RemoveAt(int index)
-        {
-            MapperConfigurationBase itemToDelete = this[index];
-            if (itemToDelete != null)
-            {
-                _items.Remove(itemToDelete);
-            }
-        }
-
-        /// <summary>
-        /// 清除
-        /// </summary>
-        public void Clear()
-        {
-            _items.Clear();
-        }
-
-        /// <summary>
-        /// 添加
-        /// </summary>
-        /// <param name="value"></param>
-        public void Add(MapperConfigurationBase value)
-        {
-            _items.Add(value);
-        }
-
-        /// <summary>
-        /// 迭代器
-        /// </summary>
-        /// <returns></returns>
-        public IEnumerator<MapperConfigurationBase> GetEnumerator()
-        {
-            return _items.GetEnumerator();
-        }
-
-        /// <summary>
-        /// 迭代器
-        /// </summary>
-        /// <returns></returns>
-        IEnumerator IEnumerable.GetEnumerator()
-        {
-            return GetEnumerator();
-        }
-    }
-}

+ 0 - 35
Masuit.Tools.Core/Mapping/Core/PropertiesNotMapped.cs

@@ -1,35 +0,0 @@
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Reflection;
-
-namespace Masuit.Tools.Mapping.Core
-{
-    /// <summary>
-    /// 未映射的属性的处理结果。
-    /// </summary>
-    public class PropertiesNotMapped
-    {
-
-        internal List<PropertyInfo> sourceProperties;
-        internal List<PropertyInfo> targetProperties;
-
-        /// <summary>
-        /// 获取未映射的源属性。
-        /// </summary>
-        public ReadOnlyCollection<PropertyInfo> SourceProperties => new ReadOnlyCollection<PropertyInfo>(sourceProperties);
-
-        /// <summary>
-        /// 获取未映射的目标属性。
-        /// </summary>
-        public ReadOnlyCollection<PropertyInfo> TargetProperties => new ReadOnlyCollection<PropertyInfo>(targetProperties);
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        public PropertiesNotMapped()
-        {
-            sourceProperties = new List<PropertyInfo>();
-            targetProperties = new List<PropertyInfo>();
-        }
-    }
-}

+ 0 - 59
Masuit.Tools.Core/Mapping/Core/TypePairMapper.cs

@@ -1,59 +0,0 @@
-using System;
-
-namespace Masuit.Tools.Mapping.Core
-{
-    internal struct TypePairMapper : IEquatable<TypePairMapper>
-    {
-        public TypePairMapper(Type source, Type target, string name = null) : this()
-        {
-            Target = target;
-            Source = source;
-            Name = name;
-        }
-
-        public Type Source { get; }
-        public Type Target { get; }
-
-        public string Name { get; private set; }
-
-        public static TypePairMapper Create(Type source, Type target, string name = null)
-        {
-            return new TypePairMapper(source, target, name);
-        }
-
-        public static TypePairMapper Create<TSource, TDest>(string name = null)
-        {
-            return new TypePairMapper(typeof(TSource), typeof(TDest), name);
-        }
-
-        public override bool Equals(object obj)
-        {
-            if (ReferenceEquals(null, obj))
-            {
-                return false;
-            }
-            return obj is TypePairMapper && Equals((TypePairMapper)obj);
-        }
-
-        public override int GetHashCode()
-        {
-            unchecked
-            {
-                return ((Source != null ? Source.GetHashCode() : 0) * 397) ^ (Target != null ? Target.GetHashCode() : 0);
-            }
-        }
-        public bool Equals(TypePairMapper other)
-        {
-            bool result;
-            if (!string.IsNullOrEmpty(other.Name))
-            {
-                result = Source == other.Source && Target == other.Target && Name == other.Name;
-            }
-            else
-            {
-                result = Source == other.Source && Target == other.Target;
-            }
-            return result;
-        }
-    }
-}

+ 0 - 56
Masuit.Tools.Core/Mapping/Exceptions/MapperExceptionBase.cs

@@ -1,56 +0,0 @@
-using System;
-using System.Runtime.Serialization;
-
-namespace Masuit.Tools.Mapping.Exceptions
-{
-    /// <summary>
-    /// mapper异常基类
-    /// </summary>
-    [Serializable]
-    public class MapperExceptionBase : Exception
-    {
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="exceptionMessage">异常信息</param>
-        public MapperExceptionBase(string exceptionMessage) : base(exceptionMessage)
-        {
-        }
-
-        /// <summary>
-        /// 无参构造函数
-        /// </summary>
-        public MapperExceptionBase()
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="serializer">序列化信息</param>
-        /// <param name="context">上下文</param>
-        protected MapperExceptionBase(SerializationInfo serializer, StreamingContext context) : base(serializer, context)
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="exceptionMessage">异常信息</param>
-        /// <param name="innerException">内部异常</param>
-        public MapperExceptionBase(string exceptionMessage, Exception innerException) : base(exceptionMessage, innerException)
-        {
-        }
-
-        /// <summary>
-        /// 验证参数
-        /// </summary>
-        /// <param name="message">消息</param>
-        /// <param name="conditions">条件</param>
-        /// <returns>异常信息</returns>
-        protected static string ValideParameter(string message, params bool[] conditions)
-        {
-            return message;
-        }
-    }
-}

+ 0 - 55
Masuit.Tools.Core/Mapping/Exceptions/MapperExistException.cs

@@ -1,55 +0,0 @@
-using System;
-using System.Runtime.Serialization;
-
-namespace Masuit.Tools.Mapping.Exceptions
-{
-    /// <summary>
-    /// 映射已存在时的异常
-    /// </summary>
-    [Serializable]
-    public class MapperExistException : MapperExceptionBase
-
-    {
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="source">源类型</param>
-        /// <param name="dest">目标类型</param>
-        public MapperExistException(Type source, Type dest) : base(ValideParameter($"对于源“{source.FullName}”的类型和目标类型“{dest.FullName}”的映射关系已经存在", source != null, dest != null))
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        public MapperExistException()
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="exceptionMessage">异常信息</param>
-        public MapperExistException(string exceptionMessage) : base(exceptionMessage)
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="serializer">序列化信息</param>
-        /// <param name="context">上下文</param>
-        protected MapperExistException(SerializationInfo serializer, StreamingContext context) : base(serializer, context)
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="exceptionMessage">异常信息</param>
-        /// <param name="innerException">内部异常</param>
-        public MapperExistException(string exceptionMessage, Exception innerException) : base(exceptionMessage, innerException)
-        {
-        }
-    }
-}

+ 0 - 54
Masuit.Tools.Core/Mapping/Exceptions/MapperNotInitializedException.cs

@@ -1,54 +0,0 @@
-using System;
-using System.Runtime.Serialization;
-
-namespace Masuit.Tools.Mapping.Exceptions
-{
-    /// <summary>
-    /// 映射未初始化时的异常
-    /// </summary>
-    [Serializable]
-    public class MapperNotInitializedException : MapperExceptionBase
-    {
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="typeSource">源类型</param>
-        /// <param name="typeDest">目标类型</param>
-        public MapperNotInitializedException(Type typeSource, Type typeDest) : base(ValideParameter($"源类型“{typeSource.FullName}”和目标类型“{typeDest.FullName}”的映射关系未被初始化,需要在此之前调用ExpressionMapper.Initialize()", typeSource != null, typeDest != null))
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        public MapperNotInitializedException()
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="exceptionMessage">异常信息</param>
-        public MapperNotInitializedException(string exceptionMessage) : base(exceptionMessage)
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="serializer">序列化信息</param>
-        /// <param name="context">上下文</param>
-        protected MapperNotInitializedException(SerializationInfo serializer, StreamingContext context) : base(serializer, context)
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="exceptionMessage">异常信息</param>
-        /// <param name="innerException">内部异常</param>
-        public MapperNotInitializedException(string exceptionMessage, Exception innerException) : base(exceptionMessage, innerException)
-        {
-        }
-    }
-}

+ 0 - 46
Masuit.Tools.Core/Mapping/Exceptions/NoActionAfterMappingException.cs

@@ -1,46 +0,0 @@
-using System;
-using System.Runtime.Serialization;
-
-namespace Masuit.Tools.Mapping.Exceptions
-{
-    /// <summary>
-    /// 无法执行任何操作时的异常
-    /// </summary>
-    /// <seealso cref="MapperExceptionBase" />
-    [Serializable]
-    public class NoActionAfterMappingException : MapperExceptionBase
-    {
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        public NoActionAfterMappingException() : base("无法执行操作,因为操作未定义")
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="serializer">序列化信息</param>
-        /// <param name="context">上下文</param>
-        protected NoActionAfterMappingException(SerializationInfo serializer, StreamingContext context) : base(serializer, context)
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="exceptionMessage">异常信息</param>
-        public NoActionAfterMappingException(string exceptionMessage) : base(exceptionMessage)
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="exceptionMessage">异常信息</param>
-        /// <param name="innerException">内部异常</param>
-        public NoActionAfterMappingException(string exceptionMessage, Exception innerException) : base(exceptionMessage, innerException)
-        {
-        }
-    }
-}

+ 0 - 54
Masuit.Tools.Core/Mapping/Exceptions/NoFoundMapperException.cs

@@ -1,54 +0,0 @@
-using System;
-using System.Runtime.Serialization;
-
-namespace Masuit.Tools.Mapping.Exceptions
-{
-    /// <summary>
-    /// 未找到映射关系时出现异常
-    /// </summary>
-    [Serializable]
-    public class NoFoundMapperException : MapperExceptionBase
-    {
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="source">源类型</param>
-        /// <param name="dest">目标类型</param>
-        public NoFoundMapperException(Type source, Type dest) : base(ValideParameter($"未配置类型“{source.Name}”和“{dest.Name}”的映射", source != null, dest != null))
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="name">别名</param>
-        public NoFoundMapperException(string name) : base(ValideParameter($"找不到名称为{name}的映射", !string.IsNullOrEmpty(name)))
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        public NoFoundMapperException()
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="serializer">序列化信息</param>
-        /// <param name="context">上下文</param>
-        protected NoFoundMapperException(SerializationInfo serializer, StreamingContext context) : base(serializer, context)
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="exceptionMessage">异常信息</param>
-        /// <param name="innerException">内部异常</param>
-        public NoFoundMapperException(string exceptionMessage, Exception innerException) : base(exceptionMessage, innerException)
-        {
-        }
-    }
-}

+ 0 - 53
Masuit.Tools.Core/Mapping/Exceptions/NotSameTypePropertyException.cs

@@ -1,53 +0,0 @@
-using System;
-using System.Runtime.Serialization;
-
-namespace Masuit.Tools.Mapping.Exceptions
-{
-    /// <summary>
-    /// 当属性不是同一类型或找不到映射器时出现异常
-    /// </summary>
-    [Serializable]
-    public class NotSameTypePropertyException : MapperExceptionBase
-    {
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="typeSource">源类型</param>
-        /// <param name="typeDest">目标类型</param>
-        public NotSameTypePropertyException(Type typeSource, Type typeDest) : base(ValideParameter($"源类型{typeSource.Name}目标和类型{typeDest.Name}的属性不是同一类型或找不到映射关系", typeSource != null, typeDest != null))
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        public NotSameTypePropertyException()
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="serializer">序列化信息</param>
-        /// <param name="context">上下文</param>
-        protected NotSameTypePropertyException(SerializationInfo serializer, StreamingContext context) : base(serializer, context)
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="exceptionMessage">异常信息</param>
-        /// <param name="innerException">内部异常</param>
-        public NotSameTypePropertyException(string exceptionMessage, Exception innerException) : base(exceptionMessage, innerException)
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        public NotSameTypePropertyException(string exceptionMessage) : base(exceptionMessage)
-        {
-        }
-    }
-}

+ 0 - 54
Masuit.Tools.Core/Mapping/Exceptions/PropertyNoExistException.cs

@@ -1,54 +0,0 @@
-using System;
-using System.Runtime.Serialization;
-
-namespace Masuit.Tools.Mapping.Exceptions
-{
-    /// <summary>
-    /// 找不到属性时出现异常
-    /// </summary>
-    [Serializable]
-    public class PropertyNoExistException : MapperExceptionBase
-    {
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="propertyName">属性名</param>
-        /// <param name="typeObject">对象类型</param>
-        public PropertyNoExistException(string propertyName, Type typeObject) : base(ValideParameter($"类型“{typeObject}”不存在属性“{propertyName}”", !String.IsNullOrEmpty(propertyName), typeObject != null))
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        public PropertyNoExistException()
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="exceptionMessage">异常信息</param>
-        public PropertyNoExistException(string exceptionMessage) : base(exceptionMessage)
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="serializer">序列化信息</param>
-        /// <param name="context">上下文</param>
-        protected PropertyNoExistException(SerializationInfo serializer, StreamingContext context) : base(serializer, context)
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="exceptionMessage">异常信息</param>
-        /// <param name="innerException">内部异常</param>
-        public PropertyNoExistException(string exceptionMessage, Exception innerException) : base(exceptionMessage, innerException)
-        {
-        }
-    }
-}

+ 0 - 59
Masuit.Tools.Core/Mapping/Exceptions/ReadOnlyPropertyException.cs

@@ -1,59 +0,0 @@
-using System;
-using System.Reflection;
-using System.Runtime.Serialization;
-
-namespace Masuit.Tools.Mapping.Exceptions
-{
-    /// <summary>
-    /// 只读属性的异常
-    /// </summary>
-    [Serializable]
-    public class ReadOnlyPropertyException : MapperExceptionBase
-    {
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="property">属性</param>
-        public ReadOnlyPropertyException(PropertyInfo property) : base(ValidateParameter(property))
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        public ReadOnlyPropertyException()
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="serializer">序列化信息</param>
-        /// <param name="context">上下文</param>
-        protected ReadOnlyPropertyException(SerializationInfo serializer, StreamingContext context) : base(serializer, context)
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="exceptionMessage">异常信息</param>
-        /// <param name="innerException">内部异常</param>
-        public ReadOnlyPropertyException(string exceptionMessage, Exception innerException) : base(exceptionMessage, innerException)
-        {
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="exceptionMessage">异常信息</param>
-        public ReadOnlyPropertyException(string exceptionMessage) : base(exceptionMessage)
-        {
-        }
-
-        private static string ValidateParameter(PropertyInfo property)
-        {
-            return $"目标对象的属性 '{property.Name}' 是只读的";
-        }
-    }
-}

+ 0 - 19
Masuit.Tools.Core/Mapping/ExpressionCpoier.cs

@@ -1,19 +0,0 @@
-namespace Masuit.Tools.Mapping
-{
-    /// <summary>
-    /// 表达式树复制对象
-    /// </summary>
-    public static class ExpressionCpoier
-    {
-        /// <summary>
-        /// 复制一个新实例
-        /// </summary>
-        /// <typeparam name="T"></typeparam>
-        /// <param name="source"></param>
-        /// <returns></returns>
-        public static T Copy<T>(this T source)
-        {
-            return Copier<T>.Copy(source);
-        }
-    }
-}

+ 0 - 176
Masuit.Tools.Core/Mapping/ExpressionMapper.cs

@@ -1,176 +0,0 @@
-using Masuit.Tools.Mapping.Core;
-using Masuit.Tools.Mapping.Exceptions;
-using System;
-using System.Linq.Expressions;
-
-namespace Masuit.Tools.Mapping
-{
-    /// <summary>
-    /// mapper的基类
-    /// </summary>
-    public static class ExpressionMapper
-    {
-        private static Func<Type, object> _constructorFunc;
-        private static bool _initialized;
-
-        /// <summary>
-        /// 映射指定的源。
-        /// </summary>
-        /// <typeparam name="TSource">源类型</typeparam>
-        /// <typeparam name="TDest">目标类型</typeparam>
-        /// <param name="source">源对象</param>
-        /// <param name="name">别名</param>
-        /// <returns>
-        /// 目标对象的新实例
-        /// </returns>
-        public static TDest Map<TSource, TDest>(this TSource source, string name = null) where TSource : class where TDest : class
-        {
-            if (source == null)
-            {
-                return null;
-            }
-
-            if (!_initialized)
-            {
-                Initialize();
-            }
-            TDest result = null;
-            MapperConfiguration<TSource, TDest> mapper = GetMapper<TSource, TDest>(name);
-            Func<TSource, TDest> query = mapper.GetFuncDelegate();
-            if (query != null)
-            {
-                result = query(source);
-                // 映射后执行的操作
-                mapper.ExecuteAfterActions(source, result);
-            }
-            return result;
-        }
-
-        /// <summary>
-        /// 将指定的源映射到目标。
-        /// </summary>
-        /// <typeparam name="TSource">源类型</typeparam>
-        /// <typeparam name="TDest">目标类型</typeparam>
-        /// <param name="source">源对象</param>
-        /// <param name="target">目标对象</param>
-        /// <param name="name">别名</param>
-        public static void Map<TSource, TDest>(this TSource source, TDest target, string name = null) where TSource : class where TDest : class
-        {
-            if (!_initialized)
-            {
-                Initialize();
-            }
-            TDest result = null;
-            MapperConfiguration<TSource, TDest> mapper = GetMapper<TSource, TDest>(name);
-            Action<TSource, TDest> query = mapper.GetDelegateForExistingTarget() as Action<TSource, TDest>;
-            if (query != null)
-            {
-                query(source, target);
-                // 映射后执行的操作
-                mapper.ExecuteAfterActions(source, result);
-            }
-        }
-
-        /// <summary>
-        /// 获取查询表达式树
-        /// </summary>
-        /// <typeparam name="TSource">源类型</typeparam>
-        /// <typeparam name="TDest">目标类型</typeparam>
-        /// <returns></returns>
-        public static Expression<Func<TSource, TDest>> GetQueryExpression<TSource, TDest>() where TSource : class where TDest : class
-        {
-            return GetMapper<TSource, TDest>().GetLambdaExpression();
-        }
-
-        /// <summary>
-        /// 创建mapper对象
-        /// </summary>
-        /// <typeparam name="TSource">源类型</typeparam>
-        /// <typeparam name="TDest">目标类型</typeparam>
-        /// <returns></returns>
-        public static MapperConfiguration<TSource, TDest> CreateMap<TSource, TDest>(string name = null) where TSource : class where TDest : class
-        {
-            MapperConfigurationBase map = MapperConfigurationCollectionContainer.Instance.Find(typeof(TSource), typeof(TDest), name);
-            if (map == null)
-            {
-                string finalName = string.IsNullOrEmpty(name) ? "s" + MapperConfigurationCollectionContainer.Instance.Count.ToString() : name;
-                map = new MapperConfiguration<TSource, TDest>(finalName);
-                MapperConfigurationCollectionContainer.Instance.Add(map);
-            }
-            return map as MapperConfiguration<TSource, TDest>;
-        }
-
-        /// <summary>
-        /// 表示使用的依赖注入服务
-        /// </summary>
-        /// <param name="constructor">构造函数委托</param>
-        public static void ConstructServicesUsing(Func<Type, object> constructor)
-        {
-            _constructorFunc = constructor;
-        }
-
-        /// <summary>
-        /// 重置mapper
-        /// </summary>
-        public static void Reset()
-        {
-            MapperConfigurationCollectionContainer.Instance.Clear();
-        }
-
-        /// <summary>
-        /// 获取mapper实例
-        /// </summary>
-        /// <typeparam name="TSource">源类型</typeparam>
-        /// <typeparam name="TDest">目标类型</typeparam>
-        /// <param name="name">别名</param>
-        /// <returns></returns>
-        public static MapperConfiguration<TSource, TDest> GetMapper<TSource, TDest>(string name = null) where TSource : class where TDest : class
-        {
-            return GetMapper(typeof(TSource), typeof(TDest), name) as MapperConfiguration<TSource, TDest>;
-        }
-
-        /// <summary>
-        /// 初始化mapper
-        /// </summary>
-        public static void Initialize()
-        {
-            MapperConfigurationCollectionContainer configRegister = MapperConfigurationCollectionContainer.Instance;
-            foreach (var t in configRegister)
-            {
-                t.Initialize(_constructorFunc);
-            }
-            _initialized = true;
-        }
-
-        /// <summary>
-        /// 获取mapper的委托
-        /// </summary>
-        /// <typeparam name="TSource">源类型</typeparam>
-        /// <typeparam name="TDest">目标类型</typeparam>
-        /// <returns></returns>
-        public static Func<TSource, TDest> GetQuery<TSource, TDest>() where TSource : class where TDest : class
-        {
-            return GetMapper<TSource, TDest>().GetFuncDelegate();
-        }
-
-        /// <summary>
-        /// 获取未映射的属性
-        /// </summary>
-        public static PropertiesNotMapped GetPropertiesNotMapped<TSource, TDest>(string name = null) where TSource : class where TDest : class
-        {
-            var mapper = GetMapper<TSource, TDest>(name);
-            return mapper.GetPropertiesNotMapped();
-        }
-
-        internal static MapperConfigurationBase GetMapper(Type tSource, Type tDest, string name = null)
-        {
-            MapperConfigurationBase mapConfig = MapperConfigurationCollectionContainer.Instance.Find(tSource, tDest, name);
-            if (mapConfig == null)
-            {
-                throw new NoFoundMapperException(tSource, tDest);
-            }
-
-            return mapConfig;
-        }
-    }
-}

+ 0 - 77
Masuit.Tools.Core/Mapping/Extensions/ExpressionExtentions.cs

@@ -1,77 +0,0 @@
-using Masuit.Tools.Mapping.Visitor;
-using System;
-using System.Collections.Generic;
-using System.Linq.Expressions;
-
-namespace Masuit.Tools.Mapping.Extensions
-{
-    /// <summary>
-    ///表达式树扩展
-    /// </summary>
-    public static class ExpressionExtentions
-    {
-        /// <summary>
-        /// 转换
-        /// </summary>
-        /// <typeparam name="TFrom">源类型</typeparam>
-        /// <param name="from">来源</param>
-        /// <param name="toType">目标类型</param>
-        /// <returns></returns>
-        public static Expression ConvertTo<TFrom>(this Expression<Func<TFrom, object>> from, Type toType)
-        {
-            return ConvertImpl(from, toType);
-        }
-
-        /// <summary>
-        /// 转换
-        /// </summary>
-        /// <typeparam name="TFrom">源类型</typeparam>
-        /// <param name="from">来源</param>
-        /// <param name="toType">目标类型</param>
-        /// <returns></returns>
-        public static Expression ConvertTo<TFrom>(this Expression<Func<TFrom, bool>> from, Type toType)
-        {
-            return ConvertImpl(from, toType);
-        }
-
-        /// <summary>
-        /// 转换Lambda表达式树
-        /// </summary>
-        /// <typeparam name="TFrom">源类型</typeparam>
-        /// <typeparam name="TTo">目标类型</typeparam>
-        /// <param name="from">来源</param>
-        /// <returns></returns>
-        public static Expression ConvertTo<TFrom, TTo>(this Expression<Func<TFrom, object>> from)
-        {
-            return ConvertImpl(from, typeof(TTo));
-        }
-
-        /// <summary>
-        /// 转换表达式树
-        /// </summary>
-        /// <typeparam name="TFrom">源类型的表达式树</typeparam>
-        /// <typeparam name="TTo">目标类型的表达式树</typeparam>
-        /// <param name="from">源类型的表达式树</param>
-        /// <returns>表达式转换或如果没有找到映射原始表达式。</returns>
-        public static Expression<Func<TTo, bool>> ConvertTo<TFrom, TTo>(this Expression<Func<TFrom, bool>> from)
-        {
-            return (Expression<Func<TTo, bool>>)ConvertImpl(from, typeof(TTo));
-        }
-
-        private static Expression ConvertImpl<TFrom>(Expression<TFrom> from, Type toType) where TFrom : class
-        {
-            //  重新映射不同类型的所有参数
-            Dictionary<Expression, Expression> parameterMap = new Dictionary<Expression, Expression>();
-            ParameterExpression[] newParams = new ParameterExpression[from.Parameters.Count];
-            for (int i = 0; i < newParams.Length; i++)
-            {
-                newParams[i] = Expression.Parameter(toType, from.Parameters[i].Name);
-                parameterMap[from.Parameters[i]] = newParams[i];
-            }
-
-            // 重新构建表达式树
-            var body = new ConverterExpressionVisitor(parameterMap, toType).Visit(from.Body);
-            return Expression.Lambda(body, newParams);
-        }
-    }
-}

+ 0 - 124
Masuit.Tools.Core/Mapping/Extensions/QueryableExtentions.cs

@@ -1,124 +0,0 @@
-using Masuit.Tools.Mapping.Core;
-using System;
-using System.Linq;
-using System.Linq.Expressions;
-
-namespace Masuit.Tools.Mapping.Extensions
-{
-    /// <summary>
-    /// IQueryable的扩展
-    /// </summary>
-    public static class QueryableExtentions
-    {
-        /// <summary>
-        /// 根据键按升序对序列的元素进行排序。
-        /// </summary>
-        /// <typeparam name="TSource">源类型</typeparam>
-        /// <typeparam name="TDest">目标类型</typeparam>
-        /// <param name="query">分类化的序列值</param>
-        /// <param name="sortedPropertyDestName">目标属性的名称</param>
-        /// <returns></returns>
-        public static IOrderedQueryable<TSource> OrderBy<TSource, TDest>(this IQueryable<TSource> query, string sortedPropertyDestName) where TSource : class where TDest : class
-        {
-            // 没有使用MethodBase.GetCurrentMethod().Name,因为效率不高
-            return CreateSortedMethodCall<TSource, TDest, IOrderedQueryable<TSource>>(query, "OrderBy", sortedPropertyDestName);
-        }
-
-        /// <summary>
-        /// 根据键按降序对序列的元素进行排序。
-        /// </summary>
-        /// <typeparam name="TSource">源类型</typeparam>
-        /// <typeparam name="TDest">目标类型</typeparam>
-        /// <param name="query">分类化的序列值</param>
-        /// <param name="sortedPropertyDestName">目标属性的名称</param>
-        /// <returns></returns>
-        public static IOrderedQueryable<TSource> OrderByDescending<TSource, TDest>(this IQueryable<TSource> query, string sortedPropertyDestName) where TSource : class where TDest : class
-        {
-            return CreateSortedMethodCall<TSource, TDest, IOrderedQueryable<TSource>>(query, "OrderByDescending", sortedPropertyDestName);
-        }
-
-        /// <summary>
-        ///  根据键按升序对序列的元素进行排序。
-        /// </summary>
-        /// <typeparam name="TSource">源类型</typeparam>
-        /// <typeparam name="TDest">目标类型</typeparam>
-        /// <param name="query">分类化的序列值</param>
-        /// <param name="sortedPropertyDestName">目标属性的名称</param>
-        public static IOrderedQueryable<TSource> ThenBy<TSource, TDest>(this IQueryable<TSource> query, string sortedPropertyDestName) where TSource : class where TDest : class
-        {
-            return CreateSortedMethodCall<TSource, TDest, IOrderedQueryable<TSource>>(query, "ThenBy", sortedPropertyDestName);
-        }
-
-        /// <summary>
-        /// 根据键按降序对序列的元素进行排序。
-        /// </summary>
-        /// <typeparam name="TSource">源类型</typeparam>
-        /// <typeparam name="TDest">目标类型</typeparam>
-        /// <param name="query">分类化的序列值</param>
-        /// <param name="sortedPropertyDestName">目标属性的名称</param>
-        public static IOrderedQueryable<TSource> ThenByDescending<TSource, TDest>(this IQueryable<TSource> query, string sortedPropertyDestName) where TSource : class where TDest : class
-        {
-            return CreateSortedMethodCall<TSource, TDest, IOrderedQueryable<TSource>>(query, "ThenByDescending", sortedPropertyDestName);
-        }
-
-        /// <summary>
-        /// 通过合并目标对象将序列的每个元素投影到新表单中。
-        /// </summary>
-        /// <typeparam name="TSource">源类型.</typeparam>
-        /// <typeparam name="TDest">目标类型.</typeparam>
-        /// <param name="query">分类化的序列值</param>
-        public static IQueryable<TDest> ProjectTo<TSource, TDest>(this IQueryable<TSource> query) where TSource : class where TDest : class
-        {
-            return GetSelect<TSource, TDest>(query, null);
-        }
-
-        /// <summary>
-        /// 通过合并目标对象将序列的每个元素投影到新表单中。
-        /// </summary>
-        /// <typeparam name="TSource">源类型.</typeparam>
-        /// <typeparam name="TDest">目标类型.</typeparam>
-        /// <param name="query">分类化的序列值</param>
-        /// <param name="mapperName">mapper别名</param>
-        /// <returns></returns>
-        public static IQueryable<TDest> ProjectTo<TSource, TDest>(this IQueryable<TSource> query, string mapperName) where TSource : class where TDest : class
-        {
-            return GetSelect<TSource, TDest>(query, mapperName);
-        }
-
-        /// <summary>
-        /// 根据谓词过滤一系列值。
-        /// </summary>
-        /// <typeparam name="TSource">源类型</typeparam>
-        /// <typeparam name="TDest">目标类型</typeparam>
-        /// <param name="query">分类化的序列值</param>
-        /// <param name="predicate">用于根据条件测试每个元素的功能。</param>
-        /// <returns></returns>
-        public static IQueryable<TDest> WhereTo<TSource, TDest>(this IQueryable<TDest> query, Expression<Func<TSource, bool>> predicate)
-        {
-            return query.Where(predicate.ConvertTo<TSource, TDest>());
-        }
-
-        private static TQueryable CreateSortedMethodCall<TSource, TDest, TQueryable>(IQueryable<TSource> query, string methodName, string sortedPropertySourceName) where TSource : class where TDest : class where TQueryable : class, IQueryable<TSource>
-        {
-            MapperConfiguration<TSource, TDest> mapper = ExpressionMapper.GetMapper<TSource, TDest>();
-            var prop = mapper.GetLambdaDest(sortedPropertySourceName);
-            var lambda = mapper.GetSortedExpression(sortedPropertySourceName);
-            MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName, new Type[]
-            {
-                typeof(TSource),
-                prop.Type
-            }, query.Expression, Expression.Quote(lambda));
-            return query.Provider.CreateQuery<TSource>(resultExp) as TQueryable;
-        }
-
-        private static IQueryable<TDest> GetSelect<TSource, TDest>(IQueryable<TSource> query, string mapperName) where TSource : class where TDest : class
-        {
-            // 不需要mapper
-            if (typeof(TSource) == typeof(TDest))
-            {
-                return (IQueryable<TDest>)query;
-            }
-            return query.Select(ExpressionMapper.GetMapper<TSource, TDest>(mapperName).GetLambdaExpression());
-        }
-    }
-}

+ 0 - 34
Masuit.Tools.Core/Mapping/Helper/MapperHelper.cs

@@ -1,34 +0,0 @@
-using System;
-using System.Linq.Expressions;
-
-namespace Masuit.Tools.Mapping.Helper
-{
-    /// <summary>
-    /// mapper帮助类
-    /// </summary>
-    internal static class MapperHelper
-    {
-        /// <summary>
-        /// 获取类型的默认值。
-        /// </summary>
-        /// <param name="typeObject">对象类型</param>
-        internal static object GetDefaultValue(Type typeObject)
-        {
-            object defaultValue = null;
-            // 对于值类型(例如Integer),必须将对象实例化为具有其默认值。
-            if (typeObject.BaseType == typeof(ValueType))
-            {
-                NewExpression exp = Expression.New(typeObject);
-                LambdaExpression lambda = Expression.Lambda(exp);
-                Delegate constructor = lambda.Compile();
-                defaultValue = constructor.DynamicInvoke();
-            }
-            if (typeObject.IsEnum)
-            {
-                defaultValue = Enum.Parse(typeObject, Enum.GetNames(typeObject)[0]);
-            }
-
-            return defaultValue;
-        }
-    }
-}

+ 0 - 64
Masuit.Tools.Core/Mapping/Helper/TypeSystem.cs

@@ -1,64 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace Masuit.Tools.Mapping.Helper
-{
-    internal static class TypeSystem
-    {
-        internal static Type GetElementType(Type seqType)
-        {
-            Type ienum = FindIEnumerable(seqType);
-            if (ienum == null)
-            {
-                return seqType;
-            }
-
-            return ienum.GetGenericArguments()[0];
-        }
-
-        private static Type FindIEnumerable(Type seqType)
-        {
-            if (seqType == null || seqType == typeof(string))
-            {
-                return null;
-            }
-
-            if (seqType.IsArray)
-            {
-                return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType());
-            }
-
-            if (seqType.IsGenericType)
-            {
-                foreach (Type arg in seqType.GetGenericArguments())
-                {
-                    Type ienum = typeof(IEnumerable<>).MakeGenericType(arg);
-                    if (ienum.IsAssignableFrom(seqType))
-                    {
-                        return ienum;
-                    }
-                }
-            }
-
-            Type[] ifaces = seqType.GetInterfaces();
-
-            if (ifaces != null && ifaces.Length > 0)
-            {
-                foreach (Type iface in ifaces)
-                {
-                    Type ienum = FindIEnumerable(iface);
-                    if (ienum != null)
-                    {
-                        return ienum;
-                    }
-                }
-            }
-
-            if (seqType.BaseType != null && seqType.BaseType != typeof(object))
-            {
-                return FindIEnumerable(seqType.BaseType);
-            }
-            return null;
-        }
-    }
-}

+ 0 - 26
Masuit.Tools.Core/Mapping/Visitor/ChangParameterExpressionVisitor.cs

@@ -1,26 +0,0 @@
-using System.Linq;
-using System.Linq.Expressions;
-
-namespace Masuit.Tools.Mapping.Visitor
-{
-    internal class ChangParameterExpressionVisitor : ExpressionVisitor
-    {
-        private readonly Expression[] _parameter;
-        internal ChangParameterExpressionVisitor(params Expression[] parameter)
-        {
-            _parameter = parameter;
-        }
-
-        protected override Expression VisitParameter(ParameterExpression node)
-        {
-            if (node != null)
-            {
-                Expression returnParameter = _parameter.FirstOrDefault(x => x.Type == node.Type);
-                if (returnParameter != null)
-                    return returnParameter;
-            }
-            return node;
-        }
-
-    }
-}

+ 0 - 113
Masuit.Tools.Core/Mapping/Visitor/ConverterExpressionVisitor.cs

@@ -1,113 +0,0 @@
-using Masuit.Tools.Mapping.Core;
-using System;
-using System.Collections.Generic;
-using System.Linq.Expressions;
-
-namespace Masuit.Tools.Mapping.Visitor
-{
-    /// <summary>
-    /// 将表达式从源转换为目标的访问者表达式
-    /// </summary>
-    public class ConverterExpressionVisitor : ExpressionVisitor
-    {
-        private readonly Dictionary<Expression, Expression> _parameterMap;
-        private readonly Type _destinationType;
-        private MapperConfigurationBase _mapper;
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="parameterMap"></param>
-        /// <param name="typeDestination"></param>
-        public ConverterExpressionVisitor(Dictionary<Expression, Expression> parameterMap, Type typeDestination)
-        {
-            _parameterMap = parameterMap;
-            _destinationType = typeDestination;
-        }
-
-        /// <summary>
-        /// 
-        /// </summary>
-        /// <param name="node">访问表达式树</param>
-        /// <returns>
-        /// 改变表达式,如果它或它的任何子表达式被修改; 否则,返回原始表达式。
-        /// </returns>
-        protected override Expression VisitParameter(ParameterExpression node)
-        {
-            if (!_parameterMap.TryGetValue(node, out var found))
-            {
-                found = Expression.Parameter(_destinationType, "dest");
-            }
-
-            return found;
-        }
-
-        /// <summary>
-        /// 将表达式分布在此类中更专业的访问方法之一。
-        /// </summary>
-        /// <param name="node">访问表达式树</param>
-        /// <returns>
-        /// 改变表达式,如果它或它的任何子表达式被修改; 否则,返回原始表达式。
-        /// </returns>
-        public override Expression Visit(Expression node)
-        {
-            if (node != null)
-            {
-                Expression expression;
-                switch (node.NodeType)
-                {
-                    case ExpressionType.Lambda:
-                        expression = base.Visit((node as LambdaExpression).Body);
-                        break;
-                    default:
-                        expression = base.Visit(node);
-                        break;
-                }
-                return expression;
-            }
-            return node;
-        }
-
-        /// <summary>
-        /// 访问子表达式树
-        /// </summary>
-        /// <param name="node">访问表达式树</param>
-        /// <returns>
-        /// 改变表达式,如果它或它的任何子表达式被修改; 否则,返回原始表达式。
-        /// </returns>
-        protected override Expression VisitMember(MemberExpression node)
-        {
-            var expr = Visit(node.Expression);
-            if (expr != null && expr.Type != node.Type)
-            {
-                if (_mapper == null)
-                {
-                    _mapper = ExpressionMapper.GetMapper(node.Member.DeclaringType, _destinationType);
-                }
-                Expression expDest;
-                // 认为原始类是简单属性(不是子对象)。
-                if (!expr.Type.IsValueType && expr.Type != typeof(string) && expr.NodeType != ExpressionType.Parameter && expr.NodeType != ExpressionType.Constant)
-                {
-                    var subExp = ExpressionMapper.GetMapper(node.Member.DeclaringType, expr.Type);
-                    expDest = subExp.GetLambdaDest(node.Member.Name);
-                    return AnalyseDestExpression(expr, expDest);
-                }
-                expDest = _mapper.GetLambdaDest(node.Member.Name);
-                if (expDest != null)
-                {
-                    return AnalyseDestExpression(expr, expDest);
-                }
-            }
-            return base.VisitMember(node);
-        }
-
-        private Expression AnalyseDestExpression(Expression expr, Expression expDest)
-        {
-            if (expDest.NodeType == ExpressionType.MemberAccess)
-            {
-                return Expression.MakeMemberAccess(expr, (expDest as MemberExpression).Member);
-            }
-            return base.Visit(expDest);
-        }
-    }
-}

+ 0 - 210
Masuit.Tools.Core/Mapping/Visitor/MapperExpressionVisitor.cs

@@ -1,210 +0,0 @@
-using Masuit.Tools.Mapping.Helper;
-using System.Collections.Generic;
-using System.Linq.Expressions;
-
-namespace Masuit.Tools.Mapping.Visitor
-{
-    /// <summary>
-    /// mapper表达式树访问器
-    /// </summary>
-    public class MapperExpressionVisitor : ExpressionVisitor
-    {
-        private bool _checkNull;
-        readonly Stack<MemberExpression> _membersToCheck;
-
-        internal Expression Parameter { get; }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="paramClassSource"></param>
-        public MapperExpressionVisitor(Expression paramClassSource)
-        {
-            Parameter = paramClassSource;
-            _membersToCheck = new Stack<MemberExpression>();
-        }
-
-        /// <summary>
-        /// 将表达式分布在此类中更专一的访问方法之一。
-        /// </summary>
-        /// <param name="node">访问表达式树</param>
-        /// <param name="checkIfNullity">检查null值</param>
-        /// <returns>
-        /// 改变表达式,如果它或它的任何子表达式被修改; 否则,返回原始表达式。
-        /// </returns>
-        public Expression Visit(Expression node, bool checkIfNullity = false)
-        {
-            _checkNull = checkIfNullity;
-            if (node == null)
-            {
-                return node;
-            }
-
-            if (_checkNull)
-            {
-                Expression result;
-                switch (node.NodeType)
-                {
-                    case ExpressionType.MemberAccess:
-                        result = VisitMember(node as MemberExpression);
-                        break;
-                    case ExpressionType.Parameter:
-                        result = VisitParameter(node as ParameterExpression);
-                        break;
-                    case ExpressionType.Convert:
-                        result = VisitMember((node as UnaryExpression).Operand as MemberExpression);
-                        break;
-                    case ExpressionType.Lambda:
-                        LambdaExpression lambda = ((LambdaExpression)node);
-                        // 子表达式树
-                        if (lambda.Body.NodeType != ExpressionType.Lambda)
-                        {
-                            result = Visit(lambda.Body);
-                        }
-                        else
-                        {
-                            return lambda;
-                        }
-
-                        break;
-                    default:
-                        result = base.Visit(node);
-                        break;
-                }
-
-                bool isFirst = true;
-                Expression previousExpression = null;
-                if (_membersToCheck.Count > 1)
-                {
-                    // 在分配值之前测试所有子对象。例如:source.SubClass.SubClass2.MyProperty。是哪个会给:
-                    // source.SubClass!= null? source.SubClass.SubClass2!= null? source.SubClass.SubClass2.MyProperty:DefaultValueOfProperty:DefaultValueOfProperty
-                    foreach (MemberExpression item in _membersToCheck)
-                    {
-                        if (!isFirst) // 不要测试该属性的值。
-                        {
-                            object defaultValue = MapperHelper.GetDefaultValue(item.Type);
-
-                            // 创建默认值的验证。
-                            Expression notDefaultValue = Expression.NotEqual(item, Expression.Constant(defaultValue, item.Type));
-                            Expression conditional = null;
-                            // 它创建了包含上述条件的条件。
-                            if (previousExpression != null)
-                            {
-                                object defaultPreviousValue = MapperHelper.GetDefaultValue(previousExpression.Type);
-                                conditional = Expression.Condition(notDefaultValue, previousExpression, Expression.Constant(defaultPreviousValue, previousExpression.Type));
-                            }
-
-                            // 它会影响新创建的条件,这些条件将成为之前的条件。
-                            previousExpression = conditional;
-                        }
-                        else // 属性
-                        {
-                            previousExpression = item;
-                            isFirst = false;
-                        }
-                    }
-
-                    return previousExpression;
-                }
-
-                // 不需要递归的元素。
-                if (_membersToCheck.Count == 1)
-                {
-                    var item = _membersToCheck.Peek();
-                    object defaultValue = MapperHelper.GetDefaultValue(item.Type);
-                    // 创建默认值的验证。
-                    Expression notDefaultValue = Expression.NotEqual(item, Expression.Constant(defaultValue, item.Type));
-                    Expression conditional = Expression.Condition(notDefaultValue, item, Expression.Constant(defaultValue, item.Type));
-
-                    return conditional;
-                }
-
-                return result;
-            }
-
-            // 默认返回(更改参数),删除lambda表达式的验证。
-            if ((node.NodeType == ExpressionType.Lambda))
-            {
-                LambdaExpression lambda = ((LambdaExpression)node);
-                // 子表达式树
-                if (lambda.Body.NodeType != ExpressionType.Call)
-                {
-                    return base.Visit(lambda.Body);
-                }
-
-                return lambda;
-            }
-
-            return base.Visit(node);
-        }
-
-        /// <summary>
-        /// 访问表达式树
-        /// </summary>
-        /// <param name="node">表达式树节点</param>
-        /// <returns>
-        /// 改变表达式,如果它或它的任何子表达式被修改; 否则,返回原始表达式。
-        /// </returns>
-        protected override Expression VisitParameter(ParameterExpression node)
-        {
-            return Parameter;
-        }
-
-        /// <summary>
-        /// 访问子表达式树
-        /// </summary>
-        /// <param name="node">表达式树节点</param>
-        /// <returns>
-        /// 改变表达式,如果它或它的任何子表达式被修改; 否则,返回原始表达式。
-        /// </returns>
-        protected override Expression VisitMember(MemberExpression node)
-        {
-            if (node == null)
-            {
-                return node;
-            }
-
-            if (node.Member.ReflectedType != Parameter.Type)
-            {
-                var exp = Visit(node.Expression);
-                return Expression.MakeMemberAccess(exp, node.Member);
-            }
-
-            MemberExpression memberAccessExpression = (MemberExpression)base.VisitMember(node);
-
-            // 稍后处理
-            if (memberAccessExpression != null && _checkNull)
-            {
-                // 如果最后一个成员是第一次访问,那么每次都得回去,当前的插入成员位于列表的第一行以更改顺序。
-                _membersToCheck.Push(memberAccessExpression);
-            }
-
-            return memberAccessExpression;
-        }
-
-        /// <summary>
-        ///  访问子表达式树
-        /// </summary>
-        /// <param name="node">表达式树节点</param>
-        /// <returns>
-        /// 改变表达式,如果它或它的任何子表达式被修改; 否则,返回原始表达式。
-        /// </returns>
-        protected override Expression VisitUnary(UnaryExpression node)
-        {
-            if (node != null)
-            {
-                if (node.Operand.NodeType == ExpressionType.MemberAccess)
-                {
-                    return VisitMember(node.Operand as MemberExpression);
-                }
-
-                if (node.NodeType == ExpressionType.Convert)
-                {
-                    return Visit(node.Operand);
-                }
-            }
-
-            return node;
-        }
-    }
-}

+ 0 - 35
Masuit.Tools.Core/Mapping/Visitor/PropertiesVisitor.cs

@@ -1,35 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq.Expressions;
-using System.Reflection;
-
-namespace Masuit.Tools.Mapping.Visitor
-{
-    internal class PropertiesVisitor : ExpressionVisitor
-    {
-        private readonly List<PropertyInfo> _propertiesOfExpression;
-
-        private readonly Type _typeReference;
-
-        internal PropertiesVisitor(Type typeReference)
-        {
-            _typeReference = typeReference;
-            _propertiesOfExpression = new List<PropertyInfo>();
-        }
-
-        protected override Expression VisitMember(MemberExpression node)
-        {
-            if (_typeReference == node.Member.DeclaringType)
-            {
-                _propertiesOfExpression.Add(node.Member as PropertyInfo);
-            }
-            return base.VisitMember(node);
-        }
-
-        internal List<PropertyInfo> GetProperties(Expression expression)
-        {
-            Visit(expression);
-            return _propertiesOfExpression;
-        }
-    }
-}

+ 87 - 0
Masuit.Tools.Core/Masuit.Tools.Core.csproj

@@ -41,6 +41,56 @@ github:https://github.com/ldqk/Masuit.Tools</Description>
     <Compile Include="..\Masuit.Tools\DateTimeExt\TimeHelper.cs" Link="DateTimeExt\TimeHelper.cs" />
     <Compile Include="..\Masuit.Tools\DateTimeExt\WeekHolidayStruct.cs" Link="DateTimeExt\WeekHolidayStruct.cs" />
     <Compile Include="..\Masuit.Tools\Extensions.cs" Link="Extensions.cs" />
+    <Compile Include="..\Masuit.Tools\Hardware\CpuInfo.cs" Link="Hardware\CpuInfo.cs" />
+    <Compile Include="..\Masuit.Tools\Hardware\CPU_INFO.cs" Link="Hardware\CPU_INFO.cs" />
+    <Compile Include="..\Masuit.Tools\Hardware\DiskData.cs" Link="Hardware\DiskData.cs" />
+    <Compile Include="..\Masuit.Tools\Hardware\MemoryInfo.cs" Link="Hardware\MemoryInfo.cs" />
+    <Compile Include="..\Masuit.Tools\Hardware\NetData.cs" Link="Hardware\NetData.cs" />
+    <Compile Include="..\Masuit.Tools\Hardware\RamInfo.cs" Link="Hardware\RamInfo.cs" />
+    <Compile Include="..\Masuit.Tools\Hardware\SystemInfo.cs" Link="Hardware\SystemInfo.cs" />
+    <Compile Include="..\Masuit.Tools\Hardware\SystemtimeInfo.cs" Link="Hardware\SystemtimeInfo.cs" />
+    <Compile Include="..\Masuit.Tools\Hardware\Unit.cs" Link="Hardware\Unit.cs" />
+    <Compile Include="..\Masuit.Tools\Html\HtmlTools.cs" Link="Html\HtmlTools.cs" />
+    <Compile Include="..\Masuit.Tools\Linq\LinqExtension.cs" Link="Linq\LinqExtension.cs" />
+    <Compile Include="..\Masuit.Tools\Logging\LogInfo.cs" Link="Logging\LogInfo.cs" />
+    <Compile Include="..\Masuit.Tools\Logging\LogLevel.cs" Link="Logging\LogLevel.cs" />
+    <Compile Include="..\Masuit.Tools\Logging\LogManager.cs" Link="Logging\LogManager.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Copier.cs" Link="Mapping\Copier.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Core\CreateConfig.cs" Link="Mapping\Core\CreateConfig.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Core\MapperConfiguration.cs" Link="Mapping\Core\MapperConfiguration.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Core\MapperConfigurationBase.cs" Link="Mapping\Core\MapperConfigurationBase.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Core\MapperConfigurationCollectionContainer.cs" Link="Mapping\Core\MapperConfigurationCollectionContainer.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Core\PropertiesNotMapped.cs" Link="Mapping\Core\PropertiesNotMapped.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Core\TypePairMapper.cs" Link="Mapping\Core\TypePairMapper.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Exceptions\MapperExceptionBase.cs" Link="Mapping\Exceptions\MapperExceptionBase.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Exceptions\MapperExistException.cs" Link="Mapping\Exceptions\MapperExistException.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Exceptions\MapperNotInitializedException.cs" Link="Mapping\Exceptions\MapperNotInitializedException.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Exceptions\NoActionAfterMappingException.cs" Link="Mapping\Exceptions\NoActionAfterMappingException.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Exceptions\NoFoundMapperException.cs" Link="Mapping\Exceptions\NoFoundMapperException.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Exceptions\NotSameTypePropertyException.cs" Link="Mapping\Exceptions\NotSameTypePropertyException.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Exceptions\PropertyNoExistException.cs" Link="Mapping\Exceptions\PropertyNoExistException.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Exceptions\ReadOnlyPropertyException.cs" Link="Mapping\Exceptions\ReadOnlyPropertyException.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\ExpressionCpoier.cs" Link="Mapping\ExpressionCpoier.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\ExpressionMapper.cs" Link="Mapping\ExpressionMapper.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Extensions\ExpressionExtentions.cs" Link="Mapping\Extensions\ExpressionExtentions.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Extensions\QueryableExtentions.cs" Link="Mapping\Extensions\QueryableExtentions.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Helper\MapperHelper.cs" Link="Mapping\Helper\MapperHelper.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Helper\TypeSystem.cs" Link="Mapping\Helper\TypeSystem.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Visitor\ChangParameterExpressionVisitor.cs" Link="Mapping\Visitor\ChangParameterExpressionVisitor.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Visitor\ConverterExpressionVisitor.cs" Link="Mapping\Visitor\ConverterExpressionVisitor.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Visitor\MapperExpressionVisitor.cs" Link="Mapping\Visitor\MapperExpressionVisitor.cs" />
+    <Compile Include="..\Masuit.Tools\Mapping\Visitor\PropertiesVisitor.cs" Link="Mapping\Visitor\PropertiesVisitor.cs" />
+    <Compile Include="..\Masuit.Tools\Media\ImageUtilities.cs" Link="Media\ImageUtilities.cs" />
+    <Compile Include="..\Masuit.Tools\Media\ThumbnailCutMode.cs" Link="Media\ThumbnailCutMode.cs" />
+    <Compile Include="..\Masuit.Tools\Models\BaiduIP.cs" Link="Models\BaiduIP.cs" />
+    <Compile Include="..\Masuit.Tools\Models\Email.cs" Link="Models\Email.cs" />
+    <Compile Include="..\Masuit.Tools\Models\IspInfo.cs" Link="Models\IspInfo.cs" />
+    <Compile Include="..\Masuit.Tools\Models\PhysicsAddress.cs" Link="Models\PhysicsAddress.cs" />
+    <Compile Include="..\Masuit.Tools\Models\TaobaoIP.cs" Link="Models\TaobaoIP.cs" />
+    <Compile Include="..\Masuit.Tools\Net\FtpClient.cs" Link="Net\FtpClient.cs" />
+    <Compile Include="..\Masuit.Tools\Net\MultiThreadDownloader.cs" Link="Net\MultiThreadDownloader.cs" />
+    <Compile Include="..\Masuit.Tools\Net\PartialDownloader.cs" Link="Net\PartialDownloader.cs" />
+    <Compile Include="..\Masuit.Tools\Net\SocketClient.cs" Link="Net\SocketClient.cs" />
     <Compile Include="..\Masuit.Tools\RandomSelector\Algorithm\BinarySearchOptimizer.cs" Link="RandomSelector\Algorithm\BinarySearchOptimizer.cs" />
     <Compile Include="..\Masuit.Tools\RandomSelector\Algorithm\MultipleSelector.cs" Link="RandomSelector\Algorithm\MultipleSelector.cs" />
     <Compile Include="..\Masuit.Tools\RandomSelector\Algorithm\SelectorBase.cs" Link="RandomSelector\Algorithm\SelectorBase.cs" />
@@ -49,6 +99,27 @@ github:https://github.com/ldqk/Masuit.Tools</Description>
     <Compile Include="..\Masuit.Tools\RandomSelector\SelectorOptions.cs" Link="RandomSelector\SelectorOptions.cs" />
     <Compile Include="..\Masuit.Tools\RandomSelector\WeightedItem.cs" Link="RandomSelector\WeightedItem.cs" />
     <Compile Include="..\Masuit.Tools\RandomSelector\WeightedSelector.cs" Link="RandomSelector\WeightedSelector.cs" />
+    <Compile Include="..\Masuit.Tools\Reflection\ClassHelper.cs" Link="Reflection\ClassHelper.cs" />
+    <Compile Include="..\Masuit.Tools\Reflection\ReflectHelper.cs" Link="Reflection\ReflectHelper.cs" />
+    <Compile Include="..\Masuit.Tools\Reflection\ReflectionUtil.cs" Link="Reflection\ReflectionUtil.cs" />
+    <Compile Include="..\Masuit.Tools\Security\Encrypt.cs" Link="Security\Encrypt.cs" />
+    <Compile Include="..\Masuit.Tools\Security\HashEncode.cs" Link="Security\HashEncode.cs" />
+    <Compile Include="..\Masuit.Tools\Security\RSACrypt.cs" Link="Security\RSACrypt.cs" />
+    <Compile Include="..\Masuit.Tools\Systems\ConcurrentLimitedQueue.cs" Link="Systems\ConcurrentLimitedQueue.cs" />
+    <Compile Include="..\Masuit.Tools\Systems\Disposable.cs" Link="Systems\Disposable.cs" />
+    <Compile Include="..\Masuit.Tools\Systems\EnumExt.cs" Link="Systems\EnumExt.cs" />
+    <Compile Include="..\Masuit.Tools\Systems\HiPerfTimer.cs" Link="Systems\HiPerfTimer.cs" />
+    <Compile Include="..\Masuit.Tools\Systems\LimitedQueue.cs" Link="Systems\LimitedQueue.cs" />
+    <Compile Include="..\Masuit.Tools\Systems\SnowFlake.cs" Link="Systems\SnowFlake.cs" />
+    <Compile Include="..\Masuit.Tools\Systems\StopwatchHelper.cs" Link="Systems\StopwatchHelper.cs" />
+    <Compile Include="..\Masuit.Tools\Validator\ComplexPassword.cs" Link="Validator\ComplexPassword.cs" />
+    <Compile Include="..\Masuit.Tools\Validator\IsEmailAttribute.cs" Link="Validator\IsEmailAttribute.cs" />
+    <Compile Include="..\Masuit.Tools\Validator\IsIPAddressAttribute.cs" Link="Validator\IsIPAddressAttribute.cs" />
+    <Compile Include="..\Masuit.Tools\Validator\IsPhoneAttribute.cs" Link="Validator\IsPhoneAttribute.cs" />
+    <Compile Include="..\Masuit.Tools\Validator\MaxValueAttribute.cs" Link="Validator\MaxValueAttribute.cs" />
+    <Compile Include="..\Masuit.Tools\Validator\MinValueAttribute.cs" Link="Validator\MinValueAttribute.cs" />
+    <Compile Include="..\Masuit.Tools\Win32\Windows.cs" Link="Win32\Windows.cs" />
+    <Compile Include="..\Masuit.Tools\Win32\WindowsCommand.cs" Link="Win32\WindowsCommand.cs" />
   </ItemGroup>
 
   <ItemGroup>
@@ -73,7 +144,23 @@ github:https://github.com/ldqk/Masuit.Tools</Description>
 
   <ItemGroup>
     <Folder Include="DateTimeExt\" />
+    <Folder Include="Hardware\" />
+    <Folder Include="Html\" />
+    <Folder Include="Linq\" />
+    <Folder Include="Logging\" />
+    <Folder Include="Mapping\Core\" />
+    <Folder Include="Mapping\Exceptions\" />
+    <Folder Include="Mapping\Extensions\" />
+    <Folder Include="Mapping\Helper\" />
+    <Folder Include="Mapping\Visitor\" />
+    <Folder Include="Media\" />
+    <Folder Include="Models\" />
     <Folder Include="RandomSelector\Algorithm\" />
+    <Folder Include="Reflection\" />
+    <Folder Include="Security\" />
+    <Folder Include="Systems\" />
+    <Folder Include="Validator\" />
+    <Folder Include="Win32\" />
   </ItemGroup>
 
 </Project>

+ 0 - 1132
Masuit.Tools.Core/Media/ImageUtilities.cs

@@ -1,1132 +0,0 @@
-using System;
-using System.Drawing;
-using System.Drawing.Drawing2D;
-using System.Drawing.Imaging;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace Masuit.Tools.Media
-{
-    /// <summary>
-    /// 图片处理
-    /// </summary>
-    public static class ImageUtilities
-    {
-        #region 正方型裁剪并缩放
-
-        /// <summary>
-        /// 正方型裁剪
-        /// 以图片中心为轴心,截取正方型,然后等比缩放
-        /// 用于头像处理
-        /// </summary>
-        /// <param name="fromFile">原图Stream对象</param>
-        /// <param name="fileSaveUrl">缩略图存放地址</param>
-        /// <param name="side">指定的边长(正方型)</param>
-        /// <param name="quality">质量(范围0-100)</param>
-        public static void CutForSquare(this Stream fromFile, string fileSaveUrl, int side, int quality)
-        {
-            //创建目录
-            string dir = Path.GetDirectoryName(fileSaveUrl);
-            if (!Directory.Exists(dir))
-            {
-                Directory.CreateDirectory(dir);
-            }
-
-            //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
-            Image initImage = Image.FromStream(fromFile, true);
-
-            //原图宽高均小于模版,不作处理,直接保存
-            if ((initImage.Width <= side) && (initImage.Height <= side))
-            {
-                initImage.Save(fileSaveUrl, ImageFormat.Jpeg);
-            }
-            else
-            {
-                //原始图片的宽、高
-                int initWidth = initImage.Width;
-                int initHeight = initImage.Height;
-
-                //非正方型先裁剪为正方型
-                if (initWidth != initHeight)
-                {
-                    //截图对象
-                    Image pickedImage;
-                    Graphics pickedG;
-
-                    //宽大于高的横图
-                    if (initWidth > initHeight)
-                    {
-                        //对象实例化
-                        pickedImage = new Bitmap(initHeight, initHeight);
-                        pickedG = Graphics.FromImage(pickedImage);
-                        //设置质量
-                        pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic;
-                        pickedG.SmoothingMode = SmoothingMode.HighQuality;
-                        //定位
-                        Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight);
-                        Rectangle toR = new Rectangle(0, 0, initHeight, initHeight);
-                        //画图
-                        pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
-                        //重置宽
-                        initWidth = initHeight;
-                    }
-                    //高大于宽的竖图
-                    else
-                    {
-                        //对象实例化
-                        pickedImage = new Bitmap(initWidth, initWidth);
-                        pickedG = Graphics.FromImage(pickedImage);
-                        //设置质量
-                        pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic;
-                        pickedG.SmoothingMode = SmoothingMode.HighQuality;
-                        //定位
-                        Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth);
-                        Rectangle toR = new Rectangle(0, 0, initWidth, initWidth);
-                        //画图
-                        pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
-                        //重置高
-                        initHeight = initWidth;
-                    }
-
-                    //将截图对象赋给原图
-                    initImage = (Image)pickedImage.Clone();
-                    //释放截图资源
-                    pickedG.Dispose();
-                    pickedImage.Dispose();
-                }
-
-                //缩略图对象
-                Image resultImage = new Bitmap(side, side);
-                Graphics resultG = Graphics.FromImage(resultImage);
-                //设置质量
-                resultG.InterpolationMode = InterpolationMode.HighQualityBicubic;
-                resultG.SmoothingMode = SmoothingMode.HighQuality;
-                //用指定背景色清空画布
-                resultG.Clear(Color.White);
-                //绘制缩略图
-                resultG.DrawImage(initImage, new Rectangle(0, 0, side, side), new Rectangle(0, 0, initWidth, initHeight), GraphicsUnit.Pixel);
-
-                //关键质量控制
-                //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
-                ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
-                ImageCodecInfo ici = null;
-                foreach (ImageCodecInfo i in icis)
-                {
-                    if ((i.MimeType == "image/jpeg") || (i.MimeType == "image/bmp") || (i.MimeType == "image/png") || (i.MimeType == "image/gif"))
-                        ici = i;
-                }
-                EncoderParameters ep = new EncoderParameters(1);
-                ep.Param[0] = new EncoderParameter(Encoder.Quality, quality);
-                //保存缩略图
-                resultImage.Save(fileSaveUrl, ici, ep);
-                //释放关键质量控制所用资源
-                ep.Dispose();
-                //释放缩略图资源
-                resultG.Dispose();
-                resultImage.Dispose();
-                //释放原始图片资源
-                initImage.Dispose();
-            }
-        }
-
-        #endregion
-
-        #region 自定义裁剪并缩放
-
-        /// <summary>
-        /// 指定长宽裁剪
-        /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸
-        /// </summary>
-        /// <param name="fromFile">原图Stream对象</param>
-        /// <param name="fileSaveUrl">保存路径</param>
-        /// <param name="maxWidth">最大宽(单位:px)</param>
-        /// <param name="maxHeight">最大高(单位:px)</param>
-        /// <param name="quality">质量(范围0-100)</param>
-        public static void CutForCustom(this Stream fromFile, string fileSaveUrl, int maxWidth, int maxHeight, int quality)
-        {
-            //从文件获取原始图片,并使用流中嵌入的颜色管理信息
-            Image initImage = Image.FromStream(fromFile, true);
-
-            //原图宽高均小于模版,不作处理,直接保存
-            if ((initImage.Width <= maxWidth) && (initImage.Height <= maxHeight))
-            {
-                initImage.Save(fileSaveUrl, ImageFormat.Jpeg);
-            }
-            else
-            {
-                //模版的宽高比例
-                double templateRate = (double)maxWidth / maxHeight;
-                //原图片的宽高比例
-                double initRate = (double)initImage.Width / initImage.Height;
-
-                //原图与模版比例相等,直接缩放
-                if (templateRate == initRate)
-                {
-                    //按模版大小生成最终图片
-                    Image templateImage = new Bitmap(maxWidth, maxHeight);
-                    Graphics templateG = Graphics.FromImage(templateImage);
-                    templateG.InterpolationMode = InterpolationMode.High;
-                    templateG.SmoothingMode = SmoothingMode.HighQuality;
-                    templateG.Clear(Color.White);
-                    templateG.DrawImage(initImage, new Rectangle(0, 0, maxWidth, maxHeight), new Rectangle(0, 0, initImage.Width, initImage.Height), GraphicsUnit.Pixel);
-                    templateImage.Save(fileSaveUrl, ImageFormat.Jpeg);
-                }
-                //原图与模版比例不等,裁剪后缩放
-                else
-                {
-                    //裁剪对象
-                    Image pickedImage;
-                    Graphics pickedG;
-
-                    //定位
-                    Rectangle fromR = new Rectangle(0, 0, 0, 0); //原图裁剪定位
-                    Rectangle toR = new Rectangle(0, 0, 0, 0); //目标定位
-
-                    //宽为标准进行裁剪
-                    if (templateRate > initRate)
-                    {
-                        //裁剪对象实例化
-                        pickedImage = new Bitmap(initImage.Width, (int)Math.Floor(initImage.Width / templateRate));
-                        pickedG = Graphics.FromImage(pickedImage);
-
-                        //裁剪源定位
-                        fromR.X = 0;
-                        fromR.Y = (int)Math.Floor((initImage.Height - initImage.Width / templateRate) / 2);
-                        fromR.Width = initImage.Width;
-                        fromR.Height = (int)Math.Floor(initImage.Width / templateRate);
-
-                        //裁剪目标定位
-                        toR.X = 0;
-                        toR.Y = 0;
-                        toR.Width = initImage.Width;
-                        toR.Height = (int)Math.Floor(initImage.Width / templateRate);
-                    }
-                    //高为标准进行裁剪
-                    else
-                    {
-                        pickedImage = new Bitmap((int)Math.Floor(initImage.Height * templateRate), initImage.Height);
-                        pickedG = Graphics.FromImage(pickedImage);
-
-                        fromR.X = (int)Math.Floor((initImage.Width - initImage.Height * templateRate) / 2);
-                        fromR.Y = 0;
-                        fromR.Width = (int)Math.Floor(initImage.Height * templateRate);
-                        fromR.Height = initImage.Height;
-
-                        toR.X = 0;
-                        toR.Y = 0;
-                        toR.Width = (int)Math.Floor(initImage.Height * templateRate);
-                        toR.Height = initImage.Height;
-                    }
-
-                    //设置质量
-                    pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic;
-                    pickedG.SmoothingMode = SmoothingMode.HighQuality;
-
-                    //裁剪
-                    pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
-
-                    //按模版大小生成最终图片
-                    Image templateImage = new Bitmap(maxWidth, maxHeight);
-                    Graphics templateG = Graphics.FromImage(templateImage);
-                    templateG.InterpolationMode = InterpolationMode.High;
-                    templateG.SmoothingMode = SmoothingMode.HighQuality;
-                    templateG.Clear(Color.White);
-                    templateG.DrawImage(pickedImage, new Rectangle(0, 0, maxWidth, maxHeight), new Rectangle(0, 0, pickedImage.Width, pickedImage.Height), GraphicsUnit.Pixel);
-
-                    //关键质量控制
-                    //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
-                    ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
-                    ImageCodecInfo ici = null;
-                    foreach (ImageCodecInfo i in icis)
-                    {
-                        if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
-                            ici = i;
-                    }
-
-                    EncoderParameters ep = new EncoderParameters(1);
-                    ep.Param[0] = new EncoderParameter(Encoder.Quality, quality);
-
-                    //保存缩略图
-                    templateImage.Save(fileSaveUrl, ici, ep);
-                    //templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
-
-                    //释放资源
-                    templateG.Dispose();
-                    templateImage.Dispose();
-
-                    pickedG.Dispose();
-                    pickedImage.Dispose();
-                }
-            }
-
-            //释放资源
-            initImage.Dispose();
-        }
-
-        #endregion
-
-        #region 等比缩放
-
-        /// <summary>
-        /// 图片等比缩放
-        /// </summary>
-        /// <param name="fromFile">原图Stream对象</param>
-        /// <param name="savePath">缩略图存放地址</param>
-        /// <param name="targetWidth">指定的最大宽度</param>
-        /// <param name="targetHeight">指定的最大高度</param>
-        /// <param name="watermarkText">水印文字(为""表示不使用水印)</param>
-        /// <param name="watermarkImage">水印图片路径(为""表示不使用水印)</param>
-        public static void ZoomAuto(this Stream fromFile, string savePath, double targetWidth, double targetHeight, string watermarkText, string watermarkImage)
-        {
-            //创建目录
-            string dir = Path.GetDirectoryName(savePath);
-            if (!Directory.Exists(dir))
-                Directory.CreateDirectory(dir);
-
-            //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
-            Image initImage = Image.FromStream(fromFile, true);
-
-            //原图宽高均小于模版,不作处理,直接保存
-            if ((initImage.Width <= targetWidth) && (initImage.Height <= targetHeight))
-            {
-                //文字水印
-                if (watermarkText != "")
-                {
-                    using var gWater = Graphics.FromImage(initImage);
-                    Font fontWater = new Font("黑体", 10);
-                    Brush brushWater = new SolidBrush(Color.White);
-                    gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
-                    gWater.Dispose();
-                }
-
-                //透明图片水印
-                if (watermarkImage != "")
-                {
-                    if (File.Exists(watermarkImage))
-                    {
-                        using var wrImage = Image.FromFile(watermarkImage);
-                        //水印绘制条件:原始图片宽高均大于或等于水印图片
-                        if ((initImage.Width >= wrImage.Width) && (initImage.Height >= wrImage.Height))
-                        {
-                            Graphics gWater = Graphics.FromImage(initImage);
-
-                            //透明属性
-                            ImageAttributes imgAttributes = new ImageAttributes();
-                            ColorMap colorMap = new ColorMap();
-                            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
-                            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
-                            ColorMap[] remapTable = { colorMap };
-                            imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
-
-                            float[][] colorMatrixElements =
-                            {
-                                new[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
-                                new[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
-                                new[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
-                                new[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, //透明度:0.5
-                                new[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
-                            };
-
-                            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
-                            imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
-                            gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
-
-                            gWater.Dispose();
-                        }
-                        wrImage.Dispose();
-                    }
-                }
-
-                //保存
-                initImage.Save(savePath, ImageFormat.Jpeg);
-            }
-            else
-            {
-                //缩略图宽、高计算
-                double newWidth = initImage.Width;
-                double newHeight = initImage.Height;
-
-                //宽大于高或宽等于高(横图或正方)
-                if ((initImage.Width > initImage.Height) || (initImage.Width == initImage.Height))
-                {
-                    //如果宽大于模版
-                    if (initImage.Width > targetWidth)
-                    {
-                        //宽按模版,高按比例缩放
-                        newWidth = targetWidth;
-                        newHeight = initImage.Height * (targetWidth / initImage.Width);
-                    }
-                }
-                //高大于宽(竖图)
-                else
-                {
-                    //如果高大于模版
-                    if (initImage.Height > targetHeight)
-                    {
-                        //高按模版,宽按比例缩放
-                        newHeight = targetHeight;
-                        newWidth = initImage.Width * (targetHeight / initImage.Height);
-                    }
-                }
-
-                //生成新图
-                //新建一个bmp图片
-                Image newImage = new Bitmap((int)newWidth, (int)newHeight);
-                //新建一个画板
-                Graphics newG = Graphics.FromImage(newImage);
-
-                //设置质量
-                newG.InterpolationMode = InterpolationMode.HighQualityBicubic;
-                newG.SmoothingMode = SmoothingMode.HighQuality;
-
-                //置背景色
-                newG.Clear(Color.White);
-                //画图
-                newG.DrawImage(initImage, new Rectangle(0, 0, newImage.Width, newImage.Height), new Rectangle(0, 0, initImage.Width, initImage.Height), GraphicsUnit.Pixel);
-
-                //文字水印
-                if (watermarkText != "")
-                {
-                    using var gWater = Graphics.FromImage(newImage);
-                    Font fontWater = new Font("宋体", 10);
-                    Brush brushWater = new SolidBrush(Color.White);
-                    gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
-                    gWater.Dispose();
-                }
-
-                //透明图片水印
-                if (watermarkImage != "")
-                {
-                    if (File.Exists(watermarkImage))
-                    {
-                        using Image wrImage = Image.FromFile(watermarkImage);
-                        //水印绘制条件:原始图片宽高均大于或等于水印图片
-                        if ((newImage.Width >= wrImage.Width) && (newImage.Height >= wrImage.Height))
-                        {
-                            Graphics gWater = Graphics.FromImage(newImage);
-
-                            //透明属性
-                            ImageAttributes imgAttributes = new ImageAttributes();
-                            ColorMap colorMap = new ColorMap();
-                            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
-                            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
-                            ColorMap[] remapTable = { colorMap };
-                            imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
-
-                            float[][] colorMatrixElements =
-                            {
-                                new[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
-                                new[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
-                                new[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
-                                new[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, //透明度:0.5
-                                new[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
-                            };
-
-                            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
-                            imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
-                            gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
-                            gWater.Dispose();
-                        }
-                        wrImage.Dispose();
-                    }
-                }
-
-                //保存缩略图
-                newImage.Save(savePath, ImageFormat.Jpeg);
-
-                //释放资源
-                newG.Dispose();
-                newImage.Dispose();
-                initImage.Dispose();
-            }
-        }
-
-        #endregion
-
-        #region 判断文件类型是否为WEB格式图片
-
-        /// <summary>
-        /// 判断文件类型是否为WEB格式图片
-        /// (注:JPG,GIF,BMP,PNG)
-        /// </summary>
-        /// <param name="contentType">HttpPostedFile.ContentType</param>
-        /// <returns>是否为WEB格式图片</returns>
-        public static bool IsWebImage(string contentType)
-        {
-            if ((contentType == "image/pjpeg") || (contentType == "image/jpeg") || (contentType == "image/gif") || (contentType == "image/bmp") || (contentType == "image/png"))
-                return true;
-            return false;
-        }
-
-        #endregion
-
-        #region 裁剪图片
-
-        /// <summary>
-        /// 裁剪图片 -- 用GDI+   
-        /// </summary>
-        /// <param name="b">原始Bitmap</param>
-        /// <param name="rec">裁剪区域</param>
-        /// <returns>剪裁后的Bitmap</returns>
-        public static Bitmap CutImage(this Bitmap b, Rectangle rec)
-        {
-            int w = b.Width;
-            int h = b.Height;
-            if ((rec.X >= w) || (rec.Y >= h))
-            {
-                return null;
-            }
-
-            if (rec.X + rec.Width > w)
-                rec.Width = w - rec.X;
-            if (rec.Y + rec.Height > h)
-                rec.Height = h - rec.Y;
-            try
-            {
-                Bitmap bmpOut = new Bitmap(rec.Width, rec.Height, PixelFormat.Format24bppRgb);
-                Graphics g = Graphics.FromImage(bmpOut);
-                g.DrawImage(b, new Rectangle(0, 0, rec.Width, rec.Height), new Rectangle(rec.X, rec.Y, rec.Width, rec.Height), GraphicsUnit.Pixel);
-                g.Dispose();
-                return bmpOut;
-            }
-            catch (Exception)
-            {
-                return null;
-            }
-        }
-
-        #endregion
-
-        #region 缩放图片
-
-        /// <summary>  
-        ///  Resize图片   
-        /// </summary>  
-        /// <param name="bmp">原始Bitmap </param>  
-        /// <param name="newWidth">新的宽度</param>  
-        /// <param name="newHeight">新的高度</param>  
-        /// <returns>处理以后的图片</returns>  
-        public static Bitmap ResizeImage(this Bitmap bmp, int newWidth, int newHeight)
-        {
-            try
-            {
-                Bitmap b = new Bitmap(newWidth, newHeight);
-                Graphics g = Graphics.FromImage(b);
-                // 插值算法的质量   
-                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
-                g.DrawImage(bmp, new Rectangle(0, 0, newWidth, newHeight), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
-                g.Dispose();
-                return b;
-            }
-            catch (Exception)
-            {
-                return null;
-            }
-        }
-
-        #endregion
-
-        #region 裁剪并缩放
-
-        /// <summary>
-        /// 裁剪并缩放
-        /// </summary>
-        /// <param name="bmp">原始图片</param>
-        /// <param name="rec">裁剪的矩形区域</param>
-        /// <param name="newWidth">新的宽度</param>  
-        /// <param name="newHeight">新的高度</param>  
-        /// <returns>处理以后的图片</returns>
-        public static Bitmap CutAndResize(this Bitmap bmp, Rectangle rec, int newWidth, int newHeight) => bmp.CutImage(rec).ResizeImage(newWidth, newHeight);
-
-        #endregion
-
-        #region 无损压缩图片
-
-        /// <summary>
-        /// 无损压缩图片
-        /// </summary>
-        /// <param name="sFile">原图片地址</param>
-        /// <param name="dFile">压缩后保存图片地址</param>
-        /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
-        /// <param name="size">压缩后图片的最大大小</param>
-        /// <param name="sfsc">是否是第一次调用</param>
-        /// <returns></returns>
-        public static bool CompressImage(string sFile, string dFile, int flag = 90, int size = 1024, bool sfsc = true)
-        {
-            //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
-            FileInfo firstFileInfo = new FileInfo(sFile);
-            if (sfsc && firstFileInfo.Length < size * 1024)
-            {
-                firstFileInfo.CopyTo(dFile);
-                return true;
-            }
-
-            using Image iSource = Image.FromFile(sFile);
-            ImageFormat tFormat = iSource.RawFormat;
-            int dHeight = iSource.Height;
-            int dWidth = iSource.Width;
-            int sW, sH;
-            //按比例缩放
-            Size temSize = new Size(iSource.Width, iSource.Height);
-            if (temSize.Width > dHeight || temSize.Width > dWidth)
-            {
-                if ((temSize.Width * dHeight) > (temSize.Width * dWidth))
-                {
-                    sW = dWidth;
-                    sH = (dWidth * temSize.Height) / temSize.Width;
-                }
-                else
-                {
-                    sH = dHeight;
-                    sW = (temSize.Width * dHeight) / temSize.Height;
-                }
-            }
-            else
-            {
-                sW = temSize.Width;
-                sH = temSize.Height;
-            }
-
-            using Bitmap bmp = new Bitmap(dWidth, dHeight);
-            using Graphics g = Graphics.FromImage(bmp);
-            g.Clear(Color.WhiteSmoke);
-            g.CompositingQuality = CompositingQuality.HighQuality;
-            g.SmoothingMode = SmoothingMode.HighQuality;
-            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
-            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
-
-            //以下代码为保存图片时,设置压缩质量
-            using EncoderParameters ep = new EncoderParameters();
-            long[] qy = new long[1];
-            qy[0] = flag;//设置压缩的比例1-100
-            using EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy);
-            ep.Param[0] = eParam;
-            try
-            {
-                ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders();
-                ImageCodecInfo jpegIcIinfo = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG"));
-                if (jpegIcIinfo != null)
-                {
-                    bmp.Save(dFile, jpegIcIinfo, ep);//dFile是压缩后的新路径
-                    FileInfo fi = new FileInfo(dFile);
-                    if (fi.Length > 1024 * size)
-                    {
-                        flag = flag - 10;
-                        CompressImage(sFile, dFile, flag, size, false);
-                    }
-                }
-                else
-                {
-                    bmp.Save(dFile, tFormat);
-                }
-                return true;
-            }
-            catch
-            {
-                return false;
-            }
-        }
-
-        /// <summary>
-        /// 无损压缩图片
-        /// </summary>
-        /// <param name="src">原图片文件流</param>
-        /// <param name="dest">压缩后图片文件流</param>
-        /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
-        /// <param name="size">压缩后图片的最大大小</param>
-        /// <param name="sfsc">是否是第一次调用</param>
-        /// <returns></returns>
-        public static bool CompressImage(Stream src, Stream dest, int flag = 90, int size = 1024, bool sfsc = true)
-        {
-            //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
-            if (sfsc && src.Length < size * 1024)
-            {
-                src.CopyTo(dest);
-                return true;
-            }
-
-            using Image iSource = Image.FromStream(src);
-            ImageFormat tFormat = iSource.RawFormat;
-            int dHeight = iSource.Height;
-            int dWidth = iSource.Width;
-            int sW, sH;
-            //按比例缩放
-            Size temSize = new Size(iSource.Width, iSource.Height);
-            if (temSize.Width > dHeight || temSize.Width > dWidth)
-            {
-                if ((temSize.Width * dHeight) > (temSize.Width * dWidth))
-                {
-                    sW = dWidth;
-                    sH = (dWidth * temSize.Height) / temSize.Width;
-                }
-                else
-                {
-                    sH = dHeight;
-                    sW = (temSize.Width * dHeight) / temSize.Height;
-                }
-            }
-            else
-            {
-                sW = temSize.Width;
-                sH = temSize.Height;
-            }
-
-            using Bitmap bmp = new Bitmap(dWidth, dHeight);
-            using Graphics g = Graphics.FromImage(bmp);
-            g.Clear(Color.WhiteSmoke);
-            g.CompositingQuality = CompositingQuality.HighQuality;
-            g.SmoothingMode = SmoothingMode.HighQuality;
-            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
-            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
-
-            //以下代码为保存图片时,设置压缩质量
-            using EncoderParameters ep = new EncoderParameters();
-            long[] qy = new long[1];
-            qy[0] = flag;//设置压缩的比例1-100
-            using EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy);
-            ep.Param[0] = eParam;
-            try
-            {
-                ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders();
-                ImageCodecInfo jpegIcIinfo = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG"));
-                if (jpegIcIinfo != null)
-                {
-                    bmp.Save(dest, jpegIcIinfo, ep);//dFile是压缩后的新路径
-                    if (dest.Length > 1024 * size)
-                    {
-                        flag = flag - 10;
-                        CompressImage(src, dest, flag, size, false);
-                    }
-                }
-                else
-                {
-                    bmp.Save(dest, tFormat);
-                }
-                return true;
-            }
-            catch
-            {
-                return false;
-            }
-        }
-
-        #endregion
-
-        #region 缩略图
-
-        /// <summary>
-        /// 生成缩略图
-        /// </summary>
-        /// <param name="originalImage">原图</param>
-        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
-        /// <param name="width">缩略图宽度</param>
-        /// <param name="height">缩略图高度</param>
-        /// <param name="mode">生成缩略图的方式</param>    
-        public static void MakeThumbnail(this Image originalImage, string thumbnailPath, int width, int height, ThumbnailCutMode mode)
-        {
-            int towidth = width;
-            int toheight = height;
-
-            int x = 0;
-            int y = 0;
-            int ow = originalImage.Width;
-            int oh = originalImage.Height;
-
-            switch (mode)
-            {
-                case ThumbnailCutMode.Fixed: //指定高宽缩放(可能变形)                
-                    break;
-                case ThumbnailCutMode.LockWidth: //指定宽,高按比例                    
-                    toheight = originalImage.Height * width / originalImage.Width;
-                    break;
-                case ThumbnailCutMode.LockHeight: //指定高,宽按比例
-                    towidth = originalImage.Width * height / originalImage.Height;
-                    break;
-                case ThumbnailCutMode.Cut: //指定高宽裁减(不变形)                
-                    if (originalImage.Width / (double)originalImage.Height > towidth / (double)toheight)
-                    {
-                        oh = originalImage.Height;
-                        ow = originalImage.Height * towidth / toheight;
-                        y = 0;
-                        x = (originalImage.Width - ow) / 2;
-                    }
-                    else
-                    {
-                        ow = originalImage.Width;
-                        oh = originalImage.Width * height / towidth;
-                        x = 0;
-                        y = (originalImage.Height - oh) / 2;
-                    }
-                    break;
-            }
-
-            //新建一个bmp图片
-            Image bitmap = new Bitmap(towidth, toheight);
-
-            //新建一个画板
-            Graphics g = Graphics.FromImage(bitmap);
-
-            //设置高质量插值法
-            g.InterpolationMode = InterpolationMode.High;
-
-            //设置高质量,低速度呈现平滑程度
-            g.SmoothingMode = SmoothingMode.HighQuality;
-
-            //清空画布并以透明背景色填充
-            g.Clear(Color.Transparent);
-
-            //在指定位置并且按指定大小绘制原图片的指定部分
-            //第一个:对哪张图片进行操作。
-            //二:画多么大。
-            //三:画那块区域。
-            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);
-
-            try
-            {
-                //以jpg格式保存缩略图
-                bitmap.Save(thumbnailPath, ImageFormat.Jpeg);
-            }
-            finally
-            {
-                originalImage.Dispose();
-                bitmap.Dispose();
-                g.Dispose();
-            }
-        }
-
-        #endregion
-
-        #region 调整光暗
-
-        /// <summary>
-        /// 调整光暗
-        /// </summary>
-        /// <param name="mybm">原始图片</param>
-        /// <param name="width">原始图片的长度</param>
-        /// <param name="height">原始图片的高度</param>
-        /// <param name="val">增加或减少的光暗值</param>
-        public static Bitmap LDPic(this Bitmap mybm, int width, int height, int val)
-        {
-            Bitmap bm = new Bitmap(width, height); //初始化一个记录经过处理后的图片对象
-            int x, y; //x、y是循环次数,后面三个是记录红绿蓝三个值的
-            for (x = 0; x < width; x++)
-            {
-                for (y = 0; y < height; y++)
-                {
-                    var pixel = mybm.GetPixel(x, y);
-                    var resultR = pixel.R + val; //x、y是循环次数,后面三个是记录红绿蓝三个值的
-                    var resultG = pixel.G + val; //x、y是循环次数,后面三个是记录红绿蓝三个值的
-                    var resultB = pixel.B + val; //x、y是循环次数,后面三个是记录红绿蓝三个值的
-                    bm.SetPixel(x, y, Color.FromArgb(resultR, resultG, resultB)); //绘图
-                }
-            }
-
-            return bm;
-        }
-
-        #endregion
-
-        #region 反色处理
-
-        /// <summary>
-        /// 反色处理
-        /// </summary>
-        /// <param name="mybm">原始图片</param>
-        /// <param name="width">原始图片的长度</param>
-        /// <param name="height">原始图片的高度</param>
-        public static Bitmap RePic(this Bitmap mybm, int width, int height)
-        {
-            Bitmap bm = new Bitmap(width, height); //初始化一个记录处理后的图片的对象
-            int x, y, resultR, resultG, resultB;
-            Color pixel;
-            for (x = 0; x < width; x++)
-            {
-                for (y = 0; y < height; y++)
-                {
-                    pixel = mybm.GetPixel(x, y); //获取当前坐标的像素值
-                    resultR = 255 - pixel.R; //反红
-                    resultG = 255 - pixel.G; //反绿
-                    resultB = 255 - pixel.B; //反蓝
-                    bm.SetPixel(x, y, Color.FromArgb(resultR, resultG, resultB)); //绘图
-                }
-            }
-
-            return bm;
-        }
-
-        #endregion
-
-        #region 浮雕处理
-
-        /// <summary>
-        /// 浮雕处理
-        /// </summary>
-        /// <param name="oldBitmap">原始图片</param>
-        /// <param name="width">原始图片的长度</param>
-        /// <param name="height">原始图片的高度</param>
-        public static Bitmap Relief(this Bitmap oldBitmap, int width, int height)
-        {
-            Bitmap newBitmap = new Bitmap(width, height);
-            for (int x = 0; x < width - 1; x++)
-            {
-                for (int y = 0; y < height - 1; y++)
-                {
-                    var color1 = oldBitmap.GetPixel(x, y);
-                    var color2 = oldBitmap.GetPixel(x + 1, y + 1);
-                    var r = Math.Abs(color1.R - color2.R + 128);
-                    var g = Math.Abs(color1.G - color2.G + 128);
-                    var b = Math.Abs(color1.B - color2.B + 128);
-                    if (r > 255) r = 255;
-                    if (r < 0) r = 0;
-                    if (g > 255) g = 255;
-                    if (g < 0) g = 0;
-                    if (b > 255) b = 255;
-                    if (b < 0) b = 0;
-                    newBitmap.SetPixel(x, y, Color.FromArgb(r, g, b));
-                }
-            }
-
-            return newBitmap;
-        }
-
-        #endregion
-
-        #region 拉伸图片
-
-        /// <summary>
-        /// 拉伸图片
-        /// </summary>
-        /// <param name="bmp">原始图片</param>
-        /// <param name="newW">新的宽度</param>
-        /// <param name="newH">新的高度</param>
-        public static async Task<Bitmap> ResizeImageAsync(this Bitmap bmp, int newW, int newH)
-        {
-            try
-            {
-                using Bitmap bap = new Bitmap(newW, newH);
-                return await Task.Run(() =>
-                {
-                    using Graphics g = Graphics.FromImage(bap);
-                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
-                    g.DrawImage(bap, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bap.Width, bap.Height), GraphicsUnit.Pixel);
-                    return bap;
-                }).ConfigureAwait(false);
-            }
-            catch (Exception)
-            {
-                return null;
-            }
-        }
-
-        #endregion
-
-        #region 滤色处理
-
-        /// <summary>
-        /// 滤色处理
-        /// </summary>
-        /// <param name="mybm">原始图片</param>
-        /// <param name="width">原始图片的长度</param>
-        /// <param name="height">原始图片的高度</param>
-        public static Bitmap FilPic(this Bitmap mybm, int width, int height)
-        {
-            using var bm = new Bitmap(width, height);
-            for (var x = 0; x < width; x++)
-            {
-                int y;
-                for (y = 0; y < height; y++)
-                {
-                    var pixel = mybm.GetPixel(x, y);
-                    bm.SetPixel(x, y, Color.FromArgb(0, pixel.G, pixel.B)); //绘图
-                }
-            }
-
-            return bm;
-        }
-
-        #endregion
-
-        #region 左右翻转
-
-        /// <summary>
-        /// 左右翻转
-        /// </summary>
-        /// <param name="mybm">原始图片</param>
-        /// <param name="width">原始图片的长度</param>
-        /// <param name="height">原始图片的高度</param>
-        public static Bitmap RevPicLR(this Bitmap mybm, int width, int height)
-        {
-            using var bm = new Bitmap(width, height);
-            //x,y是循环次数,z是用来记录像素点的x坐标的变化的
-            for (var y = height - 1; y >= 0; y--)
-            {
-                int x; //x,y是循环次数,z是用来记录像素点的x坐标的变化的
-                int z; //x,y是循环次数,z是用来记录像素点的x坐标的变化的
-                for (x = width - 1, z = 0; x >= 0; x--)
-                {
-                    var pixel = mybm.GetPixel(x, y);
-                    bm.SetPixel(z++, y, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
-                }
-            }
-
-            return bm;
-        }
-
-        #endregion
-
-        #region 上下翻转
-
-        /// <summary>
-        /// 上下翻转
-        /// </summary>
-        /// <param name="mybm">原始图片</param>
-        /// <param name="width">原始图片的长度</param>
-        /// <param name="height">原始图片的高度</param>
-        public static Bitmap RevPicUD(this Bitmap mybm, int width, int height)
-        {
-            using var bm = new Bitmap(width, height);
-            for (var x = 0; x < width; x++)
-            {
-                int y;
-                int z;
-                for (y = height - 1, z = 0; y >= 0; y--)
-                {
-                    var pixel = mybm.GetPixel(x, y);
-                    bm.SetPixel(x, z++, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
-                }
-            }
-
-            return bm;
-        }
-
-        #endregion
-
-        #region 压缩图片
-
-        /// <summary>
-        /// 压缩到指定尺寸
-        /// </summary>
-        /// <param name="img"></param>
-        /// <param name="newfile">新文件</param>
-        public static bool Compress(this Image img, string newfile)
-        {
-            try
-            {
-                Size newSize = new Size(100, 125);
-                Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height);
-                Graphics g = Graphics.FromImage(outBmp);
-                g.CompositingQuality = CompositingQuality.HighQuality;
-                g.SmoothingMode = SmoothingMode.HighQuality;
-                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
-                g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
-                g.Dispose();
-                var encoderParams = new EncoderParameters();
-                var quality = new long[1];
-                quality[0] = 100;
-                encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, quality);
-                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
-                ImageCodecInfo jpegICI = null;
-                for (int x = 0; x < arrayICI.Length; x++)
-                {
-                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
-                    {
-                        jpegICI = arrayICI[x]; //设置JPEG编码
-                        break;
-                    }
-                }
-
-                if (jpegICI != null) outBmp.Save(newfile, ImageFormat.Jpeg);
-                outBmp.Dispose();
-                return true;
-            }
-            catch (Exception)
-            {
-                return false;
-            }
-        }
-
-        #endregion
-
-        #region 图片灰度化
-
-        /// <summary>
-        /// 图片灰度化
-        /// </summary>
-        /// <param name="c">输入颜色</param>
-        /// <returns>输出颜色</returns>
-        public static Color Gray(this Color c)
-        {
-            int rgb = Convert.ToInt32(0.3 * c.R + 0.59 * c.G + 0.11 * c.B);
-            return Color.FromArgb(rgb, rgb, rgb);
-        }
-
-        #endregion
-
-        #region 转换为黑白图片
-
-        /// <summary>
-        /// 转换为黑白图片
-        /// </summary>
-        /// <param name="mybm">要进行处理的图片</param>
-        /// <param name="width">图片的长度</param>
-        /// <param name="height">图片的高度</param>
-        public static Bitmap BWPic(this Bitmap mybm, int width, int height)
-        {
-            using var bm = new Bitmap(width, height);
-            for (var x = 0; x < width; x++)
-            {
-                for (var y = 0; y < height; y++)
-                {
-                    var pixel = mybm.GetPixel(x, y);
-                    var result = (pixel.R + pixel.G + pixel.B) / 3; //记录处理后的像素值
-                    bm.SetPixel(x, y, Color.FromArgb(result, result, result));
-                }
-            }
-
-            return bm;
-        }
-
-        #endregion
-
-        #region 获取图片中的各帧
-
-        /// <summary>
-        /// 获取图片中的各帧
-        /// </summary>
-        /// <param name="gif">源gif</param>
-        /// <param name="pSavedPath">保存路径</param>
-        public static void GetFrames(this Image gif, string pSavedPath)
-        {
-            var fd = new FrameDimension(gif.FrameDimensionsList[0]);
-            int count = gif.GetFrameCount(fd); //获取帧数(gif图片可能包含多帧,其它格式图片一般仅一帧)
-            for (int i = 0; i < count; i++) //以Jpeg格式保存各帧
-            {
-                gif.SelectActiveFrame(fd, i);
-                gif.Save(pSavedPath + "\\frame_" + i + ".jpg", ImageFormat.Jpeg);
-            }
-        }
-
-        #endregion
-
-
-        /// <summary>
-        /// 将dataUri保存为图片
-        /// </summary>
-        /// <param name="source">dataUri数据源</param>
-        /// <returns></returns>
-        /// <exception cref="Exception">操作失败。</exception>
-        public static Bitmap SaveDataUriAsImageFile(this string source)
-        {
-            string strbase64 = source.Substring(source.IndexOf(',') + 1).Trim('\0');
-            byte[] arr = Convert.FromBase64String(strbase64);
-            using var ms = new MemoryStream(arr);
-            using var bmp = new Bitmap(ms);
-            //新建第二个bitmap类型的bmp2变量。
-            using var bmp2 = new Bitmap(bmp, bmp.Width, bmp.Height);
-            using var draw = Graphics.FromImage(bmp2);
-            draw.DrawImage(bmp, 0, 0, bmp.Width, bmp.Height);
-            return bmp2;
-        }
-    }
-}

+ 0 - 28
Masuit.Tools.Core/Media/ThumbnailCutMode.cs

@@ -1,28 +0,0 @@
-namespace Masuit.Tools.Media
-{
-    /// <summary>
-    /// 图像裁剪模式
-    /// </summary>
-    public enum ThumbnailCutMode
-    {
-        /// <summary>
-        /// 锁定高度
-        /// </summary>
-        LockHeight,
-
-        /// <summary>
-        /// 锁定宽度
-        /// </summary>
-        LockWidth,
-
-        /// <summary>
-        /// 固定宽高
-        /// </summary>
-        Fixed,
-
-        /// <summary>
-        /// 裁剪
-        /// </summary>
-        Cut
-    }
-}

+ 0 - 64
Masuit.Tools.Core/Models/BaiduIP.cs

@@ -1,64 +0,0 @@
-using Newtonsoft.Json;
-
-namespace Masuit.Tools.Models
-{
-    /// <summary>
-    /// 百度IP接口的信息
-    /// </summary>
-    public class BaiduIP
-    {
-        /// <summary>
-        /// 基本信息
-        /// </summary>
-        [JsonProperty("address")]
-        public string Address { get; set; }
-
-        /// <summary>
-        /// 基本地理信息
-        /// </summary>
-        [JsonProperty("content")]
-        public AddressInfo AddressInfo { get; set; }
-
-        /// <summary>
-        /// 返回状态,0正常,1出错
-        /// </summary>
-        [JsonProperty("status")]
-        public int Status { get; set; }
-    }
-
-    /// <summary>
-    /// 基本地理信息
-    /// </summary>
-    public class AddressInfo
-    {
-        /// <summary>
-        /// 基本地址
-        /// </summary>
-        [JsonProperty("address")]
-        public string Address { get; set; }
-
-        /// <summary>
-        /// 经纬度
-        /// </summary>
-        [JsonProperty("point")]
-        public LatiLongitude LatiLongitude { get; set; }
-    }
-
-    /// <summary>
-    /// 经纬度
-    /// </summary>
-    public class LatiLongitude
-    {
-        /// <summary>
-        /// 经度
-        /// </summary>
-        [JsonProperty("x")]
-        public string X { get; set; }
-
-        /// <summary>
-        /// 纬度
-        /// </summary>
-        [JsonProperty("y")]
-        public string Y { get; set; }
-    }
-}

+ 0 - 142
Masuit.Tools.Core/Models/Email.cs

@@ -1,142 +0,0 @@
-using System;
-using System.Net.Mail;
-
-namespace Masuit.Tools.Models
-{
-#pragma warning disable 1591
-    public class Email
-    {
-        /// <summary>
-        /// 发件人用户名
-        /// </summary>
-        public string Username { get; set; }
-        /// <summary>
-        /// 发件人邮箱密码
-        /// </summary>
-        public string Password { get; set; }
-        /// <summary>
-        /// 发送服务器端口号,默认25
-        /// </summary>
-        public int SmtpPort { get; set; } = 25;
-        /// <summary>
-        /// 发送服务器地址
-        /// </summary>
-        public string SmtpServer { get; set; }
-        /// <summary>
-        /// 邮件标题
-        /// </summary>
-        public string Subject { get; set; }
-        /// <summary>
-        /// 邮件正文
-        /// </summary>
-        public string Body { get; set; }
-        /// <summary>
-        /// 收件人,多个收件人用英文逗号隔开
-        /// </summary>
-        public string Tos { get; set; }
-
-        /// <summary>
-        /// 是否启用SSL,默认已启用
-        /// </summary>
-        public bool EnableSsl { get; set; } = true;
-        /// <summary>
-        /// 邮件消息对象
-        /// </summary>
-        MailMessage GetClient
-        {
-            get
-            {
-                if (string.IsNullOrEmpty(Tos)) return null;
-                MailMessage mailMessage = new MailMessage();
-                //多个接收者                
-                foreach (string _str in Tos.Split(','))
-                {
-                    mailMessage.To.Add(_str);
-                }
-                mailMessage.From = new MailAddress(Username, Username);
-                mailMessage.Subject = Subject;
-                mailMessage.Body = Body;
-                mailMessage.IsBodyHtml = true;
-                mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
-                mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
-                mailMessage.Priority = MailPriority.High;
-                return mailMessage;
-            }
-        }
-        SmtpClient GetSmtpClient => new SmtpClient
-        {
-            UseDefaultCredentials = false,
-            EnableSsl = EnableSsl,
-            Host = SmtpServer,
-            Port = SmtpPort,
-            Credentials = new System.Net.NetworkCredential(Username, Password),
-            DeliveryMethod = SmtpDeliveryMethod.Network,
-        };
-
-        //回调方法
-        Action<string> actionSendCompletedCallback = null;
-
-        /// <summary>
-        /// 使用异步发送邮件
-        /// </summary>
-        /// <param name="completedCallback">邮件发送后的回调方法</param>
-        /// <returns></returns>
-        public void SendAsync(Action<string> completedCallback)
-        {
-            using var smtpClient = GetSmtpClient;
-            using var mailMessage = GetClient;
-            if (smtpClient == null || mailMessage == null) return;
-            Subject = Subject;
-            Body = Body;
-            //EnableSsl = false;
-            //发送邮件回调方法
-            actionSendCompletedCallback = completedCallback;
-            smtpClient.SendCompleted += SendCompletedCallback;
-            smtpClient.SendAsync(mailMessage, "true"); //异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
-        }
-
-        /// <summary>
-        /// 使用同步发送邮件
-        /// </summary>
-        public void Send()
-        {
-            using SmtpClient smtpClient = GetSmtpClient;
-            using MailMessage mailMessage = GetClient;
-            if (smtpClient == null || mailMessage == null) return;
-            Subject = Subject;
-            Body = Body;
-            //EnableSsl = false;
-            smtpClient.Send(mailMessage); //异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
-        }
-
-        /// <summary>
-        /// 异步操作完成后执行回调方法
-        /// </summary>
-        /// <param name="sender"></param>
-        /// <param name="e"></param>
-        private void SendCompletedCallback(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
-        {
-            //同一组件下不需要回调方法,直接在此写入日志即可
-            //写入日志
-            //return;
-            if (actionSendCompletedCallback == null) return;
-            string message;
-            if (e.Cancelled)
-            {
-                message = "异步操作取消";
-            }
-            else if (e.Error != null)
-            {
-                message = ($"UserState:{(string)e.UserState},Message:{e.Error}");
-            }
-            else
-            {
-                message = (string)e.UserState;
-            }
-
-            //执行回调方法
-            actionSendCompletedCallback(message);
-        }
-    }
-#pragma warning restore 1591
-}

+ 0 - 16
Masuit.Tools.Core/Models/IspInfo.cs

@@ -1,16 +0,0 @@
-using Newtonsoft.Json;
-
-namespace Masuit.Tools.Models
-{
-    /// <summary>
-    /// ISP信息
-    /// </summary>
-    public class IspInfo
-    {
-        /// <summary>
-        /// 运营商
-        /// </summary>
-        [JsonProperty("wl")]
-        public string ISPName { get; set; }
-    }
-}

+ 0 - 191
Masuit.Tools.Core/Models/PhysicsAddress.cs

@@ -1,191 +0,0 @@
-using System.Collections.Generic;
-using Newtonsoft.Json;
-
-namespace Masuit.Tools.Models
-{
-    /// <summary>
-    /// 详细地理信息
-    /// </summary>
-    public class PhysicsAddress
-    {
-        /// <summary>
-        /// 返回状态,0正常,1出错
-        /// </summary>
-        [JsonProperty("status")]
-        public int Status { get; set; }
-
-        /// <summary>
-        /// 返回结果集
-        /// </summary>
-        [JsonProperty("result")]
-        public AddressResult AddressResult { get; set; }
-    }
-
-    /// <summary>
-    /// 返回结果集
-    /// </summary>
-    public class AddressResult
-    {
-        /// <summary>
-        /// 经纬度
-        /// </summary>
-        [JsonProperty("location")]
-        public Location Location { get; set; }
-
-        /// <summary>
-        /// 详细地址
-        /// </summary>
-        [JsonProperty("formatted_address")]
-        public string FormattedAddress { get; set; }
-
-        /// <summary>
-        /// 商业地址
-        /// </summary>
-        [JsonProperty("business")]
-        public string Business { get; set; }
-
-        /// <summary>
-        /// 地理信息成分
-        /// </summary>
-        [JsonProperty("addressComponent")]
-        public AddressComponent AddressComponent { get; set; }
-
-        /// <summary>
-        /// 参考地址
-        /// </summary>
-        [JsonProperty("pois")]
-        public List<Pois> Pois { get; set; }
-
-        /// <summary>
-        /// 语义描述
-        /// </summary>
-        [JsonProperty("sematic_description")]
-        public string SematicDescription { get; set; }
-    }
-
-    /// <summary>
-    /// 经纬度
-    /// </summary>
-    public class Location
-    {
-        /// <summary>
-        /// 经度
-        /// </summary>
-        [JsonProperty("lng")]
-        public double Lng { get; set; }
-
-        /// <summary>
-        /// 纬度
-        /// </summary>
-        [JsonProperty("lat")]
-        public double Lat { get; set; }
-    }
-
-    /// <summary>
-    /// 地理信息成分
-    /// </summary>
-    public class AddressComponent
-    {
-        /// <summary>
-        /// 国家
-        /// </summary>
-        [JsonProperty("country")]
-        public string Country { get; set; }
-
-        /// <summary>
-        /// 国家代码
-        /// </summary>
-        [JsonProperty("country_code")]
-        public int CountryCode { get; set; }
-
-        /// <summary>
-        /// 省
-        /// </summary>
-        [JsonProperty("province")]
-        public string Province { get; set; }
-
-        /// <summary>
-        /// 市
-        /// </summary>
-        [JsonProperty("city")]
-        public string City { get; set; }
-
-        /// <summary>
-        /// 区
-        /// </summary>
-        [JsonProperty("district")]
-        public string District { get; set; }
-
-        /// <summary>
-        /// 街道
-        /// </summary>
-        [JsonProperty("street")]
-        public string Street { get; set; }
-
-        /// <summary>
-        /// 门牌号
-        /// </summary>
-        [JsonProperty("street_number")]
-        public string StreetNumber { get; set; }
-
-        /// <summary>
-        /// 方位
-        /// </summary>
-        [JsonProperty("direction")]
-        public string Direction { get; set; }
-
-        /// <summary>
-        /// 距离
-        /// </summary>
-        [JsonProperty("distance")]
-        public string Distance { get; set; } = "0";
-    }
-
-    /// <summary>
-    /// 参考位置
-    /// </summary>
-    public class Pois
-    {
-        /// <summary>
-        /// 地理位置详细
-        /// </summary>
-        [JsonProperty("addr")]
-        public string AddressDetail { get; set; }
-
-        /// <summary>
-        /// 方位
-        /// </summary>
-        [JsonProperty("direction")]
-        public string Direction { get; set; }
-
-        /// <summary>
-        /// 距离
-        /// </summary>
-        [JsonProperty("distance")]
-        public string Distance { get; set; } = "0";
-
-        /// <summary>
-        /// 建筑物名字
-        /// </summary>
-        [JsonProperty("name")]
-        public string Name { get; set; }
-
-        /// <summary>
-        /// 建筑物类型
-        /// </summary>
-        [JsonProperty("poiType")]
-        public string PoiType { get; set; }
-
-        /// <summary>
-        /// 经纬度
-        /// </summary>
-        [JsonProperty("point")]
-        public LatiLongitude Point { get; set; }
-
-        /// <summary>
-        /// 标签
-        /// </summary>
-        [JsonProperty("tag")]
-        public string Tag { get; set; }
-    }
-}

+ 0 - 52
Masuit.Tools.Core/Models/TaobaoIP.cs

@@ -1,52 +0,0 @@
-using Newtonsoft.Json;
-
-namespace Masuit.Tools.Models
-{
-    /// <summary>
-    /// 淘宝IP接口信息
-    /// </summary>
-    public class TaobaoIP
-    {
-        /// <summary>
-        /// 返回状态码
-        /// </summary>
-        [JsonProperty("code")]
-        public int Code { get; set; }
-
-        /// <summary>
-        /// 数据
-        /// </summary>
-        [JsonProperty("data")]
-        public IPData IpData { get; set; }
-    }
-
-    /// <summary>
-    /// 淘宝IP接口信息
-    /// </summary>
-    public class IPData
-    {
-        /// <summary>
-        /// 国家
-        /// </summary>
-        [JsonProperty("country")]
-        public string Country { get; set; }
-
-        /// <summary>
-        /// 省
-        /// </summary>
-        [JsonProperty("region")]
-        public string Region { get; set; }
-
-        /// <summary>
-        /// 市
-        /// </summary>
-        [JsonProperty("city")]
-        public string City { get; set; }
-
-        /// <summary>
-        /// ISP
-        /// </summary>
-        [JsonProperty("isp")]
-        public string Isp { get; set; }
-    }
-}

+ 0 - 634
Masuit.Tools.Core/Net/FtpClient.cs

@@ -1,634 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net;
-using System.Text;
-
-namespace Masuit.Tools.Net
-{
-    /// <summary>
-    /// FTP客户端操作类
-    /// </summary>
-    public class FtpClient
-    {
-        #region 变量属性
-
-        /// <summary>
-        /// Ftp服务器ip
-        /// </summary>
-        private string FtpServer { get; set; }
-
-        /// <summary>
-        /// Ftp 指定用户名
-        /// </summary>
-        private string Username { get; set; }
-
-        /// <summary>
-        /// Ftp 指定用户密码
-        /// </summary>
-        private string Password { get; set; }
-
-        #endregion
-
-        /// <summary>
-        /// 获取一个匿名登录的ftp客户端
-        /// </summary>
-        /// <param name="serverIp">服务器IP地址</param>
-        /// <returns></returns>
-        public static FtpClient GetAnonymousClient(string serverIp)
-        {
-            if (!serverIp.MatchInetAddress())
-            {
-                throw new ArgumentException("IP地址格式不正确");
-            }
-
-            FtpClient ftpClient = new FtpClient
-            {
-                FtpServer = serverIp
-            };
-            return ftpClient;
-        }
-
-        /// <summary>
-        /// 获取一个匿名登录的ftp客户端
-        /// </summary>
-        /// <param name="serverIp">服务器ip</param>
-        /// <param name="username">用户名</param>
-        /// <param name="password">密码</param>
-        /// <returns></returns>
-        public static FtpClient GetClient(string serverIp, string username, string password)
-        {
-            if (!serverIp.MatchInetAddress())
-            {
-                throw new ArgumentException("IP地址格式不正确");
-            }
-
-            FtpClient ftpClient = new FtpClient
-            {
-                FtpServer = serverIp,
-                Username = username,
-                Password = password
-            };
-            return ftpClient;
-        }
-
-        #region 从FTP服务器下载文件,指定本地路径和本地文件名
-
-        /// <summary>
-        /// 从FTP服务器下载文件,指定本地路径和本地文件名
-        /// </summary>
-        /// <param name="remoteFileName">远程文件名</param>
-        /// <param name="localFileName">保存本地的文件名(包含路径)</param>
-        /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
-        /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
-        public void Download(string remoteFileName, string localFileName, bool ifCredential = false, Action<int, int> updateProgress = null)
-        {
-            using FileStream outputStream = new FileStream(localFileName, FileMode.Create);
-            if (FtpServer == null || FtpServer.Trim().Length == 0)
-            {
-                throw new Exception("ftp下载目标服务器地址未设置!");
-            }
-
-            Uri uri = new Uri("ftp://" + FtpServer + "/" + remoteFileName);
-            var ftpsize = (FtpWebRequest)WebRequest.Create(uri);
-            ftpsize.UseBinary = true;
-            var reqFtp = (FtpWebRequest)WebRequest.Create(uri);
-            reqFtp.UseBinary = true;
-            reqFtp.KeepAlive = false;
-            if (ifCredential) //使用用户身份认证
-            {
-                ftpsize.Credentials = new NetworkCredential(Username, Password);
-                reqFtp.Credentials = new NetworkCredential(Username, Password);
-            }
-
-            ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
-            using var re = (FtpWebResponse)ftpsize.GetResponse();
-            long totalBytes = re.ContentLength;
-            reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
-            using var response = (FtpWebResponse)reqFtp.GetResponse();
-            using var ftpStream = response.GetResponseStream();
-            //更新进度 
-            updateProgress?.Invoke((int)totalBytes, 0); //更新进度条 
-            long totalDownloadedByte = 0;
-            int bufferSize = 1024 * 1024;
-            byte[] buffer = new byte[bufferSize];
-            if (ftpStream != null)
-            {
-                var readCount = ftpStream.Read(buffer, 0, bufferSize);
-                while (readCount > 0)
-                {
-                    totalDownloadedByte = readCount + totalDownloadedByte;
-                    outputStream.Write(buffer, 0, readCount);
-                    //更新进度 
-                    updateProgress?.Invoke((int)totalBytes, (int)totalDownloadedByte); //更新进度条 
-                    readCount = ftpStream.Read(buffer, 0, bufferSize);
-                }
-            }
-        }
-
-        /// <summary>
-        /// 从FTP服务器下载文件,指定本地路径和本地文件名(支持断点下载)
-        /// </summary>
-        /// <param name="remoteFileName">远程文件名</param>
-        /// <param name="localFileName">保存本地的文件名(包含路径)</param>
-        /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
-        /// <param name="size">已下载文件流大小</param>
-        /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
-        public void BrokenDownload(string remoteFileName, string localFileName, bool ifCredential, long size, Action<int, int> updateProgress = null)
-        {
-            using var outputStream = new FileStream(localFileName, FileMode.Append);
-            if (FtpServer == null || FtpServer.Trim().Length == 0)
-            {
-                throw new Exception("ftp下载目标服务器地址未设置!");
-            }
-
-            Uri uri = new Uri("ftp://" + FtpServer + "/" + remoteFileName);
-            var ftpsize = (FtpWebRequest)WebRequest.Create(uri);
-            ftpsize.UseBinary = true;
-            ftpsize.ContentOffset = size;
-            var reqFtp = (FtpWebRequest)WebRequest.Create(uri);
-            reqFtp.UseBinary = true;
-            reqFtp.KeepAlive = false;
-            reqFtp.ContentOffset = size;
-            if (ifCredential) //使用用户身份认证
-            {
-                ftpsize.Credentials = new NetworkCredential(Username, Password);
-                reqFtp.Credentials = new NetworkCredential(Username, Password);
-            }
-
-            ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
-            using FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
-            var totalBytes = re.ContentLength;
-            reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
-            using var response = (FtpWebResponse)reqFtp.GetResponse();
-            using var ftpStream = response.GetResponseStream();
-            updateProgress?.Invoke((int)totalBytes, 0); //更新进度条 
-            long totalDownloadedByte = 0;
-            int bufferSize = 1024 * 1024;
-            byte[] buffer = new byte[bufferSize];
-            if (ftpStream != null)
-            {
-                var readCount = ftpStream.Read(buffer, 0, bufferSize);
-                while (readCount > 0)
-                {
-                    totalDownloadedByte = readCount + totalDownloadedByte;
-                    outputStream.Write(buffer, 0, readCount);
-                    //更新进度 
-                    updateProgress?.Invoke((int)totalBytes, (int)totalDownloadedByte); //更新进度条 
-                    readCount = ftpStream.Read(buffer, 0, bufferSize);
-                }
-            }
-        }
-
-        /// <summary>
-        /// 从FTP服务器下载文件,指定本地路径和本地文件名
-        /// </summary>
-        /// <param name="remoteFileName">远程文件名</param>
-        /// <param name="localFileName">保存本地的文件名(包含路径)</param>
-        /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
-        /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
-        /// <param name="brokenOpen">是否断点下载:true 会在localFileName 找是否存在已经下载的文件,并计算文件流大小</param>
-        public void Download(string remoteFileName, string localFileName, bool ifCredential, bool brokenOpen, Action<int, int> updateProgress = null)
-        {
-            if (brokenOpen)
-            {
-                long size = 0;
-                if (File.Exists(localFileName))
-                {
-                    using var outputStream = new FileStream(localFileName, FileMode.Open);
-                    size = outputStream.Length;
-                }
-
-                BrokenDownload(remoteFileName, localFileName, ifCredential, size, updateProgress);
-            }
-
-            Download(remoteFileName, localFileName, ifCredential, updateProgress);
-        }
-
-        #endregion
-
-        #region 上传文件到FTP服务器
-
-        /// <summary>
-        /// 上传文件到FTP服务器
-        /// </summary>
-        /// <param name="relativePath">相对目录</param>
-        /// <param name="localFullPathName">本地带有完整路径的文件名</param>
-        /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
-        public void UploadFile(string relativePath, string localFullPathName, Action<int, int> updateProgress = null)
-        {
-            FileInfo finfo = new FileInfo(localFullPathName);
-            if (FtpServer == null || FtpServer.Trim().Length == 0)
-            {
-                throw new Exception("ftp上传目标服务器地址未设置!");
-            }
-
-            Uri uri = new Uri("ftp://" + FtpServer + "/" + relativePath + "/" + finfo.Name);
-            var reqFtp = (FtpWebRequest)WebRequest.Create(uri);
-            reqFtp.KeepAlive = false;
-            reqFtp.UseBinary = true;
-            reqFtp.Credentials = new NetworkCredential(Username, Password); //用户,密码
-            reqFtp.Method = WebRequestMethods.Ftp.UploadFile; //向服务器发出下载请求命令
-            reqFtp.ContentLength = finfo.Length; //为request指定上传文件的大小
-            int buffLength = 1024 * 1024;
-            byte[] buff = new byte[buffLength];
-            using var fs = finfo.OpenRead();
-            using var stream = reqFtp.GetRequestStream();
-            var contentLen = fs.Read(buff, 0, buffLength);
-            int allbye = (int)finfo.Length;
-            //更新进度 
-            updateProgress?.Invoke(allbye, 0); //更新进度条 
-            int startbye = 0;
-            while (contentLen != 0)
-            {
-                startbye = contentLen + startbye;
-                stream.Write(buff, 0, contentLen);
-                //更新进度 
-                updateProgress?.Invoke(allbye, startbye); //更新进度条 
-                contentLen = fs.Read(buff, 0, buffLength);
-            }
-        }
-
-        /// <summary>
-        /// 上传文件到FTP服务器(断点续传)
-        /// </summary>
-        /// <param name="localFullPath">本地文件全路径名称:C:\Users\JianKunKing\Desktop\IronPython脚本测试工具</param>
-        /// <param name="remoteFilepath">远程文件所在文件夹路径</param>
-        /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
-        /// <returns></returns> 
-        public bool UploadBroken(string localFullPath, string remoteFilepath, Action<int, int> updateProgress = null)
-        {
-            if (remoteFilepath == null)
-            {
-                remoteFilepath = "";
-            }
-
-            string newFileName;
-            FileInfo fileInf = new FileInfo(localFullPath);
-            long allbye = fileInf.Length;
-            if (fileInf.Name.IndexOf("#", StringComparison.Ordinal) == -1)
-            {
-                newFileName = RemoveSpaces(fileInf.Name);
-            }
-            else
-            {
-                newFileName = fileInf.Name.Replace("#", "#");
-                newFileName = RemoveSpaces(newFileName);
-            }
-
-            long startfilesize = GetFileSize(newFileName, remoteFilepath);
-            if (startfilesize >= allbye)
-            {
-                return false;
-            }
-
-            long startbye = startfilesize;
-            //更新进度 
-            updateProgress?.Invoke((int)allbye, (int)startfilesize); //更新进度条 
-
-            string uri;
-            if (remoteFilepath.Length == 0)
-            {
-                uri = "ftp://" + FtpServer + "/" + newFileName;
-            }
-            else
-            {
-                uri = "ftp://" + FtpServer + "/" + remoteFilepath + "/" + newFileName;
-            }
-
-            // 根据uri创建FtpWebRequest对象 
-            var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(uri));
-            // ftp用户名和密码 
-            reqFtp.Credentials = new NetworkCredential(Username, Password);
-            // 默认为true,连接不会被关闭 
-            // 在一个命令之后被执行 
-            reqFtp.KeepAlive = false;
-            // 指定执行什么命令 
-            reqFtp.Method = WebRequestMethods.Ftp.AppendFile;
-            // 指定数据传输类型 
-            reqFtp.UseBinary = true;
-            // 上传文件时通知服务器文件的大小 
-            reqFtp.ContentLength = fileInf.Length;
-            int buffLength = 1024 * 1024; // 缓冲大小设置为2kb 
-            byte[] buff = new byte[buffLength];
-            // 打开一个文件流 (System.IO.FileStream) 去读上传的文件 
-            using FileStream fs = fileInf.OpenRead();
-            using var strm = reqFtp.GetRequestStream();
-            // 把上传的文件写入流 
-            fs.Seek(startfilesize, 0);
-            int contentLen = fs.Read(buff, 0, buffLength);
-            // 流内容没有结束 
-            while (contentLen != 0)
-            {
-                // 把内容从file stream 写入 upload stream 
-                strm.Write(buff, 0, contentLen);
-                contentLen = fs.Read(buff, 0, buffLength);
-                startbye += contentLen;
-                //更新进度 
-                updateProgress?.Invoke((int)allbye, (int)startbye); //更新进度条 
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// 去除空格
-        /// </summary>
-        /// <param name="str"></param>
-        /// <returns></returns>
-        private string RemoveSpaces(string str)
-        {
-            string a = "";
-            foreach (char c in str)
-            {
-                var array = Encoding.ASCII.GetBytes(c.ToString());
-                int asciicode = array[0];
-                if (asciicode != 32)
-                {
-                    a += c.ToString();
-                }
-            }
-
-            return a.Split('.')[a.Split('.').Length - 2] + "." + a.Split('.')[a.Split('.').Length - 1];
-        }
-
-        /// <summary>
-        /// 获取已上传文件大小
-        /// </summary>
-        /// <param name="filePath">文件名称</param>
-        /// <param name="remoteFilepath">服务器文件路径</param>
-        /// <returns></returns>
-        public long GetFileSize(string filePath, string remoteFilepath)
-        {
-            try
-            {
-                FileInfo fi = new FileInfo(filePath);
-                string uri;
-                if (remoteFilepath.Length == 0)
-                {
-                    uri = "ftp://" + FtpServer + "/" + fi.Name;
-                }
-                else
-                {
-                    uri = "ftp://" + FtpServer + "/" + remoteFilepath + "/" + fi.Name;
-                }
-
-                var reqFtp = (FtpWebRequest)WebRequest.Create(uri);
-                reqFtp.KeepAlive = false;
-                reqFtp.UseBinary = true;
-                reqFtp.Credentials = new NetworkCredential(Username, Password); //用户,密码
-                reqFtp.Method = WebRequestMethods.Ftp.GetFileSize;
-                var response = (FtpWebResponse)reqFtp.GetResponse();
-                var filesize = response.ContentLength;
-                return filesize;
-            }
-            catch
-            {
-                return 0;
-            }
-        }
-
-        #endregion
-
-        #region 获取当前目录下明细
-
-        /// <summary>
-        /// 获取当前目录下明细(包含文件和文件夹)
-        /// </summary>
-        /// <returns></returns>
-        public List<string> GetFilesDetails(string relativePath = "")
-        {
-            var result = new List<string>();
-            var ftp = (FtpWebRequest)WebRequest.Create(new Uri(Path.Combine("ftp://" + FtpServer, relativePath).Replace("\\", "/")));
-            ftp.Credentials = new NetworkCredential(Username, Password);
-            ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
-            using var response = ftp.GetResponse();
-            using var reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8);
-            string line = reader.ReadLine();
-            while (line != null)
-            {
-                result.Add(line);
-                line = reader.ReadLine();
-            }
-
-            return result;
-        }
-
-        /// <summary>
-        /// 获取当前目录下文件列表(仅文件)
-        /// </summary>
-        /// <returns></returns>
-        public List<string> GetFiles(string relativePath = "", string mask = "*.*")
-        {
-            var result = new List<string>();
-            var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(Path.Combine("ftp://" + FtpServer, relativePath).Replace("\\", "/")));
-            reqFtp.UseBinary = true;
-            reqFtp.Credentials = new NetworkCredential(Username, Password);
-            reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
-            using var response = reqFtp.GetResponse();
-            using var reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8);
-            string line = reader.ReadLine();
-            while (line != null)
-            {
-                if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
-                {
-                    string temp = mask.Substring(0, mask.IndexOf("*", StringComparison.Ordinal));
-                    if (line.Substring(0, temp.Length) == temp)
-                    {
-                        result.Add(line);
-                    }
-                }
-                else
-                {
-                    result.Add(line);
-                }
-
-                line = reader.ReadLine();
-            }
-
-            return result;
-        }
-
-        /// <summary>
-        /// 获取当前目录下所有的文件夹列表(仅文件夹)
-        /// </summary>
-        /// <returns></returns>
-        public string[] GetDirectories(string relativePath)
-        {
-            var drectory = GetFilesDetails(relativePath);
-            string m = string.Empty;
-            foreach (string str in drectory)
-            {
-                int dirPos = str.IndexOf("<DIR>", StringComparison.Ordinal);
-                if (dirPos > 0)
-                {
-                    /*判断 Windows 风格*/
-                    m += str.Substring(dirPos + 5).Trim() + "\n";
-                }
-                else if (str.Trim().StartsWith("d"))
-                {
-                    /*判断 Unix 风格*/
-                    string dir = str.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)[8];
-                    if (dir != "." && dir != "..")
-                    {
-                        dir = str.Substring(str.IndexOf(dir, StringComparison.Ordinal));
-                        m += dir + "\n";
-                    }
-                }
-            }
-
-            char[] n =
-            {
-                '\n'
-            };
-            return m.Split(n);
-        }
-        #endregion
-
-        #region 删除文件及文件夹
-
-        /// <summary>
-        /// 删除文件
-        /// </summary>
-        /// <param name="filePath"></param>
-        public void Delete(string filePath)
-        {
-            string uri = Path.Combine("ftp://" + FtpServer, filePath).Replace("\\", "/");
-            var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(uri));
-
-            reqFtp.Credentials = new NetworkCredential(Username, Password);
-            reqFtp.KeepAlive = false;
-            reqFtp.Method = WebRequestMethods.Ftp.DeleteFile;
-
-            using FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
-            using Stream datastream = response.GetResponseStream();
-            using StreamReader sr = new StreamReader(datastream ?? throw new InvalidOperationException());
-            sr.ReadToEnd();
-        }
-
-        /// <summary>
-        /// 删除文件夹
-        /// </summary>
-        /// <param name="dirPath"></param>
-        public void RemoveDirectory(string dirPath)
-        {
-            string uri = Path.Combine("ftp://" + FtpServer, dirPath).Replace("\\", "/");
-            var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(uri));
-            reqFtp.Credentials = new NetworkCredential(Username, Password);
-            reqFtp.KeepAlive = false;
-            reqFtp.Method = WebRequestMethods.Ftp.RemoveDirectory;
-            using var response = (FtpWebResponse)reqFtp.GetResponse();
-            using var datastream = response.GetResponseStream();
-            using var sr = new StreamReader(datastream ?? throw new InvalidOperationException());
-            sr.ReadToEnd();
-        }
-
-        #endregion
-
-        #region 其他操作
-
-        /// <summary>
-        /// 获取指定文件大小
-        /// </summary>
-        /// <param name="filePath"></param>
-        /// <returns></returns>
-        public long GetFileSize(string filePath)
-        {
-            var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(Path.Combine("ftp://" + FtpServer, filePath).Replace("\\", "/")));
-            reqFtp.Method = WebRequestMethods.Ftp.GetFileSize;
-            reqFtp.UseBinary = true;
-            reqFtp.Credentials = new NetworkCredential(Username, Password);
-            using var response = (FtpWebResponse)reqFtp.GetResponse();
-            var fileSize = response.ContentLength;
-            return fileSize;
-        }
-
-        /// <summary>
-        /// 判断当前目录下指定的子目录是否存在
-        /// </summary>
-        /// <param name="remoteDirPath">指定的目录名</param>
-        public bool DirectoryExist(string remoteDirPath)
-        {
-            try
-            {
-                string[] dirList = GetDirectories(remoteDirPath);
-                foreach (string str in dirList)
-                {
-                    if (str.Trim() == remoteDirPath.Trim())
-                    {
-                        return true;
-                    }
-                }
-
-                return false;
-            }
-            catch
-            {
-                return false;
-            }
-        }
-
-        /// <summary>
-        /// 判断当前目录下指定的文件是否存在
-        /// </summary>
-        /// <param name="remoteFileName">远程文件名</param>
-        public bool FileExist(string remoteFileName)
-        {
-            var fileList = GetFiles("*.*");
-            foreach (string str in fileList)
-            {
-                if (str.Trim() == remoteFileName.Trim())
-                {
-                    return true;
-                }
-            }
-
-            return false;
-        }
-
-        /// <summary>
-        /// 创建文件夹
-        /// </summary>
-        /// <param name="relativePath">路径</param>
-        /// <param name="newDir">新建文件夹</param>
-        public void MakeDir(string relativePath, string newDir)
-        {
-            // dirName = name of the directory to create.
-            var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(Path.Combine("ftp://" + FtpServer, relativePath, newDir).Replace("\\", "/")));
-            reqFtp.Method = WebRequestMethods.Ftp.MakeDirectory;
-            reqFtp.UseBinary = true;
-            reqFtp.Credentials = new NetworkCredential(Username, Password);
-            using var response = (FtpWebResponse)reqFtp.GetResponse();
-            using var _ = response.GetResponseStream();
-        }
-
-        /// <summary>
-        /// 改名
-        /// </summary>
-        /// <param name="relativePath">相对路径</param>
-        /// <param name="currentFilename"></param>
-        /// <param name="newFilename"></param>
-        public void Rename(string relativePath, string currentFilename, string newFilename)
-        {
-            var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(Path.Combine("ftp://" + FtpServer, relativePath, currentFilename).Replace("\\", "/")));
-            reqFtp.Method = WebRequestMethods.Ftp.Rename;
-            reqFtp.RenameTo = newFilename;
-            reqFtp.UseBinary = true;
-            reqFtp.Credentials = new NetworkCredential(Username, Password);
-            using FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
-            using var _ = response.GetResponseStream();
-        }
-
-        /// <summary>
-        /// 移动文件
-        /// </summary>
-        /// <param name="relativePath">相对路径</param>
-        /// <param name="currentFilename"></param>
-        /// <param name="newDirectory"></param>
-        public void MoveFile(string relativePath, string currentFilename, string newDirectory)
-        {
-            Rename(relativePath, currentFilename, newDirectory);
-        }
-        #endregion
-    }
-}

+ 0 - 413
Masuit.Tools.Core/Net/MultiThreadDownloader.cs

@@ -1,413 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Masuit.Tools.Net
-{
-    /// <summary>
-    /// 文件合并改变事件
-    /// </summary>
-    /// <param name="sender"></param>
-    /// <param name="e"></param>
-    public delegate void FileMergeProgressChangedEventHandler(object sender, int e);
-
-    /// <summary>
-    /// 多线程下载器
-    /// </summary>
-    public class MultiThreadDownloader
-    {
-        #region 属性
-
-        private string _url;
-        private bool _rangeAllowed;
-
-        #endregion
-
-        #region 公共属性
-
-        /// <summary>
-        /// RangeAllowed
-        /// </summary>
-        public bool RangeAllowed
-        {
-            get => _rangeAllowed;
-            set => _rangeAllowed = value;
-        }
-
-        /// <summary>
-        /// 临时文件夹
-        /// </summary>
-        public string TempFileDirectory { get; set; }
-
-        /// <summary>
-        /// url地址
-        /// </summary>
-        public string Url
-        {
-            get => _url;
-            set => _url = value;
-        }
-
-        /// <summary>
-        /// 第几部分
-        /// </summary>
-        public int NumberOfParts { get; set; }
-
-        /// <summary>
-        /// 已接收字节数
-        /// </summary>
-        public long TotalBytesReceived => PartialDownloaderList.Where(t => t != null).Sum(t => t.TotalBytesRead);
-
-        /// <summary>
-        /// 总进度
-        /// </summary>
-        public float TotalProgress { get; private set; }
-
-        /// <summary>
-        /// 文件大小
-        /// </summary>
-        public long Size { get; private set; }
-
-        /// <summary>
-        /// 下载速度
-        /// </summary>
-        public float TotalSpeedInBytes => PartialDownloaderList.Sum(t => t.SpeedInBytes);
-
-        /// <summary>
-        /// 下载块
-        /// </summary>
-        public List<PartialDownloader> PartialDownloaderList { get; }
-
-        /// <summary>
-        /// 文件路径
-        /// </summary>
-        public string FilePath { get; set; }
-
-        #endregion
-
-        #region 变量
-
-        /// <summary>
-        /// 总下载进度更新事件
-        /// </summary>
-        public event EventHandler TotalProgressChanged;
-
-        /// <summary>
-        /// 文件合并事件
-        /// </summary>
-        public event FileMergeProgressChangedEventHandler FileMergeProgressChanged;
-
-        private readonly AsyncOperation _aop;
-
-        #endregion
-
-        #region 下载管理器
-
-        /// <summary>
-        /// 多线程下载管理器
-        /// </summary>
-        /// <param name="sourceUrl"></param>
-        /// <param name="tempDir"></param>
-        /// <param name="savePath"></param>
-        /// <param name="numOfParts"></param>
-        public MultiThreadDownloader(string sourceUrl, string tempDir, string savePath, int numOfParts)
-        {
-            _url = sourceUrl;
-            NumberOfParts = numOfParts;
-            TempFileDirectory = tempDir;
-            PartialDownloaderList = new List<PartialDownloader>();
-            _aop = AsyncOperationManager.CreateOperation(null);
-            FilePath = savePath;
-        }
-
-        /// <summary>
-        /// 多线程下载管理器
-        /// </summary>
-        /// <param name="sourceUrl"></param>
-        /// <param name="savePath"></param>
-        /// <param name="numOfParts"></param>
-        public MultiThreadDownloader(string sourceUrl, string savePath, int numOfParts) : this(sourceUrl, null, savePath, numOfParts)
-        {
-            TempFileDirectory = Environment.GetEnvironmentVariable("temp");
-        }
-
-        /// <summary>
-        /// 多线程下载管理器
-        /// </summary>
-        /// <param name="sourceUrl"></param>
-        /// <param name="numOfParts"></param>
-        public MultiThreadDownloader(string sourceUrl, int numOfParts) : this(sourceUrl, null, numOfParts)
-        {
-        }
-
-        #endregion
-
-        #region 事件
-
-        private void temp_DownloadPartCompleted(object sender, EventArgs e)
-        {
-            WaitOrResumeAll(PartialDownloaderList, true);
-
-            if (TotalBytesReceived == Size)
-            {
-                UpdateProgress();
-                MergeParts();
-                return;
-            }
-
-            OrderByRemaining(PartialDownloaderList);
-
-            int rem = PartialDownloaderList[0].RemainingBytes;
-            if (rem < 50 * 1024)
-            {
-                WaitOrResumeAll(PartialDownloaderList, false);
-                return;
-            }
-
-            int from = PartialDownloaderList[0].CurrentPosition + rem / 2;
-            int to = PartialDownloaderList[0].To;
-            if (from > to)
-            {
-                WaitOrResumeAll(PartialDownloaderList, false);
-                return;
-            }
-
-            PartialDownloaderList[0].To = from - 1;
-
-            WaitOrResumeAll(PartialDownloaderList, false);
-
-            PartialDownloader temp = new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), from, to, true);
-            temp.DownloadPartCompleted += temp_DownloadPartCompleted;
-            temp.DownloadPartProgressChanged += temp_DownloadPartProgressChanged;
-            PartialDownloaderList.Add(temp);
-            temp.Start();
-        }
-
-        void temp_DownloadPartProgressChanged(object sender, EventArgs e)
-        {
-            UpdateProgress();
-        }
-
-        void UpdateProgress()
-        {
-            int pr = (int)(TotalBytesReceived * 1d / Size * 100);
-            if (Math.Abs(TotalProgress - pr) > 0.01)
-            {
-                TotalProgress = pr;
-                if (TotalProgressChanged != null)
-                {
-                    _aop.Post(state => TotalProgressChanged(this, EventArgs.Empty), null);
-                }
-            }
-        }
-
-        #endregion
-
-        #region 方法
-
-        void CreateFirstPartitions()
-        {
-            Size = GetContentLength(_url, ref _rangeAllowed, ref _url);
-            int maximumPart = (int)(Size / (25 * 1024));
-            maximumPart = maximumPart == 0 ? 1 : maximumPart;
-            if (!_rangeAllowed)
-                NumberOfParts = 1;
-            else if (NumberOfParts > maximumPart)
-                NumberOfParts = maximumPart;
-
-            for (int i = 0; i < NumberOfParts; i++)
-            {
-                PartialDownloader temp = CreateNewPd(i, NumberOfParts, Size);
-                temp.DownloadPartProgressChanged += temp_DownloadPartProgressChanged;
-                temp.DownloadPartCompleted += temp_DownloadPartCompleted;
-                PartialDownloaderList.Add(temp);
-                temp.Start();
-            }
-        }
-
-        void MergeParts()
-        {
-            List<PartialDownloader> mergeOrderedList = SortPDsByFrom(PartialDownloaderList);
-            using var fs = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite);
-            long totalBytesWritten = 0;
-            int mergeProgress = 0;
-            foreach (var item in mergeOrderedList)
-            {
-                using var pds = new FileStream(item.FullPath, FileMode.Open, FileAccess.Read);
-                byte[] buffer = new byte[4096];
-                int read;
-                while ((read = pds.Read(buffer, 0, buffer.Length)) > 0)
-                {
-                    fs.Write(buffer, 0, read);
-                    totalBytesWritten += read;
-                    int temp = (int)(totalBytesWritten * 1d / Size * 100);
-                    if (temp != mergeProgress && FileMergeProgressChanged != null)
-                    {
-                        mergeProgress = temp;
-                        _aop.Post(state => FileMergeProgressChanged(this, temp), null);
-                    }
-                }
-
-                try
-                {
-                    File.Delete(item.FullPath);
-                }
-                catch
-                {
-                    // ignored
-                }
-            }
-        }
-
-        PartialDownloader CreateNewPd(int order, int parts, long contentLength)
-        {
-            int division = (int)contentLength / parts;
-            int remaining = (int)contentLength % parts;
-            int start = division * order;
-            int end = start + division - 1;
-            end += (order == parts - 1) ? remaining : 0;
-            return new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), start, end, true);
-        }
-
-        /// <summary>
-        /// 暂停或继续
-        /// </summary>
-        /// <param name="list"></param>
-        /// <param name="wait"></param>
-        public static void WaitOrResumeAll(List<PartialDownloader> list, bool wait)
-        {
-            foreach (PartialDownloader item in list)
-            {
-                if (wait)
-                    item.Wait();
-                else
-                    item.ResumeAfterWait();
-            }
-        }
-
-        /// <summary>
-        /// 冒泡排序
-        /// </summary>
-        /// <param name="list"></param>
-        private static void BubbleSort(List<PartialDownloader> list)
-        {
-            bool switched = true;
-            while (switched)
-            {
-                switched = false;
-                for (int i = 0; i < list.Count - 1; i++)
-                {
-                    if (list[i].RemainingBytes < list[i + 1].RemainingBytes)
-                    {
-                        PartialDownloader temp = list[i];
-                        list[i] = list[i + 1];
-                        list[i + 1] = temp;
-                        switched = true;
-                    }
-                }
-            }
-        }
-
-        /// <summary>
-        /// Sorts the downloader by From property to merge the parts
-        /// </summary>
-        /// <param name="list"></param>
-        /// <returns></returns>
-        public static List<PartialDownloader> SortPDsByFrom(List<PartialDownloader> list)
-        {
-            return list.OrderBy(x => x.From).ToList();
-        }
-
-        /// <summary>
-        /// 按剩余时间排序
-        /// </summary>
-        /// <param name="list"></param>
-        public static void OrderByRemaining(List<PartialDownloader> list)
-        {
-            BubbleSort(list);
-        }
-
-        /// <summary>
-        /// 获取内容长度
-        /// </summary>
-        /// <param name="url"></param>
-        /// <param name="rangeAllowed"></param>
-        /// <param name="redirectedUrl"></param>
-        /// <returns></returns>
-        public static long GetContentLength(string url, ref bool rangeAllowed, ref string redirectedUrl)
-        {
-            var req = WebRequest.Create(url) as HttpWebRequest;
-            req.UserAgent = "Mozilla/4.0 (compatible; MSIE 11.0; Windows NT 6.2; .NET CLR 1.0.3705;)";
-            req.ServicePoint.ConnectionLimit = 4;
-            using var resp = req.GetResponse() as HttpWebResponse;
-            redirectedUrl = resp.ResponseUri.OriginalString;
-            var ctl = resp.ContentLength;
-            rangeAllowed = resp.Headers.AllKeys.Select((v, i) => new
-            {
-                HeaderName = v,
-                HeaderValue = resp.Headers[i]
-            }).Any(k => k.HeaderName.ToLower().Contains("range") && k.HeaderValue.ToLower().Contains("byte"));
-            req.Abort();
-            return ctl;
-        }
-
-        #endregion
-
-        #region 公共方法
-
-        /// <summary>
-        /// 暂停下载
-        /// </summary>
-        public void Pause()
-        {
-            foreach (var t in PartialDownloaderList)
-            {
-                if (!t.Completed)
-                    t.Stop();
-            }
-
-            //Setting a Thread.Sleep ensures all downloads are stopped and exit from loop.
-            Thread.Sleep(200);
-        }
-
-        /// <summary>
-        /// 开始下载
-        /// </summary>
-        public void Start()
-        {
-            Task th = new Task(CreateFirstPartitions);
-            th.Start();
-        }
-
-        /// <summary>
-        /// 唤醒下载
-        /// </summary>
-        public void Resume()
-        {
-            int count = PartialDownloaderList.Count;
-            for (int i = 0; i < count; i++)
-            {
-                if (PartialDownloaderList[i].Stopped)
-                {
-                    int from = PartialDownloaderList[i].CurrentPosition + 1;
-                    int to = PartialDownloaderList[i].To;
-                    if (from > to) continue;
-                    PartialDownloader temp = new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), from, to, _rangeAllowed);
-
-                    temp.DownloadPartProgressChanged += temp_DownloadPartProgressChanged;
-                    temp.DownloadPartCompleted += temp_DownloadPartCompleted;
-                    PartialDownloaderList.Add(temp);
-                    PartialDownloaderList[i].To = PartialDownloaderList[i].CurrentPosition;
-                    temp.Start();
-                }
-            }
-        }
-
-        #endregion
-    }
-}

+ 0 - 319
Masuit.Tools.Core/Net/PartialDownloader.cs

@@ -1,319 +0,0 @@
-using System;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Threading;
-
-namespace Masuit.Tools.Net
-{
-    /// <summary>
-    /// 部分下载器
-    /// </summary>
-    public class PartialDownloader
-    {
-        #region Variables
-
-        /// <summary>
-        /// 这部分完成事件
-        /// </summary>
-        public event EventHandler DownloadPartCompleted;
-
-        /// <summary>
-        /// 部分下载进度改变事件
-        /// </summary>
-        public event EventHandler DownloadPartProgressChanged;
-
-        /// <summary>
-        /// 部分下载停止事件
-        /// </summary>
-        public event EventHandler DownloadPartStopped;
-
-        HttpWebRequest _req;
-        HttpWebResponse _resp;
-        Stream _tempStream;
-        FileStream _file;
-        private readonly AsyncOperation _aop = AsyncOperationManager.CreateOperation(null);
-        private readonly Stopwatch _stp;
-        readonly int[] _lastSpeeds;
-        int _counter;
-        bool _stop, _wait;
-
-        #endregion
-
-        #region PartialDownloader
-
-        /// <summary>
-        /// 部分块下载
-        /// </summary>
-        /// <param name="url"></param>
-        /// <param name="dir"></param>
-        /// <param name="fileGuid"></param>
-        /// <param name="from"></param>
-        /// <param name="to"></param>
-        /// <param name="rangeAllowed"></param>
-        public PartialDownloader(string url, string dir, string fileGuid, int from, int to, bool rangeAllowed)
-        {
-            _from = from;
-            _to = to;
-            _url = url;
-            _rangeAllowed = rangeAllowed;
-            _fileGuid = fileGuid;
-            _directory = dir;
-            _lastSpeeds = new int[10];
-            _stp = new Stopwatch();
-        }
-
-        #endregion
-
-        void DownloadProcedure()
-        {
-            _file = new FileStream(FullPath, FileMode.Create, FileAccess.ReadWrite);
-
-            #region Request-Response
-
-            _req = WebRequest.Create(_url) as HttpWebRequest;
-            if (_req != null)
-            {
-                _req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
-                _req.AllowAutoRedirect = true;
-                _req.MaximumAutomaticRedirections = 5;
-                _req.ServicePoint.ConnectionLimit += 1;
-                _req.ServicePoint.Expect100Continue = true;
-                _req.ProtocolVersion = HttpVersion.Version10;
-                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.SystemDefault;
-                ServicePointManager.Expect100Continue = true;
-                if (_rangeAllowed)
-                    _req.AddRange(_from, _to);
-                _resp = _req.GetResponse() as HttpWebResponse;
-
-                #endregion
-
-                #region Some Stuff
-
-                if (_resp != null)
-                {
-                    _contentLength = _resp.ContentLength;
-                    if (_contentLength <= 0 || (_rangeAllowed && _contentLength != _to - _from + 1))
-                        throw new Exception("Invalid response content");
-                    _tempStream = _resp.GetResponseStream();
-                    int bytesRead;
-                    byte[] buffer = new byte[4096];
-                    _stp.Start();
-
-                    #endregion
-
-                    #region Procedure Loop
-
-                    while (_tempStream != null && (bytesRead = _tempStream.Read(buffer, 0, buffer.Length)) > 0)
-                    {
-                        while (_wait)
-                        {
-                        }
-
-                        if (_totalBytesRead + bytesRead > _contentLength)
-                            bytesRead = (int)(_contentLength - _totalBytesRead);
-                        _file.Write(buffer, 0, bytesRead);
-                        _totalBytesRead += bytesRead;
-                        _lastSpeeds[_counter] = (int)(_totalBytesRead / Math.Ceiling(_stp.Elapsed.TotalSeconds));
-                        _counter = (_counter >= 9) ? 0 : _counter + 1;
-                        int tempProgress = (int)(_totalBytesRead * 100 / _contentLength);
-                        if (_progress != tempProgress)
-                        {
-                            _progress = tempProgress;
-                            _aop.Post(state =>
-                            {
-                                DownloadPartProgressChanged?.Invoke(this, EventArgs.Empty);
-                            }, null);
-                        }
-
-                        if (_stop || (_rangeAllowed && _totalBytesRead == _contentLength))
-                        {
-                            break;
-                        }
-                    }
-
-                    #endregion
-
-                    #region Close Resources
-
-                    _file.Close();
-                    _resp.Close();
-                }
-
-                _tempStream?.Close();
-                _req.Abort();
-            }
-
-            _stp.Stop();
-
-            #endregion
-
-            #region Fire Events
-
-            if (!_stop && DownloadPartCompleted != null)
-                _aop.Post(state =>
-                {
-                    _completed = true;
-                    DownloadPartCompleted(this, EventArgs.Empty);
-                }, null);
-
-            if (_stop && DownloadPartStopped != null)
-                _aop.Post(state => DownloadPartStopped(this, EventArgs.Empty), null);
-
-            #endregion
-        }
-
-        #region Public Methods
-
-        /// <summary>
-        /// 启动下载
-        /// </summary>
-        public void Start()
-        {
-            _stop = false;
-            Thread procThread = new Thread(DownloadProcedure);
-            procThread.Start();
-        }
-
-        /// <summary>
-        /// 下载停止
-        /// </summary>
-        public void Stop()
-        {
-            _stop = true;
-        }
-
-        /// <summary>
-        /// 暂停等待下载
-        /// </summary>
-        public void Wait()
-        {
-            _wait = true;
-        }
-
-        /// <summary>
-        /// 稍后唤醒
-        /// </summary>
-        public void ResumeAfterWait()
-        {
-            _wait = false;
-        }
-
-        #endregion
-
-        #region Property Variables
-
-        private readonly int _from;
-        private int _to;
-        private readonly string _url;
-        private readonly bool _rangeAllowed;
-        private long _contentLength;
-        private int _totalBytesRead;
-        private readonly string _fileGuid;
-        private readonly string _directory;
-        private int _progress;
-        private bool _completed;
-
-        #endregion
-
-        #region Properties
-
-        /// <summary>
-        /// 下载已停止
-        /// </summary>
-        public bool Stopped => _stop;
-
-        /// <summary>
-        /// 下载已完成
-        /// </summary>
-        public bool Completed => _completed;
-
-        /// <summary>
-        /// 下载进度
-        /// </summary>
-        public int Progress => _progress;
-
-        /// <summary>
-        /// 下载目录
-        /// </summary>
-        public string Directory => _directory;
-
-        /// <summary>
-        /// 文件名
-        /// </summary>
-        public string FileName => _fileGuid;
-
-        /// <summary>
-        /// 已读字节数
-        /// </summary>
-        public long TotalBytesRead => _totalBytesRead;
-
-        /// <summary>
-        /// 内容长度
-        /// </summary>
-        public long ContentLength => _contentLength;
-
-        /// <summary>
-        /// RangeAllowed
-        /// </summary>
-        public bool RangeAllowed => _rangeAllowed;
-
-        /// <summary>
-        /// url
-        /// </summary>
-        public string Url => _url;
-
-        /// <summary>
-        /// to
-        /// </summary>
-        public int To
-        {
-            get => _to;
-            set
-            {
-                _to = value;
-                _contentLength = _to - _from + 1;
-            }
-        }
-
-        /// <summary>
-        /// from
-        /// </summary>
-        public int From => _from;
-
-        /// <summary>
-        /// 当前位置
-        /// </summary>
-        public int CurrentPosition => _from + _totalBytesRead - 1;
-
-        /// <summary>
-        /// 剩余字节数
-        /// </summary>
-        public int RemainingBytes => (int)(_contentLength - _totalBytesRead);
-
-        /// <summary>
-        /// 完整路径
-        /// </summary>
-        public string FullPath => Path.Combine(_directory, _fileGuid);
-
-        /// <summary>
-        /// 下载速度
-        /// </summary>
-        public int SpeedInBytes
-        {
-            get
-            {
-                if (_completed)
-                    return 0;
-
-                int totalSpeeds = _lastSpeeds.Sum();
-
-                return totalSpeeds / 10;
-            }
-        }
-
-        #endregion
-    }
-}

+ 0 - 566
Masuit.Tools.Core/Net/SocketClient.cs

@@ -1,566 +0,0 @@
-using System;
-using System.IO;
-using System.Net;
-using System.Net.Sockets;
-using System.Runtime.Serialization;
-using System.Runtime.Serialization.Formatters.Binary;
-using System.Text;
-using System.Threading;
-
-namespace Masuit.Tools.Net
-{
-    /// <summary>
-    /// Socket客户端操作类
-    /// </summary>
-    public static class SocketClient
-    {
-        #region 私有字段
-
-        /// <summary>
-        /// 设置数据缓冲区大小 默认1024
-        /// </summary>
-        private static readonly int m_maxpacket = 1024 * 4;
-
-        #endregion
-
-        #region 服务器侦听
-
-        /// <summary>
-        /// 服务器侦听方法 返回null则说明没有链接上
-        /// </summary>
-        /// <returns>返回一个套接字(Socket)</returns>
-        public static Socket ListenerSocket(this TcpListener listener)
-        {
-            try
-            {
-                Socket socket = listener.AcceptSocket();
-                return socket;
-            }
-            catch (Exception)
-            {
-                return null;
-            }
-        }
-
-        /// <summary>
-        /// 服务器侦听方法 返回null则说明没有链接上
-        /// </summary>
-        /// <param name="listener">TCP监听对象</param>
-        /// <returns>返回一个网络流</returns>
-        public static NetworkStream ListenerStream(this TcpListener listener)
-        {
-            try
-            {
-                TcpClient client = listener.AcceptTcpClient();
-                return client.GetStream();
-            }
-            catch (Exception)
-            {
-                return null;
-            }
-        }
-
-        #endregion
-
-        #region 客户端连接
-
-        /// <summary>
-        /// 从客户端连接获取socket对象
-        /// </summary>
-        /// <param name="tcpclient">TCP客户端</param>
-        /// <param name="ipendpoint">客户端节点</param>
-        /// <returns>客户端socket</returns>
-        public static Socket ConnectSocket(this TcpClient tcpclient, IPEndPoint ipendpoint)
-        {
-            try
-            {
-                tcpclient.Connect(ipendpoint);
-                return tcpclient.Client;
-            }
-            catch (Exception)
-            {
-                return null;
-            }
-        }
-
-        /// <summary>
-        /// 从客户端连接获取socket对象
-        /// </summary>
-        /// <param name="tcpclient">TCP客户端</param>
-        /// <param name="ipadd">IP地址</param>
-        /// <param name="port">端口号</param>
-        /// <returns>客户端socket</returns>
-        public static Socket ConnectSocket(this TcpClient tcpclient, IPAddress ipadd, int port)
-        {
-            try
-            {
-                tcpclient.Connect(ipadd, port);
-                return tcpclient.Client;
-            }
-            catch (Exception)
-            {
-                return null;
-            }
-        }
-
-        /// <summary>
-        /// 从客户端获取网络流对象
-        /// </summary>
-        /// <param name="tcpclient">TCP客户端</param>
-        /// <param name="ipendpoint">客户端节点</param>
-        /// <returns>客户端的网络流</returns>
-        public static NetworkStream ConnectStream(this TcpClient tcpclient, IPEndPoint ipendpoint)
-        {
-            try
-            {
-                tcpclient.Connect(ipendpoint);
-                return tcpclient.GetStream();
-            }
-            catch (Exception)
-            {
-                return null;
-            }
-        }
-
-        /// <summary>
-        /// 从客户端获取网络流对象
-        /// </summary>
-        /// <param name="tcpclient">TCP客户端</param>
-        /// <param name="ipadd">IP地址</param>
-        /// <param name="port">端口号</param>
-        /// <returns>客户端网络流对象</returns>
-        public static NetworkStream ConnectStream(this TcpClient tcpclient, IPAddress ipadd, int port)
-        {
-            try
-            {
-                tcpclient.Connect(ipadd, port);
-                return tcpclient.GetStream();
-            }
-            catch (Exception)
-            {
-                return null;
-            }
-        }
-
-        #endregion
-
-        #region Socket接收数据
-
-        /// <summary>
-        /// 接受固定长度字符串
-        /// </summary>
-        /// <param name="socket">socket对象</param>
-        /// <param name="size">字符串长度</param>
-        /// <returns>字节数据</returns>
-        public static byte[] ReceiveFixData(this Socket socket, int size)
-        {
-            int offset = 0;
-            int dataleft = size;
-            byte[] msg = new byte[size];
-            while (dataleft > 0)
-            {
-                var recv = socket.Receive(msg, offset, dataleft, 0);
-                if (recv == 0)
-                    break;
-                offset += recv;
-                dataleft -= recv;
-            }
-
-            return msg;
-        }
-
-        /// <summary>
-        /// 接收变长字符串
-        /// 为了处理粘包问题 ,每次发送数据时 包头(数据字节长度) + 正文
-        /// 这个发送小数据
-        /// 设置包头的字节为8,不能超过8位数的字节数组
-        /// </summary>
-        /// <param name="socket">客户端socket</param>
-        /// <returns>byte[]数组</returns>
-        public static byte[] ReceiveVarData(this Socket socket)
-        {
-            //每次接受数据时,接收固定长度的包头,包头长度为8
-            byte[] lengthbyte = ReceiveFixData(socket, 8);
-            //length得到字符长度 然后加工处理得到数字
-            int length = GetPacketLength(lengthbyte);
-            //得到正文
-            return ReceiveFixData(socket, length);
-        }
-
-        /// <summary>
-        /// 接收T类对象,反序列化
-        /// </summary>
-        /// <typeparam name="T">接收T类对象,T类必须是一个可序列化类</typeparam>
-        /// <param name="socket">客户端socket</param>
-        /// <returns>强类型对象</returns>
-        public static T ReceiveVarData<T>(this Socket socket)
-        {
-            //先接收包头长度 固定8个字节
-            byte[] lengthbyte = ReceiveFixData(socket, 8);
-            //得到字节长度
-            int length = GetPacketLength(lengthbyte);
-            byte[] bytecoll = new byte[m_maxpacket];
-            IFormatter format = new BinaryFormatter();
-            MemoryStream stream = new MemoryStream();
-            int offset = 0; //接收字节个数
-            int lastdata = length; //还剩下多少没有接收,初始大小等于实际大小
-            int receivedata = m_maxpacket; //每次接收大小
-            //循环接收
-            int mark = 0; //标记几次接收到的数据为0长度
-            while (true)
-            {
-                //剩下的字节数是否小于缓存大小
-                if (lastdata < m_maxpacket)
-                    receivedata = lastdata; //就只接收剩下的字节数
-                int count = socket.Receive(bytecoll, 0, receivedata, 0);
-                if (count > 0)
-                {
-                    stream.Write(bytecoll, 0, count);
-                    offset += count;
-                    lastdata -= count;
-                    mark = 0;
-                }
-                else
-                {
-                    mark++;
-                    if (mark == 10)
-                        break;
-                }
-
-                if (offset == length)
-                    break;
-            }
-
-            stream.Seek(0, SeekOrigin.Begin); //必须要这个 或者stream.Position = 0;
-            T t = (T)format.Deserialize(stream);
-            stream.Close();
-            return t;
-        }
-
-        /// <summary>
-        /// 在预先得到文件的文件名和大小
-        /// 调用此方法接收文件
-        /// </summary>
-        /// <param name="socket">socket服务端</param>
-        /// <param name="path">路径必须存在</param>
-        /// <param name="filename">文件名</param>
-        /// <param name="size">预先知道的文件大小</param>
-        /// <param name="progress">处理过程</param>
-        public static bool ReceiveFile(this Socket socket, string path, string filename, long size, Action<int> progress)
-        {
-            if (!Directory.Exists(path))
-            {
-                return false;
-            }
-
-            //主要是防止有重名文件
-            string savepath = GetPath(path, filename); //得到文件路径
-            //缓冲区
-            byte[] file = new byte[m_maxpacket];
-            int receivedata = m_maxpacket; //每次要接收的长度
-            long offset = 0; //循环接收的总长度
-            long lastdata = size; //剩余多少还没接收
-            int mark = 0;
-            using var fs = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.Write);
-            if (size <= 0)
-            {
-                return false;
-            }
-
-            bool ret = false;
-            while (true)
-            {
-                if (lastdata < receivedata)
-                {
-                    receivedata = Convert.ToInt32(lastdata);
-                }
-
-                var count = socket.Receive(file, 0, receivedata, SocketFlags.None); //每次接收的实际长度
-                if (count > 0)
-                {
-                    fs.Write(file, 0, count);
-                    offset += count;
-                    lastdata -= count;
-                    mark = 0;
-                }
-                else
-                {
-                    mark++; //连续5次接收为0字节 则跳出循环
-                    if (mark == 10)
-                    {
-                        break;
-                    }
-                }
-
-                //接收进度
-                progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(size) * 100));
-                //接收完毕
-                if (offset == size)
-                {
-                    ret = true;
-                    break;
-                }
-            }
-
-            return ret;
-        }
-
-        /// <summary>
-        /// 从socket服务端接收文件
-        /// </summary>
-        /// <param name="socket">socket服务端</param>
-        /// <param name="path">文件保存路径(必须存在)</param>
-        /// <param name="filename">文件名</param>
-        /// <param name="size">预先知道的文件大小</param>
-        /// <returns>处理结果</returns>
-        public static bool ReceiveFile(this Socket socket, string path, string filename, long size)
-        {
-            return ReceiveFile(socket, path, filename, size, null);
-        }
-
-        /// <summary>
-        /// 预先不知道文件名和文件大小 用此方法接收
-        /// 此方法对于的发送方法是SendFile()
-        /// </summary>
-        /// <param name="socket">socket服务端</param>
-        /// <param name="path">要保存的目录</param>
-        public static void ReceiveFile(this Socket socket, string path)
-        {
-            //得到包头信息字节数组 (文件名 + 文件大小 的字符串长度)
-            //取前8位
-            byte[] info_bt = ReceiveFixData(socket, 8);
-            //得到包头信息字符长度
-            int info_length = GetPacketLength(info_bt);
-            //提取包头信息,(文件名 + 文件大小 的字符串长度)
-            byte[] info = ReceiveFixData(socket, info_length);
-            //得到文件信息字符串 (文件名 + 文件大小)
-            string info_str = Encoding.UTF8.GetString(info);
-            string[] strs = info_str.Split('|');
-            string filename = strs[0]; //文件名
-            long length = Convert.ToInt64(strs[1]); //文件大小
-            //开始接收文件
-            ReceiveFile(socket, path, filename, length);
-        }
-
-        private static int GetPacketLength(byte[] length)
-        {
-            string str = Encoding.UTF8.GetString(length);
-            str = str.TrimEnd('*');
-            ; //("*", "");
-            int _length = 0;
-            if (int.TryParse(str, out _length))
-                return _length;
-            return 0;
-        }
-
-        private static int i;
-
-        private static string markPath = string.Empty;
-
-        /// <summary>
-        /// 得到文件路径(防止有文件名重复)
-        ///  如:aaa.txt已经在directory目录下存在,则会得到文件aaa(1).txt
-        /// </summary>
-        /// <param name="directory">目录名</param>
-        /// <param name="file">文件名</param>
-        /// <returns>文件路径</returns>
-        public static string GetPath(string directory, string file)
-        {
-            if (markPath == string.Empty)
-                markPath = Path.Combine(directory, file);
-            string path = Path.Combine(directory, file);
-            if (File.Exists(path))
-            {
-                i++;
-                string filename = Path.GetFileNameWithoutExtension(markPath) + "(" + i + ")";
-                string extension = Path.GetExtension(markPath);
-                return GetPath(directory, filename + extension);
-            }
-
-            i = 0;
-            markPath = string.Empty;
-            return path;
-        }
-
-        #endregion
-
-        #region Socket发送数据
-
-        /// <summary>
-        /// 发送固定长度消息
-        /// 发送字节数不能大于int型最大值
-        /// </summary>
-        /// <param name="socket">源socket</param>
-        /// <param name="msg">消息的字节数组</param>
-        /// <returns>返回发送字节个数</returns>
-        public static int SendFixData(this Socket socket, byte[] msg)
-        {
-            int size = msg.Length; //要发送字节长度
-            int offset = 0; //已经发送长度
-            int dataleft = size; //剩下字符
-            int senddata = m_maxpacket; //每次发送大小
-            while (true)
-            {
-                //如过剩下的字节数 小于 每次发送字节数
-                if (dataleft < senddata)
-                    senddata = dataleft;
-                int count = socket.Send(msg, offset, senddata, SocketFlags.None);
-                offset += count;
-                dataleft -= count;
-                if (offset == size)
-                    break;
-            }
-
-            return offset;
-        }
-
-        /// <summary>
-        /// 发送变长信息 格式 包头(包头占8位) + 正文
-        /// </summary>
-        /// <param name="socket">发送方socket对象</param>
-        /// <param name="contact">发送文本</param>
-        /// <returns>发送的数据内容长度</returns>
-        public static int SendVarData(this Socket socket, string contact)
-        {
-            //得到字符长度
-            int size = Encoding.UTF8.GetBytes(contact).Length;
-            //包头字符
-            string length = GetSendPacketLengthStr(size);
-            //包头 + 正文
-            byte[] sendbyte = Encoding.UTF8.GetBytes(length + contact);
-            //发送
-            return SendFixData(socket, sendbyte);
-        }
-
-        /// <summary>
-        /// 发送变成信息
-        /// </summary>
-        /// <param name="socket">发送方socket对象</param>
-        /// <param name="bytes">消息的 字节数组</param>
-        /// <returns>消息长度</returns>
-        public static int SendVarData(this Socket socket, byte[] bytes)
-        {
-            //得到包头字节
-            int size = bytes.Length;
-            string length = GetSendPacketLengthStr(size);
-            byte[] lengthbyte = Encoding.UTF8.GetBytes(length);
-            //发送包头
-            SendFixData(socket, lengthbyte); //因为不知道正文是什么编码所以没有合并
-            //发送正文
-            return SendFixData(socket, bytes);
-        }
-
-        /// <summary>
-        /// 发送T类型对象,序列化
-        /// </summary>
-        /// <typeparam name="T">T类型</typeparam>
-        /// <param name="socket">发送方的socket对象</param>
-        /// <param name="obj">T类型对象,必须是可序列化的</param>
-        /// <returns>消息长度</returns>
-        public static int SendSerializeObject<T>(this Socket socket, T obj)
-        {
-            byte[] bytes = SerializeObject(obj);
-            return SendVarData(socket, bytes);
-        }
-
-        /// <summary>
-        /// 发送文件
-        /// </summary>
-        /// <param name="socket">socket对象</param>
-        /// <param name="path">文件路径</param>
-        /// <param name="issend">是否发送文件(头)信息,如果当前知道文件[大小,名称]则为false</param>
-        /// <param name="progress">处理过程</param>
-        /// <returns>处理结果</returns>
-        public static bool SendFile(this Socket socket, string path, bool issend, Action<int> progress)
-        {
-            if (!File.Exists(path))
-            {
-                return false;
-            }
-
-            var fileinfo = new FileInfo(path);
-            string filename = fileinfo.Name;
-            long length = fileinfo.Length;
-            //发送文件信息
-            if (issend)
-            {
-                SendVarData(socket, filename + "|" + length);
-            }
-
-            //发送文件
-            long offset = 0;
-            byte[] b = new byte[m_maxpacket];
-            int mark = 0;
-            using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
-            int senddata = b.Length;
-            //循环读取发送
-            while (true)
-            {
-                int count = fs.Read(b, 0, senddata);
-                if (count > 0)
-                {
-                    socket.Send(b, 0, count, SocketFlags.None);
-                    offset += count;
-                    mark = 0;
-                }
-                else
-                {
-                    mark++;
-                    if (mark == 10)
-                    {
-                        break;
-                    }
-                }
-
-                progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(length) * 100));
-                if (offset == length)
-                {
-                    return true;
-                }
-
-                Thread.Sleep(50); //设置等待时间,以免粘包
-            }
-
-            return false;
-        }
-
-        /// <summary>
-        /// 发送文件,不需要进度信息
-        /// </summary>
-        /// <param name="socket">socket对象</param>
-        /// <param name="path">文件路径</param>
-        /// <param name="issend">是否发生(头)信息</param>
-        /// <returns>处理结果</returns>
-        public static bool SendFile(this Socket socket, string path, bool issend)
-        {
-            return SendFile(socket, path, issend, null);
-        }
-
-        /// <summary>
-        /// 发送文件,不需要进度信息和(头)信息
-        /// </summary>
-        /// <param name="socket">socket对象</param>
-        /// <param name="path">文件路径</param>
-        /// <returns>处理结果</returns>
-        public static bool SendFile(this Socket socket, string path)
-        {
-            return SendFile(socket, path, false, null);
-        }
-
-        private static byte[] SerializeObject(object obj)
-        {
-            IFormatter format = new BinaryFormatter();
-            using var stream = new MemoryStream();
-            format.Serialize(stream, obj);
-            return stream.ToArray();
-        }
-
-        private static string GetSendPacketLengthStr(int size)
-        {
-            string length = size + "********"; //得到size的长度
-            return length.Substring(0, 8); //截取前前8位
-        }
-
-        #endregion
-    }
-}

+ 0 - 450
Masuit.Tools.Core/Reflection/ClassHelper.cs

@@ -1,450 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Reflection;
-using System.Reflection.Emit;
-
-namespace Masuit.Tools.Reflection
-{
-    /// <summary>  
-    /// 类帮助器,可以动态对类,类成员进行控制(添加,删除),目前只支持属性控制。  
-    /// 注意,属性以外的其它成员会被清空,功能还有待完善,使其不影响其它成员。  
-    /// </summary>  
-    public static class ClassHelper
-    {
-        #region 公有方法  
-
-        /// <summary>  
-        /// 根据类的类型型创建类实例。  
-        /// </summary>  
-        /// <param name="t">将要创建的类型。</param>  
-        /// <returns>返回创建的类实例。</returns>  
-        public static object CreateInstance(this Type t)
-        {
-            return Activator.CreateInstance(t);
-        }
-
-
-        /// <summary>  
-        /// 根据类的名称,属性列表创建型实例。  
-        /// </summary>  
-        /// <param name="className">将要创建的类的名称。</param>  
-        /// <param name="lcpi">将要创建的类的属性列表。</param>  
-        /// <returns>返回创建的类实例</returns>  
-        public static object CreateInstance(string className, List<CustPropertyInfo> lcpi)
-        {
-            return Activator.CreateInstance(AddProperty(BuildType(className), lcpi));
-        }
-
-
-        /// <summary>  
-        /// 根据属性列表创建类的实例,默认类名为DefaultClass,由于生成的类不是强类型,所以类名可以忽略。  
-        /// </summary>  
-        /// <param name="lcpi">将要创建的类的属性列表</param>  
-        /// <returns>返回创建的类的实例。</returns>  
-        public static object CreateInstance(List<CustPropertyInfo> lcpi)
-        {
-            return CreateInstance("DefaultClass", lcpi);
-        }
-
-        /// <summary>  
-        /// 创建一个没有成员的类型的实例,类名为"DefaultClass"。  
-        /// </summary>  
-        /// <returns>返回创建的类型的实例。</returns>  
-        public static Type BuildType()
-        {
-            return BuildType("DefaultClass");
-        }
-
-
-        /// <summary>  
-        /// 根据类名创建一个没有成员的类型的实例。  
-        /// </summary>  
-        /// <param name="className">将要创建的类型的实例的类名。</param>  
-        /// <returns>返回创建的类型的实例。</returns>  
-        public static Type BuildType(string className)
-        {
-            AssemblyName myAsmName = new AssemblyName
-            {
-                Name = "MyDynamicAssembly"
-            };
-
-            //创建一个程序集,设置为AssemblyBuilderAccess.RunAndCollect。  
-            AssemblyBuilder myAsmBuilder = AssemblyBuilder.DefineDynamicAssembly(myAsmName, AssemblyBuilderAccess.RunAndCollect);
-
-            //创建一个单模程序块。  
-            ModuleBuilder myModBuilder = myAsmBuilder.DefineDynamicModule(myAsmName.Name);
-            //创建TypeBuilder。  
-            TypeBuilder myTypeBuilder = myModBuilder.DefineType(className, TypeAttributes.Public);
-
-            //创建类型。  
-            Type retval = myTypeBuilder.CreateType();
-
-            //保存程序集,以便可以被Ildasm.exe解析,或被测试程序引用。  
-            //myAsmBuilder.Save(myAsmName.Name + ".dll");  
-            return retval;
-        }
-
-        /// <summary>  
-        /// 添加属性到类型的实例,注意:该操作会将其它成员清除掉,其功能有待完善。  
-        /// </summary>  
-        /// <param name="classType">指定类型的实例。</param>  
-        /// <param name="lcpi">表示属性的一个列表。</param>  
-        /// <returns>返回处理过的类型的实例。</returns>  
-        public static Type AddProperty(this Type classType, List<CustPropertyInfo> lcpi)
-        {
-            //合并先前的属性,以便一起在下一步进行处理。  
-            MergeProperty(classType, lcpi);
-            //把属性加入到Type。  
-            return AddPropertyToType(classType, lcpi);
-        }
-
-
-        /// <summary>  
-        /// 添加属性到类型的实例,注意:该操作会将其它成员清除掉,其功能有待完善。  
-        /// </summary>  
-        /// <param name="classType">指定类型的实例。</param>  
-        /// <param name="cpi">表示一个属性。</param>  
-        /// <returns>返回处理过的类型的实例。</returns>  
-        public static Type AddProperty(this Type classType, CustPropertyInfo cpi)
-        {
-            List<CustPropertyInfo> lcpi = new List<CustPropertyInfo>
-            {
-                cpi
-            };
-            //合并先前的属性,以便一起在下一步进行处理。  
-            MergeProperty(classType, lcpi);
-            //把属性加入到Type。  
-            return AddPropertyToType(classType, lcpi);
-        }
-
-        /// <summary>
-        /// 给对象实例添加新属性并返回新对象实例
-        /// </summary>
-        /// <param name="obj"></param>
-        /// <param name="lcpi">自定义属性对象集合</param>
-        /// <returns></returns>
-        public static object AddProperty(this object obj, List<CustPropertyInfo> lcpi)
-        {
-            Type originType = obj.GetType();
-            var customs = lcpi.ToDictionary(i => i.PropertyName, i => i.PropertyValue);
-            var dest = AddProperty(originType, lcpi).CreateInstance();
-            foreach (var originProperty in originType.GetProperties())
-            {
-                dest.SetProperty(originProperty.Name, originProperty.GetValue(obj));
-            }
-            foreach (var cpi in customs)
-            {
-                dest.SetProperty(cpi.Key, cpi.Value);
-            }
-            return dest;
-        }
-
-        /// <summary>
-        /// 给对象实例添加新属性并返回新对象实例
-        /// </summary>
-        /// <param name="obj"></param>
-        /// <param name="cpi">自定义属性对象</param>
-        /// <returns></returns>
-        public static object AddProperty(this object obj, CustPropertyInfo cpi)
-        {
-            return AddProperty(obj, new List<CustPropertyInfo>() { cpi });
-        }
-
-        /// <summary>
-        /// 给对象实例添加新属性并返回新对象实例
-        /// </summary>
-        /// <param name="obj"></param>
-        /// <param name="propertyName">属性名</param>
-        /// <param name="propertyValue">属性值</param>
-        /// <returns></returns>
-        public static object AddProperty(this object obj, string propertyName, object propertyValue)
-        {
-            return AddProperty(obj, new List<CustPropertyInfo>() { new CustPropertyInfo(propertyValue.GetType(), propertyName, propertyValue) });
-        }
-
-        /// <summary>  
-        /// 从类型的实例中移除属性,注意:该操作会将其它成员清除掉,其功能有待完善。  
-        /// </summary>  
-        /// <param name="classType">指定类型的实例。</param>  
-        /// <param name="propertyName">要移除的属性。</param>  
-        /// <returns>返回处理过的类型的实例。</returns>  
-        public static Type DeleteProperty(this Type classType, string propertyName)
-        {
-            List<string> ls = new List<string>
-            {
-                propertyName
-            };
-
-            //合并先前的属性,以便一起在下一步进行处理。  
-            List<CustPropertyInfo> lcpi = SeparateProperty(classType, ls);
-            //把属性加入到Type。  
-            return AddPropertyToType(classType, lcpi);
-        }
-
-
-        /// <summary>  
-        /// 从类型的实例中移除属性,注意:该操作会将其它成员清除掉,其功能有待完善。  
-        /// </summary>  
-        /// <param name="classType">指定类型的实例。</param>  
-        /// <param name="propertyNames">要移除的属性列表。</param>  
-        /// <returns>返回处理过的类型的实例。</returns>  
-        public static Type DeleteProperty(this Type classType, List<string> propertyNames)
-        {
-            //合并先前的属性,以便一起在下一步进行处理。  
-            List<CustPropertyInfo> lcpi = SeparateProperty(classType, propertyNames);
-            //把属性加入到Type。  
-            return AddPropertyToType(classType, lcpi);
-        }
-
-        /// <summary>
-        /// 删除对象的属性并返回新对象实例
-        /// </summary>
-        /// <param name="obj"></param>
-        /// <param name="propertyNames">属性名集合</param>
-        /// <returns></returns>
-        public static object DeleteProperty(this object obj, List<string> propertyNames)
-        {
-            PropertyInfo[] oldProperties = obj.GetType().GetProperties();
-            Type t = obj.GetType();
-            foreach (string p in propertyNames)
-            {
-                t = t.DeleteProperty(p);
-            }
-            var newInstance = t.CreateInstance();
-            foreach (var p in newInstance.GetProperties())
-            {
-                newInstance.SetProperty(p.Name, oldProperties.FirstOrDefault(i => i.Name.Equals(p.Name)).GetValue(obj));
-            }
-            return newInstance;
-        }
-
-        /// <summary>
-        /// 删除对象的属性并返回新对象实例
-        /// </summary>
-        /// <param name="obj"></param>
-        /// <param name="property">属性名</param>
-        /// <returns></returns>
-        public static object DeleteProperty(this object obj, string property)
-        {
-            return DeleteProperty(obj, new List<string>() { property });
-        }
-        #endregion
-
-        #region 私有方法  
-
-        /// <summary>  
-        /// 把类型的实例t和lcpi参数里的属性进行合并。  
-        /// </summary>  
-        /// <param name="t">实例t</param>  
-        /// <param name="lcpi">里面包含属性列表的信息。</param>  
-        private static void MergeProperty(Type t, List<CustPropertyInfo> lcpi)
-        {
-            foreach (PropertyInfo pi in t.GetProperties())
-            {
-                CustPropertyInfo cpi = new CustPropertyInfo(pi.PropertyType, pi.Name);
-                lcpi.Add(cpi);
-            }
-        }
-
-
-        /// <summary>  
-        /// 从类型的实例t的属性移除属性列表lcpi,返回的新属性列表在lcpi中。  
-        /// </summary>  
-        /// <param name="t">类型的实例t。</param>  
-        /// <param name="ls">要移除的属性列表。</param>  
-        private static List<CustPropertyInfo> SeparateProperty(Type t, List<string> ls)
-        {
-            List<CustPropertyInfo> ret = new List<CustPropertyInfo>();
-            foreach (PropertyInfo pi in t.GetProperties())
-            {
-                foreach (string s in ls)
-                {
-                    if (pi.Name != s)
-                    {
-                        CustPropertyInfo cpi = new CustPropertyInfo(pi.PropertyType, pi.Name);
-                        ret.Add(cpi);
-                    }
-                }
-            }
-
-            return ret;
-        }
-
-
-        /// <summary>  
-        /// 把lcpi参数里的属性加入到myTypeBuilder中。注意:该操作会将其它成员清除掉,其功能有待完善。  
-        /// </summary>  
-        /// <param name="myTypeBuilder">类型构造器的实例。</param>  
-        /// <param name="lcpi">里面包含属性列表的信息。</param>  
-        private static void AddPropertyToTypeBuilder(TypeBuilder myTypeBuilder, List<CustPropertyInfo> lcpi)
-        {
-            // 属性Set和Get方法要一个专门的属性。这里设置为Public。  
-            var getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
-
-            // 添加属性到myTypeBuilder。  
-            foreach (CustPropertyInfo cpi in lcpi)
-            {
-                //定义字段。  
-                FieldBuilder customerNameBldr = myTypeBuilder.DefineField(cpi.FieldName, cpi.Type, FieldAttributes.Private);
-
-                //customerNameBldr.SetConstant("11111111");
-                //定义属性。  
-                //最后一个参数为null,因为属性没有参数。  
-                var custNamePropBldr = myTypeBuilder.DefineProperty(cpi.PropertyName, PropertyAttributes.HasDefault, cpi.Type, null);
-
-                //custNamePropBldr.SetConstant("111111111");
-                //定义Get方法。  
-                var custNameGetPropMthdBldr = myTypeBuilder.DefineMethod(cpi.GetPropertyMethodName, getSetAttr, cpi.Type, Type.EmptyTypes);
-
-                var custNameGetIL = custNameGetPropMthdBldr.GetILGenerator();
-
-                try
-                {
-                    custNameGetIL.Emit(OpCodes.Ldarg_0);
-                    //custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr);  
-                    custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr);
-                    custNameGetIL.Emit(OpCodes.Ret);
-                }
-                catch (Exception)
-                {
-                    // ignored
-                }
-
-                //定义Set方法。  
-                var custNameSetPropMthdBldr = myTypeBuilder.DefineMethod(cpi.SetPropertyMethodName, getSetAttr, null, new[]
-                {
-                    cpi.Type
-                });
-
-                var custNameSetIL = custNameSetPropMthdBldr.GetILGenerator();
-
-                custNameSetIL.Emit(OpCodes.Ldarg_0);
-                custNameSetIL.Emit(OpCodes.Ldarg_1);
-                custNameSetIL.Emit(OpCodes.Stfld, customerNameBldr);
-                custNameSetIL.Emit(OpCodes.Ret);
-                //custNamePropBldr.SetConstant("ceshi");  
-                //把创建的两个方法(Get,Set)加入到PropertyBuilder中。  
-                custNamePropBldr.SetGetMethod(custNameGetPropMthdBldr);
-                custNamePropBldr.SetSetMethod(custNameSetPropMthdBldr);
-            }
-        }
-
-
-        /// <summary>  
-        /// 把属性加入到类型的实例。  
-        /// </summary>  
-        /// <param name="classType">类型的实例。</param>  
-        /// <param name="lcpi">要加入的属性列表。</param>  
-        /// <returns>返回处理过的类型的实例。</returns>  
-        public static Type AddPropertyToType(this Type classType, List<CustPropertyInfo> lcpi)
-        {
-            AssemblyName myAsmName = new AssemblyName
-            {
-                Name = "MyDynamicAssembly"
-            };
-
-            //创建一个程序集,设置为AssemblyBuilderAccess.RunAndCollect。  
-            AssemblyBuilder myAsmBuilder = AssemblyBuilder.DefineDynamicAssembly(myAsmName, AssemblyBuilderAccess.RunAndCollect);
-
-            //创建一个单模程序块。  
-            ModuleBuilder myModBuilder = myAsmBuilder.DefineDynamicModule(myAsmName.Name);
-            //创建TypeBuilder。  
-            // ReSharper disable once AssignNullToNotNullAttribute
-            TypeBuilder myTypeBuilder = myModBuilder.DefineType(classType.FullName, TypeAttributes.Public);
-
-            //把lcpi中定义的属性加入到TypeBuilder。将清空其它的成员。其功能有待扩展,使其不影响其它成员。  
-            AddPropertyToTypeBuilder(myTypeBuilder, lcpi);
-
-            //创建类型。  
-            Type retval = myTypeBuilder.CreateType();
-
-            //保存程序集,以便可以被Ildasm.exe解析,或被测试程序引用。  
-            //myAsmBuilder.Save(myAsmName.Name + ".dll");  
-            return retval;
-        }
-
-        #endregion
-
-        #region 辅助类  
-
-        /// <summary>  
-        /// 自定义的属性信息类型。  
-        /// </summary>  
-        public class CustPropertyInfo
-        {
-            /// <summary>  
-            /// 空构造。  
-            /// </summary>  
-            public CustPropertyInfo()
-            {
-            }
-
-            /// <summary>  
-            /// 根据属性类型名称,属性名称构造实例。  
-            /// </summary>  
-            /// <param name="type">属性类型名称。</param>  
-            /// <param name="propertyName">属性名称。</param>  
-            public CustPropertyInfo(Type type, string propertyName)
-            {
-                Type = type;
-                PropertyName = propertyName;
-            }
-
-            /// <summary>
-            /// 根据属性类型名称,属性名称构造实例,并设置属性值。
-            /// </summary>
-            /// <param name="type"></param>
-            /// <param name="propertyName"></param>
-            /// <param name="propertyValue"></param>
-            public CustPropertyInfo(Type type, string propertyName, object propertyValue) : this(type, propertyName)
-            {
-                PropertyValue = propertyValue;
-            }
-
-            /// <summary>  
-            /// 获取或设置属性类型名称。  
-            /// </summary>  
-            public Type Type { get; set; }
-
-            /// <summary>  
-            /// 获取或设置属性名称。  
-            /// </summary>  
-            public string PropertyName { get; set; }
-
-            /// <summary>
-            /// 属性值
-            /// </summary>
-            public object PropertyValue { get; set; }
-
-            /// <summary>  
-            /// 获取属性字段名称。  
-            /// </summary>  
-            public string FieldName
-            {
-                get
-                {
-                    if (PropertyName.Length < 1)
-                    {
-                        return "";
-                    }
-
-                    return PropertyName.Substring(0, 1).ToLower() + PropertyName.Substring(1);
-                }
-            }
-
-            /// <summary>  
-            /// 获取属性在IL中的Set方法名。  
-            /// </summary>  
-            public string SetPropertyMethodName => "set_" + PropertyName;
-
-
-            /// <summary>  
-            ///  获取属性在IL中的Get方法名。  
-            /// </summary>  
-            public string GetPropertyMethodName => "get_" + PropertyName;
-        }
-
-        #endregion
-    }
-}

+ 0 - 233
Masuit.Tools.Core/Reflection/ReflectHelper.cs

@@ -1,233 +0,0 @@
-using System;
-using System.ComponentModel;
-using System.Drawing;
-using System.IO;
-using System.Reflection;
-using System.Resources;
-using System.Text;
-
-namespace Masuit.Tools.Reflection
-{
-    /// <summary>
-    /// 反射辅助类
-    /// </summary>
-    public static class ReflectHelper
-    {
-        #region 成员读写
-
-        /// <summary>
-        /// 获取实体相关属性的值
-        /// </summary>
-        /// <param name="obj">反射对象</param>
-        /// <param name="propertyName">属性名</param>
-        /// <returns>属性值</returns>
-        public static object GetInstanceValue(this object obj, string propertyName)
-        {
-            object objRet = null;
-            if (!string.IsNullOrEmpty(propertyName))
-            {
-                PropertyDescriptor descriptor = TypeDescriptor.GetProperties(obj).Find(propertyName, true);
-                if (descriptor != null)
-                {
-                    objRet = descriptor.GetValue(obj);
-                }
-            }
-
-            return objRet;
-        }
-
-        #endregion
-
-        #region 方法调用
-
-        /// <summary>
-        /// 直接调用内部对象的方法/函数或获取属性(支持重载调用)
-        /// </summary>
-        /// <typeparam name="T">泛型T</typeparam>
-        /// <param name="refType">目标数据类型</param>
-        /// <param name="funName">函数名称,区分大小写。</param>
-        /// <param name="objInitial">如果调用属性,则为相关对象的初始化数据,否则为Null。</param>
-        /// <param name="funParams">函数参数信息</param>
-        /// <returns>运行结果</returns>
-        /// <exception cref="InvalidProgramException">非法异常</exception>
-        public static T InvokeMethodOrGetProperty<T>(this Type refType, string funName, object[] objInitial, params object[] funParams)
-        {
-            MemberInfo[] mis = refType.GetMember(funName);
-            if (mis.Length < 1)
-            {
-                throw new InvalidProgramException(string.Concat("函数/方法 [", funName, "] 在指定类型(", refType.ToString(), ")中不存在!"));
-            }
-
-            MethodInfo targetMethod = null;
-            StringBuilder pb = new StringBuilder();
-            foreach (MemberInfo mi in mis)
-            {
-                if (mi.MemberType != MemberTypes.Method)
-                {
-                    if (mi.MemberType == MemberTypes.Property)
-                    {
-                        #region 调用属性方法Get
-
-                        targetMethod = ((PropertyInfo)mi).GetGetMethod();
-                        break;
-
-                        #endregion
-                    }
-
-                    throw new InvalidProgramException(string.Concat("[", funName, "] 不是有效的函数/属性方法!"));
-                }
-
-                #region 检查函数参数和数据类型 绑定正确的函数到目标调用
-
-                MethodInfo curMethod = (MethodInfo)mi;
-                ParameterInfo[] pis = curMethod.GetParameters();
-                if (pis.Length == funParams.Length)
-                {
-                    var validParamsLen = true;
-
-                    pb = new StringBuilder();
-                    bool paramFlag = true;
-                    int paramIdx = 0;
-
-                    #region 检查数据类型 设置validParamsType是否有效
-
-                    foreach (ParameterInfo pi in pis)
-                    {
-                        pb.AppendFormat("Parameter {0}: Type={1}, Name={2}\n", paramIdx, pi.ParameterType, pi.Name);
-
-                        //不对Null和接受Object类型的参数检查
-                        if (funParams[paramIdx] != null && pi.ParameterType != typeof(object) && (pi.ParameterType != funParams[paramIdx].GetType()))
-                        {
-                            #region 检查类型是否兼容
-
-                            try
-                            {
-                                funParams[paramIdx] = Convert.ChangeType(funParams[paramIdx], pi.ParameterType);
-                            }
-                            catch (Exception)
-                            {
-                                paramFlag = false;
-                            }
-
-                            #endregion
-
-                            //break;
-                        }
-
-                        ++paramIdx;
-                    }
-
-                    #endregion
-
-                    bool validParamsType;
-                    if (paramFlag)
-                    {
-                        validParamsType = true;
-                    }
-                    else
-                    {
-                        continue;
-                    }
-
-                    if (validParamsLen && validParamsType)
-                    {
-                        targetMethod = curMethod;
-                        break;
-                    }
-                }
-
-                #endregion
-            }
-
-            if (targetMethod != null)
-            {
-                object objReturn;
-
-                #region 兼顾效率和兼容重载函数调用
-
-                try
-                {
-                    object objInstance = Activator.CreateInstance(refType, objInitial);
-                    objReturn = targetMethod.Invoke(objInstance, BindingFlags.InvokeMethod, Type.DefaultBinder, funParams, System.Globalization.CultureInfo.InvariantCulture);
-                }
-                catch (Exception)
-                {
-                    objReturn = refType.InvokeMember(funName, BindingFlags.InvokeMethod, Type.DefaultBinder, null, funParams);
-                }
-
-                #endregion
-
-                return (T)objReturn;
-            }
-
-            throw new InvalidProgramException(string.Concat("函数/方法 [", refType.ToString(), ".", funName, "(args ...) ] 参数长度和数据类型不正确!\n 引用参数信息参考:\n", pb.ToString()));
-        }
-
-        /// <summary>
-        /// 调用相关实体类型的函数方法
-        /// </summary>
-        /// <typeparam name="T">泛型T</typeparam>
-        /// <param name="refType">实体类型</param>
-        /// <param name="funName">函数名称</param>
-        /// <param name="funParams">函数参数列表</param>
-        /// <returns>调用该函数之后的结果</returns>
-        public static T InvokeFunction<T>(this Type refType, string funName, params object[] funParams)
-        {
-            return InvokeMethodOrGetProperty<T>(refType, funName, null, funParams);
-        }
-
-        #endregion
-
-        #region 资源获取
-
-        /// <summary>
-        /// 获取程序集资源的位图资源
-        /// </summary>
-        /// <param name="assemblyType">程序集中的某一对象类型</param>
-        /// <param name="resourceHolder">资源的根名称。例如,名为“MyResource.en-US.resources”的资源文件的根名称为“MyResource”。</param>
-        /// <param name="imageName">资源项名称</param>
-        public static Bitmap LoadBitmap(this Type assemblyType, string resourceHolder, string imageName)
-        {
-            Assembly thisAssembly = Assembly.GetAssembly(assemblyType);
-            var rm = new ResourceManager(resourceHolder, thisAssembly);
-            return (Bitmap)rm.GetObject(imageName);
-        }
-
-        /// <summary>
-        ///  获取程序集资源的文本资源
-        /// </summary>
-        /// <param name="assemblyType">程序集中的某一对象类型</param>
-        /// <param name="resName">资源项名称</param>
-        /// <param name="resourceHolder">资源的根名称。例如,名为“MyResource.en-US.resources”的资源文件的根名称为“MyResource”。</param>
-        public static string GetStringRes(this Type assemblyType, string resName, string resourceHolder)
-        {
-            Assembly thisAssembly = Assembly.GetAssembly(assemblyType);
-            ResourceManager rm = new ResourceManager(resourceHolder, thisAssembly);
-            return rm.GetString(resName);
-        }
-
-        /// <summary>
-        /// 获取程序集嵌入资源的文本形式
-        /// </summary>
-        /// <param name="assemblyType">程序集中的某一对象类型</param>
-        /// <param name="charset">字符集编码</param>
-        /// <param name="resName">嵌入资源相对路径</param>
-        /// <returns>如没找到该资源则返回空字符</returns>
-        public static string GetManifestString(this Type assemblyType, string charset, string resName)
-        {
-            Assembly asm = Assembly.GetAssembly(assemblyType);
-            Stream st = asm.GetManifestResourceStream(string.Concat(assemblyType.Namespace, ".", resName.Replace("/", ".")));
-            if (st == null)
-            {
-                return "";
-            }
-
-            int iLen = (int)st.Length;
-            byte[] bytes = new byte[iLen];
-            st.Read(bytes, 0, iLen);
-            return (bytes != null) ? Encoding.GetEncoding(charset).GetString(bytes) : "";
-        }
-
-        #endregion
-    }
-}

+ 0 - 542
Masuit.Tools.Core/Reflection/ReflectionUtil.cs

@@ -1,542 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Drawing;
-using System.IO;
-using System.Linq;
-using System.Linq.Expressions;
-using System.Reflection;
-using System.Resources;
-using System.Text;
-
-namespace Masuit.Tools.Reflection
-{
-    /// <summary>
-    /// 反射操作辅助类,如获取或设置字段、属性的值等反射信息。
-    /// </summary>
-    public static class ReflectionUtil
-    {
-        #region 属性字段设置
-
-#pragma warning disable 1591
-        public static BindingFlags bf = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
-#pragma warning restore 1591
-
-        /// <summary>
-        /// 执行方法
-        /// </summary>
-        /// <param name="obj">反射对象</param>
-        /// <param name="methodName">方法名,区分大小写</param>
-        /// <param name="args">方法参数</param>
-        /// <typeparam name="T">约束返回的T必须是引用类型</typeparam>
-        /// <returns>T类型</returns>
-        public static T InvokeMethod<T>(this object obj, string methodName, object[] args) where T : class
-        {
-            T objReturn;
-            Type type = obj.GetType();
-            objReturn = type.InvokeMember(methodName, bf | BindingFlags.InvokeMethod, null, obj, args) as T;
-            return objReturn;
-        }
-
-        /// <summary>
-        /// 设置字段
-        /// </summary>
-        /// <param name="obj">反射对象</param>
-        /// <param name="name">字段名</param>
-        /// <param name="value">值</param>
-        public static void SetField(this object obj, string name, object value)
-        {
-            FieldInfo fi = obj.GetType().GetField(name, bf);
-            fi.SetValue(obj, value);
-        }
-
-        /// <summary>
-        /// 获取字段
-        /// </summary>
-        /// <param name="obj">反射对象</param>
-        /// <param name="name">字段名</param>
-        /// <typeparam name="T">约束返回的T必须是引用类型</typeparam>
-        /// <returns>T类型</returns>
-        public static T GetField<T>(this object obj, string name) where T : class
-        {
-            FieldInfo fi = obj.GetType().GetField(name, bf);
-            return fi.GetValue(obj) as T;
-        }
-
-        /// <summary>
-        /// 获取所有的字段信息
-        /// </summary>
-        /// <param name="obj">反射对象</param>
-        /// <returns>字段信息</returns>
-        public static FieldInfo[] GetFields(this object obj)
-        {
-            FieldInfo[] fieldInfos = obj.GetType().GetFields(bf);
-            return fieldInfos;
-        }
-
-        /// <summary>
-        /// 设置属性
-        /// </summary>
-        /// <param name="obj">反射对象</param>
-        /// <param name="name">属性名</param>
-        /// <param name="value">值</param>
-        public static void SetProperty(this object obj, string name, object value)
-        {
-            PropertyInfo fieldInfo = obj.GetType().GetProperty(name, bf);
-            value = Convert.ChangeType(value, fieldInfo.PropertyType);
-            fieldInfo.SetValue(obj, value, null);
-        }
-
-        /// <summary>
-        /// 获取属性
-        /// </summary>
-        /// <param name="obj">反射对象</param>
-        /// <param name="name">属性名</param>
-        /// <typeparam name="T">约束返回的T必须是引用类型</typeparam>
-        /// <returns>T类型</returns>
-        public static T GetProperty<T>(this object obj, string name) where T : class
-        {
-            PropertyInfo fieldInfo = obj.GetType().GetProperty(name, bf);
-            return fieldInfo.GetValue(obj, null) as T;
-        }
-
-        /// <summary>
-        /// 获取所有的属性信息
-        /// </summary>
-        /// <param name="obj">反射对象</param>
-        /// <returns>属性信息</returns>
-        public static PropertyInfo[] GetProperties(this object obj)
-        {
-            PropertyInfo[] propertyInfos = obj.GetType().GetProperties(bf);
-            return propertyInfos;
-        }
-
-        #endregion
-
-        #region 获取Description
-
-        /// <overloads>
-        ///		Get The Member Description using Description Attribute.
-        /// </overloads>
-        /// <summary>
-        /// Get The Enum Field Description using Description Attribute.
-        /// </summary>
-        /// <param name="value">The value.</param>
-        /// <returns>return description or value.ToString()</returns>
-        public static string GetDescription(this Enum value)
-        {
-            return GetDescription(value, null);
-        }
-
-        /// <summary>
-        /// Get The Enum Field Description using Description Attribute and 
-        /// objects to format the Description.
-        /// </summary>
-        /// <param name="value">Enum For Which description is required.</param>
-        /// <param name="args">An Object array containing zero or more objects to format.</param>
-        /// <returns>return null if DescriptionAttribute is not found or return type description</returns>
-        /// <exception cref="ArgumentNullException"><paramref name="value"/>"/> is <c>null</c>.</exception>
-        public static string GetDescription(this Enum value, params object[] args)
-        {
-            if (value == null)
-            {
-                throw new ArgumentNullException(nameof(value));
-            }
-
-            FieldInfo fi = value.GetType().GetField(value.ToString());
-            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
-            var text = attributes.Length > 0 ? attributes[0].Description : value.ToString();
-            if ((args != null) && (args.Length > 0))
-            {
-                return string.Format(null, text, args);
-            }
-
-            return text;
-        }
-
-        /// <summary>
-        ///	Get The Type Description using Description Attribute.
-        /// </summary>
-        /// <param name="member">Specified Member for which Info is Required</param>
-        /// <returns>return null if DescriptionAttribute is not found or return type description</returns>
-        public static string GetDescription(this MemberInfo member)
-        {
-            return GetDescription(member, null);
-        }
-
-        /// <summary>
-        /// Get The Type Description using Description Attribute and 
-        /// objects to format the Description.
-        /// </summary>
-        /// <param name="member"> Specified Member for which Info is Required</param>
-        /// <param name="args">An Object array containing zero or more objects to format.</param>
-        /// <returns>return <see cref="String.Empty"/> if DescriptionAttribute is 
-        /// not found or return type description</returns>
-        /// <exception cref="ArgumentNullException"><paramref name="member"/>"/> is <c>null</c>.</exception>
-        public static string GetDescription(this MemberInfo member, params object[] args)
-        {
-            string text1;
-
-            if (member == null)
-            {
-                throw new ArgumentNullException(nameof(member));
-            }
-
-            if (member.IsDefined(typeof(DescriptionAttribute), false))
-            {
-                DescriptionAttribute[] attributes = (DescriptionAttribute[])member.GetCustomAttributes(typeof(DescriptionAttribute), false);
-                text1 = attributes[0].Description;
-            }
-            else
-            {
-                return string.Empty;
-            }
-
-            if (args != null && args.Length > 0)
-            {
-                return string.Format(null, text1, args);
-            }
-
-            return text1;
-        }
-
-        #endregion
-
-        #region 获取Attribute信息
-
-        /// <overloads>
-        /// Gets the specified object attributes
-        /// </overloads>
-        /// <summary>
-        /// Gets the specified object attributes for assembly as specified by type
-        /// </summary>
-        /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
-        /// <param name="assembly">the assembly in which the specified attribute is defined</param>
-        /// <returns>Attribute as Object or null if not found.</returns>
-        /// <exception cref="ArgumentNullException"><paramref name="attributeType"/>"/> is <c>null</c>.</exception>
-        public static object GetAttribute(this Type attributeType, Assembly assembly)
-        {
-            if (attributeType == null)
-            {
-                throw new ArgumentNullException(nameof(attributeType));
-            }
-
-            if (assembly == null)
-            {
-                throw new ArgumentNullException(nameof(assembly));
-            }
-
-            if (assembly.IsDefined(attributeType, false))
-            {
-                object[] attributes = assembly.GetCustomAttributes(attributeType, false);
-                return attributes[0];
-            }
-
-            return null;
-        }
-
-        /// <summary>
-        /// Gets the specified object attributes for type as specified by type
-        /// </summary>
-        /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
-        /// <param name="type">the type on which the specified attribute is defined</param>
-        /// <returns>Attribute as Object or null if not found.</returns>
-        public static object GetAttribute(this Type attributeType, MemberInfo type)
-        {
-            return GetAttribute(attributeType, type, false);
-        }
-
-        /// <summary>
-        /// Gets the specified object attributes for type as specified by type with option to serach parent
-        /// </summary>
-        /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
-        /// <param name="type">the type on which the specified attribute is defined</param>
-        /// <param name="searchParent">if set to <see langword="true"/> [search parent].</param>
-        /// <returns>
-        /// Attribute as Object or null if not found.
-        /// </returns>
-        public static object GetAttribute(this Type attributeType, MemberInfo type, bool searchParent)
-        {
-            if (type == null)
-            {
-                return null;
-            }
-
-            if (!(attributeType.IsSubclassOf(typeof(Attribute))))
-            {
-                return null;
-            }
-
-            if (type.IsDefined(attributeType, searchParent))
-            {
-                object[] attributes = type.GetCustomAttributes(attributeType, searchParent);
-
-                if (attributes.Length > 0)
-                {
-                    return attributes[0];
-                }
-            }
-
-            return null;
-        }
-
-        /// <summary>
-        /// Gets the collection of all specified object attributes for type as specified by type
-        /// </summary>
-        /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
-        /// <param name="type">the type on which the specified attribute is defined</param>
-        /// <returns>Attribute as Object or null if not found.</returns>
-        public static object[] GetAttributes(this Type attributeType, MemberInfo type)
-        {
-            return GetAttributes(attributeType, type, false);
-        }
-
-        /// <summary>
-        /// Gets the collection of all specified object attributes for type as specified by type with option to serach parent
-        /// </summary>
-        /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
-        /// <param name="type">the type on which the specified attribute is defined</param>
-        /// <param name="searchParent">The attribute Type for which the custom attribute is to be returned.</param>
-        /// <returns>
-        /// Attribute as Object or null if not found.
-        /// </returns>
-        public static object[] GetAttributes(this Type attributeType, MemberInfo type, bool searchParent)
-        {
-            if (type == null)
-            {
-                return null;
-            }
-
-            if (!(attributeType.IsSubclassOf(typeof(Attribute))))
-            {
-                return null;
-            }
-
-            if (type.IsDefined(attributeType, false))
-            {
-                return type.GetCustomAttributes(attributeType, searchParent);
-            }
-
-            return null;
-        }
-
-        #endregion
-
-        #region 资源获取
-
-        /// <summary>
-        /// 根据资源名称获取图片资源流
-        /// </summary>
-        /// <param name="_"></param>
-        /// <param name="resourceName">资源的名称</param>
-        /// <returns>数据流</returns>
-        public static Stream GetImageResource(this Assembly _, string resourceName)
-        {
-            Assembly asm = Assembly.GetExecutingAssembly();
-            return asm.GetManifestResourceStream(resourceName);
-        }
-
-        /// <summary>
-        /// 获取程序集资源的位图资源
-        /// </summary>
-        /// <param name="assemblyType">程序集中的某一对象类型</param>
-        /// <param name="resourceHolder">资源的根名称。例如,名为“MyResource.en-US.resources”的资源文件的根名称为“MyResource”。</param>
-        /// <param name="imageName">资源项名称</param>
-        public static Bitmap LoadBitmap(this Type assemblyType, string resourceHolder, string imageName)
-        {
-            Assembly thisAssembly = Assembly.GetAssembly(assemblyType);
-            ResourceManager rm = new ResourceManager(resourceHolder, thisAssembly);
-            return (Bitmap)rm.GetObject(imageName);
-        }
-
-        /// <summary>
-        ///  获取程序集资源的文本资源
-        /// </summary>
-        /// <param name="assemblyType">程序集中的某一对象类型</param>
-        /// <param name="resName">资源项名称</param>
-        /// <param name="resourceHolder">资源的根名称。例如,名为“MyResource.en-US.resources”的资源文件的根名称为“MyResource”。</param>
-        public static string GetStringRes(this Type assemblyType, string resName, string resourceHolder)
-        {
-            Assembly thisAssembly = Assembly.GetAssembly(assemblyType);
-            ResourceManager rm = new ResourceManager(resourceHolder, thisAssembly);
-            return rm.GetString(resName);
-        }
-
-        /// <summary>
-        /// 获取程序集嵌入资源的文本形式
-        /// </summary>
-        /// <param name="assemblyType">程序集中的某一对象类型</param>
-        /// <param name="charset">字符集编码</param>
-        /// <param name="resName">嵌入资源相对路径</param>
-        /// <returns>如没找到该资源则返回空字符</returns>
-        public static string GetManifestString(this Type assemblyType, string charset, string resName)
-        {
-            Assembly asm = Assembly.GetAssembly(assemblyType);
-            Stream st = asm.GetManifestResourceStream(string.Concat(assemblyType.Namespace, ".", resName.Replace("/", ".")));
-            if (st == null)
-            {
-                return "";
-            }
-
-            int iLen = (int)st.Length;
-            byte[] bytes = new byte[iLen];
-            st.Read(bytes, 0, iLen);
-            return (bytes != null) ? Encoding.GetEncoding(charset).GetString(bytes) : "";
-        }
-
-        #endregion
-
-        #region 创建实例
-
-        /// <summary>
-        /// 获取默认实例
-        /// </summary>
-        /// <param name="type">类型</param>
-        /// <returns></returns>
-        public static object GetInstance(this Type type)
-        {
-            return GetInstance<TypeToIgnore>(type, null);
-        }
-
-        /// <summary>
-        /// 获取默认实例
-        /// </summary>
-        /// <param name="type">类型</param>
-        /// <returns></returns>
-        public static object GetInstance(string type)
-        {
-            return GetInstance<TypeToIgnore>(Type.GetType(type), null);
-        }
-
-        /// <summary>
-        /// 获取一个构造参数的实例
-        /// </summary>
-        /// <typeparam name="TArg">参数类型</typeparam>
-        /// <param name="type">实例类型</param>
-        /// <param name="argument">参数值</param>
-        /// <returns></returns>
-        public static object GetInstance<TArg>(this Type type, TArg argument)
-        {
-            return GetInstance<TArg, TypeToIgnore>(type, argument, null);
-        }
-
-        /// <summary>
-        /// 获取一个构造参数的实例
-        /// </summary>
-        /// <typeparam name="TArg">参数类型</typeparam>
-        /// <param name="type">实例类型</param>
-        /// <param name="argument">参数值</param>
-        /// <returns></returns>
-        public static object GetInstance<TArg>(string type, TArg argument)
-        {
-            return GetInstance<TArg, TypeToIgnore>(Type.GetType(type), argument, null);
-        }
-
-        /// <summary>
-        /// 获取2个构造参数的实例
-        /// </summary>
-        /// <typeparam name="TArg1">参数类型</typeparam>
-        /// <typeparam name="TArg2">参数类型</typeparam>
-        /// <param name="type">实例类型</param>
-        /// <param name="argument1">参数值</param>
-        /// <param name="argument2">参数值</param>
-        /// <returns></returns>
-        public static object GetInstance<TArg1, TArg2>(this Type type, TArg1 argument1, TArg2 argument2)
-        {
-            return GetInstance<TArg1, TArg2, TypeToIgnore>(type, argument1, argument2, null);
-        }
-
-        /// <summary>
-        /// 获取2个构造参数的实例
-        /// </summary>
-        /// <typeparam name="TArg1">参数类型</typeparam>
-        /// <typeparam name="TArg2">参数类型</typeparam>
-        /// <param name="type">实例类型</param>
-        /// <param name="argument1">参数值</param>
-        /// <param name="argument2">参数值</param>
-        /// <returns></returns>
-        public static object GetInstance<TArg1, TArg2>(string type, TArg1 argument1, TArg2 argument2)
-        {
-            return GetInstance<TArg1, TArg2, TypeToIgnore>(Type.GetType(type), argument1, argument2, null);
-        }
-
-        /// <summary>
-        /// 获取3个构造参数的实例
-        /// </summary>
-        /// <typeparam name="TArg1">参数类型</typeparam>
-        /// <typeparam name="TArg2">参数类型</typeparam>
-        /// <typeparam name="TArg3">参数类型</typeparam>
-        /// <param name="type">实例类型</param>
-        /// <param name="argument1">参数值</param>
-        /// <param name="argument2">参数值</param>
-        /// <param name="argument3">参数值</param>
-        /// <returns></returns>
-        public static object GetInstance<TArg1, TArg2, TArg3>(this Type type, TArg1 argument1, TArg2 argument2, TArg3 argument3)
-        {
-            return InstanceCreationFactory<TArg1, TArg2, TArg3>.CreateInstanceOf(type, argument1, argument2, argument3);
-        }
-
-        /// <summary>
-        /// 获取3个构造参数的实例
-        /// </summary>
-        /// <typeparam name="TArg1">参数类型</typeparam>
-        /// <typeparam name="TArg2">参数类型</typeparam>
-        /// <typeparam name="TArg3">参数类型</typeparam>
-        /// <param name="type">实例类型</param>
-        /// <param name="argument1">参数值</param>
-        /// <param name="argument2">参数值</param>
-        /// <param name="argument3">参数值</param>
-        /// <returns></returns>
-        public static object GetInstance<TArg1, TArg2, TArg3>(string type, TArg1 argument1, TArg2 argument2, TArg3 argument3)
-        {
-            return InstanceCreationFactory<TArg1, TArg2, TArg3>.CreateInstanceOf(Type.GetType(type), argument1, argument2, argument3);
-        }
-
-        private class TypeToIgnore
-        {
-        }
-
-        private static class InstanceCreationFactory<TArg1, TArg2, TArg3>
-        {
-            private static readonly Dictionary<Type, Func<TArg1, TArg2, TArg3, object>> InstanceCreationMethods = new Dictionary<Type, Func<TArg1, TArg2, TArg3, object>>();
-
-            public static object CreateInstanceOf(Type type, TArg1 arg1, TArg2 arg2, TArg3 arg3)
-            {
-                CacheInstanceCreationMethodIfRequired(type);
-
-                return InstanceCreationMethods[type].Invoke(arg1, arg2, arg3);
-            }
-
-            private static void CacheInstanceCreationMethodIfRequired(Type type)
-            {
-                if (InstanceCreationMethods.ContainsKey(type))
-                {
-                    return;
-                }
-
-                var argumentTypes = new[]
-                {
-                    typeof(TArg1),
-                    typeof(TArg2),
-                    typeof(TArg3)
-                };
-
-                Type[] constructorArgumentTypes = argumentTypes.Where(t => t != typeof(TypeToIgnore)).ToArray();
-                var constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, CallingConventions.HasThis, constructorArgumentTypes, new ParameterModifier[0]);
-
-                var lamdaParameterExpressions = new[]
-                {
-                    Expression.Parameter(typeof(TArg1), "param1"),
-                    Expression.Parameter(typeof(TArg2), "param2"),
-                    Expression.Parameter(typeof(TArg3), "param3")
-                };
-
-                var constructorParameterExpressions = lamdaParameterExpressions.Take(constructorArgumentTypes.Length).ToArray();
-                var constructorCallExpression = Expression.New(constructor, constructorParameterExpressions);
-                var constructorCallingLambda = Expression.Lambda<Func<TArg1, TArg2, TArg3, object>>(constructorCallExpression, lamdaParameterExpressions).Compile();
-                InstanceCreationMethods[type] = constructorCallingLambda;
-            }
-        }
-        #endregion
-    }
-}

+ 0 - 1536
Masuit.Tools.Core/Security/Encrypt.cs

@@ -1,1536 +0,0 @@
-using System;
-using System.Collections;
-using System.IO;
-using System.Security.Cryptography;
-using System.Text;
-
-namespace Masuit.Tools.Security
-{
-    /// <summary>
-    /// 常用的加密解密算法
-    /// </summary>
-    public static class Encrypt
-    {
-        #region DES对称加密解密
-
-        /// <summary>
-        /// 加密密钥,需要在config配置文件中AppSettings节点中配置desSecret值,若未配置,默认取“masuit”的MD5值
-        /// </summary>
-        public static string DefaultEncryptKey = "masuit".MDString2();
-
-        /// <summary>
-        /// 使用默认加密
-        /// </summary>
-        /// <param name="strText">被加密的字符串</param>
-        /// <returns>加密后的数据</returns>
-        public static string DesEncrypt(this string strText)
-        {
-            try
-            {
-                return DesEncrypt(strText, DefaultEncryptKey);
-            }
-            catch
-            {
-                return "";
-            }
-        }
-
-        /// <summary>
-        /// 使用默认解密
-        /// </summary>
-        /// <param name="strText">需要解密的 字符串</param>
-        /// <returns>解密后的数据</returns>
-        public static string DesDecrypt(this string strText)
-        {
-            try
-            {
-                return DesDecrypt(strText, DefaultEncryptKey);
-            }
-            catch
-            {
-                return "";
-            }
-        }
-
-        /// <summary> 
-        /// 解密字符串
-        /// 加密密钥必须为8位
-        /// </summary> 
-        /// <param name="strText">被解密的字符串</param> 
-        /// <param name="strEncrKey">密钥</param> 
-        /// <returns>解密后的数据</returns> 
-        public static string DesEncrypt(this string strText, string strEncrKey)
-        {
-            if (strEncrKey.Length < 8)
-            {
-                throw new Exception("密钥长度无效,密钥必须是8位!");
-            }
-
-            StringBuilder ret = new StringBuilder();
-            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
-            byte[] inputByteArray = Encoding.Default.GetBytes(strText);
-            des.Key = Encoding.ASCII.GetBytes(strEncrKey.Substring(0, 8));
-            des.IV = Encoding.ASCII.GetBytes(strEncrKey.Substring(0, 8));
-            MemoryStream ms = new MemoryStream();
-            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
-            cs.Write(inputByteArray, 0, inputByteArray.Length);
-            cs.FlushFinalBlock();
-            foreach (byte b in ms.ToArray())
-            {
-                ret.AppendFormat($"{b:X2}");
-            }
-
-            return ret.ToString();
-        }
-
-        /// <summary>
-        /// DES加密文件
-        /// </summary>
-        /// <param name="fin">文件输入流</param>
-        /// <param name="outFilePath">文件输出路径</param>
-        /// <param name="strEncrKey">加密密钥</param>
-        public static void DesEncrypt(this FileStream fin, string outFilePath, string strEncrKey)
-        {
-            byte[] iv =
-            {
-                0x12,
-                0x34,
-                0x56,
-                0x78,
-                0x90,
-                0xAB,
-                0xCD,
-                0xEF
-            };
-            var byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
-            using var fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write);
-            fout.SetLength(0);
-            byte[] bin = new byte[100];
-            long rdlen = 0;
-            long totlen = fin.Length;
-            DES des = new DESCryptoServiceProvider();
-            var encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, iv), CryptoStreamMode.Write);
-            while (rdlen < totlen)
-            {
-                var len = fin.Read(bin, 0, 100);
-                encStream.Write(bin, 0, len);
-                rdlen += len;
-            }
-        }
-
-        /// <summary>
-        /// DES解密文件
-        /// </summary>
-        /// <param name="fin">输入文件流</param>
-        /// <param name="outFilePath">文件输出路径</param>
-        /// <param name="sDecrKey">解密密钥</param>
-        public static void DesDecrypt(this FileStream fin, string outFilePath, string sDecrKey)
-        {
-            byte[] iv =
-            {
-                0x12,
-                0x34,
-                0x56,
-                0x78,
-                0x90,
-                0xAB,
-                0xCD,
-                0xEF
-            };
-            var byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
-            using var fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write);
-            fout.SetLength(0);
-            byte[] bin = new byte[100];
-            long rdlen = 0;
-            long totlen = fin.Length;
-            DES des = new DESCryptoServiceProvider();
-            var encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, iv), CryptoStreamMode.Write);
-            while (rdlen < totlen)
-            {
-                var len = fin.Read(bin, 0, 100);
-                encStream.Write(bin, 0, len);
-                rdlen += len;
-            }
-        }
-
-        /// <summary>
-        ///     DES解密算法
-        ///     密钥为8位
-        /// </summary>
-        /// <param name="pToDecrypt">需要解密的字符串</param>
-        /// <param name="sKey">密钥</param>
-        /// <returns>解密后的数据</returns>
-        public static string DesDecrypt(this string pToDecrypt, string sKey)
-        {
-            if (sKey.Length < 8)
-            {
-                throw new Exception("密钥长度无效,密钥必须是8位!");
-            }
-
-            var ms = new MemoryStream();
-
-            var des = new DESCryptoServiceProvider();
-            var inputByteArray = new byte[pToDecrypt.Length / 2];
-            for (int x = 0; x < pToDecrypt.Length / 2; x++)
-            {
-                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
-                inputByteArray[x] = (byte)i;
-            }
-
-            des.Key = Encoding.ASCII.GetBytes(sKey.Substring(0, 8));
-            des.IV = Encoding.ASCII.GetBytes(sKey.Substring(0, 8));
-            var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
-            cs.Write(inputByteArray, 0, inputByteArray.Length);
-            cs.FlushFinalBlock();
-            return Encoding.Default.GetString(ms.ToArray());
-        }
-
-        #endregion
-
-        #region 对称加密算法AES RijndaelManaged加密解密
-
-        private static readonly string Default_AES_Key = "@#kim123";
-
-        private static byte[] Keys =
-        {
-            0x41,
-            0x72,
-            0x65,
-            0x79,
-            0x6F,
-            0x75,
-            0x6D,
-            0x79,
-            0x53,
-            0x6E,
-            0x6F,
-            0x77,
-            0x6D,
-            0x61,
-            0x6E,
-            0x3F
-        };
-
-        /// <summary>
-        /// 对称加密算法AES RijndaelManaged加密(RijndaelManaged(AES)算法是块式加密算法)
-        /// </summary>
-        /// <param name="encryptString">待加密字符串</param>
-        /// <returns>加密结果字符串</returns>
-        public static string AESEncrypt(this string encryptString)
-        {
-            return AESEncrypt(encryptString, Default_AES_Key);
-        }
-
-        /// <summary>
-        /// 对称加密算法AES RijndaelManaged加密(RijndaelManaged(AES)算法是块式加密算法)
-        /// </summary>
-        /// <param name="encryptString">待加密字符串</param>
-        /// <param name="encryptKey">加密密钥,须半角字符</param>
-        /// <returns>加密结果字符串</returns>
-        public static string AESEncrypt(this string encryptString, string encryptKey)
-        {
-            encryptKey = GetSubString(encryptKey, 32, "");
-            encryptKey = encryptKey.PadRight(32, ' ');
-            var rijndaelProvider = new RijndaelManaged
-            {
-                Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32)),
-                IV = Keys
-            };
-            ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();
-            byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
-            byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);
-            return Convert.ToBase64String(encryptedData);
-        }
-
-        /// <summary>
-        /// 对称加密算法AES RijndaelManaged解密字符串
-        /// </summary>
-        /// <param name="decryptString">待解密的字符串</param>
-        /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
-        public static string AESDecrypt(this string decryptString)
-        {
-            return AESDecrypt(decryptString, Default_AES_Key);
-        }
-
-        /// <summary>
-        /// 对称加密算法AES RijndaelManaged解密字符串
-        /// </summary>
-        /// <param name="decryptString">待解密的字符串</param>
-        /// <param name="decryptKey">解密密钥,和加密密钥相同</param>
-        /// <returns>解密成功返回解密后的字符串,失败返回空</returns>
-        public static string AESDecrypt(this string decryptString, string decryptKey)
-        {
-            try
-            {
-                decryptKey = GetSubString(decryptKey, 32, "");
-                decryptKey = decryptKey.PadRight(32, ' ');
-                var rijndaelProvider = new RijndaelManaged()
-                {
-                    Key = Encoding.UTF8.GetBytes(decryptKey),
-                    IV = Keys
-                };
-                ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();
-                byte[] inputData = Convert.FromBase64String(decryptString);
-                byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);
-                return Encoding.UTF8.GetString(decryptedData);
-            }
-            catch
-            {
-                return string.Empty;
-            }
-        }
-
-        /// <summary>
-        /// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分
-        /// </summary>
-        /// <param name="sourceString">源字符串</param>
-        /// <param name="length">所取字符串字节长度</param>
-        /// <param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,一般为"...")</param>
-        /// <returns>某字符串的一部分</returns>
-        private static string GetSubString(this string sourceString, int length, string tailString)
-        {
-            return GetSubString(sourceString, 0, length, tailString);
-        }
-
-        /// <summary>
-        /// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分
-        /// </summary>
-        /// <param name="sourceString">源字符串</param>
-        /// <param name="startIndex">索引位置,以0开始</param>
-        /// <param name="length">所取字符串字节长度</param>
-        /// <param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,一般为"...")</param>
-        /// <returns>某字符串的一部分</returns>
-        private static string GetSubString(this string sourceString, int startIndex, int length, string tailString)
-        {
-            //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3)
-            if (System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[\u0800-\u4e00]+") || System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[\xAC00-\xD7A3]+"))
-            {
-                //当截取的起始位置超出字段串长度时
-                if (startIndex >= sourceString.Length)
-                {
-                    return string.Empty;
-                }
-
-                return sourceString.Substring(startIndex, length + startIndex > sourceString.Length ? (sourceString.Length - startIndex) : length);
-            }
-
-            //中文字符,如"中国人民abcd123"
-            if (length <= 0)
-            {
-                return string.Empty;
-            }
-
-            byte[] bytesSource = Encoding.Default.GetBytes(sourceString);
-
-            //当字符串长度大于起始位置
-            if (bytesSource.Length > startIndex)
-            {
-                int endIndex = bytesSource.Length;
-
-                //当要截取的长度在字符串的有效长度范围内
-                if (bytesSource.Length > (startIndex + length))
-                {
-                    endIndex = length + startIndex;
-                }
-                else
-                {
-                    //当不在有效范围内时,只取到字符串的结尾
-                    length = bytesSource.Length - startIndex;
-                    tailString = "";
-                }
-
-                var anResultFlag = new int[length];
-                int nFlag = 0;
-                //字节大于127为双字节字符
-                for (int i = startIndex; i < endIndex; i++)
-                {
-                    if (bytesSource[i] > 127)
-                    {
-                        nFlag++;
-                        if (nFlag == 3)
-                        {
-                            nFlag = 1;
-                        }
-                    }
-                    else
-                    {
-                        nFlag = 0;
-                    }
-
-                    anResultFlag[i] = nFlag;
-                }
-
-                //最后一个字节为双字节字符的一半
-                if ((bytesSource[endIndex - 1] > 127) && (anResultFlag[length - 1] == 1))
-                {
-                    length++;
-                }
-
-                byte[] bsResult = new byte[length];
-                Array.Copy(bytesSource, startIndex, bsResult, 0, length);
-                var myResult = Encoding.Default.GetString(bsResult);
-                myResult += tailString;
-                return myResult;
-            }
-
-            return string.Empty;
-        }
-
-        /// <summary>
-        /// 加密文件流
-        /// </summary>
-        /// <param name="fs">需要加密的文件流</param>
-        /// <param name="decryptKey">加密密钥</param>
-        /// <returns>加密流</returns>
-        public static CryptoStream AESEncryptStrream(this FileStream fs, string decryptKey)
-        {
-            decryptKey = GetSubString(decryptKey, 32, "");
-            decryptKey = decryptKey.PadRight(32, ' ');
-            var rijndaelProvider = new RijndaelManaged()
-            {
-                Key = Encoding.UTF8.GetBytes(decryptKey),
-                IV = Keys
-            };
-            ICryptoTransform encrypto = rijndaelProvider.CreateEncryptor();
-            return new CryptoStream(fs, encrypto, CryptoStreamMode.Write);
-        }
-
-        /// <summary>
-        /// 解密文件流
-        /// </summary>
-        /// <param name="fs">需要解密的文件流</param>
-        /// <param name="decryptKey">解密密钥</param>
-        /// <returns>加密流</returns>
-        public static CryptoStream AESDecryptStream(this FileStream fs, string decryptKey)
-        {
-            decryptKey = GetSubString(decryptKey, 32, "");
-            decryptKey = decryptKey.PadRight(32, ' ');
-            var rijndaelProvider = new RijndaelManaged()
-            {
-                Key = Encoding.UTF8.GetBytes(decryptKey),
-                IV = Keys
-            };
-            var decrypto = rijndaelProvider.CreateDecryptor();
-            return new CryptoStream(fs, decrypto, CryptoStreamMode.Read);
-        }
-
-        /// <summary>
-        /// 对指定文件AES加密
-        /// </summary>
-        /// <param name="input">源文件流</param>
-        /// <param name="outputPath">输出文件路径</param>
-        public static void AESEncryptFile(this FileStream input, string outputPath)
-        {
-            using var fren = new FileStream(outputPath, FileMode.Create);
-            var enfr = AESEncryptStrream(fren, Default_AES_Key);
-            byte[] bytearrayinput = new byte[input.Length];
-            input.Read(bytearrayinput, 0, bytearrayinput.Length);
-            enfr.Write(bytearrayinput, 0, bytearrayinput.Length);
-        }
-
-        /// <summary>
-        /// 对指定的文件AES解密
-        /// </summary>
-        /// <param name="input">源文件流</param>
-        /// <param name="outputPath">输出文件路径</param>
-        public static void AESDecryptFile(this FileStream input, string outputPath)
-        {
-            FileStream frde = new FileStream(outputPath, FileMode.Create);
-            CryptoStream defr = AESDecryptStream(input, Default_AES_Key);
-            byte[] bytearrayoutput = new byte[1024];
-            while (true)
-            {
-                var count = defr.Read(bytearrayoutput, 0, bytearrayoutput.Length);
-                frde.Write(bytearrayoutput, 0, count);
-                if (count < bytearrayoutput.Length)
-                {
-                    break;
-                }
-            }
-        }
-
-        #endregion
-
-        #region Base64加密解密
-
-        /// <summary>
-        /// Base64加密
-        /// </summary>
-        /// <param name="str">需要加密的字符串</param>
-        /// <returns>加密后的数据</returns>
-        public static string Base64Encrypt(this string str)
-        {
-            byte[] encbuff = Encoding.UTF8.GetBytes(str);
-            return Convert.ToBase64String(encbuff);
-        }
-
-        /// <summary>
-        /// Base64解密
-        /// </summary>
-        /// <param name="str">需要解密的字符串</param>
-        /// <returns>解密后的数据</returns>
-        public static string Base64Decrypt(this string str)
-        {
-            byte[] decbuff = Convert.FromBase64String(str);
-            return Encoding.UTF8.GetString(decbuff);
-        }
-
-        #endregion
-
-        #region MD5加密
-
-        /// <summary> 
-        /// MD5加密
-        /// </summary> 
-        /// <param name="strText">原数据</param> 
-        /// <returns>MD5字符串</returns> 
-        public static string MD5Encrypt(this string strText)
-        {
-            MD5 md5 = new MD5CryptoServiceProvider();
-            byte[] result = md5.ComputeHash(Encoding.Default.GetBytes(strText));
-            return Encoding.Default.GetString(result);
-        }
-
-        #endregion
-
-        /// <summary>
-        /// SHA256函数
-        /// </summary>
-        /// <param name="str">原始字符串</param>
-        /// <returns>SHA256结果(返回长度为44字节的字符串)</returns>
-        public static string SHA256(this string str)
-        {
-            byte[] sha256Data = Encoding.UTF8.GetBytes(str);
-            var sha256 = new SHA256Managed();
-            byte[] result = sha256.ComputeHash(sha256Data);
-            return Convert.ToBase64String(result); //返回长度为44字节的字符串
-        }
-
-        #region 创建Key
-
-        /// <summary>
-        ///     创建Key
-        /// </summary>
-        /// <returns>密钥</returns>
-        public static string GenerateKey()
-        {
-            var desCrypto = (DESCryptoServiceProvider)DES.Create();
-            return Encoding.ASCII.GetString(desCrypto.Key);
-        }
-
-        #endregion
-
-        #region MD5加密
-
-        /// <summary>
-        ///     MD5加密
-        /// </summary>
-        /// <param name="pToEncrypt">加密字符串</param>
-        /// <param name="sKey">密钥Key</param>
-        /// <returns>加密后的字符串</returns>
-        public static string MD5Encrypt(this string pToEncrypt, string sKey)
-        {
-            var des = new DESCryptoServiceProvider();
-            var inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
-            des.Key = Encoding.ASCII.GetBytes(sKey);
-            des.IV = Encoding.ASCII.GetBytes(sKey);
-            var ms = new MemoryStream();
-            var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
-            cs.Write(inputByteArray, 0, inputByteArray.Length);
-            cs.FlushFinalBlock();
-            var ret = new StringBuilder();
-            foreach (var b in ms.ToArray())
-            {
-                ret.AppendFormat("{0:X2}", b);
-            }
-
-            ret.ToString();
-            return ret.ToString();
-        }
-
-        #endregion
-
-        #region MD5解密
-
-        /// <summary>
-        ///     MD5解密
-        /// </summary>
-        /// <param name="pToDecrypt">解密字符串</param>
-        /// <param name="sKey">密钥Key</param>
-        /// <returns>解密后的数据</returns>
-        public static string MD5Decrypt(this string pToDecrypt, string sKey)
-        {
-            var des = new DESCryptoServiceProvider();
-
-            var inputByteArray = new byte[pToDecrypt.Length / 2];
-            for (var x = 0; x < pToDecrypt.Length / 2; x++)
-            {
-                var i = Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16);
-                inputByteArray[x] = (byte)i;
-            }
-
-            des.Key = Encoding.ASCII.GetBytes(sKey);
-            des.IV = Encoding.ASCII.GetBytes(sKey);
-            var ms = new MemoryStream();
-            var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
-            cs.Write(inputByteArray, 0, inputByteArray.Length);
-            cs.FlushFinalBlock();
-            return Encoding.Default.GetString(ms.ToArray());
-        }
-
-        #endregion
-
-        #region MD5加密算法
-
-        //number of bits to rotate in tranforming
-        private const int S11 = 7;
-
-        private const int S12 = 12;
-        private const int S13 = 17;
-        private const int S14 = 22;
-        private const int S21 = 5;
-        private const int S22 = 9;
-        private const int S23 = 14;
-        private const int S24 = 20;
-        private const int S31 = 4;
-        private const int S32 = 11;
-        private const int S33 = 16;
-        private const int S34 = 23;
-        private const int S41 = 6;
-        private const int S42 = 10;
-        private const int S43 = 15;
-        private const int S44 = 21;
-
-        //static state variables
-        private static uint A;
-
-        private static uint B;
-        private static uint C;
-        private static uint D;
-
-        private static uint F(uint x, uint y, uint z)
-        {
-            return (x & y) | (~x & z);
-        }
-
-        private static uint G(uint x, uint y, uint z)
-        {
-            return (x & z) | (y & ~z);
-        }
-
-        private static uint H(uint x, uint y, uint z)
-        {
-            return x ^ y ^ z;
-        }
-
-        private static uint I(uint x, uint y, uint z)
-        {
-            return y ^ (x | ~z);
-        }
-
-        private static void FF(ref uint a, uint b, uint c, uint d, uint mj, int s, uint ti)
-        {
-            a = a + F(b, c, d) + mj + ti;
-            a = (a << s) | (a >> (32 - s));
-            a += b;
-        }
-
-        private static void GG(ref uint a, uint b, uint c, uint d, uint mj, int s, uint ti)
-        {
-            a = a + G(b, c, d) + mj + ti;
-            a = (a << s) | (a >> (32 - s));
-            a += b;
-        }
-
-        private static void HH(ref uint a, uint b, uint c, uint d, uint mj, int s, uint ti)
-        {
-            a = a + H(b, c, d) + mj + ti;
-            a = (a << s) | (a >> (32 - s));
-            a += b;
-        }
-
-        private static void II(ref uint a, uint b, uint c, uint d, uint mj, int s, uint ti)
-        {
-            a = a + I(b, c, d) + mj + ti;
-            a = (a << s) | (a >> (32 - s));
-            a += b;
-        }
-
-        private static void MD5_Init()
-        {
-            A = 0x67452301; //in memory, this is 0x01234567
-            B = 0xefcdab89; //in memory, this is 0x89abcdef
-            C = 0x98badcfe; //in memory, this is 0xfedcba98
-            D = 0x10325476; //in memory, this is 0x76543210
-        }
-
-        private static uint[] MD5_Append(byte[] input)
-        {
-            int zeros;
-            var ones = 1;
-            int size;
-            var n = input.Length;
-            var m = n % 64;
-            if (m < 56)
-            {
-                zeros = 55 - m;
-                size = n - m + 64;
-            }
-            else if (m == 56)
-            {
-                zeros = 0;
-                ones = 0;
-                size = n + 8;
-            }
-            else
-            {
-                zeros = 63 - m + 56;
-                size = n + 64 - m + 64;
-            }
-
-            var bs = new ArrayList(input);
-            if (ones == 1)
-                bs.Add((byte)0x80); // 0x80 = $10000000
-            for (var i = 0; i < zeros; i++)
-                bs.Add((byte)0);
-
-            var N = (ulong)n * 8;
-            var h1 = (byte)(N & 0xFF);
-            var h2 = (byte)((N >> 8) & 0xFF);
-            var h3 = (byte)((N >> 16) & 0xFF);
-            var h4 = (byte)((N >> 24) & 0xFF);
-            var h5 = (byte)((N >> 32) & 0xFF);
-            var h6 = (byte)((N >> 40) & 0xFF);
-            var h7 = (byte)((N >> 48) & 0xFF);
-            var h8 = (byte)(N >> 56);
-            bs.Add(h1);
-            bs.Add(h2);
-            bs.Add(h3);
-            bs.Add(h4);
-            bs.Add(h5);
-            bs.Add(h6);
-            bs.Add(h7);
-            bs.Add(h8);
-            var ts = (byte[])bs.ToArray(typeof(byte));
-
-            /* Decodes input (byte[]) into output (UInt32[]). Assumes len is
-            * a multiple of 4.
-           */
-            var output = new uint[size / 4];
-            for (long i = 0, j = 0; i < size; j++, i += 4)
-                output[j] = (uint)(ts[i] | (ts[i + 1] << 8) | (ts[i + 2] << 16) | (ts[i + 3] << 24));
-            return output;
-        }
-
-        private static uint[] MD5_Trasform(uint[] x)
-        {
-            uint a, b, c, d;
-
-            for (var k = 0; k < x.Length; k += 16)
-            {
-                a = A;
-                b = B;
-                c = C;
-                d = D;
-
-                /* Round 1 */
-                FF(ref a, b, c, d, x[k + 0], S11, 0xd76aa478); /* 1 */
-                FF(ref d, a, b, c, x[k + 1], S12, 0xe8c7b756); /* 2 */
-                FF(ref c, d, a, b, x[k + 2], S13, 0x242070db); /* 3 */
-                FF(ref b, c, d, a, x[k + 3], S14, 0xc1bdceee); /* 4 */
-                FF(ref a, b, c, d, x[k + 4], S11, 0xf57c0faf); /* 5 */
-                FF(ref d, a, b, c, x[k + 5], S12, 0x4787c62a); /* 6 */
-                FF(ref c, d, a, b, x[k + 6], S13, 0xa8304613); /* 7 */
-                FF(ref b, c, d, a, x[k + 7], S14, 0xfd469501); /* 8 */
-                FF(ref a, b, c, d, x[k + 8], S11, 0x698098d8); /* 9 */
-                FF(ref d, a, b, c, x[k + 9], S12, 0x8b44f7af); /* 10 */
-                FF(ref c, d, a, b, x[k + 10], S13, 0xffff5bb1); /* 11 */
-                FF(ref b, c, d, a, x[k + 11], S14, 0x895cd7be); /* 12 */
-                FF(ref a, b, c, d, x[k + 12], S11, 0x6b901122); /* 13 */
-                FF(ref d, a, b, c, x[k + 13], S12, 0xfd987193); /* 14 */
-                FF(ref c, d, a, b, x[k + 14], S13, 0xa679438e); /* 15 */
-                FF(ref b, c, d, a, x[k + 15], S14, 0x49b40821); /* 16 */
-
-                /* Round 2 */
-                GG(ref a, b, c, d, x[k + 1], S21, 0xf61e2562); /* 17 */
-                GG(ref d, a, b, c, x[k + 6], S22, 0xc040b340); /* 18 */
-                GG(ref c, d, a, b, x[k + 11], S23, 0x265e5a51); /* 19 */
-                GG(ref b, c, d, a, x[k + 0], S24, 0xe9b6c7aa); /* 20 */
-                GG(ref a, b, c, d, x[k + 5], S21, 0xd62f105d); /* 21 */
-                GG(ref d, a, b, c, x[k + 10], S22, 0x2441453); /* 22 */
-                GG(ref c, d, a, b, x[k + 15], S23, 0xd8a1e681); /* 23 */
-                GG(ref b, c, d, a, x[k + 4], S24, 0xe7d3fbc8); /* 24 */
-                GG(ref a, b, c, d, x[k + 9], S21, 0x21e1cde6); /* 25 */
-                GG(ref d, a, b, c, x[k + 14], S22, 0xc33707d6); /* 26 */
-                GG(ref c, d, a, b, x[k + 3], S23, 0xf4d50d87); /* 27 */
-                GG(ref b, c, d, a, x[k + 8], S24, 0x455a14ed); /* 28 */
-                GG(ref a, b, c, d, x[k + 13], S21, 0xa9e3e905); /* 29 */
-                GG(ref d, a, b, c, x[k + 2], S22, 0xfcefa3f8); /* 30 */
-                GG(ref c, d, a, b, x[k + 7], S23, 0x676f02d9); /* 31 */
-                GG(ref b, c, d, a, x[k + 12], S24, 0x8d2a4c8a); /* 32 */
-
-                /* Round 3 */
-                HH(ref a, b, c, d, x[k + 5], S31, 0xfffa3942); /* 33 */
-                HH(ref d, a, b, c, x[k + 8], S32, 0x8771f681); /* 34 */
-                HH(ref c, d, a, b, x[k + 11], S33, 0x6d9d6122); /* 35 */
-                HH(ref b, c, d, a, x[k + 14], S34, 0xfde5380c); /* 36 */
-                HH(ref a, b, c, d, x[k + 1], S31, 0xa4beea44); /* 37 */
-                HH(ref d, a, b, c, x[k + 4], S32, 0x4bdecfa9); /* 38 */
-                HH(ref c, d, a, b, x[k + 7], S33, 0xf6bb4b60); /* 39 */
-                HH(ref b, c, d, a, x[k + 10], S34, 0xbebfbc70); /* 40 */
-                HH(ref a, b, c, d, x[k + 13], S31, 0x289b7ec6); /* 41 */
-                HH(ref d, a, b, c, x[k + 0], S32, 0xeaa127fa); /* 42 */
-                HH(ref c, d, a, b, x[k + 3], S33, 0xd4ef3085); /* 43 */
-                HH(ref b, c, d, a, x[k + 6], S34, 0x4881d05); /* 44 */
-                HH(ref a, b, c, d, x[k + 9], S31, 0xd9d4d039); /* 45 */
-                HH(ref d, a, b, c, x[k + 12], S32, 0xe6db99e5); /* 46 */
-                HH(ref c, d, a, b, x[k + 15], S33, 0x1fa27cf8); /* 47 */
-                HH(ref b, c, d, a, x[k + 2], S34, 0xc4ac5665); /* 48 */
-
-                /* Round 4 */
-                II(ref a, b, c, d, x[k + 0], S41, 0xf4292244); /* 49 */
-                II(ref d, a, b, c, x[k + 7], S42, 0x432aff97); /* 50 */
-                II(ref c, d, a, b, x[k + 14], S43, 0xab9423a7); /* 51 */
-                II(ref b, c, d, a, x[k + 5], S44, 0xfc93a039); /* 52 */
-                II(ref a, b, c, d, x[k + 12], S41, 0x655b59c3); /* 53 */
-                II(ref d, a, b, c, x[k + 3], S42, 0x8f0ccc92); /* 54 */
-                II(ref c, d, a, b, x[k + 10], S43, 0xffeff47d); /* 55 */
-                II(ref b, c, d, a, x[k + 1], S44, 0x85845dd1); /* 56 */
-                II(ref a, b, c, d, x[k + 8], S41, 0x6fa87e4f); /* 57 */
-                II(ref d, a, b, c, x[k + 15], S42, 0xfe2ce6e0); /* 58 */
-                II(ref c, d, a, b, x[k + 6], S43, 0xa3014314); /* 59 */
-                II(ref b, c, d, a, x[k + 13], S44, 0x4e0811a1); /* 60 */
-                II(ref a, b, c, d, x[k + 4], S41, 0xf7537e82); /* 61 */
-                II(ref d, a, b, c, x[k + 11], S42, 0xbd3af235); /* 62 */
-                II(ref c, d, a, b, x[k + 2], S43, 0x2ad7d2bb); /* 63 */
-                II(ref b, c, d, a, x[k + 9], S44, 0xeb86d391); /* 64 */
-
-                A += a;
-                B += b;
-                C += c;
-                D += d;
-            }
-
-            return new[]
-            {
-                A,
-                B,
-                C,
-                D
-            };
-        }
-
-        #region MD5对数组数据加密
-
-        /// <summary>
-        ///     MD5对数组数据加密
-        /// </summary>
-        /// <param name="input">包含需要加密的数据的数组</param>
-        /// <returns>加密后的字节流</returns>
-        public static byte[] MD5Array(this byte[] input)
-        {
-            MD5_Init();
-            var block = MD5_Append(input);
-            var bits = MD5_Trasform(block);
-
-            var output = new byte[bits.Length * 4];
-            for (int i = 0, j = 0; i < bits.Length; i++, j += 4)
-            {
-                output[j] = (byte)(bits[i] & 0xff);
-                output[j + 1] = (byte)((bits[i] >> 8) & 0xff);
-                output[j + 2] = (byte)((bits[i] >> 16) & 0xff);
-                output[j + 3] = (byte)((bits[i] >> 24) & 0xff);
-            }
-
-            return output;
-        }
-
-        #endregion
-
-        #region 获取数组的Hex值
-
-        /// <summary>
-        ///     获取数组的Hex值
-        /// </summary>
-        /// <param name="array">需要求Hex值的数组</param>
-        /// <param name="uppercase">是否转大写</param>
-        /// <returns>字节数组的16进制表示</returns>
-        public static string ArrayToHexString(this byte[] array, bool uppercase)
-        {
-            var hexString = "";
-            var format = "x2";
-            if (uppercase)
-                format = "X2";
-            foreach (var b in array)
-                hexString += b.ToString(format);
-            return hexString;
-        }
-
-        #endregion
-
-        #region 对字符串进行MD5加密
-
-        /// <summary>
-        ///     对字符串进行MD5加密
-        /// </summary>
-        /// <param name="message">需要加密的字符串</param>
-        /// <returns>加密后的结果</returns>
-        public static string MDString(this string message)
-        {
-            var c = message.ToCharArray();
-            var b = new byte[c.Length];
-            for (var i = 0; i < c.Length; i++)
-                b[i] = (byte)c[i];
-            var digest = MD5Array(b);
-            return ArrayToHexString(digest, false);
-        }
-
-        /// <summary>
-        ///     对字符串进行MD5二次加密
-        /// </summary>
-        /// <param name="message">需要加密的字符串</param>
-        /// <returns>加密后的结果</returns>
-        public static string MDString2(this string message) => MDString(MDString(message));
-
-        /// <summary>
-        /// MD5 三次加密算法
-        /// </summary>
-        /// <param name="s">需要加密的字符串</param>
-        /// <returns>MD5字符串</returns>
-        public static string MDString3(this string s)
-        {
-            MD5 md5 = MD5.Create();
-            byte[] bytes = Encoding.ASCII.GetBytes(s);
-            byte[] bytes1 = md5.ComputeHash(bytes);
-            byte[] bytes2 = md5.ComputeHash(bytes1);
-            byte[] bytes3 = md5.ComputeHash(bytes2);
-
-            StringBuilder sb = new StringBuilder();
-            foreach (var item in bytes3)
-            {
-                sb.Append(item.ToString("x").PadLeft(2, '0'));
-            }
-
-            return sb.ToString();
-        }
-
-        /// <summary>
-        ///     对字符串进行MD5加盐加密
-        /// </summary>
-        /// <param name="message">需要加密的字符串</param>
-        /// <param name="salt">盐</param>
-        /// <returns>加密后的结果</returns>
-        public static string MDString(this string message, string salt) => MDString(message + salt);
-
-        /// <summary>
-        ///     对字符串进行MD5二次加盐加密
-        /// </summary>
-        /// <param name="message">需要加密的字符串</param>
-        /// <param name="salt">盐</param>
-        /// <returns>加密后的结果</returns>
-        public static string MDString2(this string message, string salt) => MDString(MDString(message + salt), salt);
-
-        /// <summary>
-        /// MD5 三次加密算法
-        /// </summary>
-        /// <param name="s">需要加密的字符串</param>
-        /// <param name="salt">盐</param>
-        /// <returns>MD5字符串</returns>
-        public static string MDString3(this string s, string salt)
-        {
-            MD5 md5 = MD5.Create();
-            byte[] bytes = Encoding.ASCII.GetBytes(s + salt);
-            byte[] bytes1 = md5.ComputeHash(bytes);
-            byte[] bytes2 = md5.ComputeHash(bytes1);
-            byte[] bytes3 = md5.ComputeHash(bytes2);
-
-            StringBuilder sb = new StringBuilder();
-            foreach (var item in bytes3)
-            {
-                sb.Append(item.ToString("x").PadLeft(2, '0'));
-            }
-
-            return sb.ToString();
-        }
-
-        #endregion
-
-        #region 获取文件的MD5值
-
-        /// <summary>
-        /// 获取文件的MD5值
-        /// </summary>
-        /// <param name="fileName">需要求MD5值的文件的文件名及路径</param>
-        /// <returns>MD5字符串</returns>
-        public static string MDFile(this string fileName)
-        {
-            var fs = File.Open(fileName, FileMode.Open, FileAccess.Read);
-            var array = new byte[fs.Length];
-            fs.Read(array, 0, (int)fs.Length);
-            var digest = MD5Array(array);
-            fs.Close();
-            return ArrayToHexString(digest, false);
-        }
-
-        #endregion
-
-        #region 测试MD5加密算法的函数
-
-        /// <summary>
-        ///     测试MD5加密算法的函数
-        /// </summary>
-        /// <param name="message">需要加密的字符串</param>
-        /// <returns>加密后的 数据</returns>
-        private static string MD5Test(this string message)
-        {
-            return "rnMD5 (" + "message" + ") = " + MDString(message);
-        }
-
-        #endregion
-
-        #region MD5加密算法测试用数据
-
-        /// <summary>
-        ///     MD5加密算法测试用数据
-        /// </summary>
-        /// <returns> </returns>
-        private static string TestSuite()
-        {
-            var s = "";
-            s += MD5Test("");
-            s += MD5Test("a");
-            s += MD5Test("abc");
-            s += MD5Test("message digest");
-            s += MD5Test("abcdefghijklmnopqrstuvwxyz");
-            s += MD5Test("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
-            s += MD5Test("12345678901234567890123456789012345678901234567890123456789012345678901234567890");
-            return s;
-        }
-
-        #endregion
-
-        #endregion MD5加密算法
-    }
-
-    /// <summary>
-    ///     RC2加密解密算法
-    /// </summary>
-    public static class RC2
-    {
-        private static ASCIIEncoding _asciiEncoding;
-        private static byte[] _iv;
-        private static byte[] _key;
-        private static RC2CryptoServiceProvider _rc2Csp;
-        private static UnicodeEncoding _textConverter;
-
-        static RC2()
-        {
-            InitializeComponent();
-        }
-
-        private static void InitializeComponent()
-        {
-            _key = new byte[]
-            {
-                106,
-                51,
-                25,
-                141,
-                157,
-                142,
-                23,
-                111,
-                234,
-                159,
-                187,
-                154,
-                215,
-                34,
-                37,
-                204
-            };
-            _iv = new byte[]
-            {
-                135,
-                186,
-                133,
-                136,
-                184,
-                149,
-                153,
-                144
-            };
-            _asciiEncoding = new ASCIIEncoding();
-            _textConverter = new UnicodeEncoding();
-            _rc2Csp = new RC2CryptoServiceProvider();
-        }
-
-        #region 新建一个大小为10261B的文件,以便将加密数据写入固定大小的文件。
-
-        /// <summary>
-        ///     新建一个大小为10261B的文件,以便将加密数据写入固定大小的文件。
-        /// </summary>
-        /// <param name="filePath">文件保存的地址,包含文件名</param>
-        public static string InitBinFile(this string filePath)
-        {
-            var tmp = new byte[10261];
-            try //创建文件流,将其内容全部写入0
-            {
-                var writeFileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, 512, false);
-
-                for (var i = 0; i < 10261; i++)
-                    tmp[i] = 0;
-                writeFileStream.Write(tmp, 0, 10261);
-                writeFileStream.Flush();
-                writeFileStream.Close();
-            }
-            catch (IOException)
-            {
-                // MessageBox.Show("文件操作错误!", "错误!", MessageBoxButtons.OK, MessageBoxIcon.Error);
-                return "Error,file operation error!";
-            }
-
-            return "OK";
-        }
-
-        #endregion
-
-        #region 将文本数据加密后写入一个文件
-
-        /// <summary>
-        ///     将文本数据加密后写入一个文件,其中,这个文件是用InitBinFile建立的,这个文件将被分成十块,
-        ///     用来分别保存10组不同的数据,第一个byte位保留,第2位到第21位分别用来存放每块数据的长度,但
-        ///     一个byte的取值为0-127,所以,用两个byte来存放一个长度。
-        /// </summary>
-        /// <param name="toEncryptText">要加密的文本数据</param>
-        /// <param name="filePath">要写入的文件</param>
-        /// <param name="dataIndex">写入第几块,取值为1--10</param>
-        /// <returns>是否操作成功</returns>
-        public static bool EncryptToFile(this string toEncryptText, string filePath, int dataIndex)
-        {
-            var r = false;
-            if ((dataIndex > 10) && (dataIndex < 1))
-            {
-                return r;
-            }
-
-            //打开要写入的文件,主要是为了保持原文件的内容不丢失
-            var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
-
-            var index = new byte[10261];
-            //将读取的内容写到byte数组
-            tmpFileStream.Read(index, 0, 10261);
-            tmpFileStream.Close();
-            //定义基本的加密转换运算
-            var Encryptor = _rc2Csp.CreateEncryptor(_key, _iv);
-            var msEncrypt = new MemoryStream();
-            //在此加密转换流中,加密将从csEncrypt,加密后,结果在msEncrypt流中。
-            var csEncrypt = new CryptoStream(msEncrypt, Encryptor, CryptoStreamMode.Write);
-            //将要加密的文本转换成UTF-16 编码,保存在tmp数组。
-            var tmp = _textConverter.GetBytes(toEncryptText);
-            //将tmp输入csEncrypt,将通过Encryptor来加密。
-            csEncrypt.Write(tmp, 0, tmp.Length);
-            //输出到msEnctypt
-            csEncrypt.FlushFinalBlock();
-            //将流转成byte[]
-            var encrypted = msEncrypt.ToArray();
-            if (encrypted.Length > 1024)
-                return false;
-            //得到加密后数据的大小,将结果存在指定的位置。
-            index[dataIndex * 2 - 1] = Convert.ToByte(Convert.ToString(encrypted.Length / 128));
-            index[dataIndex * 2] = Convert.ToByte(Convert.ToString(encrypted.Length % 128));
-            //将加密后的结果写入index(覆盖)
-            for (var i = 0; i < encrypted.Length; i++)
-                index[1024 * (dataIndex - 1) + 21 + i] = encrypted[i];
-            //建立文件流
-            tmpFileStream = new FileStream(filePath, FileMode.Truncate, FileAccess.Write, FileShare.None, 1024, true);
-            //写文件
-            tmpFileStream.Write(index, 0, 10261);
-            tmpFileStream.Flush();
-            r = true;
-            tmpFileStream.Close();
-            return r;
-        }
-
-        #endregion
-
-        #region 从一个文件中解密出一段文本,其中,这个文件是由InitBinFile建立的,并且由 EncryptToFile加密的
-
-        /// <summary>
-        ///     从一个文件中解密出一段文本,其中,这个文件是由InitBinFile建立的,并且由 EncryptToFile加密的
-        /// </summary>
-        /// <param name="filePath">要解密的文件</param>
-        /// <param name="dataIndex">要从哪一个块中解密</param>
-        /// <returns>解密后的文本</returns>
-        public static string DecryptFromFile(this string filePath, int dataIndex)
-        {
-            var r = "";
-            if ((dataIndex > 10) && (dataIndex < 1))
-            {
-                return r;
-            }
-
-            var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
-
-            var decryptor = _rc2Csp.CreateDecryptor(_key, _iv);
-            var msDecrypt = new MemoryStream();
-            var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
-            var index = new byte[10261];
-
-            tmpFileStream.Read(index, 0, 10261);
-            //var startIndex = 1024 * (dataIndex - 1) + 21;
-            var count = index[dataIndex * 2 - 1] * 128 + index[dataIndex * 2];
-            var tmp = new byte[count];
-
-            Array.Copy(index, 1024 * (dataIndex - 1) + 21, tmp, 0, count);
-            csDecrypt.Write(tmp, 0, count);
-            csDecrypt.FlushFinalBlock();
-            var decrypted = msDecrypt.ToArray();
-            r = _textConverter.GetString(decrypted, 0, decrypted.Length);
-            tmpFileStream.Close();
-            return r;
-        }
-
-        #endregion
-
-        #region 将一段文本加密后保存到一个文件
-
-        /// <summary>
-        ///     将一段文本加密后保存到一个文件
-        /// </summary>
-        /// <param name="toEncryptText">要加密的文本数据</param>
-        /// <param name="filePath">要保存的文件</param>
-        /// <returns>是否加密成功</returns>
-        public static void EncryptToFile(this string toEncryptText, string filePath)
-        {
-            using var tmpFileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, true);
-            using var encryptor = _rc2Csp.CreateEncryptor(_key, _iv);
-            var msEncrypt = new MemoryStream();
-            using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
-            var tmp = _textConverter.GetBytes(toEncryptText);
-            csEncrypt.Write(tmp, 0, tmp.Length);
-            csEncrypt.FlushFinalBlock();
-            var encrypted = msEncrypt.ToArray();
-            tmpFileStream.Write(encrypted, 0, encrypted.Length);
-        }
-
-        #endregion
-
-        #region 将一个被加密的文件解密
-
-        /// <summary>
-        ///     将一个被加密的文件解密
-        /// </summary>
-        /// <param name="filePath">要解密的文件</param>
-        /// <returns>解密后的文本</returns>
-        public static string DecryptFromFile(this string filePath)
-        {
-            using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
-            using var decryptor = _rc2Csp.CreateDecryptor(_key, _iv);
-            var msDecrypt = new MemoryStream();
-            using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
-            var tmp = new byte[tmpFileStream.Length];
-            tmpFileStream.Read(tmp, 0, tmp.Length);
-            csDecrypt.Write(tmp, 0, tmp.Length);
-            csDecrypt.FlushFinalBlock();
-            var decrypted = msDecrypt.ToArray();
-            var r = _textConverter.GetString(decrypted, 0, decrypted.Length);
-            return r;
-        }
-
-        #endregion
-
-        #region 将文本数据加密后写入一个文件
-
-        /// <summary>
-        ///     将文本数据加密后写入一个文件,其中,这个文件是用InitBinFile建立的,这个文件将被分成十块,
-        ///     用来分别保存10组不同的数据,第一个byte位保留,第2位到第21位分别用来存放每块数据的长度,但
-        ///     一个byte的取值为0-127,所以,用两个byte来存放一个长度。
-        /// </summary>
-        /// <param name="toEncryptText">要加密的文本数据</param>
-        /// <param name="filePath">要写入的文件</param>
-        /// <param name="dataIndex">写入第几块,取值为1--10</param>
-        /// <param name="IV">初始化向量</param>
-        /// <param name="Key">加密密匙</param>
-        /// <returns>是否操作成功</returns>
-        public static void EncryptToFile(this string toEncryptText, string filePath, int dataIndex, byte[] IV, byte[] Key)
-        {
-            if ((dataIndex > 10) && (dataIndex < 1))
-            {
-                return;
-            }
-            //打开要写入的文件,主要是为了保持原文件的内容不丢失
-            using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
-            var index = new byte[10261];
-            //将读取的内容写到byte数组
-            fs.Read(index, 0, 10261);
-
-            //定义基本的加密转换运算
-            using var encryptor = _rc2Csp.CreateEncryptor(Key, IV);
-            var msEncrypt = new MemoryStream();
-            //在此加密转换流中,加密将从csEncrypt,加密后,结果在msEncrypt流中。
-            using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
-            var tmp = _textConverter.GetBytes(toEncryptText);
-            //将tmp输入csEncrypt,将通过Encryptor来加密。
-            csEncrypt.Write(tmp, 0, tmp.Length);
-            //输出到msEnctypt
-            csEncrypt.FlushFinalBlock();
-
-            //将流转成byte[]
-            var encrypted = msEncrypt.ToArray();
-            if (encrypted.Length > 1024)
-            {
-                return;
-            }
-
-            //得到加密后数据的大小,将结果存在指定的位置。
-            index[dataIndex * 2 - 1] = Convert.ToByte(Convert.ToString(encrypted.Length / 128));
-            index[dataIndex * 2] = Convert.ToByte(Convert.ToString(encrypted.Length % 128));
-            //将加密后的结果写入index(覆盖)
-            for (int i = 0; i < encrypted.Length; i++)
-            {
-                index[1024 * (dataIndex - 1) + 21 + i] = encrypted[i];
-            }
-
-            //建立文件流
-            using var newStream = new FileStream(filePath, FileMode.Truncate, FileAccess.Write, FileShare.None, 1024, true);
-            newStream.Write(index, 0, 10261);
-            newStream.Flush();
-            newStream.Close();
-        }
-
-        #endregion
-
-        #region 从一个文件中解密出一段文本
-
-        /// <summary>
-        ///     从一个文件中解密出一段文本,其中,这个文件是由InitBinFile建立的,并且由 EncryptToFile加密的
-        /// </summary>
-        /// <param name="filePath">要解密的文件</param>
-        /// <param name="dataIndex">要从哪一个块中解密</param>
-        /// <param name="iv">初始化向量</param>
-        /// <param name="key">解密密匙</param>
-        /// <returns>解密后的文本</returns>
-        public static string DecryptFromFile(this string filePath, int dataIndex, byte[] iv, byte[] key)
-        {
-            if ((dataIndex > 10) && (dataIndex < 1))
-            {
-                return "";
-            }
-
-            using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
-            using var decryptor = _rc2Csp.CreateDecryptor(key, iv);
-            var msDecrypt = new MemoryStream();
-            using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
-            var index = new byte[10261];
-
-            tmpFileStream.Read(index, 0, 10261);
-            var count = index[dataIndex * 2 - 1] * 128 + index[dataIndex * 2];
-            var tmp = new byte[count];
-
-            Array.Copy(index, 1024 * (dataIndex - 1) + 21, tmp, 0, count);
-            csDecrypt.Write(tmp, 0, count);
-            csDecrypt.FlushFinalBlock();
-            var decrypted = msDecrypt.ToArray();
-            return _textConverter.GetString(decrypted, 0, decrypted.Length);
-        }
-
-        #endregion
-
-        #region 将一段文本加密后保存到一个文件
-
-        /// <summary>
-        ///     将一段文本加密后保存到一个文件
-        /// </summary>
-        /// <param name="toEncryptText">要加密的文本数据</param>
-        /// <param name="filePath">要保存的文件</param>
-        /// <param name="iv">初始化向量</param>
-        /// <param name="key">加密密匙</param>
-        /// <returns>是否加密成功</returns>
-        public static void EncryptToFile(this string toEncryptText, string filePath, byte[] iv, byte[] key)
-        {
-            using var tmpFileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, true);
-            using var encryptor = _rc2Csp.CreateEncryptor(key, iv);
-            var msEncrypt = new MemoryStream();
-            using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
-            var tmp = _textConverter.GetBytes(toEncryptText);
-            csEncrypt.Write(tmp, 0, tmp.Length);
-            csEncrypt.FlushFinalBlock();
-            var encrypted = msEncrypt.ToArray();
-            tmpFileStream.Write(encrypted, 0, encrypted.Length);
-            tmpFileStream.Flush();
-        }
-
-        #endregion
-
-        #region 将一个被加密的文件解密
-
-        /// <summary>
-        ///     将一个被加密的文件解密
-        /// </summary>
-        /// <param name="filePath">要解密的文件</param>
-        /// <param name="iv">初始化向量</param>
-        /// <param name="key">解密密匙</param>
-        /// <returns>解密后的文本</returns>
-        public static string DecryptFromFile(this string filePath, byte[] iv, byte[] key)
-        {
-            using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
-            using var decryptor = _rc2Csp.CreateDecryptor(key, iv);
-            var msDecrypt = new MemoryStream();
-            using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
-            var tmp = new byte[tmpFileStream.Length];
-            tmpFileStream.Read(tmp, 0, tmp.Length);
-            csDecrypt.Write(tmp, 0, tmp.Length);
-            csDecrypt.FlushFinalBlock();
-            var decrypted = msDecrypt.ToArray();
-            return _textConverter.GetString(decrypted, 0, decrypted.Length);
-        }
-
-        #endregion
-
-        #region 设置加密或解密的初始化向量
-
-        /// <summary>
-        ///     设置加密或解密的初始化向量
-        /// </summary>
-        /// <param name="s">长度等于8的ASCII字符集的字符串</param>
-        public static void SetIV(this string s)
-        {
-            if (s.Length != 8)
-            {
-                // MessageBox.Show("输入的字符串必须为长度为8的且属于ASCII字符集的字符串");
-                _iv = null;
-                return;
-            }
-
-            try
-            {
-                _iv = _asciiEncoding.GetBytes(s);
-            }
-            catch (Exception)
-            {
-                // MessageBox.Show("输入的字符串必须为长度为8的且属于ASCII字符集的字符串");
-                _iv = null;
-            }
-        }
-
-        #endregion
-
-        #region 设置加密或解密的密匙
-
-        /// <summary>
-        ///     设置加密或解密的密匙
-        /// </summary>
-        /// <param name="s">长度等于16的ASCII字符集的字符串</param>
-        public static void SetKey(this string s)
-        {
-            if (s.Length != 16)
-            {
-                // MessageBox.Show("输入的字符串必须为长度为16的且属于ASCII字符集的字符串");
-                _key = null;
-                return;
-            }
-
-            try
-            {
-                _key = _asciiEncoding.GetBytes(s);
-            }
-            catch (Exception)
-            {
-                //MessageBox.Show("输入的字符串必须为长度为16的且属于ASCII字符集的字符串");
-                _key = null;
-            }
-        }
-
-        #endregion
-    }
-
-    /// <summary>
-    ///     对称加密解密算法类
-    /// </summary>
-    public static class Rijndael
-    {
-        private static string _key;
-        private static SymmetricAlgorithm _mobjCryptoService;
-
-        /// <summary>
-        ///     对称加密类的构造函数
-        /// </summary>
-        public static void SymmetricMethod()
-        {
-            _mobjCryptoService = new RijndaelManaged();
-            _key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
-        }
-
-        /// <summary>
-        ///     获得密钥
-        /// </summary>
-        /// <returns>密钥</returns>
-        private static byte[] GetLegalKey()
-        {
-            var sTemp = _key;
-            _mobjCryptoService.GenerateKey();
-            var bytTemp = _mobjCryptoService.Key;
-            var keyLength = bytTemp.Length;
-            if (sTemp.Length > keyLength)
-                sTemp = sTemp.Substring(0, keyLength);
-            else if (sTemp.Length < keyLength)
-                sTemp = sTemp.PadRight(keyLength, ' ');
-            return Encoding.ASCII.GetBytes(sTemp);
-        }
-
-        /// <summary>
-        ///     获得初始向量IV
-        /// </summary>
-        /// <returns>初试向量IV</returns>
-        private static byte[] GetLegalIV()
-        {
-            var sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUber57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
-            _mobjCryptoService.GenerateIV();
-            var bytTemp = _mobjCryptoService.IV;
-            var ivLength = bytTemp.Length;
-            if (sTemp.Length > ivLength)
-                sTemp = sTemp.Substring(0, ivLength);
-            else if (sTemp.Length < ivLength)
-                sTemp = sTemp.PadRight(ivLength, ' ');
-            return Encoding.ASCII.GetBytes(sTemp);
-        }
-
-        /// <summary>
-        ///     加密方法
-        /// </summary>
-        /// <param name="source">待加密的串</param>
-        /// <returns>经过加密的串</returns>
-        public static string Encrypto(this string source)
-        {
-            var bytIn = Encoding.UTF8.GetBytes(source);
-            var ms = new MemoryStream();
-            _mobjCryptoService.Key = GetLegalKey();
-            _mobjCryptoService.IV = GetLegalIV();
-            var encrypto = _mobjCryptoService.CreateEncryptor();
-            var cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
-            cs.Write(bytIn, 0, bytIn.Length);
-            cs.FlushFinalBlock();
-            ms.Close();
-            var bytOut = ms.ToArray();
-            return Convert.ToBase64String(bytOut);
-        }
-
-        /// <summary>
-        ///     解密方法
-        /// </summary>
-        /// <param name="source">待解密的串</param>
-        /// <returns>经过解密的串</returns>
-        public static string Decrypto(this string source)
-        {
-            var bytIn = Convert.FromBase64String(source);
-            var ms = new MemoryStream(bytIn, 0, bytIn.Length);
-            _mobjCryptoService.Key = GetLegalKey();
-            _mobjCryptoService.IV = GetLegalIV();
-            var encrypto = _mobjCryptoService.CreateDecryptor();
-            var cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
-            var sr = new StreamReader(cs);
-            return sr.ReadToEnd();
-        }
-    }
-}

+ 0 - 39
Masuit.Tools.Core/Security/HashEncode.cs

@@ -1,39 +0,0 @@
-using Masuit.Tools.Win32;
-using System;
-using System.Security.Cryptography;
-using System.Text;
-
-namespace Masuit.Tools.Security
-{
-    /// <summary>
-    /// 得到随机安全码(哈希加密)。
-    /// </summary>
-    public static class HashEncode
-    {
-        /// <summary>
-        /// 得到随机哈希加密字符串
-        /// </summary>
-        /// <returns>随机哈希加密字符串</returns>
-        public static string GetSecurity(this Random r) => HashEncoding(r.StrictNext().ToString());
-
-        /// <summary>
-        /// 哈希加密一个字符串
-        /// </summary>
-        /// <param name="security">需要加密的字符串</param>
-        /// <returns>加密后的数据</returns>
-        public static string HashEncoding(this string security)
-        {
-            var code = new UnicodeEncoding();
-            byte[] message = code.GetBytes(security);
-            var arithmetic = new SHA512Managed();
-            var value = arithmetic.ComputeHash(message);
-            var sb = new StringBuilder();
-            foreach (byte o in value)
-            {
-                sb.Append((int)o + "O");
-            }
-
-            return sb.ToString();
-        }
-    }
-}

+ 0 - 397
Masuit.Tools.Core/Security/RSACrypt.cs

@@ -1,397 +0,0 @@
-using System;
-using System.IO;
-using System.Security.Cryptography;
-using System.Text;
-
-namespace Masuit.Tools.Security
-{
-    /// <summary>
-    /// RSA密钥对
-    /// </summary>
-    public class RsaKey
-    {
-        /// <summary>
-        /// 公钥
-        /// </summary>
-        public string PublicKey;
-
-        /// <summary>
-        /// 私钥
-        /// </summary>
-        public string PrivateKey;
-    }
-
-    /// <summary> 
-    /// RSA加密解密及RSA签名和验证
-    /// </summary> 
-    public static class RsaCrypt
-    {
-        private static RsaKey RsaKey = GenerateRsaKeys();
-        #region RSA 加密解密 
-
-        #region RSA 的密钥产生 
-
-        /// <summary>
-        /// 生成 RSA 公钥和私钥
-        /// </summary>
-        public static RsaKey GenerateRsaKeys()
-        {
-            using var rsa = new RSACryptoServiceProvider();
-            return RsaKey ??= new RsaKey
-            {
-                PrivateKey = rsa.ToXmlString(true),
-                PublicKey = rsa.ToXmlString(false)
-            };
-        }
-
-        #endregion
-
-        #region RSA的加密函数 
-
-        /// <summary>
-        /// RSA的加密函数 string
-        /// </summary>
-        /// <param name="publicKey">公钥</param>
-        /// <param name="mStrEncryptString">需要加密的字符串</param>
-        /// <returns>加密后的内容</returns>
-        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired. </exception>
-        public static string RSAEncrypt(this string mStrEncryptString, string publicKey)
-        {
-            var rsa = new RSACryptoServiceProvider();
-            rsa.FromXmlString(publicKey);
-            var plainTextBArray = new UnicodeEncoding().GetBytes(mStrEncryptString);
-            var cypherTextBArray = rsa.Encrypt(plainTextBArray, false);
-            return Convert.ToBase64String(cypherTextBArray);
-        }
-
-        /// <summary>
-        /// RSA的加密函数 string
-        /// </summary>
-        /// <param name="mStrEncryptString">需要加密的字符串</param>
-        /// <returns>加密后的内容</returns>
-        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired. </exception>
-        public static string RSAEncrypt(this string mStrEncryptString)
-        {
-            return RSAEncrypt(mStrEncryptString, RsaKey.PublicKey);
-        }
-
-        /// <summary>
-        /// RSA的加密函数 byte[]
-        /// </summary>
-        /// <param name="encryptString">需要加密的字节数组</param>
-        /// <param name="publicKey">公钥</param>
-        /// <returns>加密后的内容</returns>
-        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired. </exception>
-        public static string RSAEncrypt(this byte[] encryptString, string publicKey)
-        {
-            var rsa = new RSACryptoServiceProvider();
-            rsa.FromXmlString(publicKey);
-            var cypherTextBArray = rsa.Encrypt(encryptString, false);
-            return Convert.ToBase64String(cypherTextBArray);
-        }
-
-        /// <summary>
-        /// RSA的加密函数 byte[]
-        /// </summary>
-        /// <param name="encryptString">需要加密的字节数组</param>
-        /// <returns>加密后的内容</returns>
-        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired. </exception>
-        public static string RSAEncrypt(this byte[] encryptString)
-        {
-            return RSAEncrypt(encryptString, RsaKey.PublicKey);
-        }
-
-        #endregion
-
-        #region RSA的解密函数 
-
-        /// <summary>
-        /// RSA的解密函数  string
-        /// </summary>
-        /// <param name="mStrDecryptString">需要解密的字符串</param>
-        /// <param name="privateKey">私钥</param>
-        /// <returns>解密后的内容</returns>
-        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired. </exception>
-        public static string RSADecrypt(this string mStrDecryptString, string privateKey)
-        {
-            var rsa = new RSACryptoServiceProvider();
-            rsa.FromXmlString(privateKey);
-            var plainTextBArray = Convert.FromBase64String(mStrDecryptString);
-            var dypherTextBArray = rsa.Decrypt(plainTextBArray, false);
-            return new UnicodeEncoding().GetString(dypherTextBArray);
-        }
-
-        /// <summary>
-        /// RSA的解密函数  string
-        /// </summary>
-        /// <param name="mStrDecryptString">需要解密的字符串</param>
-        /// <returns>解密后的内容</returns>
-        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired. </exception>
-        public static string RSADecrypt(this string mStrDecryptString)
-        {
-            return RSADecrypt(mStrDecryptString, RsaKey.PrivateKey);
-        }
-
-        /// <summary>
-        /// RSA的解密函数  byte
-        /// </summary>
-        /// <param name="decryptString">需要解密的字符串</param>
-        /// <param name="privateKey">私钥</param>
-        /// <returns>解密后的内容</returns>
-        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired. </exception>
-        public static string RSADecrypt(this byte[] decryptString, string privateKey)
-        {
-            var rsa = new RSACryptoServiceProvider();
-            rsa.FromXmlString(privateKey);
-            var dypherTextBArray = rsa.Decrypt(decryptString, false);
-            return new UnicodeEncoding().GetString(dypherTextBArray);
-        }
-
-        /// <summary>
-        /// RSA的解密函数  byte
-        /// </summary>
-        /// <param name="decryptString">需要解密的字符串</param>
-        /// <returns>解密后的内容</returns>
-        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired. </exception>
-        public static string RSADecrypt(this byte[] decryptString)
-        {
-            return RSADecrypt(decryptString, RsaKey.PrivateKey);
-        }
-
-        #endregion
-
-        #endregion
-
-        #region RSA数字签名 
-
-        #region 获取Hash描述表 
-
-        /// <summary>
-        /// 获取Hash描述表
-        /// </summary>
-        /// <param name="mStrSource">源数据</param>
-        /// <returns>Hash描述表</returns>
-        public static byte[] GetHashBytes(this string mStrSource)
-        {
-            //从字符串中取得Hash描述 
-            HashAlgorithm md5 = HashAlgorithm.Create("MD5");
-            var buffer = Encoding.UTF8.GetBytes(mStrSource);
-            return md5?.ComputeHash(buffer);
-        }
-
-        /// <summary>
-        /// 获取Hash描述表
-        /// </summary>
-        /// <param name="mStrSource">源数据</param>
-        /// <returns>Hash描述表</returns>
-        public static string GetHashString(this string mStrSource)
-        {
-            //从字符串中取得Hash描述 
-            var md5 = HashAlgorithm.Create("MD5");
-            var buffer = Encoding.UTF8.GetBytes(mStrSource);
-            var hashData = md5?.ComputeHash(buffer);
-            return Convert.ToBase64String(hashData);
-        }
-
-        /// <summary>
-        /// 从文件流获取Hash描述表
-        /// </summary>
-        /// <param name="objFile">源文件</param>
-        /// <returns>Hash描述表</returns>
-        public static byte[] GetHashBytes(this FileStream objFile)
-        {
-            //从文件中取得Hash描述 
-            var md5 = HashAlgorithm.Create("MD5");
-            return md5?.ComputeHash(objFile);
-        }
-
-        /// <summary>
-        /// 从文件流获取Hash描述表
-        /// </summary>
-        /// <param name="objFile">源文件</param>
-        /// <returns>Hash描述表</returns>
-        public static string GetHashString(this FileStream objFile)
-        {
-            //从文件中取得Hash描述 
-            HashAlgorithm md5 = HashAlgorithm.Create("MD5");
-            var hashData = md5?.ComputeHash(objFile);
-            return Convert.ToBase64String(hashData);
-        }
-
-        #endregion
-
-        #region RSA签名 
-
-        /// <summary>
-        /// RSA签名
-        /// </summary>
-        /// <param name="hashbyteSignature">签名字节数据</param>
-        /// <param name="privateKey">私钥</param>
-        /// <returns>处理结果</returns>
-        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired. </exception>
-        /// <exception cref="CryptographicUnexpectedOperationException">The key is null.-or- The hash algorithm is null. </exception>
-        public static byte[] SignatureBytes(this byte[] hashbyteSignature, string privateKey)
-        {
-            var rsa = new RSACryptoServiceProvider();
-            rsa.FromXmlString(privateKey);
-            var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
-            //设置签名的算法为MD5 
-            rsaFormatter.SetHashAlgorithm("MD5");
-            //执行签名 
-            return rsaFormatter.CreateSignature(hashbyteSignature);
-        }
-
-        /// <summary>
-        /// RSA签名
-        /// </summary>
-        /// <param name="hashbyteSignature">签名字节数据</param>
-        /// <param name="privateKey">私钥</param>
-        /// <returns>处理结果</returns>
-        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired. </exception>
-        /// <exception cref="CryptographicUnexpectedOperationException">The key is null.-or- The hash algorithm is null. </exception>
-        public static string SignatureString(this byte[] hashbyteSignature, string privateKey)
-        {
-            var rsa = new RSACryptoServiceProvider();
-            rsa.FromXmlString(privateKey);
-            var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
-            //设置签名的算法为MD5 
-            rsaFormatter.SetHashAlgorithm("MD5");
-            //执行签名 
-            var encryptedSignatureData = rsaFormatter.CreateSignature(hashbyteSignature);
-            return Convert.ToBase64String(encryptedSignatureData);
-        }
-
-        /// <summary>
-        /// RSA签名
-        /// </summary>
-        /// <param name="mStrHashbyteSignature">签名字符串数据</param>
-        /// <param name="pStrKeyPrivate">私钥</param>
-        /// <returns>处理结果</returns>
-        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired. </exception>
-        /// <exception cref="CryptographicUnexpectedOperationException">The key is null.-or- The hash algorithm is null. </exception>
-        public static byte[] SignatureBytes(this string mStrHashbyteSignature, string pStrKeyPrivate)
-        {
-            byte[] hashbyteSignature = Convert.FromBase64String(mStrHashbyteSignature);
-            var rsa = new RSACryptoServiceProvider();
-            rsa.FromXmlString(pStrKeyPrivate);
-            var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
-            //设置签名的算法为MD5 
-            rsaFormatter.SetHashAlgorithm("MD5");
-            //执行签名 
-            return rsaFormatter.CreateSignature(hashbyteSignature);
-        }
-
-        /// <summary>
-        /// RSA签名
-        /// </summary>
-        /// <param name="mStrHashbyteSignature">签名字符串数据</param>
-        /// <param name="pStrKeyPrivate">私钥</param>
-        /// <returns>处理结果</returns>
-        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired. </exception>
-        /// <exception cref="CryptographicUnexpectedOperationException">The key is null.-or- The hash algorithm is null. </exception>
-        public static string SignatureString(this string mStrHashbyteSignature, string pStrKeyPrivate)
-        {
-            var hashbyteSignature = Convert.FromBase64String(mStrHashbyteSignature);
-            var rsa = new RSACryptoServiceProvider();
-            rsa.FromXmlString(pStrKeyPrivate);
-            var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
-            //设置签名的算法为MD5 
-            rsaFormatter.SetHashAlgorithm("MD5");
-            //执行签名 
-            var encryptedSignatureData = rsaFormatter.CreateSignature(hashbyteSignature);
-            return Convert.ToBase64String(encryptedSignatureData);
-        }
-
-        #endregion
-
-        #region RSA 签名验证 
-
-        /// <summary>
-        /// RSA 签名验证 
-        /// </summary>
-        /// <param name="deformatterData">反格式化字节数据</param>
-        /// <param name="publicKey">公钥</param>
-        /// <param name="hashbyteDeformatter">哈希字节数据</param>
-        /// <returns>处理结果</returns>
-        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired. </exception>
-        /// <exception cref="CryptographicUnexpectedOperationException">The key is null.-or- The hash algorithm is null. </exception>
-        public static bool SignatureDeformatter(this byte[] deformatterData, string publicKey, byte[] hashbyteDeformatter)
-        {
-            var rsa = new RSACryptoServiceProvider();
-            rsa.FromXmlString(publicKey);
-            var rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);
-            //指定解密的时候HASH算法为MD5 
-            rsaDeformatter.SetHashAlgorithm("MD5");
-            if (rsaDeformatter.VerifySignature(hashbyteDeformatter, deformatterData)) return true;
-            return false;
-        }
-
-        /// <summary>
-        /// RSA 签名验证 
-        /// </summary>
-        /// <param name="deformatterData">反格式化字节数据</param>
-        /// <param name="publicKey">公钥</param>
-        /// <param name="pStrHashbyteDeformatter">哈希字符串数据</param>
-        /// <returns>处理结果</returns>
-        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired. </exception>
-        /// <exception cref="CryptographicUnexpectedOperationException">The key is null.-or- The hash algorithm is null. </exception>
-        public static bool SignatureDeformatter(this byte[] deformatterData, string publicKey, string pStrHashbyteDeformatter)
-        {
-            byte[] hashbyteDeformatter = Convert.FromBase64String(pStrHashbyteDeformatter);
-            var rsa = new RSACryptoServiceProvider();
-            rsa.FromXmlString(publicKey);
-            var rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);
-            //指定解密的时候HASH算法为MD5 
-            rsaDeformatter.SetHashAlgorithm("MD5");
-            if (rsaDeformatter.VerifySignature(hashbyteDeformatter, deformatterData)) return true;
-            return false;
-        }
-
-        /// <summary>
-        /// RSA 签名验证
-        /// </summary>
-        /// <param name="pStrDeformatterData">反格式化字符串数据</param>
-        /// <param name="publicKey">公钥</param>
-        /// <param name="hashbyteDeformatter">哈希字节数据</param>
-        /// <returns>处理结果</returns>
-        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired. </exception>
-        /// <exception cref="CryptographicUnexpectedOperationException">The key is null.-or- The hash algorithm is null. </exception>
-        public static bool SignatureDeformatter(this string pStrDeformatterData, string publicKey, byte[] hashbyteDeformatter)
-        {
-            var rsa = new RSACryptoServiceProvider();
-            rsa.FromXmlString(publicKey);
-            var rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);
-            //指定解密的时候HASH算法为MD5 
-            rsaDeformatter.SetHashAlgorithm("MD5");
-            var deformatterData = Convert.FromBase64String(pStrDeformatterData);
-            if (rsaDeformatter.VerifySignature(hashbyteDeformatter, deformatterData)) return true;
-            return false;
-        }
-
-        /// <summary>
-        /// RSA 签名验证
-        /// </summary>
-        /// <param name="pStrDeformatterData">格式字符串数据</param>
-        /// <param name="publicKey">公钥</param>
-        /// <param name="pStrHashbyteDeformatter">哈希字符串数据</param>
-        /// <returns>处理结果</returns>
-        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired. </exception>
-        /// <exception cref="CryptographicUnexpectedOperationException">The key is null.-or- The hash algorithm is null. </exception>
-        public static bool SignatureDeformatter(this string pStrDeformatterData, string publicKey, string pStrHashbyteDeformatter)
-        {
-            byte[] hashbyteDeformatter = Convert.FromBase64String(pStrHashbyteDeformatter);
-            var rsa = new RSACryptoServiceProvider();
-            rsa.FromXmlString(publicKey);
-            var rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);
-            //指定解密的时候HASH算法为MD5 
-            rsaDeformatter.SetHashAlgorithm("MD5");
-            var deformatterData = Convert.FromBase64String(pStrDeformatterData);
-            if (rsaDeformatter.VerifySignature(hashbyteDeformatter, deformatterData)) return true;
-            return false;
-        }
-
-        #endregion
-
-        #endregion
-    }
-}

+ 0 - 50
Masuit.Tools.Core/Systems/ConcurrentLimitedQueue.cs

@@ -1,50 +0,0 @@
-using System.Collections.Concurrent;
-using System.Collections.Generic;
-using System.Linq;
-
-namespace Masuit.Tools.Systems
-{
-    /// <summary>
-    /// 定长队列
-    /// </summary>
-    /// <typeparam name="T"></typeparam>
-    public class ConcurrentLimitedQueue<T> : ConcurrentQueue<T>
-    {
-        /// <summary>
-        /// 长度
-        /// </summary>
-        public int Limit { get; set; }
-
-        /// <summary>
-        /// 定长队列
-        /// </summary>
-        /// <param name="limit"></param>
-        public ConcurrentLimitedQueue(int limit)
-        {
-            Limit = limit;
-        }
-
-        /// <summary>
-        /// 定长队列
-        /// </summary>
-        /// <param name="list"></param>
-        public ConcurrentLimitedQueue(IEnumerable<T> list) : base(list)
-        {
-            Limit = list.Count();
-        }
-
-        /// <summary>
-        /// 入队
-        /// </summary>
-        /// <param name="item"></param>
-        public new void Enqueue(T item)
-        {
-            if (Count >= Limit)
-            {
-                TryDequeue(out var _);
-            }
-
-            base.Enqueue(item);
-        }
-    }
-}

+ 0 - 41
Masuit.Tools.Core/Systems/Disposable.cs

@@ -1,41 +0,0 @@
-using System;
-
-namespace Masuit.Tools.Systems
-{
-    /// <summary>
-    /// Disposable
-    /// </summary>
-    public abstract class Disposable : IDisposable
-    {
-        private bool isDisposed;
-
-        /// <summary>
-        /// 终结器
-        /// </summary>
-        ~Disposable()
-        {
-            Dispose(false);
-        }
-
-        /// <summary>
-        /// 
-        /// </summary>
-        public void Dispose()
-        {
-            if (isDisposed)
-            {
-                return;
-            }
-
-            Dispose(true);
-            isDisposed = true;
-            GC.SuppressFinalize(this);
-        }
-
-        /// <summary>
-        /// 释放
-        /// </summary>
-        /// <param name="disposing"></param>
-        public abstract void Dispose(bool disposing);
-    }
-}

+ 0 - 209
Masuit.Tools.Core/Systems/EnumExt.cs

@@ -1,209 +0,0 @@
-using System;
-using System.Collections.Concurrent;
-using System.Collections.Generic;
-using System.Collections.Specialized;
-using System.ComponentModel;
-using System.ComponentModel.DataAnnotations;
-using System.Linq;
-using System.Reflection;
-
-namespace Masuit.Tools.Systems
-{
-    /// <summary>
-    /// 枚举扩展类
-    /// </summary>
-    public static class EnumExt
-    {
-        private static readonly ConcurrentDictionary<Type, Dictionary<int, string>> EnumNameValueDict = new ConcurrentDictionary<Type, Dictionary<int, string>>();
-        private static readonly ConcurrentDictionary<Type, Dictionary<string, int>> EnumValueNameDict = new ConcurrentDictionary<Type, Dictionary<string, int>>();
-        private static ConcurrentDictionary<string, Type> _enumTypeDict;
-
-        /// <summary>
-        /// 获取枚举对象Key与显示名称的字典
-        /// </summary>
-        /// <param name="enumType"></param>
-        /// <returns></returns>
-        public static Dictionary<int, string> GetDictionary(this Type enumType)
-        {
-            if (!enumType.IsEnum) throw new Exception("给定的类型不是枚举类型");
-            Dictionary<int, string> names = EnumNameValueDict.ContainsKey(enumType) ? EnumNameValueDict[enumType] : new Dictionary<int, string>();
-            if (names.Count == 0)
-            {
-                names = GetDictionaryItems(enumType);
-                EnumNameValueDict[enumType] = names;
-            }
-
-            return names;
-        }
-
-        private static Dictionary<int, string> GetDictionaryItems(Type enumType)
-        {
-            FieldInfo[] enumItems = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
-            Dictionary<int, string> names = new Dictionary<int, string>(enumItems.Length);
-            foreach (FieldInfo enumItem in enumItems)
-            {
-                int intValue = (int)enumItem.GetValue(enumType);
-                names[intValue] = enumItem.Name;
-            }
-
-            return names;
-        }
-
-        /// <summary>
-        /// 获取枚举对象显示名称与Key的字典
-        /// </summary>
-        /// <param name="enumType"></param>
-        /// <returns></returns>
-        public static Dictionary<string, int> GetValueItems(this Type enumType)
-        {
-            if (!enumType.IsEnum) throw new Exception("给定的类型不是枚举类型");
-            Dictionary<string, int> values = EnumValueNameDict.ContainsKey(enumType) ? EnumValueNameDict[enumType] : new Dictionary<string, int>();
-            if (values.Count == 0)
-            {
-                values = GetValueNameItems(enumType);
-                EnumValueNameDict[enumType] = values;
-            }
-
-            return values;
-        }
-
-        private static Dictionary<string, int> GetValueNameItems(Type enumType)
-        {
-            FieldInfo[] enumItems = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
-            Dictionary<string, int> values = new Dictionary<string, int>(enumItems.Length);
-            foreach (FieldInfo enumItem in enumItems)
-            {
-                values[enumItem.Name] = (int)enumItem.GetValue(enumType);
-            }
-
-            return values;
-        }
-
-
-        /// <summary>
-        /// 获取枚举对象的值内容
-        /// </summary>
-        /// <param name="enumType"></param>
-        /// <param name="name"></param>
-        /// <returns></returns>
-        public static int GetValue(this Type enumType, string name)
-        {
-            if (!enumType.IsEnum) throw new Exception("给定的类型不是枚举类型");
-            Dictionary<string, int> enumDict = GetValueNameItems(enumType);
-            return enumDict.ContainsKey(name) ? enumDict[name] : enumDict.Select(d => d.Value).FirstOrDefault();
-        }
-
-        /// <summary>
-        /// 获取枚举类型
-        /// </summary>
-        /// <param name="assembly"></param>
-        /// <param name="typeName"></param>
-        /// <returns></returns>
-        public static Type GetEnumType(Assembly assembly, string typeName)
-        {
-            _enumTypeDict ??= LoadEnumTypeDict(assembly);
-            if (_enumTypeDict.ContainsKey(typeName))
-            {
-                return _enumTypeDict[typeName];
-            }
-
-            return null;
-        }
-
-        private static ConcurrentDictionary<string, Type> LoadEnumTypeDict(Assembly assembly)
-        {
-            Type[] typeArray = assembly.GetTypes();
-            Dictionary<string, Type> dict = typeArray.Where(o => o.IsEnum).ToDictionary(o => o.Name, o => o);
-            return new ConcurrentDictionary<string, Type>(dict);
-        }
-
-
-        /// <summary>
-        /// 根据枚举成员获取自定义属性EnumDisplayNameAttribute的属性DisplayName
-        /// </summary>
-        /// <returns></returns>
-        public static Dictionary<string, int> GetDescriptionAndValue(this Type enumType)
-        {
-            Dictionary<string, int> dicResult = new Dictionary<string, int>();
-            foreach (object e in Enum.GetValues(enumType))
-            {
-                dicResult.Add(GetDescription(e as Enum), (int)e);
-            }
-
-            return dicResult;
-        }
-
-        /// <summary>
-        /// 根据枚举成员获取DescriptionAttribute的属性Description
-        /// </summary>
-        /// <returns></returns>
-        public static string GetDescription(this Enum en)
-        {
-            Type type = en.GetType(); //获取类型  
-            MemberInfo[] memberInfos = type.GetMember(en.ToString()); //获取成员  
-            if (memberInfos.Any())
-            {
-                DescriptionAttribute[] attrs = memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[]; //获取描述特性  
-                if (attrs != null && attrs.Length > 0)
-                {
-                    return attrs[0].Description; //返回当前描述  
-                }
-            }
-
-            return en.ToString();
-        }
-
-        /// <summary>
-        /// 根据枚举成员获取Display的属性Name
-        /// </summary>
-        /// <returns></returns>
-        public static string GetDisplay(this Enum en)
-        {
-            Type type = en.GetType(); //获取类型  
-            MemberInfo[] memberInfos = type.GetMember(en.ToString()); //获取成员  
-            if (memberInfos.Any())
-            {
-                DisplayAttribute[] attrs = memberInfos[0]?.GetCustomAttributes(typeof(DisplayAttribute), false) as DisplayAttribute[]; //获取描述特性  
-                if (attrs != null && attrs.Length > 0)
-                {
-                    return attrs[0].Name; //返回当前描述  
-                }
-            }
-
-            return en.ToString();
-        }
-
-        /// <summary>  
-        /// 扩展方法:根据枚举值得到相应的枚举定义字符串  
-        /// </summary>  
-        /// <param name="value"></param>  
-        /// <param name="enumType"></param>  
-        /// <returns></returns>  
-        public static String ToEnumString(this int value, Type enumType)
-        {
-            NameValueCollection nvc = GetEnumStringFromEnumValue(enumType);
-            return nvc[value.ToString()];
-        }
-
-        /// <summary>  
-        /// 根据枚举类型得到其所有的 值 与 枚举定义字符串 的集合  
-        /// </summary>  
-        /// <param name="enumType"></param>  
-        /// <returns></returns>  
-        public static NameValueCollection GetEnumStringFromEnumValue(Type enumType)
-        {
-            NameValueCollection nvc = new NameValueCollection();
-            FieldInfo[] fields = enumType.GetFields();
-            foreach (FieldInfo field in fields)
-            {
-                if (field.FieldType.IsEnum)
-                {
-                    var strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
-                    nvc.Add(strValue, field.Name);
-                }
-            }
-
-            return nvc;
-        }
-    }
-}

+ 0 - 86
Masuit.Tools.Core/Systems/HiPerfTimer.cs

@@ -1,86 +0,0 @@
-using System;
-using System.ComponentModel;
-using System.Runtime.InteropServices;
-using System.Threading;
-
-namespace Masuit.Tools.Systems
-{
-    /// <summary>
-    /// 纳秒级计时器
-    /// </summary>
-    public class HiPerfTimer
-    {
-        [DllImport("Kernel32.dll")]
-        private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
-
-        [DllImport("Kernel32.dll")]
-        private static extern bool QueryPerformanceFrequency(out long lpFrequency);
-
-        private long _startTime;
-        private long _stopTime;
-        private readonly long _freq;
-
-        /// <summary>
-        /// 纳秒计数器
-        /// </summary>
-        public HiPerfTimer()
-        {
-            _startTime = 0;
-            _stopTime = 0;
-
-            if (QueryPerformanceFrequency(out _freq) == false)
-            {
-                // 不支持高性能计数器 
-                throw new Win32Exception();
-            }
-        }
-
-        /// <summary>
-        /// 开始计时器
-        /// </summary>
-        public void Start()
-        {
-            // 来让等待线程工作 
-            Thread.Sleep(0);
-            QueryPerformanceCounter(out _startTime);
-        }
-
-        /// <summary>
-        /// 启动一个新的计时器
-        /// </summary>
-        /// <returns></returns>
-        public static HiPerfTimer StartNew()
-        {
-            HiPerfTimer timer = new HiPerfTimer();
-            timer.Start();
-            return timer;
-        }
-
-        /// <summary>
-        /// 停止计时器
-        /// </summary>
-        public void Stop()
-        {
-            QueryPerformanceCounter(out _stopTime);
-        }
-
-        /// <summary>
-        /// 时器经过时间(单位:秒)
-        /// </summary>
-        public double Duration => (_stopTime - _startTime) / (double)_freq;
-
-        /// <summary>
-        /// 执行一个方法并测试执行时间
-        /// </summary>
-        /// <param name="action"></param>
-        /// <returns></returns>
-        public static double Execute(Action action)
-        {
-            var timer = new HiPerfTimer();
-            timer.Start();
-            action();
-            timer.Stop();
-            return timer.Duration;
-        }
-    }
-}

+ 0 - 39
Masuit.Tools.Core/Systems/LimitedQueue.cs

@@ -1,39 +0,0 @@
-using System.Collections.Generic;
-
-namespace Masuit.Tools.Systems
-{
-    /// <summary>
-    /// 定长队列
-    /// </summary>
-    /// <typeparam name="T"></typeparam>
-    public class LimitedQueue<T> : Queue<T>
-    {
-        /// <summary>
-        /// 队列长度
-        /// </summary>
-        public int Limit { get; set; }
-
-        /// <summary>
-        /// 定长队列
-        /// </summary>
-        /// <param name="limit"></param>
-        public LimitedQueue(int limit) : base(limit)
-        {
-            Limit = limit;
-        }
-
-        /// <summary>
-        /// 入队
-        /// </summary>
-        /// <param name="item"></param>
-        public new void Enqueue(T item)
-        {
-            if (Count >= Limit)
-            {
-                Dequeue();
-            }
-
-            base.Enqueue(item);
-        }
-    }
-}

+ 0 - 173
Masuit.Tools.Core/Systems/SnowFlake.cs

@@ -1,173 +0,0 @@
-using Masuit.Tools.DateTimeExt;
-using Masuit.Tools.Strings;
-using System;
-
-namespace Masuit.Tools.Systems
-{
-    /// <summary>
-    /// 动态生产有规律的分布式ID
-    /// </summary>
-    public class SnowFlake
-    {
-        #region 私有字段
-
-        private static long _machineId; //机器码
-        private static long _datacenterId; //数据ID
-        private static long _sequence; //计数从零开始
-        private static long _lastTimestamp = -1L; //最后时间戳
-
-        private const long Twepoch = 687888001020L; //唯一时间随机量
-
-        private const long MachineIdBits = 5L; //机器码字节数
-        private const long DatacenterIdBits = 5L; //数据字节数
-        private const long MaxMachineId = -1L ^ -1L << (int)MachineIdBits; //最大机器码
-        private const long MaxDatacenterId = -1L ^ (-1L << (int)DatacenterIdBits); //最大数据ID
-
-        private const long SequenceBits = 12L; //计数器字节数,12个字节用来保存计数码        
-        private const long MachineIdShift = SequenceBits; //机器码数据左移位数,就是后面计数器占用的位数
-        private const long DatacenterIdShift = SequenceBits + MachineIdBits;
-        private const long TimestampLeftShift = DatacenterIdShift + DatacenterIdBits; //时间戳左移动位数就是机器码+计数器总字节数+数据字节数
-        private const long SequenceMask = -1L ^ -1L << (int)SequenceBits; //一毫秒内可以产生计数,如果达到该值则等到下一毫秒在进行生成
-
-        private static readonly object SyncRoot = new object(); //加锁对象
-        private static NumberFormater _numberFormater = new NumberFormater(36);
-        private static SnowFlake _snowFlake;
-
-        #endregion
-
-        /// <summary>
-        /// 获取一个新的id
-        /// </summary>
-        public static string NewId => GetInstance().GetUniqueId();
-
-        /// <summary>
-        /// 创建一个实例
-        /// </summary>
-        /// <returns></returns>
-        public static SnowFlake GetInstance()
-        {
-            return _snowFlake ??= new SnowFlake();
-        }
-
-        /// <summary>
-        /// 默认构造函数
-        /// </summary>
-        public SnowFlake()
-        {
-            Snowflakes(0, -1);
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="machineId">机器码</param>
-        public SnowFlake(long machineId)
-        {
-            Snowflakes(machineId, -1);
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="machineId">机器码</param>
-        /// <param name="datacenterId">数据中心id</param>
-        public SnowFlake(long machineId, long datacenterId)
-        {
-            Snowflakes(machineId, datacenterId);
-        }
-
-        private void Snowflakes(long machineId, long datacenterId)
-        {
-            if (machineId >= 0)
-            {
-                if (machineId > MaxMachineId)
-                {
-                    throw new Exception("机器码ID非法");
-                }
-
-                _machineId = machineId;
-            }
-
-            if (datacenterId >= 0)
-            {
-                if (datacenterId > MaxDatacenterId)
-                {
-                    throw new Exception("数据中心ID非法");
-                }
-
-                _datacenterId = datacenterId;
-            }
-        }
-
-        /// <summary>
-        /// 设置数制格式化器
-        /// </summary>
-        /// <param name="nf"></param>
-        public static void SetNumberFormater(NumberFormater nf)
-        {
-            _numberFormater = nf;
-        }
-
-        /// <summary>
-        /// 获取长整形的ID
-        /// </summary>
-        /// <returns></returns>
-        public long GetLongId()
-        {
-            lock (SyncRoot)
-            {
-                var timestamp = (long)DateTime.UtcNow.GetTotalMilliseconds();
-                if (_lastTimestamp == timestamp)
-                {
-                    //同一毫秒中生成ID
-                    _sequence = (_sequence + 1) & SequenceMask; //用&运算计算该毫秒内产生的计数是否已经到达上限
-                    if (_sequence == 0)
-                    {
-                        //一毫秒内产生的ID计数已达上限,等待下一毫秒
-                        timestamp = (long)DateTime.UtcNow.GetTotalMilliseconds();
-                    }
-                }
-                else
-                {
-                    //不同毫秒生成ID
-                    _sequence = 0L;
-                }
-
-                _lastTimestamp = timestamp; //把当前时间戳保存为最后生成ID的时间戳
-                long id = ((timestamp - Twepoch) << (int)TimestampLeftShift) | (_datacenterId << (int)DatacenterIdShift) | (_machineId << (int)MachineIdShift) | _sequence;
-                return id;
-            }
-        }
-
-        /// <summary>
-        /// 获取一个字符串表示形式的id
-        /// </summary>
-        /// <returns></returns>
-        public string GetUniqueId()
-        {
-            return _numberFormater.ToString(GetLongId());
-        }
-
-        /// <summary>
-        /// 获取一个字符串表示形式的id
-        /// </summary>
-        /// <param name="maxLength">最大长度,至少6位</param>
-        /// <returns></returns>
-        public string GetUniqueShortId(int maxLength = 8)
-        {
-            if (maxLength < 6)
-            {
-                throw new ArgumentException("最大长度至少需要6位");
-            }
-
-            string id = GetUniqueId();
-            int index = id.Length - maxLength;
-            if (index < 0)
-            {
-                index = 0;
-            }
-
-            return id.Substring(index);
-        }
-    }
-}

+ 0 - 15
Masuit.Tools.Core/Systems/StopwatchHelper.cs

@@ -1,15 +0,0 @@
-using System;
-using System.Diagnostics;
-
-namespace Masuit.Tools.Systems
-{
-    public static class StopwatchHelper
-    {
-        public static double Execute(Action action)
-        {
-            Stopwatch sw = Stopwatch.StartNew();
-            action();
-            return sw.ElapsedMilliseconds;
-        }
-    }
-}

+ 0 - 37
Masuit.Tools.Core/Validator/ComplexPassword.cs

@@ -1,37 +0,0 @@
-using System.ComponentModel.DataAnnotations;
-using System.Text.RegularExpressions;
-
-namespace Masuit.Tools.Core.Validator
-{
-    /// <summary>
-    /// 强密码验证
-    /// </summary>
-    public class ComplexPassword : ValidationAttribute
-    {
-        /// <summary>
-        /// 校验密码强度
-        /// </summary>
-        /// <param name="value"></param>
-        /// <returns></returns>
-        public override bool IsValid(object value)
-        {
-            string pwd = value as string;
-            if (pwd.Length <= 6)
-            {
-                ErrorMessage = "密码过短,至少需要6个字符!";
-                return false;
-            }
-            var regex = new Regex(@"(?=.*[0-9])                     #必须包含数字
-                                            (?=.*[a-zA-Z])                  #必须包含小写或大写字母
-                                            (?=([\x21-\x7e]+)[^a-zA-Z0-9])  #必须包含特殊符号
-                                            .{6,30}                         #至少6个字符,最多30个字符
-                                            ", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
-            if (regex.Match(pwd).Success)
-            {
-                return true;
-            }
-            ErrorMessage = "密码强度值不够,密码必须包含数字,必须包含小写或大写字母,必须包含至少一个特殊符号,至少6个字符,最多30个字符!";
-            return false;
-        }
-    }
-}

+ 0 - 43
Masuit.Tools.Core/Validator/IsEmailAttribute.cs

@@ -1,43 +0,0 @@
-using System.ComponentModel.DataAnnotations;
-
-namespace Masuit.Tools.Core.Validator
-{
-    /// <summary>
-    /// 邮箱校验
-    /// </summary>
-    public class IsEmailAttribute : ValidationAttribute
-    {
-        /// <summary>
-        /// 邮箱校验
-        /// </summary>
-        /// <param name="value"></param>
-        /// <returns></returns>
-        public override bool IsValid(object value)
-        {
-            if (value == null)
-            {
-                ErrorMessage = "邮箱不能为空!";
-                return false;
-            }
-
-            var email = value as string;
-            if (email.Length < 6)
-            {
-                ErrorMessage = "您输入的邮箱格式不正确!";
-                return false;
-            }
-
-            if (email.Length > 256)
-            {
-                ErrorMessage = "邮箱长度最大允许255个字符!";
-                return false;
-            }
-            if (email.MatchEmail())
-            {
-                return true;
-            }
-            ErrorMessage = "您输入的邮箱格式不正确!";
-            return false;
-        }
-    }
-}

+ 0 - 31
Masuit.Tools.Core/Validator/IsIPAddressAttribute.cs

@@ -1,31 +0,0 @@
-using System.ComponentModel.DataAnnotations;
-
-namespace Masuit.Tools.Core.Validator
-{
-    /// <summary>
-    /// 验证IPv4地址是否合法
-    /// </summary>
-    public class IsIPAddressAttribute : ValidationAttribute
-    {
-        /// <summary>
-        /// 验证IPv4地址是否合法
-        /// </summary>
-        /// <param name="value"></param>
-        /// <returns></returns>
-        public override bool IsValid(object value)
-        {
-            if (value is null)
-            {
-                ErrorMessage = "IP地址不能为空!";
-                return false;
-            }
-            string email = value as string;
-            if (email.MatchInetAddress())
-            {
-                return true;
-            }
-            ErrorMessage = "IP地址格式不正确,请输入有效的IPv4地址";
-            return false;
-        }
-    }
-}

+ 0 - 31
Masuit.Tools.Core/Validator/IsPhoneAttribute.cs

@@ -1,31 +0,0 @@
-using System.ComponentModel.DataAnnotations;
-
-namespace Masuit.Tools.Core.Validator
-{
-    /// <summary>
-    /// 验证手机号码是否合法
-    /// </summary>
-    public class IsPhoneAttribute : ValidationAttribute
-    {
-        /// <summary>
-        /// 验证手机号码是否合法
-        /// </summary>
-        /// <param name="value"></param>
-        /// <returns></returns>
-        public override bool IsValid(object value)
-        {
-            if (value is null)
-            {
-                ErrorMessage = "手机号码不能为空";
-                return false;
-            }
-            string phone = value as string;
-            if (phone.MatchPhoneNumber())
-            {
-                return true;
-            }
-            ErrorMessage = "手机号码格式不正确,请输入有效的大陆11位手机号码!";
-            return false;
-        }
-    }
-}

+ 0 - 46
Masuit.Tools.Core/Validator/MaxValueAttribute.cs

@@ -1,46 +0,0 @@
-using System;
-using System.ComponentModel.DataAnnotations;
-
-namespace Masuit.Tools.Core.Validator
-{
-    /// <summary>
-    /// 最大值校验
-    /// </summary>
-    public class MaxValueAttribute : ValidationAttribute
-    {
-        private double MaxValue { get; }
-
-        /// <summary>
-        /// 最大值
-        /// </summary>
-        /// <param name="value"></param>
-        public MaxValueAttribute(double value)
-        {
-            MaxValue = value;
-        }
-
-        /// <summary>
-        /// 最大值校验
-        /// </summary>
-        /// <param name="value"></param>
-        /// <returns></returns>
-        public override bool IsValid(object value)
-        {
-            if (value is null)
-            {
-                return true;
-            }
-
-            var input = Convert.ToDouble(value);
-            return input <= MaxValue;
-        }
-
-        /// <summary>Applies formatting to an error message, based on the data field where the error occurred.</summary>
-        /// <param name="name">The name to include in the formatted message.</param>
-        /// <returns>An instance of the formatted error message.</returns>
-        public override string FormatErrorMessage(string name)
-        {
-            return base.FormatErrorMessage(name);
-        }
-    }
-}

+ 0 - 46
Masuit.Tools.Core/Validator/MinValueAttribute.cs

@@ -1,46 +0,0 @@
-using System;
-using System.ComponentModel.DataAnnotations;
-
-namespace Masuit.Tools.Core.Validator
-{
-    /// <summary>
-    /// 最小值校验
-    /// </summary>
-    public class MinValueAttribute : ValidationAttribute
-    {
-        private double MinValue { get; set; }
-
-        /// <summary>
-        /// 最小值
-        /// </summary>
-        /// <param name="value"></param>
-        public MinValueAttribute(double value)
-        {
-            MinValue = value;
-        }
-
-        /// <summary>
-        /// 最小值校验
-        /// </summary>
-        /// <param name="value"></param>
-        /// <returns></returns>
-        public override bool IsValid(object value)
-        {
-            if (value is null)
-            {
-                return true;
-            }
-
-            var input = Convert.ToDouble(value);
-            return input > MinValue;
-        }
-
-        /// <summary>Applies formatting to an error message, based on the data field where the error occurred.</summary>
-        /// <param name="name">The name to include in the formatted message.</param>
-        /// <returns>An instance of the formatted error message.</returns>
-        public override string FormatErrorMessage(string name)
-        {
-            return base.FormatErrorMessage(name);
-        }
-    }
-}

+ 0 - 431
Masuit.Tools.Core/Win32/Windows.cs

@@ -1,431 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Linq;
-using System.Management;
-using System.Net;
-using System.Net.NetworkInformation;
-using System.Text;
-using System.Threading;
-using static System.String;
-
-namespace Masuit.Tools.Win32
-{
-    /// <summary>
-    /// Windows系统的系列方法
-    /// </summary>
-    public static class Windows
-    {
-        /// <summary>  
-        /// 获取当前使用的IP  
-        /// </summary>  
-        /// <returns></returns>  
-        public static IPAddress GetLocalUsedIP()
-        {
-            return NetworkInterface.GetAllNetworkInterfaces().Select(p => p.GetIPProperties()).SelectMany(p => p.UnicastAddresses).Where(p => p.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred && !IPAddress.IsLoopback(p.Address)).Select(x => x.Address).FirstOrDefault();
-        }
-
-        /// <summary>  
-        /// 获取本机所有的ip地址
-        /// </summary>  
-        /// <returns></returns>  
-        public static List<UnicastIPAddressInformation> GetLocalIPs()
-        {
-            return NetworkInterface.GetAllNetworkInterfaces().Select(p => p.GetIPProperties()).SelectMany(p => p.UnicastAddresses).Where(p => !IPAddress.IsLoopback(p.Address)).ToList();
-        }
-
-        /// <summary>  
-        /// 运行一个控制台程序并返回其输出参数。  
-        /// </summary>  
-        /// <param name="filename">程序名</param>  
-        /// <param name="arguments">输入参数</param>
-        /// <param name="recordLog">是否在控制台输出日志</param>
-        /// <returns></returns>  
-        public static string RunApp(string filename, string arguments, bool recordLog)
-        {
-            try
-            {
-                if (recordLog)
-                {
-                    Trace.WriteLine(filename + " " + arguments);
-                }
-
-                Process proc = new Process
-                {
-                    StartInfo =
-                    {
-                        FileName = filename,
-                        CreateNoWindow = true,
-                        Arguments = arguments,
-                        RedirectStandardOutput = true,
-                        UseShellExecute = false
-                    }
-                };
-                proc.Start();
-
-                using var sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default);
-                //上面标记的是原文,下面是我自己调试错误后自行修改的  
-                Thread.Sleep(100); //貌似调用系统的nslookup还未返回数据或者数据未编码完成,程序就已经跳过直接执行  
-                //txt = sr.ReadToEnd()了,导致返回的数据为空,故睡眠令硬件反应  
-                if (!proc.HasExited) //在无参数调用nslookup后,可以继续输入命令继续操作,如果进程未停止就直接执行  
-                {
-                    //txt = sr.ReadToEnd()程序就在等待输入,而且又无法输入,直接掐住无法继续运行  
-                    proc.Kill();
-                }
-
-                string txt = sr.ReadToEnd();
-                if (recordLog)
-                {
-                    Trace.WriteLine(txt);
-                }
-
-                return txt;
-            }
-            catch (Exception ex)
-            {
-                Trace.WriteLine(ex);
-                return ex.Message;
-            }
-        }
-    }
-
-    /// <summary>
-    /// 服务器信息
-    /// </summary>
-    public class WindowsServer
-    {
-        /// <summary>
-        /// CPUID
-        /// </summary>
-        public string CpuId; //CPU的ID
-
-        /// <summary>
-        /// CPU插槽数
-        /// </summary>
-        public int CpuCount; //CPU的个数
-
-        /// <summary>
-        /// CPU主频
-        /// </summary>
-        public string[] CpuMhz; //CPU频率  单位:hz
-
-        /// <summary>
-        /// mac地址
-        /// </summary>
-        public string MacAddress; //计算机的MAC地址
-
-        /// <summary>
-        /// 硬盘ID
-        /// </summary>
-        public string DiskId; //硬盘的ID
-
-        /// <summary>
-        /// 硬盘大小
-        /// </summary>
-        public string DiskSize; //硬盘大小  单位:bytes
-
-        /// <summary>
-        /// IP地址
-        /// </summary>
-        public string IpAddress; //计算机的IP地址
-
-        /// <summary>
-        /// 系统当前登录用户
-        /// </summary>
-        public string LoginUserName; //操作系统登录用户名
-
-        /// <summary>
-        /// 计算机名
-        /// </summary>
-        public string ComputerName; //计算机名
-
-        /// <summary>
-        /// 操作系统架构
-        /// </summary>
-        public string SystemType; //系统类型
-
-        /// <summary>
-        /// 物理内存,单位MB
-        /// </summary>
-        public string TotalPhysicalMemory; //总共的内存  单位:M 
-
-        private static WindowsServer _instance;
-
-        /// <summary>
-        /// 获取实例
-        /// </summary>
-        public static WindowsServer Instance
-        {
-            get
-            {
-                if (_instance == null) _instance = new WindowsServer();
-                return _instance;
-            }
-        }
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        public WindowsServer()
-        {
-            CpuId = GetCpuID();
-            CpuCount = GetCpuCount();
-            CpuMhz = GetCpuMHZ();
-            MacAddress = GetMacAddress();
-            DiskId = GetDiskID();
-            DiskSize = GetSizeOfDisk();
-            IpAddress = GetIPAddress();
-            LoginUserName = GetUserName();
-            SystemType = GetSystemType();
-            TotalPhysicalMemory = GetTotalPhysicalMemory();
-            ComputerName = GetComputerName();
-        }
-
-        string GetCpuID()
-        {
-            try
-            {
-                //获取CPU序列号代码 
-                string cpuInfo = " "; //cpu序列号 
-                using var mc = new ManagementClass("Win32_Processor");
-                foreach (ManagementObject mo in mc.GetInstances())
-                {
-                    using (mo)
-                    {
-                        cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
-                    }
-                }
-
-                return cpuInfo;
-            }
-            catch
-            {
-                return "unknow ";
-            }
-        }
-
-        /// <summary>
-        /// 获取CPU个数
-        /// </summary>
-        /// <returns></returns>
-        public static int GetCpuCount()
-        {
-            try
-            {
-                using var mCpu = new ManagementClass("Win32_Processor");
-                using var cpus = mCpu.GetInstances();
-                return cpus.Count;
-            }
-            catch
-            {
-                // ignored
-            }
-
-            return -1;
-        }
-
-        /// <summary>
-        /// 获取CPU主频
-        /// </summary>
-        /// <returns></returns>
-        public static string[] GetCpuMHZ()
-        {
-            using var mc = new ManagementClass("Win32_Processor");
-            using ManagementObjectCollection cpus = mc.GetInstances();
-            var mhz = new string[cpus.Count];
-            int c = 0;
-            using var mySearch = new ManagementObjectSearcher("select * from Win32_Processor");
-            foreach (ManagementObject mo in mySearch.Get())
-            {
-                using (mo)
-                {
-                    mhz[c] = mo.Properties["CurrentClockSpeed"].Value.ToString();
-                    c++;
-                }
-            }
-
-            return mhz;
-        }
-
-        /// <summary>
-        /// 获取磁盘大小
-        /// </summary>
-        /// <returns></returns>
-        public static string GetSizeOfDisk()
-        {
-            using var mc = new ManagementClass("Win32_DiskDrive");
-            foreach (ManagementObject m in mc.GetInstances())
-            {
-                using (m)
-                {
-                    return m.Properties["Size"].Value.ToString();
-                }
-            }
-
-            return "-1";
-        }
-
-        string GetMacAddress()
-        {
-            try
-            {
-                //获取网卡硬件地址 
-                string mac = " ";
-                using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
-                foreach (ManagementObject mo in mc.GetInstances())
-                {
-                    using (mo)
-                    {
-                        if ((bool)mo["IPEnabled"])
-                        {
-                            mac = mo["MacAddress"].ToString();
-                            break;
-                        }
-                    }
-                }
-
-                return mac;
-            }
-            catch
-            {
-                return "unknow ";
-            }
-        }
-
-        string GetIPAddress()
-        {
-            try
-            {
-                //获取IP地址 
-                string st = Empty;
-                using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
-                foreach (ManagementObject mo in mc.GetInstances())
-                {
-                    using (mo)
-                    {
-                        if ((bool)mo["IPEnabled"])
-                        {
-                            //st=mo[ "IpAddress "].ToString(); 
-                            Array ar;
-                            ar = (Array)(mo.Properties["IpAddress"].Value);
-                            st = ar.GetValue(0).ToString();
-                            break;
-                        }
-                    }
-                }
-
-                return st;
-            }
-            catch
-            {
-                return "unknow ";
-            }
-        }
-
-        string GetDiskID()
-        {
-            try
-            {
-                //获取硬盘ID 
-                string hdid = Empty;
-                using var mc = new ManagementClass("Win32_DiskDrive");
-                foreach (ManagementObject mo in mc.GetInstances())
-                {
-                    using (mo)
-                    {
-                        hdid = (string)mo.Properties["Model"].Value;
-                    }
-                }
-
-                return hdid;
-            }
-            catch
-            {
-                return "unknow ";
-            }
-        }
-
-        ///    <summary>  
-        ///   操作系统的登录用户名 
-        ///    </summary>  
-        ///    <returns>  </returns>  
-        string GetUserName()
-        {
-            try
-            {
-                string st = Empty;
-                using var mc = new ManagementClass("Win32_ComputerSystem");
-                foreach (ManagementObject mo in mc.GetInstances())
-                {
-                    using (mo)
-                    {
-                        st = mo["UserName"].ToString();
-                    }
-                }
-
-                return st;
-            }
-            catch
-            {
-                return "unknow ";
-            }
-        }
-
-        string GetSystemType()
-        {
-            try
-            {
-                string st = Empty;
-                using var mc = new ManagementClass("Win32_ComputerSystem");
-                foreach (var o in mc.GetInstances())
-                {
-                    using (o)
-                    {
-                        var mo = (ManagementObject)o;
-                        st = mo["SystemType"].ToString();
-                    }
-                }
-
-                return st;
-            }
-            catch
-            {
-                return "unknow ";
-            }
-        }
-
-        string GetTotalPhysicalMemory()
-        {
-            try
-            {
-                string st = Empty;
-                using var mc = new ManagementClass("Win32_ComputerSystem");
-                using var moc = mc.GetInstances();
-                foreach (var o in moc)
-                {
-                    var mo = (ManagementObject)o;
-
-                    st = mo["TotalPhysicalMemory"].ToString();
-                }
-
-                return st;
-            }
-            catch
-            {
-                return "unknow ";
-            }
-        }
-
-        string GetComputerName()
-        {
-            try
-            {
-                return Environment.GetEnvironmentVariable("ComputerName");
-            }
-            catch
-            {
-                return "unknow ";
-            }
-        }
-    }
-}

+ 0 - 57
Masuit.Tools.Core/Win32/WindowsCommand.cs

@@ -1,57 +0,0 @@
-using System;
-using System.ComponentModel;
-using System.Diagnostics;
-
-namespace Masuit.Tools.Win32
-{
-    /// <summary>
-    /// 命令提示符
-    /// </summary>
-    public static class WindowsCommand
-    {
-        /// <summary>
-        /// 执行一个控制台程序,并获取在控制台返回的数据
-        /// </summary>
-        /// <param name="dosCommand">dos/cmd命令</param>
-        /// <param name="outtime">等待执行时间毫秒值,默认不等待</param>
-        /// <returns>控制台输出信息</returns>
-        /// <exception cref="SystemException">尚未设置进程 <see cref="P:System.Diagnostics.Process.Id" />,而且不存在可从其确定 <see cref="P:System.Diagnostics.Process.Id" /> 属性的 <see cref="P:System.Diagnostics.Process.Handle" />。- 或 -没有与此 <see cref="T:System.Diagnostics.Process" /> 对象关联的进程。- 或 -您正尝试为远程计算机上运行的进程调用 <see cref="M:System.Diagnostics.Process.WaitForExit(System.Int32)" />。此方法仅对本地计算机上运行的进程可用。</exception>
-        /// <exception cref="Win32Exception">未能访问该等待设置。</exception>
-        /// <exception cref="Exception">命令参数无效,必须传入一个控制台能被cmd.exe可执行程序; 如:ping 127.0.0.1</exception>
-        public static string Execute(string dosCommand, int outtime = 0)
-        {
-            string output = "";
-            if (!string.IsNullOrEmpty(dosCommand))
-            {
-                using var process = new Process();
-                ProcessStartInfo startinfo = new ProcessStartInfo(); //创建进程时使用的一组值,如下面的属性  
-                startinfo.FileName = "cmd.exe"; //设定需要执行的命令程序  
-                //以下是隐藏cmd窗口的方法  
-                startinfo.Arguments = "/c" + dosCommand; //设定参数,要输入到命令程序的字符,其中"/c"表示执行完命令后马上退出  
-                startinfo.UseShellExecute = false; //不使用系统外壳程序启动  
-                startinfo.RedirectStandardInput = false; //不重定向输入  
-                startinfo.RedirectStandardOutput = true; //重定向输出,而不是默认的显示在dos控制台上  
-                startinfo.CreateNoWindow = true; //不创建窗口  
-                process.StartInfo = startinfo;
-
-                if (process.Start()) //开始进程  
-                {
-                    if (outtime == 0)
-                    {
-                        process.WaitForExit();
-                    }
-                    else
-                    {
-                        process.WaitForExit(outtime);
-                    }
-
-                    output = process.StandardOutput.ReadToEnd(); //读取进程的输出  
-                }
-
-                return output;
-            }
-
-            throw new Exception("命令参数无效,必须传入一个控制台能被cmd.exe可执行程序;\n如:ping 127.0.0.1");
-        }
-    }
-}

+ 0 - 20
Masuit.Tools.UnitTest/Mapping/Extentions/QueryableExtentionsTest.cs

@@ -68,26 +68,6 @@ namespace Masuit.Tools.UnitTest.Mapping.Extentions
             Assert.IsTrue(CheckExpressionMethod(actual.Expression, nameof(QueryableExtentions.ThenByDescending)));
         }
 
-        [TestMethod, TestCategory("Extentions")]
-        public void Select_Success()
-        {
-            Init(null);
-
-            QueryableImplTest<ClassSource> expected = new QueryableImplTest<ClassSource>();
-
-            var actual = expected.Select<ClassSource, ClassDest>();
-            Assert.IsTrue(CheckExpressionMethod(actual.Expression, nameof(QueryableExtentions.Select)));
-        }
-
-        [TestMethod, TestCategory("Extentions")]
-        public void Where_Success()
-        {
-            QueryableImplTest<ClassDest> expected = new QueryableImplTest<ClassDest>();
-            Expression<Func<ClassSource, bool>> criterias = x => x.PropInt1 == 1;
-            var actual = expected.Where(criterias);
-            Assert.IsTrue(CheckExpressionMethod(actual.Expression, nameof(QueryableExtentions.Where)));
-        }
-
         private bool CheckExpressionMethod(Expression expression, string methodeName)
         {
             if (expression.NodeType == ExpressionType.Call)

+ 26 - 2
Masuit.Tools/Hardware/RamInfo.cs

@@ -5,15 +5,39 @@
     /// </summary>
     public class RamInfo
     {
-#pragma warning disable 1591
+        /// <summary>
+        /// 可用物理内存
+        /// </summary>
         public double MemoryAvailable { get; set; }
+
+        /// <summary>
+        /// 物理总内存
+        /// </summary>
         public double PhysicalMemory { get; set; }
+
+        /// <summary>
+        /// 分页内存总数
+        /// </summary>
         public double TotalPageFile { get; set; }
+
+        /// <summary>
+        /// 分页内存可用
+        /// </summary>
         public double AvailablePageFile { get; set; }
+
+        /// <summary>
+        /// 虚拟内存总数
+        /// </summary>
         public double TotalVirtual { get; set; }
+
+        /// <summary>
+        /// 虚拟内存可用
+        /// </summary>
         public double AvailableVirtual { get; set; }
 
+        /// <summary>
+        /// 内存使用率
+        /// </summary>
         public double MemoryUsage => (1 - MemoryAvailable / PhysicalMemory) * 100;
-#pragma warning restore 1591
     }
 }

+ 5 - 5
Masuit.Tools/Mapping/Extensions/QueryableExtentions.cs

@@ -67,7 +67,7 @@ namespace Masuit.Tools.Mapping.Extensions
         /// <typeparam name="TSource">源类型.</typeparam>
         /// <typeparam name="TDest">目标类型.</typeparam>
         /// <param name="query">分类化的序列值</param>
-        public static IQueryable<TDest> Select<TSource, TDest>(this IQueryable<TSource> query) where TSource : class where TDest : class
+        public static IQueryable<TDest> ProjectTo<TSource, TDest>(this IQueryable<TSource> query) where TSource : class where TDest : class
         {
             return GetSelect<TSource, TDest>(query, null);
         }
@@ -80,7 +80,7 @@ namespace Masuit.Tools.Mapping.Extensions
         /// <param name="query">分类化的序列值</param>
         /// <param name="mapperName">mapper别名</param>
         /// <returns></returns>
-        public static IQueryable<TDest> Select<TSource, TDest>(this IQueryable<TSource> query, string mapperName) where TSource : class where TDest : class
+        public static IQueryable<TDest> ProjectTo<TSource, TDest>(this IQueryable<TSource> query, string mapperName) where TSource : class where TDest : class
         {
             return GetSelect<TSource, TDest>(query, mapperName);
         }
@@ -93,9 +93,9 @@ namespace Masuit.Tools.Mapping.Extensions
         /// <param name="query">分类化的序列值</param>
         /// <param name="predicate">用于根据条件测试每个元素的功能。</param>
         /// <returns></returns>
-        public static IQueryable<TDest> Where<TSource, TDest>(this IQueryable<TDest> query, Expression<Func<TSource, bool>> predicate)
+        public static IQueryable<TDest> WhereTo<TSource, TDest>(this IQueryable<TDest> query, Expression<Func<TSource, bool>> predicate)
         {
-            return Queryable.Where(query, predicate.ConvertTo<TSource, TDest>());
+            return query.Where(predicate.ConvertTo<TSource, TDest>());
         }
 
         private static TQueryable CreateSortedMethodCall<TSource, TDest, TQueryable>(IQueryable<TSource> query, string methodName, string sortedPropertySourceName) where TSource : class where TDest : class where TQueryable : class, IQueryable<TSource>
@@ -103,7 +103,7 @@ namespace Masuit.Tools.Mapping.Extensions
             MapperConfiguration<TSource, TDest> mapper = ExpressionMapper.GetMapper<TSource, TDest>();
             var prop = mapper.GetLambdaDest(sortedPropertySourceName);
             var lambda = mapper.GetSortedExpression(sortedPropertySourceName);
-            MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName, new[]
+            MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName, new Type[]
             {
                 typeof(TSource),
                 prop.Type

+ 142 - 195
Masuit.Tools/Net/PartialDownloader.cs

@@ -13,8 +13,6 @@ namespace Masuit.Tools.Net
     /// </summary>
     public class PartialDownloader
     {
-        #region Variables
-
         /// <summary>
         /// 这部分完成事件
         /// </summary>
@@ -30,19 +28,107 @@ namespace Masuit.Tools.Net
         /// </summary>
         public event EventHandler DownloadPartStopped;
 
-        HttpWebRequest _req;
-        HttpWebResponse _resp;
-        Stream _tempStream;
-        FileStream _file;
         private readonly AsyncOperation _aop = AsyncOperationManager.CreateOperation(null);
-        private readonly Stopwatch _stp;
         readonly int[] _lastSpeeds;
         int _counter;
-        bool _stop, _wait;
+        private bool _wait;
+        private int _to;
+        private int _totalBytesRead;
 
-        #endregion
+        /// <summary>
+        /// 下载已停止
+        /// </summary>
+        public bool Stopped { get; private set; }
 
-        #region PartialDownloader
+        /// <summary>
+        /// 下载已完成
+        /// </summary>
+        public bool Completed { get; private set; }
+
+        /// <summary>
+        /// 下载进度
+        /// </summary>
+        public int Progress { get; private set; }
+
+        /// <summary>
+        /// 下载目录
+        /// </summary>
+        public string Directory { get; }
+
+        /// <summary>
+        /// 文件名
+        /// </summary>
+        public string FileName { get; }
+
+        /// <summary>
+        /// 已读字节数
+        /// </summary>
+        public long TotalBytesRead => _totalBytesRead;
+
+        /// <summary>
+        /// 内容长度
+        /// </summary>
+        public long ContentLength { get; private set; }
+
+        /// <summary>
+        /// RangeAllowed
+        /// </summary>
+        public bool RangeAllowed { get; }
+
+        /// <summary>
+        /// url
+        /// </summary>
+        public string Url { get; }
+
+        /// <summary>
+        /// to
+        /// </summary>
+        public int To
+        {
+            get => _to;
+            set
+            {
+                _to = value;
+                ContentLength = _to - From + 1;
+            }
+        }
+
+        /// <summary>
+        /// from
+        /// </summary>
+        public int From { get; }
+
+        /// <summary>
+        /// 当前位置
+        /// </summary>
+        public int CurrentPosition => From + _totalBytesRead - 1;
+
+        /// <summary>
+        /// 剩余字节数
+        /// </summary>
+        public int RemainingBytes => (int)(ContentLength - _totalBytesRead);
+
+        /// <summary>
+        /// 完整路径
+        /// </summary>
+        public string FullPath => Path.Combine(Directory, FileName);
+
+        /// <summary>
+        /// 下载速度
+        /// </summary>
+        public int SpeedInBytes
+        {
+            get
+            {
+                if (Completed)
+                {
+                    return 0;
+                }
+
+                int totalSpeeds = _lastSpeeds.Sum();
+                return totalSpeeds / 10;
+            }
+        }
 
         /// <summary>
         /// 部分块下载
@@ -55,124 +141,100 @@ namespace Masuit.Tools.Net
         /// <param name="rangeAllowed"></param>
         public PartialDownloader(string url, string dir, string fileGuid, int from, int to, bool rangeAllowed)
         {
-            _from = from;
+            From = @from;
             _to = to;
-            _url = url;
-            _rangeAllowed = rangeAllowed;
-            _fileGuid = fileGuid;
-            _directory = dir;
+            Url = url;
+            RangeAllowed = rangeAllowed;
+            FileName = fileGuid;
+            Directory = dir;
             _lastSpeeds = new int[10];
-            _stp = new Stopwatch();
         }
 
-        #endregion
-
         void DownloadProcedure()
         {
-            _file = new FileStream(FullPath, FileMode.Create, FileAccess.ReadWrite);
-
-            #region Request-Response
-
-            _req = WebRequest.Create(_url) as HttpWebRequest;
-            if (_req != null)
+            using var file = new FileStream(FullPath, FileMode.Create, FileAccess.ReadWrite);
+            var sw = new Stopwatch();
+            if (WebRequest.Create(Url) is HttpWebRequest req)
             {
-                _req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
-                _req.AllowAutoRedirect = true;
-                _req.MaximumAutomaticRedirections = 5;
-                _req.ServicePoint.ConnectionLimit += 1;
-                _req.ServicePoint.Expect100Continue = true;
-                _req.ProtocolVersion = HttpVersion.Version10;
+                req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
+                req.AllowAutoRedirect = true;
+                req.MaximumAutomaticRedirections = 5;
+                req.ServicePoint.ConnectionLimit += 1;
+                req.ServicePoint.Expect100Continue = true;
+                req.ProtocolVersion = HttpVersion.Version10;
                 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
                 ServicePointManager.Expect100Continue = true;
-                if (_rangeAllowed)
-                    _req.AddRange(_from, _to);
-                _resp = _req.GetResponse() as HttpWebResponse;
-
-                #endregion
-
-                #region Some Stuff
+                if (RangeAllowed)
+                {
+                    req.AddRange(From, _to);
+                }
 
-                if (_resp != null)
+                if (req.GetResponse() is HttpWebResponse resp)
                 {
-                    _contentLength = _resp.ContentLength;
-                    if (_contentLength <= 0 || (_rangeAllowed && _contentLength != _to - _from + 1))
+                    ContentLength = resp.ContentLength;
+                    if (ContentLength <= 0 || (RangeAllowed && ContentLength != _to - From + 1))
+                    {
                         throw new Exception("Invalid response content");
-                    _tempStream = _resp.GetResponseStream();
+                    }
+
+                    using var tempStream = resp.GetResponseStream();
                     int bytesRead;
                     byte[] buffer = new byte[4096];
-                    _stp.Start();
-
-                    #endregion
-
-                    #region Procedure Loop
-
-                    while (_tempStream != null && (bytesRead = _tempStream.Read(buffer, 0, buffer.Length)) > 0)
+                    sw.Start();
+                    while ((bytesRead = tempStream.Read(buffer, 0, buffer.Length)) > 0)
                     {
-                        while (_wait)
+                        if (_totalBytesRead + bytesRead > ContentLength)
                         {
+                            bytesRead = (int)(ContentLength - _totalBytesRead);
                         }
 
-                        if (_totalBytesRead + bytesRead > _contentLength)
-                            bytesRead = (int)(_contentLength - _totalBytesRead);
-                        _file.Write(buffer, 0, bytesRead);
+                        file.Write(buffer, 0, bytesRead);
                         _totalBytesRead += bytesRead;
-                        _lastSpeeds[_counter] = (int)(_totalBytesRead / Math.Ceiling(_stp.Elapsed.TotalSeconds));
+                        _lastSpeeds[_counter] = (int)(_totalBytesRead / Math.Ceiling(sw.Elapsed.TotalSeconds));
                         _counter = (_counter >= 9) ? 0 : _counter + 1;
-                        int tempProgress = (int)(_totalBytesRead * 100 / _contentLength);
-                        if (_progress != tempProgress)
+                        int tempProgress = (int)(_totalBytesRead * 100 / ContentLength);
+                        if (Progress != tempProgress)
                         {
-                            _progress = tempProgress;
+                            Progress = tempProgress;
                             _aop.Post(state =>
                             {
                                 DownloadPartProgressChanged?.Invoke(this, EventArgs.Empty);
                             }, null);
                         }
 
-                        if (_stop || (_rangeAllowed && _totalBytesRead == _contentLength))
+                        if (Stopped || (RangeAllowed && _totalBytesRead == ContentLength))
                         {
                             break;
                         }
                     }
-
-                    #endregion
-
-                    #region Close Resources
-
-                    _file.Close();
-                    _resp.Close();
                 }
 
-                _tempStream?.Close();
-                _req.Abort();
+                req.Abort();
             }
 
-            _stp.Stop();
-
-            #endregion
+            sw.Stop();
 
-            #region Fire Events
-
-            if (!_stop && DownloadPartCompleted != null)
+            if (!Stopped && DownloadPartCompleted != null)
+            {
                 _aop.Post(state =>
                 {
-                    _completed = true;
+                    Completed = true;
                     DownloadPartCompleted(this, EventArgs.Empty);
                 }, null);
+            }
 
-            if (_stop && DownloadPartStopped != null)
+            if (Stopped && DownloadPartStopped != null)
+            {
                 _aop.Post(state => DownloadPartStopped(this, EventArgs.Empty), null);
-
-            #endregion
+            }
         }
 
-        #region Public Methods
-
         /// <summary>
         /// 启动下载
         /// </summary>
         public void Start()
         {
-            _stop = false;
+            Stopped = false;
             Thread procThread = new Thread(DownloadProcedure);
             procThread.Start();
         }
@@ -182,7 +244,7 @@ namespace Masuit.Tools.Net
         /// </summary>
         public void Stop()
         {
-            _stop = true;
+            Stopped = true;
         }
 
         /// <summary>
@@ -200,120 +262,5 @@ namespace Masuit.Tools.Net
         {
             _wait = false;
         }
-
-        #endregion
-
-        #region Property Variables
-
-        private readonly int _from;
-        private int _to;
-        private readonly string _url;
-        private readonly bool _rangeAllowed;
-        private long _contentLength;
-        private int _totalBytesRead;
-        private readonly string _fileGuid;
-        private readonly string _directory;
-        private int _progress;
-        private bool _completed;
-
-        #endregion
-
-        #region Properties
-
-        /// <summary>
-        /// 下载已停止
-        /// </summary>
-        public bool Stopped => _stop;
-
-        /// <summary>
-        /// 下载已完成
-        /// </summary>
-        public bool Completed => _completed;
-
-        /// <summary>
-        /// 下载进度
-        /// </summary>
-        public int Progress => _progress;
-
-        /// <summary>
-        /// 下载目录
-        /// </summary>
-        public string Directory => _directory;
-
-        /// <summary>
-        /// 文件名
-        /// </summary>
-        public string FileName => _fileGuid;
-
-        /// <summary>
-        /// 已读字节数
-        /// </summary>
-        public long TotalBytesRead => _totalBytesRead;
-
-        /// <summary>
-        /// 内容长度
-        /// </summary>
-        public long ContentLength => _contentLength;
-
-        /// <summary>
-        /// RangeAllowed
-        /// </summary>
-        public bool RangeAllowed => _rangeAllowed;
-
-        /// <summary>
-        /// url
-        /// </summary>
-        public string Url => _url;
-
-        /// <summary>
-        /// to
-        /// </summary>
-        public int To
-        {
-            get => _to;
-            set
-            {
-                _to = value;
-                _contentLength = _to - _from + 1;
-            }
-        }
-
-        /// <summary>
-        /// from
-        /// </summary>
-        public int From => _from;
-
-        /// <summary>
-        /// 当前位置
-        /// </summary>
-        public int CurrentPosition => _from + _totalBytesRead - 1;
-
-        /// <summary>
-        /// 剩余字节数
-        /// </summary>
-        public int RemainingBytes => (int)(_contentLength - _totalBytesRead);
-
-        /// <summary>
-        /// 完整路径
-        /// </summary>
-        public string FullPath => Path.Combine(_directory, _fileGuid);
-
-        /// <summary>
-        /// 下载速度
-        /// </summary>
-        public int SpeedInBytes
-        {
-            get
-            {
-                if (_completed)
-                    return 0;
-
-                int totalSpeeds = _lastSpeeds.Sum();
-
-                return totalSpeeds / 10;
-            }
-        }
-
-        #endregion
     }
 }

+ 2 - 3
Masuit.Tools/Security/Encrypt.cs

@@ -1,6 +1,5 @@
 using System;
 using System.Collections;
-using System.Configuration;
 using System.IO;
 using System.Security.Cryptography;
 using System.Text;
@@ -15,9 +14,9 @@ namespace Masuit.Tools.Security
         #region DES对称加密解密
 
         /// <summary>
-        /// 加密密钥,需要在config配置文件中AppSettings节点中配置desSecret值,若未配置,默认取“masuit”的MD5值
+        /// 加密密钥,默认取“masuit”的MD5值
         /// </summary>
-        public static string DefaultEncryptKey = ConfigurationManager.AppSettings["desSecret"] ?? "masuit".MDString2();
+        public static string DefaultEncryptKey = "masuit".MDString2();
 
         /// <summary>
         /// 使用默认加密

+ 19 - 5
Masuit.Tools/Systems/HiPerfTimer.cs

@@ -5,6 +5,9 @@ using System.Threading;
 
 namespace Masuit.Tools.Systems
 {
+    /// <summary>
+    /// 纳秒级计时器
+    /// </summary>
     public class HiPerfTimer
     {
         [DllImport("Kernel32.dll")]
@@ -17,7 +20,9 @@ namespace Masuit.Tools.Systems
         private long _stopTime;
         private readonly long _freq;
 
-        // 构造函数 
+        /// <summary>
+        /// 纳秒计数器
+        /// </summary>
         public HiPerfTimer()
         {
             _startTime = 0;
@@ -30,7 +35,9 @@ namespace Masuit.Tools.Systems
             }
         }
 
-        // 开始计时器 
+        /// <summary>
+        /// 开始计时器
+        /// </summary>
         public void Start()
         {
             // 来让等待线程工作 
@@ -38,7 +45,10 @@ namespace Masuit.Tools.Systems
             QueryPerformanceCounter(out _startTime);
         }
 
-        // 开始计时器 
+        /// <summary>
+        /// 启动一个新的计时器
+        /// </summary>
+        /// <returns></returns>
         public static HiPerfTimer StartNew()
         {
             HiPerfTimer timer = new HiPerfTimer();
@@ -46,13 +56,17 @@ namespace Masuit.Tools.Systems
             return timer;
         }
 
-        // 停止计时器 
+        /// <summary>
+        /// 停止计时器
+        /// </summary>
         public void Stop()
         {
             QueryPerformanceCounter(out _stopTime);
         }
 
-        // 返回计时器经过时间(单位:秒) 
+        /// <summary>
+        /// 时器经过时间(单位:秒)
+        /// </summary>
         public double Duration => (_stopTime - _startTime) / (double)_freq;
 
         /// <summary>

+ 1 - 9
NetCoreTest/Program.cs

@@ -1,11 +1,6 @@
-using Masuit.Tools.Core.Database;
-using Masuit.Tools.Hardware;
-using Microsoft.AspNetCore;
+using Microsoft.AspNetCore;
 using Microsoft.AspNetCore.Hosting;
-using System;
-using System.Collections.Generic;
 using System.ComponentModel;
-using System.Linq;
 
 namespace NetCoreTest
 {
@@ -13,9 +8,6 @@ namespace NetCoreTest
     {
         public static void Main(string[] args)
         {
-            var table = new List<MyClass>() { new MyClass() { MyProperty = "sss", MyProperty1 = 222 } }.Select(c => new { 列1 = c.MyProperty, 列2 = c.MyProperty1 }).ToDataTable();
-
-            Console.WriteLine((long)SystemInfo.GetRamInfo().MemoryAvailable);
             CreateWebHostBuilder(args).Build().Run();
         }