From f68f03457df8aed22e5b3d256595adf052efe8dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=B0=D0=BD=D0=B8=D0=B8=D0=BB=20=D0=9F=D1=83=D1=82?= =?UTF-8?q?=D0=B8=D0=BD=D1=86=D0=B5=D0=B2?= Date: Mon, 6 May 2024 12:46:59 +0400 Subject: [PATCH] =?UTF-8?q?=D0=93=D0=BE=D1=82=D0=BE=D0=B2=D0=B0=D1=8F=20?= =?UTF-8?q?=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82=D0=BE=D1=80=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=207=20(=D0=B1=D0=B0=D0=B7=D0=B0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogics/ClientLogic.cs | 9 +- .../BusinessLogics/MessageInfoLogic.cs | 86 +++++ .../BusinessLogics/OrderLogic.cs | 24 +- .../FoodOrdersBusinessLogic.csproj | 1 + .../MailWorker/AbstractMailWorker.cs | 77 +++++ .../MailWorker/MailKitWorker.cs | 75 +++++ .../Controllers/HomeController.cs | 12 +- .../Views/Home/Mails.cshtml | 54 ++++ .../Views/Shared/_Layout.cshtml | 3 + .../BindingModels/MailConfigBindingModel.cs | 12 + .../BindingModels/MailSendInfoBindingModel.cs | 9 + .../BindingModels/MessageInfoBindingModel.cs | 19 ++ .../IMessageInfoLogic.cs | 12 + .../SearchModels/MessageInfoSearchModel.cs | 8 + .../StoragesContracts/IMessageInfoStorage.cs | 14 + .../ViewModels/MessageInfoViewModel .cs | 20 ++ .../ViewModels/OrderViewModel.cs | 2 + .../Models/IMessageInfoModel.cs | 12 + .../FoodOrdersDatabase.cs | 5 +- .../Implemets/ClientStorage.cs | 2 +- .../Implemets/MessageInfoStorage.cs | 52 +++ .../20240506071540_Mails.Designer.cs | 298 ++++++++++++++++++ .../Migrations/20240506071540_Mails.cs | 48 +++ .../FoodOrdersDatabaseModelSnapshot.cs | 41 +++ .../Models/Client.cs | 3 + .../Models/MessageInfo.cs | 52 +++ .../Models/Order.cs | 1 + .../DataFileSingleton.cs | 5 + .../Implements/MessageInfoStorage.cs | 53 ++++ .../Models/MessageInfo.cs | 75 +++++ .../DataListSingleton.cs | 3 + .../Implements/ClientStorage.cs | 3 +- .../Implements/MessageInfoStorage.cs | 60 ++++ .../Models/MessageInfo.cs | 48 +++ .../Controllers/ClientController.cs | 21 +- FoodOrders/FoodOrdersRestApi/Program.cs | 18 ++ FoodOrders/FoodOrdersRestApi/appsettings.json | 9 +- FoodOrders/FoodOrdersView/App.config | 11 + .../FoodOrdersView/FormMails.Designer.cs | 70 ++++ FoodOrders/FoodOrdersView/FormMails.cs | 45 +++ FoodOrders/FoodOrdersView/FormMails.resx | 120 +++++++ FoodOrders/FoodOrdersView/FormMain.cs | 10 + .../FoodOrdersView/FormMain.designer.cs | 19 +- FoodOrders/FoodOrdersView/Program.cs | 30 +- 44 files changed, 1534 insertions(+), 17 deletions(-) create mode 100644 FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/MessageInfoLogic.cs create mode 100644 FoodOrders/FoodOrdersBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 FoodOrders/FoodOrdersBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 FoodOrders/FoodOrdersClientApp/Views/Home/Mails.cshtml create mode 100644 FoodOrders/FoodOrdersContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 FoodOrders/FoodOrdersContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 FoodOrders/FoodOrdersContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 FoodOrders/FoodOrdersContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 FoodOrders/FoodOrdersContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 FoodOrders/FoodOrdersContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 FoodOrders/FoodOrdersContracts/ViewModels/MessageInfoViewModel .cs create mode 100644 FoodOrders/FoodOrdersDataModels/Models/IMessageInfoModel.cs create mode 100644 FoodOrders/FoodOrdersDatabaseImplement/Implemets/MessageInfoStorage.cs create mode 100644 FoodOrders/FoodOrdersDatabaseImplement/Migrations/20240506071540_Mails.Designer.cs create mode 100644 FoodOrders/FoodOrdersDatabaseImplement/Migrations/20240506071540_Mails.cs create mode 100644 FoodOrders/FoodOrdersDatabaseImplement/Models/MessageInfo.cs create mode 100644 FoodOrders/FoodOrdersFileImplement/Implements/MessageInfoStorage.cs create mode 100644 FoodOrders/FoodOrdersFileImplement/Models/MessageInfo.cs create mode 100644 FoodOrders/FoodOrdersListImplement/Implements/MessageInfoStorage.cs create mode 100644 FoodOrders/FoodOrdersListImplement/Models/MessageInfo.cs create mode 100644 FoodOrders/FoodOrdersView/App.config create mode 100644 FoodOrders/FoodOrdersView/FormMails.Designer.cs create mode 100644 FoodOrders/FoodOrdersView/FormMails.cs create mode 100644 FoodOrders/FoodOrdersView/FormMails.resx diff --git a/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/ClientLogic.cs b/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/ClientLogic.cs index 615abdc..6be6ebd 100644 --- a/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/ClientLogic.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace FoodOrdersBusinessLogic.BusinessLogics @@ -99,9 +100,13 @@ namespace FoodOrdersBusinessLogic.BusinessLogics { throw new ArgumentNullException("Нет ФИО клиента", nameof(model.ClientFIO)); } - if (string.IsNullOrEmpty(model.Email)) + if (string.IsNullOrEmpty(model.Email) || !Regex.IsMatch(model.Email, @"^[a-z0-9._%+-]+\@([a-z0-9-]+\.)+[a-z]{2,4}$")) { - throw new ArgumentNullException("Нет логина(почты) клиента", nameof(model.Email)); + throw new ArgumentNullException("Некорректно введена почта клиента", nameof(model.Email)); + } + if (string.IsNullOrEmpty(model.Password) || !Regex.IsMatch(model.Password, @"^(?=.*[A-Za-z])(?=.*\d)(?=.*[^A-Za-z0-9\n]).{10,50}$")) + { + throw new ArgumentNullException("Некорректно введен пароль клиента", nameof(model.Password)); } _logger.LogInformation("Client. Id: {Id}, FIO: {fio}, email: {email}", model.Id, model.ClientFIO, model.Email); var element = _clientStorage.GetElement(new ClientSearchModel diff --git a/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..ac3fe29 --- /dev/null +++ b/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,86 @@ +using FoodOrdersContracts.BindingModels; +using FoodOrdersContracts.BusinessLogicsContracts; +using FoodOrdersContracts.SearchModels; +using FoodOrdersContracts.StoragesContracts; +using FoodOrdersContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace FoodOrdersBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageInfoStorage; + private readonly IClientStorage _clientStorage; + public MessageInfoLogic(ILogger logger, IMessageInfoStorage MessageInfoStorage, IClientStorage clientStorage) + { + _logger = logger; + _messageInfoStorage = MessageInfoStorage; + _clientStorage = clientStorage; + } + + public bool Create(MessageInfoBindingModel model) + { + CheckModel(model); + if (_messageInfoStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId} ", model?.MessageId, model?.ClientId); + var list = (model == null) ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + private void CheckModel(MessageInfoBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.MessageId)) + { + throw new ArgumentNullException("Не указан id сообщения", nameof(model.MessageId)); + } + if (string.IsNullOrEmpty(model.SenderName)) + { + throw new ArgumentNullException("Не указана почта отправителя", nameof(model.SenderName)); + } + if (string.IsNullOrEmpty(model.Subject)) + { + throw new ArgumentNullException("Не указан заголовок", nameof(model.Subject)); + } + if (string.IsNullOrEmpty(model.Body)) + { + throw new ArgumentNullException("Не указан текст сообщения", nameof(model.Subject)); + } + _logger.LogInformation("MessageInfo. MessageId: {MessageId}. SenderName: {SenderName}. DateDelivery: {DateDelivery} Subject: {Subject}. Body: {Body}", model.MessageId, model.SenderName, model.DateDelivery, model.Subject, model.Body); + var element = _clientStorage.GetElement(new ClientSearchModel + { + Email = model.SenderName + }); + if (element == null) + { + _logger.LogWarning("Не удалось найти клиента, отправившего письмо с адреса Email: {Email}", model.SenderName); + } + else + { + model.ClientId = element.Id; + } + } + } +} diff --git a/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/OrderLogic.cs b/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/OrderLogic.cs index 2018573..2785aa0 100644 --- a/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,4 +1,5 @@ -using FoodOrdersContracts.BindingModels; +using FoodOrdersBusinessLogic.MailWorker; +using FoodOrdersContracts.BindingModels; using FoodOrdersContracts.BusinessLogicsContracts; using FoodOrdersContracts.SearchModels; using FoodOrdersContracts.StoragesContracts; @@ -14,12 +15,15 @@ namespace FoodOrdersBusinessLogic.BusinessLogics private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; + static readonly object locker = new(); - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker) { _logger = logger; _orderStorage = orderStorage; + _mailWorker = mailWorker; } public OrderViewModel? ReadElement(OrderSearchModel model) @@ -48,11 +52,18 @@ namespace FoodOrdersBusinessLogic.BusinessLogics return false; } model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) + var element = _orderStorage.Insert(model); + if (element == null) { _logger.LogWarning("Insert operation failed"); return false; } + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = element.ClientEmail, + Subject = $"Новый заказ создан. Номер заказа - {element.Id}", + Text = $"Заказ №{element.Id} от {element.DateCreate} на сумму {element.Sum} принят." + })); return true; } @@ -153,6 +164,13 @@ namespace FoodOrdersBusinessLogic.BusinessLogics _logger.LogWarning("Change status operation failed"); return false; } + string DateInfo = model.DateImplement.HasValue ? $"Дата выполнения {model.DateImplement}" : ""; + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = order.ClientEmail, + Subject = $"Заказ №{order.Id}", + Text = $"Заказ №{order.Id} изменен статус на {model.Status}. {DateInfo}" + })); return true; } } diff --git a/FoodOrders/FoodOrdersBusinessLogic/FoodOrdersBusinessLogic.csproj b/FoodOrders/FoodOrdersBusinessLogic/FoodOrdersBusinessLogic.csproj index 3d65dec..a6e4e82 100644 --- a/FoodOrders/FoodOrdersBusinessLogic/FoodOrdersBusinessLogic.csproj +++ b/FoodOrders/FoodOrdersBusinessLogic/FoodOrdersBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/FoodOrders/FoodOrdersBusinessLogic/MailWorker/AbstractMailWorker.cs b/FoodOrders/FoodOrdersBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..e8e03da --- /dev/null +++ b/FoodOrders/FoodOrdersBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,77 @@ +using FoodOrdersContracts.BindingModels; +using FoodOrdersContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; + +namespace FoodOrdersBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin = string.Empty; + protected string _mailPassword = string.Empty; + protected string _smtpClientHost = string.Empty; + protected int _smtpClientPort; + protected string _popHost = string.Empty; + protected int _popPort; + private readonly IMessageInfoLogic _messageInfoLogic; + private readonly IClientLogic _clientLogic; + private readonly ILogger _logger; + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + _clientLogic = clientLogic; + } + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.PopPort; + _logger.LogDebug("Config: {login}, {password}, {clientHost},{ clientPOrt}, { popHost}, { popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort); + } + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + { + return; + } + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); + await SendMailAsync(info); + } + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + if (_messageInfoLogic == null) + { + return; + } + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + foreach (var mail in list) + { + mail.ClientId = _clientLogic.ReadElement(new() { Email = mail.SenderName })?.Id; + _messageInfoLogic.Create(mail); + } + } + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + protected abstract Task> + ReceiveMailAsync(); + } +} diff --git a/FoodOrders/FoodOrdersBusinessLogic/MailWorker/MailKitWorker.cs b/FoodOrders/FoodOrdersBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..c4b2f03 --- /dev/null +++ b/FoodOrders/FoodOrdersBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,75 @@ +using FoodOrdersContracts.BindingModels; +using FoodOrdersContracts.BusinessLogicsContracts; +using MailKit.Net.Pop3; +using MailKit.Security; +using Microsoft.Extensions.Logging; +using System.Net.Mail; +using System.Net; +using System.Text; + +namespace FoodOrdersBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) : base(logger, messageInfoLogic, clientLogic) { } + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + protected override async Task> + ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + catch (MailKit.Security.AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/FoodOrders/FoodOrdersClientApp/Controllers/HomeController.cs b/FoodOrders/FoodOrdersClientApp/Controllers/HomeController.cs index e41468f..bd12d28 100644 --- a/FoodOrders/FoodOrdersClientApp/Controllers/HomeController.cs +++ b/FoodOrders/FoodOrdersClientApp/Controllers/HomeController.cs @@ -143,5 +143,15 @@ namespace FoodOrdersClientApp.Controllers var ic = APIClient.GetRequest($"api/main/getdish?dishId={dish}"); return count * (ic?.Price ?? 1); } - } + + [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + return View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + } + } } diff --git a/FoodOrders/FoodOrdersClientApp/Views/Home/Mails.cshtml b/FoodOrders/FoodOrdersClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..92a56a5 --- /dev/null +++ b/FoodOrders/FoodOrdersClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using FoodOrdersContracts.ViewModels + +@model List + +@{ + ViewData["Title"] = "Mails"; +} + +
+

