浏览代码

优化多字符串查找
优化email发送

懒得勤快 2 年之前
父节点
当前提交
cec6ec675f

+ 1 - 1
Masuit.Tools.Abstractions/Extensions/BaseType/IEnumerableExtensions.cs

@@ -481,7 +481,7 @@ public static class IEnumerableExtensions
     /// <returns></returns>
     public static async Task ForeachAsync<T>(this IEnumerable<T> source, Func<T, Task> action, int maxParallelCount, CancellationToken cancellationToken = default)
     {
-		if (Debugger.IsAttached)
+        if (Debugger.IsAttached)
         {
             foreach (var item in source)
             {

+ 81 - 24
Masuit.Tools.Abstractions/Extensions/BaseType/StringExtensions.cs

@@ -94,7 +94,7 @@ namespace Masuit.Tools
         #region 检测字符串中是否包含列表中的关键词
 
         /// <summary>
-        /// 检测字符串中是否包含列表中的关键词
+        /// 检测字符串中是否包含列表中的关键词(快速匹配)
         /// </summary>
         /// <param name="s">源字符串</param>
         /// <param name="keys">关键词列表</param>
@@ -102,17 +102,61 @@ namespace Masuit.Tools
         /// <returns></returns>
         public static bool Contains(this string s, IEnumerable<string> keys, bool ignoreCase = true)
         {
-            if (!keys.Any() || string.IsNullOrEmpty(s))
+            if (keys is not ICollection<string> array)
+            {
+                array = keys.ToArray();
+            }
+
+            if (array.Count == 0 || string.IsNullOrEmpty(s))
+            {
+                return false;
+            }
+
+            return ignoreCase ? array.Any(item => s.IndexOf(item, StringComparison.InvariantCultureIgnoreCase) >= 0) : array.Any(s.Contains);
+        }
+
+        /// <summary>
+        /// 检测字符串中是否包含列表中的关键词(安全匹配)
+        /// </summary>
+        /// <param name="s">源字符串</param>
+        /// <param name="keys">关键词列表</param>
+        /// <param name="ignoreCase">忽略大小写</param>
+        /// <returns></returns>
+        public static bool ContainsSafety(this string s, IEnumerable<string> keys, bool ignoreCase = true)
+        {
+            if (keys is not ICollection<string> array)
+            {
+                array = keys.ToArray();
+            }
+
+            if (array.Count == 0 || string.IsNullOrEmpty(s))
             {
                 return false;
             }
 
+            bool flag = false;
             if (ignoreCase)
             {
-                return Regex.IsMatch(s, string.Join("|", keys.Select(Regex.Escape)), RegexOptions.IgnoreCase);
+                foreach (var item in array)
+                {
+                    if (s.Contains(item))
+                    {
+                        flag = true;
+                    }
+                }
+            }
+            else
+            {
+                foreach (var item in array)
+                {
+                    if (s.IndexOf(item, StringComparison.InvariantCultureIgnoreCase) >= 0)
+                    {
+                        flag = true;
+                    }
+                }
             }
 
-            return Regex.IsMatch(s, string.Join("|", keys.Select(Regex.Escape)));
+            return flag;
         }
 
         /// <summary>
@@ -122,14 +166,43 @@ namespace Masuit.Tools
         /// <param name="keys">关键词列表</param>
         /// <param name="ignoreCase">忽略大小写</param>
         /// <returns></returns>
-        public static bool EndsWith(this string s, string[] keys, bool ignoreCase = true)
+        public static bool EndsWith(this string s, IEnumerable<string> keys, bool ignoreCase = true)
         {
-            if (keys.Length == 0 || string.IsNullOrEmpty(s))
+            if (keys is not ICollection<string> array)
+            {
+                array = keys.ToArray();
+            }
+
+            if (array.Count == 0 || string.IsNullOrEmpty(s))
             {
                 return false;
             }
 
-            return ignoreCase ? keys.Any(key => s.EndsWith(key, StringComparison.CurrentCultureIgnoreCase)) : keys.Any(s.EndsWith);
+            var pattern = $"({array.Select(Regex.Escape).Join("|")})$";
+            return ignoreCase ? Regex.IsMatch(s, pattern, RegexOptions.IgnoreCase) : Regex.IsMatch(s, pattern);
+        }
+
+        /// <summary>
+        /// 检测字符串中是否以列表中的关键词开始
+        /// </summary>
+        /// <param name="s">源字符串</param>
+        /// <param name="keys">关键词列表</param>
+        /// <param name="ignoreCase">忽略大小写</param>
+        /// <returns></returns>
+        public static bool StartsWith(this string s, IEnumerable<string> keys, bool ignoreCase = true)
+        {
+            if (keys is not ICollection<string> array)
+            {
+                array = keys.ToArray();
+            }
+
+            if (array.Count == 0 || string.IsNullOrEmpty(s))
+            {
+                return false;
+            }
+
+            var pattern = $"^({array.Select(Regex.Escape).Join("|")})";
+            return ignoreCase ? Regex.IsMatch(s, pattern, RegexOptions.IgnoreCase) : Regex.IsMatch(s, pattern);
         }
 
         /// <summary>
@@ -162,22 +235,6 @@ namespace Masuit.Tools
         /// <returns></returns>
         public static bool RegexMatch(this string s, Regex regex) => !string.IsNullOrEmpty(s) && regex.IsMatch(s);
 
-        /// <summary>
-        /// 判断是否包含符号
-        /// </summary>
-        /// <param name="str"></param>
-        /// <param name="symbols"></param>
-        /// <returns></returns>
-        public static bool ContainsSymbol(this string str, params string[] symbols)
-        {
-            return str switch
-            {
-                null => false,
-                "" => false,
-                _ => symbols.Any(str.Contains)
-            };
-        }
-
         #endregion 检测字符串中是否包含列表中的关键词
 
         /// <summary>
@@ -666,7 +723,7 @@ $", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOption
             patnum = patnum.ToUpper().Replace(".", "");
             if (patnum.Length == 9 || patnum.Length == 8)
             {
-                byte[] factors8 = new byte[8] { 2, 3, 4, 5, 6, 7, 8, 9 };
+                byte[] factors8 = new byte[] { 2, 3, 4, 5, 6, 7, 8, 9 };
                 int year = Convert.ToUInt16(patnum.Substring(0, 2));
                 year += (year >= 85) ? (ushort)1900u : (ushort)2000u;
                 if (year >= 1985 || year <= 2003)

+ 1 - 1
Masuit.Tools.Abstractions/Masuit.Tools.Abstractions.csproj

@@ -3,7 +3,7 @@
         <TargetFrameworks>netstandard2.0;netstandard2.1;net461;net5;net6;net7</TargetFrameworks>
         <LangVersion>latest</LangVersion>
         <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
-        <Version>2.5.8.1</Version>
+        <Version>2.5.8.2</Version>
         <Authors>懒得勤快</Authors>
         <Description>Masuit.Tools基础公共库,包含一些常用的操作类,大都是静态类,加密解密,反射操作,Excel简单导出,权重随机筛选算法,分布式短id,表达式树,linq扩展,文件压缩,多线程下载和FTP客户端,硬件信息,字符串扩展方法,日期时间扩展操作,中国农历,大文件拷贝,图像裁剪,验证码,断点续传,集合扩展等常用封装。</Description>
         <Copyright>懒得勤快,长空X</Copyright>

+ 156 - 138
Masuit.Tools.Abstractions/Models/Email.cs

@@ -1,146 +1,164 @@
-using System;
+using Masuit.Tools.Systems;
+using System;
 using System.Collections.Generic;
 using System.Net.Mail;
 
 namespace Masuit.Tools.Models
 {
 #pragma warning disable 1591
-    public class Email
-    {
-        /// <summary>
-        /// 发件人用户名
-        /// </summary>
-        public EmailAddress 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>
-        public List<Attachment> Attachments { get; set; } = new List<Attachment>();
-
-        private MailMessage _mailMessage => GetClient();
-        /// <summary>
-        /// 邮件消息对象
-        /// </summary>
-        private MailMessage GetClient()
-        {
-            if (string.IsNullOrEmpty(Tos)) return null;
-            var mailMessage = new MailMessage();
-            //多个接收者                
-            foreach (var 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;
-            foreach (var item in Attachments)
-            {
-                mailMessage.Attachments.Add(item);
-            }
-
-            return mailMessage;
-        }
-
-        private SmtpClient SmtpClient => new SmtpClient
-        {
-            UseDefaultCredentials = false,
-            EnableSsl = EnableSsl,
-            Host = SmtpServer,
-            Port = SmtpPort,
-            Credentials = new System.Net.NetworkCredential(Username, Password),
-            DeliveryMethod = SmtpDeliveryMethod.Network,
-        };
-
-        //回调方法
-        Action<string> _actionSendCompletedCallback;
-
-        /// <summary>
-        /// 使用异步发送邮件
-        /// </summary>
-        /// <param name="completedCallback">邮件发送后的回调方法</param>
-        /// <returns></returns>
-        public void SendAsync(Action<string> completedCallback)
-        {
-            if (_mailMessage == null) return;
-            //发送邮件回调方法
-            _actionSendCompletedCallback = completedCallback;
-            SmtpClient.SendCompleted += SendCompletedCallback;
-            SmtpClient.SendAsync(_mailMessage, "true"); //异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
-        }
-
-        /// <summary>
-        /// 使用同步发送邮件
-        /// </summary>
-        public void Send()
-        {
-            if (_mailMessage == null) return;
-            SmtpClient.Send(_mailMessage); //异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
-            _mailMessage.Dispose();
-            SmtpClient.Dispose();
-        }
-
-        /// <summary>
-        /// 异步操作完成后执行回调方法
-        /// </summary>
-        /// <param name="sender"></param>
-        /// <param name="e"></param>
-        private void SendCompletedCallback(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
-        {
-            //同一组件下不需要回调方法,直接在此写入日志即可
-            //写入日志
-            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;
-            }
-
-            _mailMessage.Dispose();
-            SmtpClient.Dispose();
-            //执行回调方法
-            _actionSendCompletedCallback(message);
-        }
-    }
+	public class Email : Disposable
+	{
+		/// <summary>
+		/// 发件人用户名
+		/// </summary>
+		public EmailAddress 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>
+		public List<Attachment> Attachments { get; set; } = new List<Attachment>();
+
+		private MailMessage MailMessage => GetClient();
+
+		/// <summary>
+		/// 邮件消息对象
+		/// </summary>
+		private MailMessage GetClient()
+		{
+			if (string.IsNullOrEmpty(Tos)) return null;
+			var mailMessage = new MailMessage();
+			//多个接收者                
+			foreach (var 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;
+			foreach (var item in Attachments)
+			{
+				mailMessage.Attachments.Add(item);
+			}
+
+			return mailMessage;
+		}
+
+		private SmtpClient SmtpClient => new SmtpClient
+		{
+			UseDefaultCredentials = false,
+			EnableSsl = EnableSsl,
+			Host = SmtpServer,
+			Port = SmtpPort,
+			Credentials = new System.Net.NetworkCredential(Username, Password),
+			DeliveryMethod = SmtpDeliveryMethod.Network,
+		};
+
+		//回调方法
+		private Action<string> _actionSendCompletedCallback;
+
+		/// <summary>
+		/// 使用异步发送邮件
+		/// </summary>
+		/// <param name="completedCallback">邮件发送后的回调方法</param>
+		/// <returns></returns>
+		public void SendAsync(Action<string> completedCallback)
+		{
+			if (MailMessage == null) return;
+			//发送邮件回调方法
+			_actionSendCompletedCallback = completedCallback;
+			SmtpClient.SendCompleted += SendCompletedCallback;
+			SmtpClient.SendAsync(MailMessage, "true"); //异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
+		}
+
+		/// <summary>
+		/// 使用同步发送邮件
+		/// </summary>
+		public void Send()
+		{
+			if (MailMessage == null) return;
+			SmtpClient.Send(MailMessage); //异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
+			Dispose(true);
+		}
+
+		/// <summary>
+		/// 异步操作完成后执行回调方法
+		/// </summary>
+		/// <param name="sender"></param>
+		/// <param name="e"></param>
+		private void SendCompletedCallback(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
+		{
+			//同一组件下不需要回调方法,直接在此写入日志即可
+			//写入日志
+			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);
+			Dispose(true);
+		}
+
+		/// <summary>
+		/// 释放
+		/// </summary>
+		/// <param name="disposing"></param>
+		public override void Dispose(bool disposing)
+		{
+			MailMessage?.Dispose();
+			SmtpClient?.Dispose();
+			Attachments.ForEach(a => a.Dispose());
+		}
+	}
 #pragma warning restore 1591
 }

+ 1 - 1
Masuit.Tools.AspNetCore/Masuit.Tools.AspNetCore.csproj

@@ -17,7 +17,7 @@
         <Product>Masuit.Tools.AspNetCore</Product>
         <PackageId>Masuit.Tools.AspNetCore</PackageId>
         <LangVersion>latest</LangVersion>
-        <Version>1.1.8.1</Version>
+        <Version>1.1.8.2</Version>
         <RepositoryType></RepositoryType>
         <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
         <FileVersion>$(Version)</FileVersion>

+ 1 - 1
Masuit.Tools.Core/Masuit.Tools.Core.csproj

@@ -6,7 +6,7 @@
 官网教程:https://ldqk.org/55
 github:https://github.com/ldqk/Masuit.Tools
         </Description>
-        <Version>2.5.8.1</Version>
+        <Version>2.5.8.2</Version>
         <Copyright>Copyright © 懒得勤快</Copyright>
         <PackageProjectUrl>https://github.com/ldqk/Masuit.Tools</PackageProjectUrl>
         <PackageTags>Masuit.Tools,工具库,Utility,Crypt,Extensions</PackageTags>