From 371ff37d2efdfe8f67434cfd90cb012337874856 Mon Sep 17 00:00:00 2001 From: Olga Nemt Date: Thu, 21 Dec 2023 10:50:26 +0500 Subject: [PATCH 1/3] =?UTF-8?q?Worker=20=D0=B4=D0=BB=D1=8F=20=D0=BE=D1=82?= =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20email?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Background/WorkToSendEmail.cs | 73 +++++++++++++++++++ .../EmailNotificationTransportService.cs | 61 +++------------- 2 files changed, 83 insertions(+), 51 deletions(-) create mode 100644 AsbCloudInfrastructure/Background/WorkToSendEmail.cs diff --git a/AsbCloudInfrastructure/Background/WorkToSendEmail.cs b/AsbCloudInfrastructure/Background/WorkToSendEmail.cs new file mode 100644 index 00000000..da1f273f --- /dev/null +++ b/AsbCloudInfrastructure/Background/WorkToSendEmail.cs @@ -0,0 +1,73 @@ +using AsbCloudApp.Data; +using AsbCloudApp.Exceptions; +using AsbCloudApp.Repositories; +using AsbCloudApp.Services; +using AsbCloudDb.Model; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net.Mail; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace AsbCloudInfrastructure.Background +{ + internal class WorkToSendEmail : Work + { + private NotificationDto notification; + private string sender; + private string smtpPassword; + private string smtpServer; + + public WorkToSendEmail(string workId, NotificationDto notification, string sender, string smtpPassword, string smtpServer) : base(workId) + { + this.notification = notification; + + this.sender = sender; + this.smtpPassword = smtpPassword; + this.smtpServer = smtpServer; + } + + protected override async Task Action(string id, IServiceProvider services, Action onProgressCallback, CancellationToken token) + { + var notificationRepository = services.GetRequiredService(); + var userRepository = services.GetRequiredService(); + + var user = await userRepository.GetOrDefaultAsync(notification.IdUser, token) + ?? throw new ArgumentInvalidException(nameof(notification.IdUser), "Пользователь не найден"); + + if (!MailAddress.TryCreate(user.Email, out var mailAddress)) + { + Trace.TraceWarning($"Mail {user.Email} is not correct."); + throw new ArgumentInvalidException(nameof(user.Email), $"Mail {user.Email} is not null."); + } + + var from = new MailAddress(sender); + var message = new MailMessage + { + From = from + }; + + message.To.Add(mailAddress.Address); + message.BodyEncoding = System.Text.Encoding.UTF8; + message.Body = notification.Message; + message.Subject = notification.Title; + message.IsBodyHtml = true; + + using var client = new SmtpClient(smtpServer); + client.EnableSsl = true; + client.UseDefaultCredentials = false; + client.Credentials = new System.Net.NetworkCredential(sender, smtpPassword); + + await client.SendMailAsync(message, token); + notification.SentDate = DateTime.UtcNow; + await notificationRepository.UpdateAsync(notification, token); + + Trace.TraceInformation($"Send email to {user.Email} subj:{notification.Title} html body count {notification.Message.Length}"); + } + } +} diff --git a/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs b/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs index e56e423f..e345c351 100644 --- a/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs +++ b/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs @@ -10,6 +10,7 @@ using AsbCloudApp.Exceptions; using AsbCloudApp.Repositories; using AsbCloudApp.Services.Notifications; using AsbCloudInfrastructure.Background; +using AsbCloudInfrastructure.Background.PeriodicWorks; using DocumentFormat.OpenXml.Presentation; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -24,6 +25,7 @@ namespace AsbCloudInfrastructure.Services.Email private readonly string sender; private readonly string smtpServer; private readonly string smtpPassword; + private IConfiguration configuration; public EmailNotificationTransportService(BackgroundWorker backgroundWorker, IConfiguration configuration) @@ -32,6 +34,7 @@ namespace AsbCloudInfrastructure.Services.Email smtpPassword = configuration.GetValue("email:password", string.Empty); smtpServer = configuration.GetValue("email:smtpServer", string.Empty); + var configError = string.IsNullOrEmpty(sender) || string.IsNullOrEmpty(smtpPassword) || string.IsNullOrEmpty(smtpServer); @@ -45,19 +48,18 @@ namespace AsbCloudInfrastructure.Services.Email public Task SendAsync(NotificationDto notification, CancellationToken cancellationToken) { - if (!IsConfigured) - { - Trace.TraceWarning("smtp is not configured"); - return Task.CompletedTask; - } + //if (!IsConfigured) + //{ + // Trace.TraceWarning("smtp is not configured"); + // return Task.CompletedTask; + //} var workId = MakeWorkId(notification.IdUser, notification.Title, notification.Message); if (!backgroundWorker.Works.Any(w=>w.Id==workId)) { - var workAction = MakeEmailSendWorkAction(notification); - - var work = Work.CreateByDelegate(workId, workAction); + var work = new WorkToSendEmail(workId, notification, sender, smtpPassword, smtpServer); backgroundWorker.Enqueue(work); + } return Task.CompletedTask; @@ -71,49 +73,6 @@ namespace AsbCloudInfrastructure.Services.Email return Task.WhenAll(tasks); } - private Func, CancellationToken, Task> MakeEmailSendWorkAction(NotificationDto notification) - { - return async (_, serviceProvider, onProgress, token) => - { - var notificationRepository = serviceProvider.GetRequiredService(); - var userRepository = serviceProvider.GetRequiredService(); - - var user = await userRepository.GetOrDefaultAsync(notification.IdUser, token) - ?? throw new ArgumentInvalidException(nameof(notification.IdUser), "Пользователь не найден"); - - if(!MailAddress.TryCreate(user.Email, out var mailAddress)) - { - Trace.TraceWarning($"Mail {user.Email} is not correct."); - throw new ArgumentInvalidException(nameof(user.Email), $"Mail {user.Email} is not null."); - } - - var from = new MailAddress(sender); - var message = new MailMessage - { - From = from - }; - - message.To.Add(mailAddress.Address); - message.BodyEncoding = System.Text.Encoding.UTF8; - message.Body = notification.Message; - message.Subject = notification.Title; - message.IsBodyHtml = true; - - using var client = new SmtpClient(smtpServer); - client.EnableSsl = true; - client.UseDefaultCredentials = false; - client.Credentials = new System.Net.NetworkCredential(sender, smtpPassword); - - await client.SendMailAsync(message, token); - - notification.SentDate = DateTime.UtcNow; - - await notificationRepository.UpdateAsync(notification, token); - - Trace.TraceInformation($"Send email to {user.Email} subj:{notification.Title} html body count {notification.Message.Length}"); - }; - } - private static string MakeWorkId(int idUser, string subject, string content) { var hash = idUser.GetHashCode(); From 9671f1552386dc204821cd426834e4c1f5bf5c14 Mon Sep 17 00:00:00 2001 From: Olga Nemt Date: Thu, 21 Dec 2023 12:31:25 +0500 Subject: [PATCH 2/3] =?UTF-8?q?=D0=A0=D0=B5=D1=84=D0=B0=D0=BA=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=B8=D0=BD=D0=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Background/WorkToSendEmail.cs | 30 +++++++---- .../EmailNotificationTransportService.cs | 51 ++++--------------- 2 files changed, 32 insertions(+), 49 deletions(-) diff --git a/AsbCloudInfrastructure/Background/WorkToSendEmail.cs b/AsbCloudInfrastructure/Background/WorkToSendEmail.cs index da1f273f..06e88342 100644 --- a/AsbCloudInfrastructure/Background/WorkToSendEmail.cs +++ b/AsbCloudInfrastructure/Background/WorkToSendEmail.cs @@ -1,39 +1,51 @@ using AsbCloudApp.Data; using AsbCloudApp.Exceptions; using AsbCloudApp.Repositories; -using AsbCloudApp.Services; -using AsbCloudDb.Model; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; -using System.Collections.Generic; using System.Diagnostics; -using System.Linq; using System.Net.Mail; -using System.Text; using System.Threading; using System.Threading.Tasks; namespace AsbCloudInfrastructure.Background { + /// + /// Класс для отправки email + /// internal class WorkToSendEmail : Work { private NotificationDto notification; private string sender; private string smtpPassword; private string smtpServer; + private bool IsConfigured; - public WorkToSendEmail(string workId, NotificationDto notification, string sender, string smtpPassword, string smtpServer) : base(workId) + public WorkToSendEmail(string workId, NotificationDto notification, IConfiguration configuration) : base(workId) { this.notification = notification; - this.sender = sender; - this.smtpPassword = smtpPassword; - this.smtpServer = smtpServer; + sender = configuration.GetValue("email:sender", string.Empty); + smtpPassword = configuration.GetValue("email:password", string.Empty); + smtpServer = configuration.GetValue("email:smtpServer", string.Empty); + + var configError = string.IsNullOrEmpty(sender) || + string.IsNullOrEmpty(smtpPassword) || + string.IsNullOrEmpty(smtpServer); + + IsConfigured = !configError; } + protected override async Task Action(string id, IServiceProvider services, Action onProgressCallback, CancellationToken token) { + if (!IsConfigured) + { + Trace.TraceWarning("smtp is not configured"); + return; + } + var notificationRepository = services.GetRequiredService(); var userRepository = services.GetRequiredService(); diff --git a/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs b/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs index e345c351..d24d150f 100644 --- a/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs +++ b/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs @@ -1,19 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Net.Mail; -using System.Threading; -using System.Threading.Tasks; -using AsbCloudApp.Data; -using AsbCloudApp.Exceptions; -using AsbCloudApp.Repositories; +using AsbCloudApp.Data; using AsbCloudApp.Services.Notifications; using AsbCloudInfrastructure.Background; -using AsbCloudInfrastructure.Background.PeriodicWorks; -using DocumentFormat.OpenXml.Presentation; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services.Email { @@ -21,45 +13,24 @@ namespace AsbCloudInfrastructure.Services.Email public class EmailNotificationTransportService : INotificationTransportService { private readonly BackgroundWorker backgroundWorker; - private readonly bool IsConfigured; - private readonly string sender; - private readonly string smtpServer; - private readonly string smtpPassword; private IConfiguration configuration; - public EmailNotificationTransportService(BackgroundWorker backgroundWorker, + public EmailNotificationTransportService(BackgroundWorker backgroundWorker, IConfiguration configuration) { - sender = configuration.GetValue("email:sender", string.Empty); - smtpPassword = configuration.GetValue("email:password", string.Empty); - smtpServer = configuration.GetValue("email:smtpServer", string.Empty); - - - var configError = string.IsNullOrEmpty(sender) || - string.IsNullOrEmpty(smtpPassword) || - string.IsNullOrEmpty(smtpServer); - - IsConfigured = !configError; - + this.configuration = configuration; this.backgroundWorker = backgroundWorker; } public int IdTransportType => 1; - + public Task SendAsync(NotificationDto notification, CancellationToken cancellationToken) { - //if (!IsConfigured) - //{ - // Trace.TraceWarning("smtp is not configured"); - // return Task.CompletedTask; - //} - var workId = MakeWorkId(notification.IdUser, notification.Title, notification.Message); - if (!backgroundWorker.Works.Any(w=>w.Id==workId)) + if (!backgroundWorker.Works.Any(w => w.Id == workId)) { - var work = new WorkToSendEmail(workId, notification, sender, smtpPassword, smtpServer); + var work = new WorkToSendEmail(workId, notification, configuration); backgroundWorker.Enqueue(work); - } return Task.CompletedTask; @@ -72,7 +43,7 @@ namespace AsbCloudInfrastructure.Services.Email return Task.WhenAll(tasks); } - + private static string MakeWorkId(int idUser, string subject, string content) { var hash = idUser.GetHashCode(); From 85d0aca9a8756d37d6389066f7d842dacccd9bff Mon Sep 17 00:00:00 2001 From: Olga Nemt Date: Thu, 21 Dec 2023 14:48:08 +0500 Subject: [PATCH 3/3] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B0=20?= =?UTF-8?q?=D0=BF=D0=BE=20=D1=80=D0=B5=D0=B7=D1=83=D0=BB=D1=8C=D1=82=D0=B0?= =?UTF-8?q?=D1=82=D0=B0=D0=BC=20=D1=80=D0=B5=D0=B2=D1=8C=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Background/WorkToSendEmail.cs | 11 ++++++++++- .../Email/EmailNotificationTransportService.cs | 15 ++++----------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/AsbCloudInfrastructure/Background/WorkToSendEmail.cs b/AsbCloudInfrastructure/Background/WorkToSendEmail.cs index 06e88342..96136cde 100644 --- a/AsbCloudInfrastructure/Background/WorkToSendEmail.cs +++ b/AsbCloudInfrastructure/Background/WorkToSendEmail.cs @@ -22,7 +22,7 @@ namespace AsbCloudInfrastructure.Background private string smtpServer; private bool IsConfigured; - public WorkToSendEmail(string workId, NotificationDto notification, IConfiguration configuration) : base(workId) + public WorkToSendEmail(NotificationDto notification, IConfiguration configuration) : base(MakeWorkId(notification)) { this.notification = notification; @@ -81,5 +81,14 @@ namespace AsbCloudInfrastructure.Background Trace.TraceInformation($"Send email to {user.Email} subj:{notification.Title} html body count {notification.Message.Length}"); } + + + private static string MakeWorkId(NotificationDto notification) + { + var hash = notification.IdUser.GetHashCode(); + hash ^= notification.Title.GetHashCode(); + hash ^= notification.Message.GetHashCode(); + return hash.ToString("x"); + } } } diff --git a/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs b/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs index d24d150f..f41bd7ad 100644 --- a/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs +++ b/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs @@ -12,8 +12,8 @@ namespace AsbCloudInfrastructure.Services.Email public class EmailNotificationTransportService : INotificationTransportService { + private readonly IConfiguration configuration; private readonly BackgroundWorker backgroundWorker; - private IConfiguration configuration; public EmailNotificationTransportService(BackgroundWorker backgroundWorker, IConfiguration configuration) @@ -26,10 +26,9 @@ namespace AsbCloudInfrastructure.Services.Email public Task SendAsync(NotificationDto notification, CancellationToken cancellationToken) { - var workId = MakeWorkId(notification.IdUser, notification.Title, notification.Message); - if (!backgroundWorker.Works.Any(w => w.Id == workId)) + var work = new WorkToSendEmail(notification, configuration); + if (!backgroundWorker.Works.Any(w => w.Id == work.Id)) { - var work = new WorkToSendEmail(workId, notification, configuration); backgroundWorker.Enqueue(work); } @@ -44,12 +43,6 @@ namespace AsbCloudInfrastructure.Services.Email return Task.WhenAll(tasks); } - private static string MakeWorkId(int idUser, string subject, string content) - { - var hash = idUser.GetHashCode(); - hash ^= subject.GetHashCode(); - hash ^= content.GetHashCode(); - return hash.ToString("x"); - } + } }