Заказы

+
+ + +
+ @{ + if (Model == null) + { +

Авторизируйтесь

+ return; + } + + + + + + + + + + + @foreach (var item in Model) + { + + + + + + } + +
+ Дата письма + + Заголовок + + Текст +
+ @Html.DisplayFor(modelItem => item.DateDelivery) + + @Html.DisplayFor(modelItem => item.Subject) + + @Html.DisplayFor(modelItem => item.Body) +
+ } +
\ No newline at end of file diff --git a/FoodOrders/FoodOrdersClientApp/Views/Shared/_Layout.cshtml b/FoodOrders/FoodOrdersClientApp/Views/Shared/_Layout.cshtml index bdd410b..2cc1604 100644 --- a/FoodOrders/FoodOrdersClientApp/Views/Shared/_Layout.cshtml +++ b/FoodOrders/FoodOrdersClientApp/Views/Shared/_Layout.cshtml @@ -28,6 +28,9 @@ + diff --git a/FoodOrders/FoodOrdersContracts/BindingModels/MailConfigBindingModel.cs b/FoodOrders/FoodOrdersContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..b435767 --- /dev/null +++ b/FoodOrders/FoodOrdersContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,12 @@ +namespace FoodOrdersContracts.BindingModels +{ + public class MailConfigBindingModel + { + public string MailLogin { get; set; } = string.Empty; + public string MailPassword { get; set; } = string.Empty; + public string SmtpClientHost { get; set; } = string.Empty; + public int SmtpClientPort { get; set; } + public string PopHost { get; set; } = string.Empty; + public int PopPort { get; set; } + } +} diff --git a/FoodOrders/FoodOrdersContracts/BindingModels/MailSendInfoBindingModel.cs b/FoodOrders/FoodOrdersContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..15e6b7f --- /dev/null +++ b/FoodOrders/FoodOrdersContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,9 @@ +namespace FoodOrdersContracts.BindingModels +{ + public class MailSendInfoBindingModel + { + public string MailAddress { get; set; } = string.Empty; + public string Subject { get; set; } = string.Empty; + public string Text { get; set; } = string.Empty; + } +} diff --git a/FoodOrders/FoodOrdersContracts/BindingModels/MessageInfoBindingModel.cs b/FoodOrders/FoodOrdersContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..09cd690 --- /dev/null +++ b/FoodOrders/FoodOrdersContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using FoodOrdersDataModels.Models; + +namespace FoodOrdersContracts.BindingModels +{ + public class MessageInfoBindingModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + public string SenderName { get; set; } = string.Empty; + + public DateTime DateDelivery { get; set; } + + public string Subject { get; set; } = string.Empty; + + public string Body { get; set; } = string.Empty; + } +} diff --git a/FoodOrders/FoodOrdersContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/FoodOrders/FoodOrdersContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..09d7901 --- /dev/null +++ b/FoodOrders/FoodOrdersContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,12 @@ +using FoodOrdersContracts.BindingModels; +using FoodOrdersContracts.SearchModels; +using FoodOrdersContracts.ViewModels; + +namespace FoodOrdersContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + bool Create(MessageInfoBindingModel model); + } +} diff --git a/FoodOrders/FoodOrdersContracts/SearchModels/MessageInfoSearchModel.cs b/FoodOrders/FoodOrdersContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..b3e1de5 --- /dev/null +++ b/FoodOrders/FoodOrdersContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,8 @@ +namespace FoodOrdersContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + public string? MessageId { get; set; } + } +} diff --git a/FoodOrders/FoodOrdersContracts/StoragesContracts/IMessageInfoStorage.cs b/FoodOrders/FoodOrdersContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..39a7b9d --- /dev/null +++ b/FoodOrders/FoodOrdersContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,14 @@ +using FoodOrdersContracts.BindingModels; +using FoodOrdersContracts.SearchModels; +using FoodOrdersContracts.ViewModels; + +namespace FoodOrdersContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + List GetFilteredList(MessageInfoSearchModel model); + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/FoodOrders/FoodOrdersContracts/ViewModels/MessageInfoViewModel .cs b/FoodOrders/FoodOrdersContracts/ViewModels/MessageInfoViewModel .cs new file mode 100644 index 0000000..466b856 --- /dev/null +++ b/FoodOrders/FoodOrdersContracts/ViewModels/MessageInfoViewModel .cs @@ -0,0 +1,20 @@ +using FoodOrdersDataModels.Models; +using System.ComponentModel; + +namespace FoodOrdersContracts.ViewModels +{ + public class MessageInfoViewModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + [DisplayName("Отправитель")] + public string SenderName { get; set; } = string.Empty; + [DisplayName("Дата письма")] + public DateTime DateDelivery { get; set; } + [DisplayName("Заголовок")] + public string Subject { get; set; } = string.Empty; + [DisplayName("Текст")] + public string Body { get; set; } = string.Empty; + } +} diff --git a/FoodOrders/FoodOrdersContracts/ViewModels/OrderViewModel.cs b/FoodOrders/FoodOrdersContracts/ViewModels/OrderViewModel.cs index bebe542..300f466 100644 --- a/FoodOrders/FoodOrdersContracts/ViewModels/OrderViewModel.cs +++ b/FoodOrders/FoodOrdersContracts/ViewModels/OrderViewModel.cs @@ -16,6 +16,8 @@ namespace FoodOrdersContracts.ViewModels public int ClientId { get; set; } [DisplayName("Клиент")] public string ClientFIO { get; set; } = string.Empty; + public string ClientEmail { get; set; } = string.Empty; + public int? ImplementerId { get; set; } [DisplayName("Исполнитель")] diff --git a/FoodOrders/FoodOrdersDataModels/Models/IMessageInfoModel.cs b/FoodOrders/FoodOrdersDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..1d87dfd --- /dev/null +++ b/FoodOrders/FoodOrdersDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,12 @@ +namespace FoodOrdersDataModels.Models +{ + public interface IMessageInfoModel + { + string MessageId { get; } + int? ClientId { get; } + string SenderName { get; } + DateTime DateDelivery { get; } + string Subject { get; } + string Body { get; } + } +} diff --git a/FoodOrders/FoodOrdersDatabaseImplement/FoodOrdersDatabase.cs b/FoodOrders/FoodOrdersDatabaseImplement/FoodOrdersDatabase.cs index 0504961..b477e18 100644 --- a/FoodOrders/FoodOrdersDatabaseImplement/FoodOrdersDatabase.cs +++ b/FoodOrders/FoodOrdersDatabaseImplement/FoodOrdersDatabase.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using FoodOrdersDatabaseImplement.Models; +using FoodOrdersDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; namespace FoodOrdersDatabaseImplement @@ -15,7 +16,7 @@ optionsBuilder) { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=.\SQLEXPRESS;Initial Catalog=FoodOrdersDatabaseFull;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); + optionsBuilder.UseSqlServer(@"Data Source=.\SQLEXPRESS;Initial Catalog=FoodOrdersDatabaseFull2;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); } base.OnConfiguring(optionsBuilder); } @@ -25,5 +26,7 @@ optionsBuilder) public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } public virtual DbSet Implementers { set; get; } + + public virtual DbSet Messages { set; get; } } } diff --git a/FoodOrders/FoodOrdersDatabaseImplement/Implemets/ClientStorage.cs b/FoodOrders/FoodOrdersDatabaseImplement/Implemets/ClientStorage.cs index db276fd..6efbb50 100644 --- a/FoodOrders/FoodOrdersDatabaseImplement/Implemets/ClientStorage.cs +++ b/FoodOrders/FoodOrdersDatabaseImplement/Implemets/ClientStorage.cs @@ -21,7 +21,7 @@ namespace FoodOrdersDatabaseImplement.Implements } using var context = new FoodOrdersDatabase(); return context.Clients.FirstOrDefault(x => - (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email) + (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email) || (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && string.IsNullOrEmpty(model.Password)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } diff --git a/FoodOrders/FoodOrdersDatabaseImplement/Implemets/MessageInfoStorage.cs b/FoodOrders/FoodOrdersDatabaseImplement/Implemets/MessageInfoStorage.cs new file mode 100644 index 0000000..c365768 --- /dev/null +++ b/FoodOrders/FoodOrdersDatabaseImplement/Implemets/MessageInfoStorage.cs @@ -0,0 +1,52 @@ +using FoodOrdersContracts.BindingModels; +using FoodOrdersContracts.SearchModels; +using FoodOrdersContracts.StoragesContracts; +using FoodOrdersContracts.ViewModels; +using FoodOrdersDatabaseImplement.Models; + +namespace FoodOrdersDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + using var context = new FoodOrdersDatabase(); + if (model.MessageId != null) + { + return context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + using var context = new FoodOrdersDatabase(); + return context.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + using var context = new FoodOrdersDatabase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + using var context = new FoodOrdersDatabase(); + var newMessage = MessageInfo.Create(model); + if (newMessage == null || context.Messages.Any(x => x.MessageId.Equals(model.MessageId))) + { + return null; + } + context.Messages.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} diff --git a/FoodOrders/FoodOrdersDatabaseImplement/Migrations/20240506071540_Mails.Designer.cs b/FoodOrders/FoodOrdersDatabaseImplement/Migrations/20240506071540_Mails.Designer.cs new file mode 100644 index 0000000..392d824 --- /dev/null +++ b/FoodOrders/FoodOrdersDatabaseImplement/Migrations/20240506071540_Mails.Designer.cs @@ -0,0 +1,298 @@ +// +using System; +using FoodOrdersDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace FoodOrdersDatabaseImplement.Migrations +{ + [DbContext(typeof(FoodOrdersDatabase))] + [Migration("20240506071540_Mails")] + partial class Mails + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.16") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Clients"); + }); + + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.Component", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Cost") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Components"); + }); + + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.Dish", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("DishName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Dishs"); + }); + + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.DishComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DishId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("DishId"); + + b.ToTable("DishComponents"); + }); + + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("DishId") + .HasColumnType("int"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("DishId"); + + b.HasIndex("ImplementerId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.DishComponent", b => + { + b.HasOne("FoodOrdersDatabaseImplement.Models.Component", "Component") + .WithMany("DishComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FoodOrdersDatabaseImplement.Models.Dish", "Dish") + .WithMany("Components") + .HasForeignKey("DishId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Dish"); + }); + + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("FoodOrdersDatabaseImplement.Models.Client", "Client") + .WithMany("ClientMessages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.Order", b => + { + b.HasOne("FoodOrdersDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FoodOrdersDatabaseImplement.Models.Dish", "Dish") + .WithMany("Orders") + .HasForeignKey("DishId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FoodOrdersDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.Navigation("Client"); + + b.Navigation("Dish"); + + b.Navigation("Implementer"); + }); + + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.Client", b => + { + b.Navigation("ClientMessages"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.Component", b => + { + b.Navigation("DishComponents"); + }); + + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.Dish", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/FoodOrders/FoodOrdersDatabaseImplement/Migrations/20240506071540_Mails.cs b/FoodOrders/FoodOrdersDatabaseImplement/Migrations/20240506071540_Mails.cs new file mode 100644 index 0000000..d7d316e --- /dev/null +++ b/FoodOrders/FoodOrdersDatabaseImplement/Migrations/20240506071540_Mails.cs @@ -0,0 +1,48 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace FoodOrdersDatabaseImplement.Migrations +{ + /// + public partial class Mails : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Messages", + columns: table => new + { + MessageId = table.Column(type: "nvarchar(450)", nullable: false), + ClientId = table.Column(type: "int", nullable: true), + SenderName = table.Column(type: "nvarchar(max)", nullable: false), + DateDelivery = table.Column(type: "datetime2", nullable: false), + Subject = table.Column(type: "nvarchar(max)", nullable: false), + Body = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Messages", x => x.MessageId); + table.ForeignKey( + name: "FK_Messages_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id"); + }); + + migrationBuilder.CreateIndex( + name: "IX_Messages_ClientId", + table: "Messages", + column: "ClientId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Messages"); + } + } +} diff --git a/FoodOrders/FoodOrdersDatabaseImplement/Migrations/FoodOrdersDatabaseModelSnapshot.cs b/FoodOrders/FoodOrdersDatabaseImplement/Migrations/FoodOrdersDatabaseModelSnapshot.cs index 7502ecc..e174d5c 100644 --- a/FoodOrders/FoodOrdersDatabaseImplement/Migrations/FoodOrdersDatabaseModelSnapshot.cs +++ b/FoodOrders/FoodOrdersDatabaseImplement/Migrations/FoodOrdersDatabaseModelSnapshot.cs @@ -140,6 +140,36 @@ namespace FoodOrdersDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -202,6 +232,15 @@ namespace FoodOrdersDatabaseImplement.Migrations b.Navigation("Dish"); }); + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("FoodOrdersDatabaseImplement.Models.Client", "Client") + .WithMany("ClientMessages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.Order", b => { b.HasOne("FoodOrdersDatabaseImplement.Models.Client", "Client") @@ -229,6 +268,8 @@ namespace FoodOrdersDatabaseImplement.Migrations modelBuilder.Entity("FoodOrdersDatabaseImplement.Models.Client", b => { + b.Navigation("ClientMessages"); + b.Navigation("Orders"); }); diff --git a/FoodOrders/FoodOrdersDatabaseImplement/Models/Client.cs b/FoodOrders/FoodOrdersDatabaseImplement/Models/Client.cs index e83b505..8e6dd8d 100644 --- a/FoodOrders/FoodOrdersDatabaseImplement/Models/Client.cs +++ b/FoodOrders/FoodOrdersDatabaseImplement/Models/Client.cs @@ -28,6 +28,9 @@ namespace FoodOrdersDatabaseImplement.Models [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); + [ForeignKey("ClientId")] + public virtual List ClientMessages { get; set; } = new(); + public static Client? Create(ClientBindingModel model) { if (model == null) diff --git a/FoodOrders/FoodOrdersDatabaseImplement/Models/MessageInfo.cs b/FoodOrders/FoodOrdersDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..0d85148 --- /dev/null +++ b/FoodOrders/FoodOrdersDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,52 @@ +using FoodOrdersContracts.BindingModels; +using FoodOrdersContracts.ViewModels; +using FoodOrdersDataModels.Models; +using System.ComponentModel.DataAnnotations; + +namespace FoodOrdersDatabaseImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + [Key] + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public virtual Client? Client { get; private set; } + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} diff --git a/FoodOrders/FoodOrdersDatabaseImplement/Models/Order.cs b/FoodOrders/FoodOrdersDatabaseImplement/Models/Order.cs index 9c61e35..e832e1c 100644 --- a/FoodOrders/FoodOrdersDatabaseImplement/Models/Order.cs +++ b/FoodOrders/FoodOrdersDatabaseImplement/Models/Order.cs @@ -78,6 +78,7 @@ namespace FoodOrdersDatabaseImplement.Models Status = Status, DishName = Dish.DishName ?? string.Empty, ClientFIO = Client.ClientFIO ?? string.Empty, + ClientEmail = Client.Email ?? string.Empty, ImplementerFIO = Implementer?.ImplementerFIO ?? string.Empty }; } diff --git a/FoodOrders/FoodOrdersFileImplement/DataFileSingleton.cs b/FoodOrders/FoodOrdersFileImplement/DataFileSingleton.cs index 0b4985c..c3037a0 100644 --- a/FoodOrders/FoodOrdersFileImplement/DataFileSingleton.cs +++ b/FoodOrders/FoodOrdersFileImplement/DataFileSingleton.cs @@ -17,6 +17,8 @@ namespace FoodOrdersFileImplement private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageInfoFileName = "MessageInfo.xml"; + public List Components { get; private set; } public List Orders { get; private set; } @@ -24,6 +26,7 @@ namespace FoodOrdersFileImplement public List Dishs { get; private set; } public List Clients { get; private set; } public List Implementers { get; private set; } + public List Messages { get; private set; } public static DataFileSingleton GetInstance() { @@ -41,6 +44,7 @@ namespace FoodOrdersFileImplement public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); + public void SaveMessages() => SaveData(Messages, MessageInfoFileName, "Messages", x => x.GetXElement); private DataFileSingleton() { @@ -49,6 +53,7 @@ namespace FoodOrdersFileImplement Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; + Messages = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) diff --git a/FoodOrders/FoodOrdersFileImplement/Implements/MessageInfoStorage.cs b/FoodOrders/FoodOrdersFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..707ef8a --- /dev/null +++ b/FoodOrders/FoodOrdersFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,53 @@ +using FoodOrdersContracts.BindingModels; +using FoodOrdersContracts.SearchModels; +using FoodOrdersContracts.StoragesContracts; +using FoodOrdersContracts.ViewModels; +using FoodOrdersFileImplement.Models; + +namespace FoodOrdersFileImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataFileSingleton _source; + public MessageInfoStorage() + { + _source = DataFileSingleton.GetInstance(); + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId != null) + { + return _source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + return _source.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + return _source.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + _source.SaveMessages(); + return newMessage.GetViewModel; + } + } +} diff --git a/FoodOrders/FoodOrdersFileImplement/Models/MessageInfo.cs b/FoodOrders/FoodOrdersFileImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..b7568c0 --- /dev/null +++ b/FoodOrders/FoodOrdersFileImplement/Models/MessageInfo.cs @@ -0,0 +1,75 @@ +using FoodOrdersContracts.BindingModels; +using FoodOrdersContracts.ViewModels; +using FoodOrdersDataModels.Models; +using System.Xml.Linq; + +namespace FoodOrdersFileImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public static MessageInfo? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Body = element.Attribute("Body")!.Value, + Subject = element.Attribute("Subject")!.Value, + ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value), + MessageId = element.Attribute("MessageId")!.Value, + SenderName = element.Attribute("SenderName")!.Value, + DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + + public XElement GetXElement => new("MessageInfo", + new XAttribute("Body", Body), + new XAttribute("Subject", Subject), + new XAttribute("ClientId", ClientId), + new XAttribute("MessageId", MessageId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery) + ); + } +} diff --git a/FoodOrders/FoodOrdersListImplement/DataListSingleton.cs b/FoodOrders/FoodOrdersListImplement/DataListSingleton.cs index 90aef00..ed8a31b 100644 --- a/FoodOrders/FoodOrdersListImplement/DataListSingleton.cs +++ b/FoodOrders/FoodOrdersListImplement/DataListSingleton.cs @@ -15,6 +15,8 @@ namespace FoodOrdersListImplement public List Implementers { get; set; } + public List Messages { get; set; } + private DataListSingleton() { Components = new List(); @@ -22,6 +24,7 @@ namespace FoodOrdersListImplement Dishs = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } public static DataListSingleton GetInstance() diff --git a/FoodOrders/FoodOrdersListImplement/Implements/ClientStorage.cs b/FoodOrders/FoodOrdersListImplement/Implements/ClientStorage.cs index 0e0d6a5..48708ff 100644 --- a/FoodOrders/FoodOrdersListImplement/Implements/ClientStorage.cs +++ b/FoodOrders/FoodOrdersListImplement/Implements/ClientStorage.cs @@ -22,7 +22,8 @@ namespace FoodOrdersListImplement.Implements } foreach (var client in _source.Clients) { - if ((!string.IsNullOrEmpty(model.Email) && client.Email == model.Email) || (model.Id.HasValue && client.Id == model.Id)) + if ((!string.IsNullOrEmpty(model.Email) && client.Email == model.Email && !string.IsNullOrEmpty(model.Password) && client.Password == model.Password) + || (!string.IsNullOrEmpty(model.Email) && client.Email == model.Email && string.IsNullOrEmpty(model.Password)) || (model.Id.HasValue && client.Id == model.Id)) { return client.GetViewModel; } diff --git a/FoodOrders/FoodOrdersListImplement/Implements/MessageInfoStorage.cs b/FoodOrders/FoodOrdersListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..80ab7ad --- /dev/null +++ b/FoodOrders/FoodOrdersListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,60 @@ +using FoodOrdersContracts.BindingModels; +using FoodOrdersContracts.SearchModels; +using FoodOrdersContracts.StoragesContracts; +using FoodOrdersContracts.ViewModels; +using FoodOrdersListImplement.Models; + +namespace FoodOrdersListImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + foreach (var message in _source.Messages) + { + if (model.MessageId != null && model.MessageId.Equals(message.MessageId)) return message.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + List result = new(); + foreach (var item in _source.Messages) + { + if (item.ClientId.HasValue && item.ClientId == model.ClientId) + { + result.Add(item.GetViewModel); + } + } + return result; + } + + public List GetFullList() + { + List result = new(); + foreach (var item in _source.Messages) + { + result.Add(item.GetViewModel); + } + return result; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/FoodOrders/FoodOrdersListImplement/Models/MessageInfo.cs b/FoodOrders/FoodOrdersListImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..31e7df0 --- /dev/null +++ b/FoodOrders/FoodOrdersListImplement/Models/MessageInfo.cs @@ -0,0 +1,48 @@ +using FoodOrdersContracts.BindingModels; +using FoodOrdersContracts.ViewModels; +using FoodOrdersDataModels.Models; + +namespace FoodOrdersListImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} diff --git a/FoodOrders/FoodOrdersRestApi/Controllers/ClientController.cs b/FoodOrders/FoodOrdersRestApi/Controllers/ClientController.cs index ad58279..62e08e4 100644 --- a/FoodOrders/FoodOrdersRestApi/Controllers/ClientController.cs +++ b/FoodOrders/FoodOrdersRestApi/Controllers/ClientController.cs @@ -12,10 +12,12 @@ namespace FoodOrdersRestApi.Controllers { private readonly ILogger _logger; private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger logger) + private readonly IMessageInfoLogic _mailLogic; + public ClientController(IClientLogic logic, ILogger logger, IMessageInfoLogic mailLogic) { _logger = logger; _logic = logic; + _mailLogic = mailLogic; } [HttpGet] public ClientViewModel? Login(string login, string password) @@ -60,5 +62,22 @@ namespace FoodOrdersRestApi.Controllers throw; } } + + [HttpGet] + public List? GetMessages(int clientId) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error receiving client's emails"); + throw; + } + } } } diff --git a/FoodOrders/FoodOrdersRestApi/Program.cs b/FoodOrders/FoodOrdersRestApi/Program.cs index e9623d3..6d5f5b0 100644 --- a/FoodOrders/FoodOrdersRestApi/Program.cs +++ b/FoodOrders/FoodOrdersRestApi/Program.cs @@ -1,4 +1,6 @@ using FoodOrdersBusinessLogic.BusinessLogics; +using FoodOrdersBusinessLogic.MailWorker; +using FoodOrdersContracts.BindingModels; using FoodOrdersContracts.BusinessLogicsContracts; using FoodOrdersContracts.StoragesContracts; using FoodOrdersDatabaseImplement.Implements; @@ -14,10 +16,14 @@ builder.Logging.AddLog4Net("log4net.config"); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); + +builder.Services.AddSingleton(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle @@ -32,6 +38,18 @@ builder.Services.AddSwaggerGen(c => }); }); var app = builder.Build(); + +var mailSender = app.Services.GetService(); +mailSender?.MailConfig(new MailConfigBindingModel +{ + MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty, + MailPassword = builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty, + SmtpClientHost = builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty, + SmtpClientPort = Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()), + PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? string.Empty, + PopPort = Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString()) +}); + // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { diff --git a/FoodOrders/FoodOrdersRestApi/appsettings.json b/FoodOrders/FoodOrdersRestApi/appsettings.json index 10f68b8..850527b 100644 --- a/FoodOrders/FoodOrdersRestApi/appsettings.json +++ b/FoodOrders/FoodOrdersRestApi/appsettings.json @@ -5,5 +5,12 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "labaporpp@gmail.com", + "MailPassword": "czja wwew vxbx badi" } diff --git a/FoodOrders/FoodOrdersView/App.config b/FoodOrders/FoodOrdersView/App.config new file mode 100644 index 0000000..55ba657 --- /dev/null +++ b/FoodOrders/FoodOrdersView/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/FoodOrders/FoodOrdersView/FormMails.Designer.cs b/FoodOrders/FoodOrdersView/FormMails.Designer.cs new file mode 100644 index 0000000..3e57b82 --- /dev/null +++ b/FoodOrders/FoodOrdersView/FormMails.Designer.cs @@ -0,0 +1,70 @@ +namespace FoodOrdersView +{ + partial class FormMails + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = SystemColors.ControlLightLight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Fill; + dataGridView.Location = new Point(0, 0); + dataGridView.Margin = new Padding(3, 2, 3, 2); + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(688, 202); + dataGridView.TabIndex = 0; + // + // FormMails + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(688, 202); + Controls.Add(dataGridView); + Margin = new Padding(3, 2, 3, 2); + Name = "FormMails"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Письма"; + Load += FormMails_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/FoodOrders/FoodOrdersView/FormMails.cs b/FoodOrders/FoodOrdersView/FormMails.cs new file mode 100644 index 0000000..b85a0de --- /dev/null +++ b/FoodOrders/FoodOrdersView/FormMails.cs @@ -0,0 +1,45 @@ +using Microsoft.Extensions.Logging; +using FoodOrdersContracts.BusinessLogicsContracts; + +namespace FoodOrdersView +{ + public partial class FormMails : Form + { + private readonly ILogger _logger; + + private readonly IMessageInfoLogic _logic; + + public FormMails(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormMails_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Messages loading"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Messages loading error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/FoodOrders/FoodOrdersView/FormMails.resx b/FoodOrders/FoodOrdersView/FormMails.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/FoodOrders/FoodOrdersView/FormMails.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/FoodOrders/FoodOrdersView/FormMain.cs b/FoodOrders/FoodOrdersView/FormMain.cs index 2e69062..6c93e7d 100644 --- a/FoodOrders/FoodOrdersView/FormMain.cs +++ b/FoodOrders/FoodOrdersView/FormMain.cs @@ -40,6 +40,7 @@ namespace FoodOrdersView dataGridView.Columns["DishId"].Visible = false; dataGridView.Columns["DishName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ClientEmail"].Visible = false; dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView.Columns["ImplementerId"].Visible = false; dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; @@ -162,5 +163,14 @@ namespace FoodOrdersView form.ShowDialog(); } } + + private void почтыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + } + } } } \ No newline at end of file diff --git a/FoodOrders/FoodOrdersView/FormMain.designer.cs b/FoodOrders/FoodOrdersView/FormMain.designer.cs index 7c7ef6b..6caebcc 100644 --- a/FoodOrders/FoodOrdersView/FormMain.designer.cs +++ b/FoodOrders/FoodOrdersView/FormMain.designer.cs @@ -43,6 +43,7 @@ buttonCreateOrder = new Button(); dataGridView = new DataGridView(); buttonUpd = new Button(); + почтыToolStripMenuItem = new ToolStripMenuItem(); menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -60,7 +61,7 @@ // // справочникиToolStripMenuItem // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, БлюдаToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, БлюдаToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem, почтыToolStripMenuItem }); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.Size = new Size(117, 24); справочникиToolStripMenuItem.Text = "Справочники"; @@ -68,28 +69,28 @@ // компонентыToolStripMenuItem // компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(185, 26); + компонентыToolStripMenuItem.Size = new Size(224, 26); компонентыToolStripMenuItem.Text = "Компоненты"; компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; // // БлюдаToolStripMenuItem // БлюдаToolStripMenuItem.Name = "БлюдаToolStripMenuItem"; - БлюдаToolStripMenuItem.Size = new Size(185, 26); + БлюдаToolStripMenuItem.Size = new Size(224, 26); БлюдаToolStripMenuItem.Text = "Еда"; БлюдаToolStripMenuItem.Click += БлюдоToolStripMenuItem_Click; // // клиентыToolStripMenuItem // клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(185, 26); + клиентыToolStripMenuItem.Size = new Size(224, 26); клиентыToolStripMenuItem.Text = "Клиенты"; клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; // // исполнителиToolStripMenuItem // исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(185, 26); + исполнителиToolStripMenuItem.Size = new Size(224, 26); исполнителиToolStripMenuItem.Text = "Исполнители"; исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; // @@ -182,6 +183,13 @@ buttonUpd.UseVisualStyleBackColor = true; buttonUpd.Click += ButtonUpd_Click; // + // почтыToolStripMenuItem + // + почтыToolStripMenuItem.Name = "почтыToolStripMenuItem"; + почтыToolStripMenuItem.Size = new Size(224, 26); + почтыToolStripMenuItem.Text = "Почты"; + почтыToolStripMenuItem.Click += почтыToolStripMenuItem_Click; + // // FormMain // AutoScaleDimensions = new SizeF(8F, 20F); @@ -222,6 +230,7 @@ private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripMenuItem почтыToolStripMenuItem; } } diff --git a/FoodOrders/FoodOrdersView/Program.cs b/FoodOrders/FoodOrdersView/Program.cs index b97fbbf..af6c9e8 100644 --- a/FoodOrders/FoodOrdersView/Program.cs +++ b/FoodOrders/FoodOrdersView/Program.cs @@ -7,6 +7,8 @@ using FoodOrdersDatabaseImplement.Implements; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; +using FoodOrdersBusinessLogic.MailWorker; +using FoodOrdersContracts.BindingModels; namespace FoodOrdersView { @@ -27,9 +29,30 @@ namespace FoodOrdersView var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); + + try + { + var mailSender = _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + // + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, " "); + } Application.Run(_serviceProvider.GetRequiredService()); } - + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); private static void ConfigureServices(ServiceCollection services) { services.AddLogging(option => @@ -42,6 +65,7 @@ namespace FoodOrdersView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -49,7 +73,10 @@ namespace FoodOrdersView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); services.AddTransient(); services.AddTransient(); @@ -67,6 +94,7 @@ namespace FoodOrdersView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file