From 9b90e7a3fbb6315c4e3e6d5e9dc955dfb43ffe29 Mon Sep 17 00:00:00 2001 From: artiogf Date: Wed, 14 Jun 2023 23:11:00 +0400 Subject: [PATCH] Lab7_Main --- .../BusinessLogics/ClientLogic.cs | 32 ++-- .../BusinessLogics/MessageInfoLogic.cs | 65 +++++++++ .../BusinessLogics/OrderLogic.cs | 62 ++++++-- .../CarpentryWorkshopBusinessLogic.csproj | 2 + .../MailWorker/AbstractMailWorker.cs | 68 +++++++++ .../MailWorker/MailKitWorker.cs | 80 ++++++++++ .../Controllers/HomeController.cs | 9 ++ .../Views/Home/Enter.cshtml | 2 +- .../Views/Home/Mails.cshtml | 54 +++++++ .../Views/Home/Register.cshtml | 2 +- .../Views/Shared/_Layout.cshtml | 3 + .../BindingModels/MailConfigBindingModel.cs | 18 +++ .../BindingModels/MailSendInfoBindingModel.cs | 15 ++ .../BindingModels/MessageInfoBindingModel.cs | 19 +++ .../IMessageInfoLogic.cs | 13 ++ .../SearchModels/MessageInfoSearchModel.cs | 9 ++ .../StoragesContracts/IMessageInfoStorage.cs | 18 +++ .../ViewModels/MessageInfoViewModel.cs | 24 +++ .../Models/IMessageInfoModel.cs | 12 ++ .../CarpentryWorkshopDatabase.cs | 3 +- .../Implements/ClientStorage.cs | 138 +++++++++--------- .../Implements/MessageInfoStorage.cs | 64 ++++++++ ... 20230614191433_InitialCreate.Designer.cs} | 47 +++++- ...ate.cs => 20230614191433_InitialCreate.cs} | 29 ++++ .../CarpentryWorkshopDatabaseModelSnapshot.cs | 45 +++++- .../Models/Client.cs | 81 +++++----- .../Models/MessageInfo.cs | 67 +++++++++ .../DataFileSingleton.cs | 4 + .../Implements/MessageInfoStorage.cs | 66 +++++++++ .../Models/Message.cs | 87 +++++++++++ .../DataListSingleton.cs | 2 + .../Implements/MessageInfoStorage.cs | 81 ++++++++++ .../Models/Message.cs | 58 ++++++++ .../Controllers/ClientController.cs | 134 ++++++++++------- CarpentryWorkshopRestApi/Program.cs | 52 +++++-- CarpentryWorkshopRestApi/appsettings.json | 12 +- CarpentryWorkshopView/App.config | 11 ++ CarpentryWorkshopView/FormMail.Designer.cs | 60 ++++++++ CarpentryWorkshopView/FormMail.cs | 56 +++++++ CarpentryWorkshopView/FormMail.resx | 60 ++++++++ CarpentryWorkshopView/FormMain.Designer.cs | 11 +- CarpentryWorkshopView/FormMain.cs | 9 ++ CarpentryWorkshopView/Program.cs | 117 +++++++++------ 43 files changed, 1536 insertions(+), 265 deletions(-) create mode 100644 CarpentryWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs create mode 100644 CarpentryWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 CarpentryWorkshopBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 CarpentryWorkshopClientApp/Views/Home/Mails.cshtml create mode 100644 CarpentryWorkshopContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 CarpentryWorkshopContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 CarpentryWorkshopContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 CarpentryWorkshopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 CarpentryWorkshopContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 CarpentryWorkshopContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 CarpentryWorkshopContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 CarpentryWorkshopDataModels/Models/IMessageInfoModel.cs create mode 100644 CarpentryWorkshopDatabaseImplement/Implements/MessageInfoStorage.cs rename CarpentryWorkshopDatabaseImplement/Migrations/{20230514182258_InitialCreate.Designer.cs => 20230614191433_InitialCreate.Designer.cs} (84%) rename CarpentryWorkshopDatabaseImplement/Migrations/{20230514182258_InitialCreate.cs => 20230614191433_InitialCreate.cs} (85%) create mode 100644 CarpentryWorkshopDatabaseImplement/Models/MessageInfo.cs create mode 100644 CarpentryWorkshopFileImplement/Implements/MessageInfoStorage.cs create mode 100644 CarpentryWorkshopFileImplement/Models/Message.cs create mode 100644 CarpentryWorkshopListImplement/Implements/MessageInfoStorage.cs create mode 100644 CarpentryWorkshopListImplement/Models/Message.cs create mode 100644 CarpentryWorkshopView/App.config create mode 100644 CarpentryWorkshopView/FormMail.Designer.cs create mode 100644 CarpentryWorkshopView/FormMail.cs create mode 100644 CarpentryWorkshopView/FormMail.resx diff --git a/CarpentryWorkshopBusinessLogic/BusinessLogics/ClientLogic.cs b/CarpentryWorkshopBusinessLogic/BusinessLogics/ClientLogic.cs index 388f6a5..7b78e6a 100644 --- a/CarpentryWorkshopBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/CarpentryWorkshopBusinessLogic/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 CarpentryWorkshopBusinessLogic.BusinessLogics @@ -52,7 +53,7 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics { throw new ArgumentNullException(nameof(model)); } - _logger.LogInformation("ReadElement. ClientFio:{ClientFio}.Id:{ Id}", model.ClientFIO, model.Id); + _logger.LogInformation("ReadElement. ClientFIO:{ClientFIO}. Email: {Email}. Id:{ Id}", model.ClientFIO, model.Email, model.Id); var element = _clientStorage.GetElement(model); if (element == null) { @@ -101,20 +102,27 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics { throw new ArgumentNullException("Нет ФИО пользователя", nameof(model.ClientFIO)); } - if (string.IsNullOrEmpty(model.Email)) + if (string.IsNullOrEmpty(model.Email)) + { + throw new ArgumentNullException("Нет почты клиента", nameof(model.Email)); + } + if (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException("Нет пароля клиента", nameof(model.Password)); + } + if (!Regex.IsMatch(model.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase)) { - throw new ArgumentNullException("Нет почты пользователя", nameof(model.Email)); - } - if (string.IsNullOrEmpty(model.Password)) - { - throw new ArgumentNullException("Нет пароля пользователя", nameof(model.Password)); - } - _logger.LogInformation("Client. ClientFIO:{ClientFIO}.Email:{Email}.Password:{Password}.Id:{Id}", - model.ClientFIO, model.Email, model.Password, model.Id); + throw new ArgumentException("Неправильно введенный email", nameof(model.Email)); + } + if (!Regex.IsMatch(model.Password, @"^^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$", RegexOptions.IgnoreCase) || model.Password.Length < 10 || model.Password.Length > 50) + { + throw new ArgumentException("Неправильно введенный пароль", nameof(model.Password)); + } + _logger.LogInformation("Client. ClientFIO:{ClientFIO}.Email:{Email}.Id:{Id}", model.ClientFIO, model.Email, model.Id); var element = _clientStorage.GetElement(new ClientSearchModel { - ClientFIO = model.ClientFIO - }); + Email = model.Email + }); if (element != null && element.Id != model.Id) { throw new InvalidOperationException("Клиент с таким именем уже есть"); diff --git a/CarpentryWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/CarpentryWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..fe4c81b --- /dev/null +++ b/CarpentryWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,65 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using CarpentryWorkshopContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarpentryWorkshopBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageInfoStorage; + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageInfoStorage) + { + _logger = logger; + _messageInfoStorage = messageInfoStorage; + } + + public bool Create(MessageInfoBindingModel model) + { + + var element = _messageInfoStorage.GetElement(new MessageInfoSearchModel + { + MessageId = model.MessageId + }); + if (element != null) + { + if (_messageInfoStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + else + { + if (_messageInfoStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + } + + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. ClientId:{ClientId}", 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; + } + } +} diff --git a/CarpentryWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs b/CarpentryWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs index 6bbfc18..920d7b7 100644 --- a/CarpentryWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/CarpentryWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,4 +1,5 @@ -using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopBusinessLogic.MailWorker; +using CarpentryWorkshopContracts.BindingModels; using CarpentryWorkshopContracts.BusinessLogicsContracts; using CarpentryWorkshopContracts.SearchModels; using CarpentryWorkshopContracts.StoragesContracts; @@ -7,9 +8,11 @@ using CarpentryWorkshopDataModels.Enums; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Xml.Linq; namespace CarpentryWorkshopBusinessLogic.BusinessLogics { @@ -17,11 +20,15 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic) { _logger = logger; _orderStorage = orderStorage; + _mailWorker = mailWorker; + _clientLogic = clientLogic; } public bool CreateOrder(OrderBindingModel model) @@ -35,14 +42,17 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics } model.Status = OrderStatus.Принят; + var result = _orderStorage.Insert(model); - if (_orderStorage.Insert(model) == null) + if (result == null) { model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } + SendOrderMessage(result.ClientId, $"Установка ПО, Заказ №{result.Id}", $"Заказ №{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); + return true; } @@ -76,13 +86,36 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics model.Sum = vmodel.Sum; model.Count = vmodel.Count; - if (_orderStorage.Update(model) == null) + var result = _orderStorage.Update(model); + + if (result == null) { _logger.LogWarning("Update operation failed"); return false; } + + SendOrderMessage(result.ClientId, $"Установка ПО, Заказ №{result.Id}", $"Заказ №{model.Id} изменен статус на {result.Status}"); + return true; + } + + private bool SendOrderMessage(int clientId, string subject, string text) + { + var client = _clientLogic.ReadElement(new() { Id = clientId }); + + if (client == null) + { + return false; + } + + _mailWorker.MailSendAsync(new() + { + MailAddress = client.Email, + Subject = subject, + Text = text + }); + return true; } @@ -118,26 +151,29 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics return list; } - private bool CheckModel(OrderBindingModel model) + private void CheckModel(OrderBindingModel model, bool withParams = true) { if (model == null) { throw new ArgumentNullException(nameof(model)); } + if (!withParams) + { + return; + } + if (model.WoodId < 0) + { + throw new ArgumentNullException("Некорректный идентификатор у изделия", nameof(model.WoodId)); + } if (model.Count <= 0) { - throw new ArgumentException("Количество изделий в заказе должно быть больше 0", nameof(model.Count)); + throw new ArgumentNullException("Количество изделий в заказе должно быть больше 0", nameof(model.Count)); } if (model.Sum <= 0) { - throw new ArgumentException("Суммарная стоимость заказа должна быть больше 0", nameof(model.Sum)); + throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum)); } - if (model.DateCreate > model.DateImplement) - { - throw new ArgumentException("Время создания заказа не может быть больше времени его выполнения", nameof(model.DateImplement)); - } - - return true; + _logger.LogInformation("Order. OrderID:{Id}. Sum:{ Sum}. WoodId: { WoodId}", model.Id, model.Sum, model.WoodId); } public OrderViewModel? ReadElement(OrderSearchModel model) diff --git a/CarpentryWorkshopBusinessLogic/CarpentryWorkshopBusinessLogic.csproj b/CarpentryWorkshopBusinessLogic/CarpentryWorkshopBusinessLogic.csproj index af9f9f4..be39102 100644 --- a/CarpentryWorkshopBusinessLogic/CarpentryWorkshopBusinessLogic.csproj +++ b/CarpentryWorkshopBusinessLogic/CarpentryWorkshopBusinessLogic.csproj @@ -8,6 +8,7 @@ + @@ -20,6 +21,7 @@ + diff --git a/CarpentryWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs b/CarpentryWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..1466d44 --- /dev/null +++ b/CarpentryWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,68 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; + +namespace CarpentryWorkshopBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin; + protected string _mailPassword; + protected string _smtpClientHost; + protected int _smtpClientPort; + protected string _popHost; + protected int _popPort; + private IMessageInfoLogic _messageInfoLogic; + public AbstractMailWorker(IMessageInfoLogic messageInfoLogic) + { + _messageInfoLogic = messageInfoLogic; + } + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.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; + } + 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(); + foreach (var mail in list) + { + _messageInfoLogic.Create(mail); + } + } + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + protected abstract Task> ReceiveMailAsync(); + } +} \ No newline at end of file diff --git a/CarpentryWorkshopBusinessLogic/MailWorker/MailKitWorker.cs b/CarpentryWorkshopBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..0d6a95b --- /dev/null +++ b/CarpentryWorkshopBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,80 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using MailKit.Net.Pop3; +using MailKit.Security; +using Microsoft.Extensions.Logging; +using System.Net; +using System.Net.Mail; +using System.Text; + +namespace CarpentryWorkshopBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + private IClientStorage _clientStorage; + public MailKitWorker(IMessageInfoLogic messageInfoLogic, IClientStorage clientStorage) : base(messageInfoLogic) + { + _clientStorage = clientStorage; + } + 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 + { + ClientId = _clientStorage.GetElement(new ClientSearchModel { Email = mail.Address })?.Id, + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} \ No newline at end of file diff --git a/CarpentryWorkshopClientApp/Controllers/HomeController.cs b/CarpentryWorkshopClientApp/Controllers/HomeController.cs index b666233..653a5b8 100644 --- a/CarpentryWorkshopClientApp/Controllers/HomeController.cs +++ b/CarpentryWorkshopClientApp/Controllers/HomeController.cs @@ -148,5 +148,14 @@ namespace CarpentryWorkshopClientApp.Controllers var prod = APIClient.GetRequest($"api/main/getwood?woodId={wood}"); return count * (prod?.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}")); + } } } \ No newline at end of file diff --git a/CarpentryWorkshopClientApp/Views/Home/Enter.cshtml b/CarpentryWorkshopClientApp/Views/Home/Enter.cshtml index bca6d69..c2cde0b 100644 --- a/CarpentryWorkshopClientApp/Views/Home/Enter.cshtml +++ b/CarpentryWorkshopClientApp/Views/Home/Enter.cshtml @@ -12,7 +12,7 @@
Пароль:
-
+
diff --git a/CarpentryWorkshopClientApp/Views/Home/Mails.cshtml b/CarpentryWorkshopClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..3a177ef --- /dev/null +++ b/CarpentryWorkshopClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using CarpentryWorkshopContracts.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) +
+ } +
diff --git a/CarpentryWorkshopClientApp/Views/Home/Register.cshtml b/CarpentryWorkshopClientApp/Views/Home/Register.cshtml index 398b516..49b221f 100644 --- a/CarpentryWorkshopClientApp/Views/Home/Register.cshtml +++ b/CarpentryWorkshopClientApp/Views/Home/Register.cshtml @@ -12,7 +12,7 @@
Пароль:
-
+
ФИО:
diff --git a/CarpentryWorkshopClientApp/Views/Shared/_Layout.cshtml b/CarpentryWorkshopClientApp/Views/Shared/_Layout.cshtml index 0390638..b7f8dbc 100644 --- a/CarpentryWorkshopClientApp/Views/Shared/_Layout.cshtml +++ b/CarpentryWorkshopClientApp/Views/Shared/_Layout.cshtml @@ -28,6 +28,9 @@ + diff --git a/CarpentryWorkshopContracts/BindingModels/MailConfigBindingModel.cs b/CarpentryWorkshopContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..a50fe43 --- /dev/null +++ b/CarpentryWorkshopContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarpentryWorkshopContracts.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/CarpentryWorkshopContracts/BindingModels/MailSendInfoBindingModel.cs b/CarpentryWorkshopContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..20e09aa --- /dev/null +++ b/CarpentryWorkshopContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarpentryWorkshopContracts.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/CarpentryWorkshopContracts/BindingModels/MessageInfoBindingModel.cs b/CarpentryWorkshopContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..4d31cfc --- /dev/null +++ b/CarpentryWorkshopContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using CarpentryWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarpentryWorkshopContracts.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 string Subject { get; set; } = string.Empty; + public string Body { get; set; } = string.Empty; + public DateTime DateDelivery { get; set; } + } +} diff --git a/CarpentryWorkshopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/CarpentryWorkshopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..8cd8d66 --- /dev/null +++ b/CarpentryWorkshopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,13 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.ViewModels; + +namespace CarpentryWorkshopContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + + bool Create(MessageInfoBindingModel model); + } +} \ No newline at end of file diff --git a/CarpentryWorkshopContracts/SearchModels/MessageInfoSearchModel.cs b/CarpentryWorkshopContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..9427672 --- /dev/null +++ b/CarpentryWorkshopContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,9 @@ +namespace CarpentryWorkshopContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + + public string? MessageId { get; set; } + } +} \ No newline at end of file diff --git a/CarpentryWorkshopContracts/StoragesContracts/IMessageInfoStorage.cs b/CarpentryWorkshopContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..a7a959e --- /dev/null +++ b/CarpentryWorkshopContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,18 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.ViewModels; + +namespace CarpentryWorkshopContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + + List GetFilteredList(MessageInfoSearchModel model); + + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + MessageInfoViewModel? Update(MessageInfoBindingModel model); + } +} \ No newline at end of file diff --git a/CarpentryWorkshopContracts/ViewModels/MessageInfoViewModel.cs b/CarpentryWorkshopContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..597eed5 --- /dev/null +++ b/CarpentryWorkshopContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,24 @@ +using CarpentryWorkshopDataModels.Models; +using System.ComponentModel; + +namespace CarpentryWorkshopContracts.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; + } +} \ No newline at end of file diff --git a/CarpentryWorkshopDataModels/Models/IMessageInfoModel.cs b/CarpentryWorkshopDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..fec8b6a --- /dev/null +++ b/CarpentryWorkshopDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,12 @@ +namespace CarpentryWorkshopDataModels.Models +{ + public interface IMessageInfoModel + { + string MessageId { get; } + int? ClientId { get; } + string SenderName { get; } + DateTime DateDelivery { get; } + string Subject { get; } + string Body { get; } + } +} \ No newline at end of file diff --git a/CarpentryWorkshopDatabaseImplement/CarpentryWorkshopDatabase.cs b/CarpentryWorkshopDatabaseImplement/CarpentryWorkshopDatabase.cs index a747aff..289a4a4 100644 --- a/CarpentryWorkshopDatabaseImplement/CarpentryWorkshopDatabase.cs +++ b/CarpentryWorkshopDatabaseImplement/CarpentryWorkshopDatabase.cs @@ -9,7 +9,7 @@ namespace CarpentryWorkshopDatabaseImplement { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-VTSC074\SQLEXPRESS;Initial Catalog=CarpentryWorkshopDatabaseFullLab6;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); + optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-VTSC074\SQLEXPRESS;Initial Catalog=CarpentryWorkshopDatabaseFullLab7;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); } base.OnConfiguring(optionsBuilder); } @@ -19,5 +19,6 @@ namespace CarpentryWorkshopDatabaseImplement public virtual DbSet WoodComponents { set; get; } public virtual DbSet Orders { set; get; } public virtual DbSet Implementers { set; get; } + public virtual DbSet MessageInfos { set; get; } } } \ No newline at end of file diff --git a/CarpentryWorkshopDatabaseImplement/Implements/ClientStorage.cs b/CarpentryWorkshopDatabaseImplement/Implements/ClientStorage.cs index bce4844..901fb24 100644 --- a/CarpentryWorkshopDatabaseImplement/Implements/ClientStorage.cs +++ b/CarpentryWorkshopDatabaseImplement/Implements/ClientStorage.cs @@ -13,78 +13,72 @@ namespace CarpentryWorkshopDatabaseImplement.Implements { public class ClientStorage : IClientStorage { - // - public List GetFullList() - { - using var context = new CarpentryWorkshopDatabase(); - return context.Clients - .Select(x => x.GetViewModel) - .ToList(); - } - // - public List GetFilteredList(ClientSearchModel model) - { - if (string.IsNullOrEmpty(model.ClientFIO)) - { - return new(); - } - using var context = new CarpentryWorkshopDatabase(); - return context.Clients - .Where(x => x.ClientFIO.Contains(model.ClientFIO)) - .Select(x => x.GetViewModel) - .ToList(); - } - // - public ClientViewModel? GetElement(ClientSearchModel model) - { - if (string.IsNullOrEmpty(model.Email) && string.IsNullOrEmpty(model.Password) && !model.Id.HasValue) - { - return null; - } - using var context = new CarpentryWorkshopDatabase(); - return context.Clients - .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && !string.IsNullOrEmpty(model.Password) && x.Password == model.Password) || - (model.Id.HasValue && x.Id == model.Id)) - ?.GetViewModel; - } - // - public ClientViewModel? Insert(ClientBindingModel model) - { - var newClient = Client.Create(model); - if (newClient == null) - { - return null; - } - using var context = new CarpentryWorkshopDatabase(); - context.Clients.Add(newClient); - context.SaveChanges(); - return newClient.GetViewModel; - } + public ClientViewModel? Delete(ClientBindingModel model) + { + using var context = new CarpentryWorkshopDatabase(); + var element = context.Clients.FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + context.Clients.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } - public ClientViewModel? Update(ClientBindingModel model) - { - using var context = new CarpentryWorkshopDatabase(); - var component = context.Clients.FirstOrDefault(x => x.Id == model.Id); - if (component == null) - { - return null; - } - component.Update(model); - context.SaveChanges(); - return component.GetViewModel; - } + public ClientViewModel? GetElement(ClientSearchModel model) + { + if (string.IsNullOrEmpty(model.Email) && string.IsNullOrEmpty(model.Password) && !model.Id.HasValue) + { + return null; + } + using var context = new CarpentryWorkshopDatabase(); + return context.Clients.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) || + (!string.IsNullOrEmpty(model.ClientFIO) && x.ClientFIO == model.ClientFIO) || + (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && (string.IsNullOrEmpty(model.Password) || x.Password == model.Password)))?.GetViewModel; - public ClientViewModel? Delete(ClientBindingModel model) - { - using var context = new CarpentryWorkshopDatabase(); - var element = context.Clients.FirstOrDefault(rec => rec.Id == model.Id); - if (element != null) - { - context.Clients.Remove(element); - context.SaveChanges(); - return element.GetViewModel; - } - return null; - } - } + } + + public List GetFilteredList(ClientSearchModel model) + { + if (string.IsNullOrEmpty(model.ClientFIO)) + { + return new(); + } + using var context = new CarpentryWorkshopDatabase(); + return context.Clients.Where(x => x.ClientFIO.Contains(model.ClientFIO)).Select(x => x.GetViewModel).ToList(); + } + + public List GetFullList() + { + using var context = new CarpentryWorkshopDatabase(); + return context.Clients.Select(x => x.GetViewModel).ToList(); + } + + public ClientViewModel? Insert(ClientBindingModel model) + { + var newComponent = Client.Create(model); + if (newComponent == null) + { + return null; + } + using var context = new CarpentryWorkshopDatabase(); + context.Clients.Add(newComponent); + context.SaveChanges(); + return newComponent.GetViewModel; + } + + public ClientViewModel? Update(ClientBindingModel model) + { + using var context = new CarpentryWorkshopDatabase(); + var component = context.Clients.FirstOrDefault(x => x.Id == model.Id); + if (component == null) + { + return null; + } + component.Update(model); + context.SaveChanges(); + return component.GetViewModel; + } + } } diff --git a/CarpentryWorkshopDatabaseImplement/Implements/MessageInfoStorage.cs b/CarpentryWorkshopDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..c943e0e --- /dev/null +++ b/CarpentryWorkshopDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,64 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarpentryWorkshopDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + public List GetFullList() + { + using var context = new CarpentryWorkshopDatabase(); + return context.MessageInfos.Select(x => x.GetViewModel).ToList(); + } + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + using var context = new CarpentryWorkshopDatabase(); + return context.MessageInfos.Where(x => x.ClientId.HasValue && x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return new(); + } + using var context = new CarpentryWorkshopDatabase(); + return context.MessageInfos.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + using var context = new CarpentryWorkshopDatabase(); + context.MessageInfos.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + public MessageInfoViewModel? Update(MessageInfoBindingModel model) + { + using var context = new CarpentryWorkshopDatabase(); + var component = context.MessageInfos.FirstOrDefault(x => x.MessageId == model.MessageId); + if (component == null) + { + return null; + } + component.Update(model); + context.SaveChanges(); + return component.GetViewModel; + } + } +} diff --git a/CarpentryWorkshopDatabaseImplement/Migrations/20230514182258_InitialCreate.Designer.cs b/CarpentryWorkshopDatabaseImplement/Migrations/20230614191433_InitialCreate.Designer.cs similarity index 84% rename from CarpentryWorkshopDatabaseImplement/Migrations/20230514182258_InitialCreate.Designer.cs rename to CarpentryWorkshopDatabaseImplement/Migrations/20230614191433_InitialCreate.Designer.cs index de27581..c388c94 100644 --- a/CarpentryWorkshopDatabaseImplement/Migrations/20230514182258_InitialCreate.Designer.cs +++ b/CarpentryWorkshopDatabaseImplement/Migrations/20230614191433_InitialCreate.Designer.cs @@ -12,7 +12,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace CarpentryWorkshopDatabaseImplement.Migrations { [DbContext(typeof(CarpentryWorkshopDatabase))] - [Migration("20230514182258_InitialCreate")] + [Migration("20230614191433_InitialCreate")] partial class InitialCreate { /// @@ -97,6 +97,36 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.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("MessageInfos"); + }); + modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -190,10 +220,19 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations b.ToTable("WoodComponents"); }); + modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", "Client") + .WithMany("ClientMessages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b => { b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", "Client") - .WithMany("Orders") + .WithMany("ClientOrders") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); @@ -236,7 +275,9 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Client", b => { - b.Navigation("Orders"); + b.Navigation("ClientMessages"); + + b.Navigation("ClientOrders"); }); modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Component", b => diff --git a/CarpentryWorkshopDatabaseImplement/Migrations/20230514182258_InitialCreate.cs b/CarpentryWorkshopDatabaseImplement/Migrations/20230614191433_InitialCreate.cs similarity index 85% rename from CarpentryWorkshopDatabaseImplement/Migrations/20230514182258_InitialCreate.cs rename to CarpentryWorkshopDatabaseImplement/Migrations/20230614191433_InitialCreate.cs index f0edaac..d818a91 100644 --- a/CarpentryWorkshopDatabaseImplement/Migrations/20230514182258_InitialCreate.cs +++ b/CarpentryWorkshopDatabaseImplement/Migrations/20230614191433_InitialCreate.cs @@ -70,6 +70,27 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations table.PrimaryKey("PK_Woods", x => x.Id); }); + migrationBuilder.CreateTable( + name: "MessageInfos", + 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_MessageInfos", x => x.MessageId); + table.ForeignKey( + name: "FK_MessageInfos_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id"); + }); + migrationBuilder.CreateTable( name: "Orders", columns: table => new @@ -135,6 +156,11 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations onDelete: ReferentialAction.Cascade); }); + migrationBuilder.CreateIndex( + name: "IX_MessageInfos_ClientId", + table: "MessageInfos", + column: "ClientId"); + migrationBuilder.CreateIndex( name: "IX_Orders_ClientId", table: "Orders", @@ -164,6 +190,9 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations /// protected override void Down(MigrationBuilder migrationBuilder) { + migrationBuilder.DropTable( + name: "MessageInfos"); + migrationBuilder.DropTable( name: "Orders"); diff --git a/CarpentryWorkshopDatabaseImplement/Migrations/CarpentryWorkshopDatabaseModelSnapshot.cs b/CarpentryWorkshopDatabaseImplement/Migrations/CarpentryWorkshopDatabaseModelSnapshot.cs index 6d0c77c..509cb0f 100644 --- a/CarpentryWorkshopDatabaseImplement/Migrations/CarpentryWorkshopDatabaseModelSnapshot.cs +++ b/CarpentryWorkshopDatabaseImplement/Migrations/CarpentryWorkshopDatabaseModelSnapshot.cs @@ -94,6 +94,36 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.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("MessageInfos"); + }); + modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -187,10 +217,19 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations b.ToTable("WoodComponents"); }); + modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", "Client") + .WithMany("ClientMessages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b => { b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", "Client") - .WithMany("Orders") + .WithMany("ClientOrders") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); @@ -233,7 +272,9 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Client", b => { - b.Navigation("Orders"); + b.Navigation("ClientMessages"); + + b.Navigation("ClientOrders"); }); modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Component", b => diff --git a/CarpentryWorkshopDatabaseImplement/Models/Client.cs b/CarpentryWorkshopDatabaseImplement/Models/Client.cs index d02b4eb..b49c39b 100644 --- a/CarpentryWorkshopDatabaseImplement/Models/Client.cs +++ b/CarpentryWorkshopDatabaseImplement/Models/Client.cs @@ -11,54 +11,49 @@ using System.Threading.Tasks; namespace CarpentryWorkshopDatabaseImplement.Models { - public class Client : IClientModel - { - public int Id { get; private set; } + public class Client : IClientModel + { + public int Id { get; set; } - [Required] - public string ClientFIO { get; private set; } = string.Empty; + [Required] + public string ClientFIO { get; set; } = string.Empty; - [Required] - public string Email { get; private set; } = string.Empty; + [Required] + public string Email { get; set; } = string.Empty; - [Required] - public string Password { get; private set; } = string.Empty; + [Required] + public string Password { get; set; } = string.Empty; - [ForeignKey("ClientId")] - public virtual List Orders { get; set; } = new(); + [ForeignKey("ClientId")] + public virtual List ClientOrders { get; set; } = new(); - public static Client? Create(ClientBindingModel model) - { - if (model == null) - { - return null; - } - return new() - { - Id = model.Id, - ClientFIO = model.ClientFIO, - Email = model.Email, - Password = model.Password - }; - } + [ForeignKey("ClientId")] + public virtual List ClientMessages { get; set; } = new(); - public void Update(ClientBindingModel model) - { - if (model == null) - { - return; - } - ClientFIO = model.ClientFIO; - Email = model.Email; - Password = model.Password; - } + public ClientViewModel GetViewModel => new() + { + Id = Id, + ClientFIO = ClientFIO, + Email = Email, + Password = Password + }; - public ClientViewModel GetViewModel => new() - { - Id = Id, - ClientFIO = ClientFIO, - Email = Email, - Password = Password, - }; - } + public static Client Create(ClientBindingModel model) + { + return new Client() + { + Id = model.Id, + ClientFIO = model.ClientFIO, + Email = model.Email, + Password = model.Password, + }; + } + + public void Update(ClientBindingModel model) + { + ClientFIO = model.ClientFIO; + Email = model.Email; + Password = model.Password; + } + } } diff --git a/CarpentryWorkshopDatabaseImplement/Models/MessageInfo.cs b/CarpentryWorkshopDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..bdfa859 --- /dev/null +++ b/CarpentryWorkshopDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,67 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarpentryWorkshopDatabaseImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + [Key] + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + public virtual Client? Client { 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; + + public static MessageInfo? Create(MessageInfoBindingModel? model) + { + if (model == null) + { + return null; + } + return new() + { + MessageId = model.MessageId, + ClientId = model.ClientId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + Subject = model.Subject, + Body = model.Body, + + }; + } + public void Update(MessageInfoBindingModel model) + { + MessageId = model.MessageId; + ClientId = model.ClientId; + SenderName = model.SenderName; + DateDelivery = model.DateDelivery; + Subject = model.Subject; + Body = model.Body; + } + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body + }; + } +} diff --git a/CarpentryWorkshopFileImplement/DataFileSingleton.cs b/CarpentryWorkshopFileImplement/DataFileSingleton.cs index 0894230..eb6294b 100644 --- a/CarpentryWorkshopFileImplement/DataFileSingleton.cs +++ b/CarpentryWorkshopFileImplement/DataFileSingleton.cs @@ -11,6 +11,8 @@ namespace CarpentryWorkshopFileImplement private readonly string WoodFileName = "Wood.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageFileName = "Message.xml"; + public List Messages { get; private set; } public List Components { get; private set; } public List Orders { get; private set; } public List Woods { get; private set; } @@ -28,6 +30,7 @@ namespace CarpentryWorkshopFileImplement public void SaveWoods() => SaveData(Woods, WoodFileName, "Woods", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); + public void SaveMessages() => SaveData(Messages, MessageFileName, "Messages", x => x.GetXElement); public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); private DataFileSingleton() @@ -37,6 +40,7 @@ namespace CarpentryWorkshopFileImplement 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(MessageFileName, "Message", x => Message.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { diff --git a/CarpentryWorkshopFileImplement/Implements/MessageInfoStorage.cs b/CarpentryWorkshopFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..21d4518 --- /dev/null +++ b/CarpentryWorkshopFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,66 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopFileImplement.Models; + +namespace CarpentryWorkshopFileImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataFileSingleton source; + public MessageInfoStorage() + { + source = DataFileSingleton.GetInstance(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId == null) + return null; + return source.Messages.FirstOrDefault(x => + x.MessageId == model.MessageId)?.GetViewModel; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + 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 = Message.Create(model); + if (newMessage == null) + { + return null; + } + source.Messages.Add(newMessage); + source.SaveMessages(); + return newMessage.GetViewModel; + } + public MessageInfoViewModel? Update(MessageInfoBindingModel model) + { + var component = source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId); + if (component == null) + { + return null; + } + component.Update(model); + source.SaveMessages(); + return component.GetViewModel; + } + } +} diff --git a/CarpentryWorkshopFileImplement/Models/Message.cs b/CarpentryWorkshopFileImplement/Models/Message.cs new file mode 100644 index 0000000..7c5271b --- /dev/null +++ b/CarpentryWorkshopFileImplement/Models/Message.cs @@ -0,0 +1,87 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; +using System.Xml.Linq; + +namespace CarpentryWorkshopFileImplement.Models +{ + public class Message : 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; } + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + DateDelivery = model.DateDelivery, + SenderName = model.SenderName, + ClientId = model.ClientId, + MessageId = model.MessageId + }; + } + + public static Message? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Body = element.Attribute("Body")!.Value, + Subject = element.Attribute("Subject")!.Value, + DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), + SenderName = element.Attribute("SenderName")!.Value, + ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value), + MessageId = element.Attribute("MessageId")!.Value, + }; + } + + internal void Update(MessageInfoBindingModel model) + { + if (model == null) + { + return; + } + SenderName = model.SenderName; + DateDelivery = model.DateDelivery; + Subject = model.Subject; + Body = model.Body; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + DateDelivery = DateDelivery, + SenderName = SenderName, + ClientId = ClientId, + MessageId = MessageId + }; + + public XElement GetXElement => new("MessageInfo", + new XAttribute("Subject", Subject), + new XAttribute("Body", Body), + new XAttribute("ClientId", ClientId), + new XAttribute("MessageId", MessageId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery) + ); + } +} diff --git a/CarpentryWorkshopListImplement/DataListSingleton.cs b/CarpentryWorkshopListImplement/DataListSingleton.cs index 496dc57..38a0e07 100644 --- a/CarpentryWorkshopListImplement/DataListSingleton.cs +++ b/CarpentryWorkshopListImplement/DataListSingleton.cs @@ -10,6 +10,7 @@ namespace CarpentryWorkshopListImplement public List Woods { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List Messages { get; set; } private DataListSingleton() { Components = new List(); @@ -17,6 +18,7 @@ namespace CarpentryWorkshopListImplement Woods = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } public static DataListSingleton GetInstance() { diff --git a/CarpentryWorkshopListImplement/Implements/MessageInfoStorage.cs b/CarpentryWorkshopListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..8371fee --- /dev/null +++ b/CarpentryWorkshopListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,81 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopListImplement.Models; + +namespace CarpentryWorkshopListImplement.Implements +{ + internal class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId == null) + { + return null; + } + foreach (var message in _source.Messages) + { + if (model.MessageId.Equals(message.MessageId)) + return message.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + var result = new List(); + foreach (var item in _source.Messages) + { + if (item.ClientId == model.ClientId) + { + result.Add(item.GetViewModel); + } + } + return result; + } + + public List GetFullList() + { + var result = new List(); + foreach (var item in _source.Messages) + { + result.Add(item.GetViewModel); + } + return result; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + public MessageInfoViewModel? Update(MessageInfoBindingModel model) + { + foreach (var massage in _source.Messages) + { + if (massage.MessageId == model.MessageId) + { + massage.Update(model); + + return massage.GetViewModel; + } + } + return null; + } + } +} diff --git a/CarpentryWorkshopListImplement/Models/Message.cs b/CarpentryWorkshopListImplement/Models/Message.cs new file mode 100644 index 0000000..a785872 --- /dev/null +++ b/CarpentryWorkshopListImplement/Models/Message.cs @@ -0,0 +1,58 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; + +namespace CarpentryWorkshopListImplement.Models +{ + public class Message : 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 Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + DateDelivery = model.DateDelivery, + SenderName = model.SenderName, + ClientId = model.ClientId, + MessageId = model.MessageId + }; + } + public void Update(MessageInfoBindingModel model) + { + if (model == null) + { + return; + } + SenderName = model.SenderName; + DateDelivery = model.DateDelivery; + Subject = model.Subject; + Body = model.Body; + } + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + DateDelivery = DateDelivery, + SenderName = SenderName, + ClientId = ClientId, + MessageId = MessageId + }; + } +} diff --git a/CarpentryWorkshopRestApi/Controllers/ClientController.cs b/CarpentryWorkshopRestApi/Controllers/ClientController.cs index cce1e4a..6f7b57f 100644 --- a/CarpentryWorkshopRestApi/Controllers/ClientController.cs +++ b/CarpentryWorkshopRestApi/Controllers/ClientController.cs @@ -6,60 +6,82 @@ using Microsoft.AspNetCore.Mvc; namespace CarpentryWorkshopRestApi.Controllers { - [Route("api/[controller]/[action]")] - [ApiController] - public class ClientController : Controller - { - private readonly ILogger _logger; - private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger - logger) - { - _logger = logger; - _logic = logic; - } - [HttpGet] - public ClientViewModel? Login(string login, string password) - { - try - { - return _logic.ReadElement(new ClientSearchModel - { - Email = login, - Password = password - }); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка входа в систему"); - throw; - } - } - [HttpPost] - public void Register(ClientBindingModel model) - { - try - { - _logic.Create(model); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка регистрации"); - throw; - } - } - [HttpPost] - public void UpdateData(ClientBindingModel model) - { - try - { - _logic.Update(model); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка обновления данных"); - throw; - } - } - } + [Route("api/[controller]/[action]")] + [ApiController] + public class ClientController : Controller + { + private readonly ILogger _logger; + private readonly IClientLogic _logic; + 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) + { + try + { + return _logic.ReadElement(new ClientSearchModel + { + Email = login, + Password = password + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка входа в систему"); + throw; + } + } + + [HttpPost] + public void Register(ClientBindingModel model) + { + try + { + _logic.Create(model); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка регистрации"); + throw; + } + } + + [HttpPost] + public void UpdateData(ClientBindingModel model) + { + try + { + _logic.Update(model); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка обновления данных"); + throw; + } + } + + [HttpGet] + public List? GetMessages(int clientId) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } + } + } } diff --git a/CarpentryWorkshopRestApi/Program.cs b/CarpentryWorkshopRestApi/Program.cs index c27b935..fa4650b 100644 --- a/CarpentryWorkshopRestApi/Program.cs +++ b/CarpentryWorkshopRestApi/Program.cs @@ -1,41 +1,67 @@ using CarpentryWorkshopBusinessLogic.BusinessLogics; +using CarpentryWorkshopBusinessLogic.MailWorker; +using CarpentryWorkshopContracts.BindingModels; using CarpentryWorkshopContracts.BusinessLogicsContracts; using CarpentryWorkshopContracts.StoragesContracts; using CarpentryWorkshopDatabaseImplement.Implements; +using CarpentryWorkshopBusinessLogic.BusinessLogics; +using CarpentryWorkshopBusinessLogic.MailWorker; +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using CarpentryWorkshopContracts.StoragesContracts; using Microsoft.OpenApi.Models; -using Microsoft.Extensions.Logging; var builder = WebApplication.CreateBuilder(args); + builder.Logging.SetMinimumLevel(LogLevel.Trace); + // Add services to the container. 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.AddTransient(); +builder.Services.AddTransient(); + +builder.Services.AddSingleton(); + builder.Services.AddControllers(); -// Learn more about configuring Swagger/OpenAPI at -https://aka.ms/aspnetcore/swashbuckle +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(c => { - c.SwaggerDoc("v1", new OpenApiInfo - { - Title = "CarpentryWorkshopRestApi", - Version - = "v1" - }); + c.SwaggerDoc("v1", new OpenApiInfo { Title = "CarpentryWorkshopRestApi", Version = "v1" }); }); + 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()) { - app.UseSwagger(); - app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", - "CarpentryWorkshopRestApi v1")); + app.UseSwagger(); + app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "CarpentryWorkshopRestApi v1")); } + app.UseHttpsRedirection(); + app.UseAuthorization(); + app.MapControllers(); -app.Run(); \ No newline at end of file + +app.Run(); diff --git a/CarpentryWorkshopRestApi/appsettings.json b/CarpentryWorkshopRestApi/appsettings.json index 10f68b8..4002d73 100644 --- a/CarpentryWorkshopRestApi/appsettings.json +++ b/CarpentryWorkshopRestApi/appsettings.json @@ -2,8 +2,16 @@ "Logging": { "LogLevel": { "Default": "Information", - "Microsoft.AspNetCore": "Warning" + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "asdqr647@gmail.com", + "MailPassword": "nzxwolohajhfqmoe" } diff --git a/CarpentryWorkshopView/App.config b/CarpentryWorkshopView/App.config new file mode 100644 index 0000000..3de0473 --- /dev/null +++ b/CarpentryWorkshopView/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/CarpentryWorkshopView/FormMail.Designer.cs b/CarpentryWorkshopView/FormMail.Designer.cs new file mode 100644 index 0000000..3ad9cd5 --- /dev/null +++ b/CarpentryWorkshopView/FormMail.Designer.cs @@ -0,0 +1,60 @@ +namespace CarpentryWorkshopView +{ + partial class FormMail + { + /// + /// 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.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(3, 3); + dataGridView.Name = "dataGridView"; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(794, 445); + dataGridView.TabIndex = 0; + // + // FormMail + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(dataGridView); + Name = "FormMail"; + Text = "Эл. письма"; + Load += FormMail_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/CarpentryWorkshopView/FormMail.cs b/CarpentryWorkshopView/FormMail.cs new file mode 100644 index 0000000..29ed5dd --- /dev/null +++ b/CarpentryWorkshopView/FormMail.cs @@ -0,0 +1,56 @@ +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace CarpentryWorkshopView +{ + public partial class FormMail : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + + public FormMail(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + LoadData(); + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + + private void FormMail_Load(object sender, EventArgs e) + { + LoadData(); + } + + } +} diff --git a/CarpentryWorkshopView/FormMail.resx b/CarpentryWorkshopView/FormMail.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/CarpentryWorkshopView/FormMail.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/CarpentryWorkshopView/FormMain.Designer.cs b/CarpentryWorkshopView/FormMain.Designer.cs index 70dd8f3..483f515 100644 --- a/CarpentryWorkshopView/FormMain.Designer.cs +++ b/CarpentryWorkshopView/FormMain.Designer.cs @@ -45,13 +45,14 @@ ButtonOrderReady = new Button(); ButtonIssuedOrder = new Button(); ButtonRef = new Button(); + письмаToolStripMenuItem = new ToolStripMenuItem(); menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); // // menuStrip1 // - menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, клиентыToolStripMenuItem, запускРаботToolStripMenuItem, исполнителиToolStripMenuItem }); + menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, клиентыToolStripMenuItem, запускРаботToolStripMenuItem, исполнителиToolStripMenuItem, письмаToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; menuStrip1.Size = new Size(1051, 24); @@ -190,6 +191,13 @@ ButtonRef.UseVisualStyleBackColor = true; ButtonRef.Click += ButtonRef_Click; // + // письмаToolStripMenuItem + // + письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; + письмаToolStripMenuItem.Size = new Size(62, 20); + письмаToolStripMenuItem.Text = "Письма"; + письмаToolStripMenuItem.Click += письмаToolStripMenuItem_Click; + // // FormMain // AutoScaleDimensions = new SizeF(7F, 15F); @@ -231,5 +239,6 @@ private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripMenuItem письмаToolStripMenuItem; } } \ No newline at end of file diff --git a/CarpentryWorkshopView/FormMain.cs b/CarpentryWorkshopView/FormMain.cs index f0ecb19..fbd304f 100644 --- a/CarpentryWorkshopView/FormMain.cs +++ b/CarpentryWorkshopView/FormMain.cs @@ -201,5 +201,14 @@ namespace CarpentryWorkshopView form.ShowDialog(); } } + + private void письмаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMail)); + if (service is FormMail form) + { + form.ShowDialog(); + } + } } } diff --git a/CarpentryWorkshopView/Program.cs b/CarpentryWorkshopView/Program.cs index 5e2f82b..dc9a41e 100644 --- a/CarpentryWorkshopView/Program.cs +++ b/CarpentryWorkshopView/Program.cs @@ -7,64 +7,91 @@ using CarpentryWorkshopDatabaseImplement.Implements; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; +using CarpentryWorkshopBusinessLogic.MailWorker; +using CarpentryWorkshopContracts.BindingModels; namespace CarpentryWorkshopView { - internal static class Program - { - private static ServiceProvider? _serviceProvider; - public static ServiceProvider? ServiceProvider => _serviceProvider; - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. - ApplicationConfiguration.Initialize(); - var services = new ServiceCollection(); - ConfigureServices(services); - _serviceProvider = services.BuildServiceProvider(); - Application.Run(_serviceProvider.GetRequiredService()); - } - private static void ConfigureServices(ServiceCollection services) - { - services.AddLogging(option => - { - option.SetMinimumLevel(LogLevel.Information); - option.AddNLog("nlog.config"); - }); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + internal static class Program + { + private static ServiceProvider? _serviceProvider; + public static ServiceProvider? ServiceProvider => _serviceProvider; + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + 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, "Error"); + } + Application.Run(_serviceProvider.GetRequiredService()); + } + private static void ConfigureServices(ServiceCollection services) + { + services.AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); + services.AddSingleton(); services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + services.AddTransient(); + services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } - } + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + } } \ No newline at end of file