From 1316bf3c5f96d995c7bb83b01fd3759729e9bf32 Mon Sep 17 00:00:00 2001 From: shoot Date: Sat, 22 Jun 2024 22:30:26 +0400 Subject: [PATCH] Pibd22_NikiforovaMV_lab7 --- AutomobilePlant/App.config | 11 + AutomobilePlant/FormMails.Designer.cs | 62 ++++ AutomobilePlant/FormMails.cs | 49 +++ AutomobilePlant/FormMails.resx | 120 +++++++ AutomobilePlant/FormMain.Designer.cs | 14 +- AutomobilePlant/FormMain.cs | 12 +- AutomobilePlant/Program.cs | 46 ++- .../AutomobilePlantBusinessLogic.csproj | 1 + .../BusinessLogics/ClientLogic.cs | 13 +- .../BusinessLogics/MessageInfoLogic.cs | 48 +++ .../BusinessLogics/OrderLogic.cs | 65 ++-- .../MailWorker/AbstractMailWorker.cs | 82 +++++ .../MailWorker/MailKitWorker.cs | 79 +++++ .../AutomobilePlantClientApp.csproj | 7 + .../Controllers/HomeController.cs | 11 +- .../Views/Home/Mails.cshtml | 54 ++++ .../Views/Shared/_Layout.cshtml | 5 +- .../BindingModels/MailConfigBindingModel.cs | 18 ++ .../BindingModels/MailSendInfoBindingModel.cs | 15 + .../BindingModels/MessageInfoBindingModel.cs | 24 ++ .../IMessageInfoLogic.cs | 17 + .../SearchModels/MessageInfoSearchModel.cs | 14 + .../StorageContracts/IMessageInfoStorage.cs | 19 ++ .../ViewModels/MessageInfoViewModel.cs | 25 ++ .../Models/IMessageInfoModel.cs | 18 ++ .../AutomobilePlantDatabase.cs | 5 +- .../AutomobilePlantDatabaseImplement.csproj | 4 + .../Implements/MessageInfoStorage.cs | 57 ++++ .../20240621185857_init.Designer.cs | 298 ++++++++++++++++++ .../Migrations/20240621185857_init.cs | 214 +++++++++++++ .../AutomobilePlantDatabaseModelSnapshot.cs | 41 +++ .../Models/Client.cs | 4 +- .../Models/MessageInfo.cs | 57 ++++ .../DataFileSingleton.cs | 12 +- .../Implements/MessageInfoStorage.cs | 58 ++++ .../Models/MessageInfo.cs | 80 +++++ .../DataListSingleton.cs | 6 +- .../Implements/MessageInfoStorage.cs | 65 ++++ .../Models/MessageInfo.cs | 53 ++++ .../Controllers/ClientController.cs | 28 +- AutomobilePlantRestApi/Program.cs | 17 + AutomobilePlantRestApi/appsettings.json | 9 +- 42 files changed, 1784 insertions(+), 53 deletions(-) create mode 100644 AutomobilePlant/App.config create mode 100644 AutomobilePlant/FormMails.Designer.cs create mode 100644 AutomobilePlant/FormMails.cs create mode 100644 AutomobilePlant/FormMails.resx create mode 100644 AutomobilePlantBusinessLogic/BusinessLogics/MessageInfoLogic.cs create mode 100644 AutomobilePlantBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 AutomobilePlantBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 AutomobilePlantClientApp/Views/Home/Mails.cshtml create mode 100644 AutomobilePlantContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 AutomobilePlantContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 AutomobilePlantContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 AutomobilePlantContracts/BusinessLogicContracts/IMessageInfoLogic.cs create mode 100644 AutomobilePlantContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 AutomobilePlantContracts/StorageContracts/IMessageInfoStorage.cs create mode 100644 AutomobilePlantContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 AutomobilePlantDataModels/Models/IMessageInfoModel.cs create mode 100644 AutomobilePlantDatabaseImplement/Implements/MessageInfoStorage.cs create mode 100644 AutomobilePlantDatabaseImplement/Migrations/20240621185857_init.Designer.cs create mode 100644 AutomobilePlantDatabaseImplement/Migrations/20240621185857_init.cs create mode 100644 AutomobilePlantDatabaseImplement/Models/MessageInfo.cs create mode 100644 AutomobilePlantFileImplement/Implements/MessageInfoStorage.cs create mode 100644 AutomobilePlantFileImplement/Models/MessageInfo.cs create mode 100644 AutomobilePlantListImplements/Implements/MessageInfoStorage.cs create mode 100644 AutomobilePlantListImplements/Models/MessageInfo.cs diff --git a/AutomobilePlant/App.config b/AutomobilePlant/App.config new file mode 100644 index 0000000..88436a6 --- /dev/null +++ b/AutomobilePlant/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/AutomobilePlant/FormMails.Designer.cs b/AutomobilePlant/FormMails.Designer.cs new file mode 100644 index 0000000..e78444a --- /dev/null +++ b/AutomobilePlant/FormMails.Designer.cs @@ -0,0 +1,62 @@ +namespace AutomobilePlant +{ + 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.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 12); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(776, 426); + dataGridView.TabIndex = 0; + // + // FormMails + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(dataGridView); + Name = "FormMails"; + Text = "Письма"; + Load += FormMails_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/AutomobilePlant/FormMails.cs b/AutomobilePlant/FormMails.cs new file mode 100644 index 0000000..e9c6469 --- /dev/null +++ b/AutomobilePlant/FormMails.cs @@ -0,0 +1,49 @@ +using AutomobilePlantContracts.BusinessLogicContracts; +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 AutomobilePlant +{ + 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) + { + 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); + } + } + } +} diff --git a/AutomobilePlant/FormMails.resx b/AutomobilePlant/FormMails.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/AutomobilePlant/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/AutomobilePlant/FormMain.Designer.cs b/AutomobilePlant/FormMain.Designer.cs index 038e381..49f6cb8 100644 --- a/AutomobilePlant/FormMain.Designer.cs +++ b/AutomobilePlant/FormMain.Designer.cs @@ -43,6 +43,7 @@ this.buttonCreateOrder = new System.Windows.Forms.Button(); this.buttonSetToFinish = new System.Windows.Forms.Button(); this.buttonUpdate = new System.Windows.Forms.Button(); + письмаToolStripMenuItem = new ToolStripMenuItem(); this.menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); this.SuspendLayout(); @@ -66,7 +67,8 @@ this.компонентыToolStripMenuItem, this.автомобилиToolStripMenuItem, this.клиентыToolStripMenuItem, - this.исполнителиToolStripMenuItem}); + this.исполнителиToolStripMenuItem, + this.письмаToolStripMenuItem}); this.справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; this.справочникиToolStripMenuItem.Size = new System.Drawing.Size(117, 24); this.справочникиToolStripMenuItem.Text = "Справочники"; @@ -137,6 +139,13 @@ this.запускРаботToolStripMenuItem.Text = "Запуск работ"; this.запускРаботToolStripMenuItem.Click += new System.EventHandler(this.запускРаботToolStripMenuItem_Click); // + // письмаToolStripMenuItem + // + письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; + письмаToolStripMenuItem.Size = new Size(224, 26); + письмаToolStripMenuItem.Text = "Письма"; + письмаToolStripMenuItem.Click += письмаToolStripMenuItem_Click; + // // dataGridView // this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; @@ -216,5 +225,6 @@ private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; - } + private ToolStripMenuItem письмаToolStripMenuItem; + } } \ No newline at end of file diff --git a/AutomobilePlant/FormMain.cs b/AutomobilePlant/FormMain.cs index 9dcd31e..38def58 100644 --- a/AutomobilePlant/FormMain.cs +++ b/AutomobilePlant/FormMain.cs @@ -172,7 +172,15 @@ namespace AutomobilePlant { _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } + + private void письмаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + } + } + } } diff --git a/AutomobilePlant/Program.cs b/AutomobilePlant/Program.cs index 25492f3..13d1471 100644 --- a/AutomobilePlant/Program.cs +++ b/AutomobilePlant/Program.cs @@ -1,6 +1,8 @@ using AutomobilePlantBusinessLogic.BusinessLogics; +using AutomobilePlantBusinessLogic.MailWorker; using AutomobilePlantBusinessLogic.OfficePackage; using AutomobilePlantBusinessLogic.OfficePackage.Implements; +using AutomobilePlantContracts.BindingModels; using AutomobilePlantContracts.BusinessLogicContracts; using AutomobilePlantContracts.StorageContracts; using AutomobilePlantDatabaseImplement.Implements; @@ -23,10 +25,33 @@ namespace AutomobilePlant ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); - Application.Run(_serviceProvider.GetRequiredService()); - } - private static void ConfigureServices(ServiceCollection services) - { + 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 => { option.SetMinimumLevel(LogLevel.Information); @@ -37,20 +62,24 @@ namespace AutomobilePlant 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.AddSingleton(); + + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -62,6 +91,7 @@ namespace AutomobilePlant services.AddTransient(); services.AddTransient(); services.AddTransient(); - } + services.AddTransient(); + } } } \ No newline at end of file diff --git a/AutomobilePlantBusinessLogic/AutomobilePlantBusinessLogic.csproj b/AutomobilePlantBusinessLogic/AutomobilePlantBusinessLogic.csproj index ba389e3..7dbb2f4 100644 --- a/AutomobilePlantBusinessLogic/AutomobilePlantBusinessLogic.csproj +++ b/AutomobilePlantBusinessLogic/AutomobilePlantBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/AutomobilePlantBusinessLogic/BusinessLogics/ClientLogic.cs b/AutomobilePlantBusinessLogic/BusinessLogics/ClientLogic.cs index d7b2693..f2a78b4 100644 --- a/AutomobilePlantBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/AutomobilePlantBusinessLogic/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 AutomobilePlantBusinessLogic.BusinessLogics @@ -103,8 +104,16 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics { throw new ArgumentNullException("Нет логина(почты) клиента", nameof(model.Email)); } - _logger.LogInformation("Client. Id: {Id}, FIO: {fio}, email: {email}", model.Id, model.ClientFIO, model.Email); - var element = _clientStorage.GetElement(new ClientSearchModel + if (!Regex.IsMatch(model.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")) + { + throw new ArgumentException("Некорретно введен email клиента", nameof(model.Email)); + } + if (!Regex.IsMatch(model.Password, @"^(?=.*\d)(?=.*\W)(?=.*[^\d\s]).+$")) + { + throw new ArgumentException("Некорректно введен пароль клиента", nameof(model.Password)); + } + _logger.LogInformation("Client. Id: {Id}, FIO: {fio}, email: {email}", model.Id, model.ClientFIO, model.Email); + var element = _clientStorage.GetElement(new ClientSearchModel { Email = model.Email, }); diff --git a/AutomobilePlantBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/AutomobilePlantBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..2f2c6c4 --- /dev/null +++ b/AutomobilePlantBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,48 @@ +using AutomobilePlantContracts.BindingModels; +using AutomobilePlantContracts.BusinessLogicContracts; +using AutomobilePlantContracts.SearchModels; +using AutomobilePlantContracts.StorageContracts; +using AutomobilePlantContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutomobilePlantBusinessLogic.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) + { + 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; + } + } +} diff --git a/AutomobilePlantBusinessLogic/BusinessLogics/OrderLogic.cs b/AutomobilePlantBusinessLogic/BusinessLogics/OrderLogic.cs index 6eae62d..e4ab5c8 100644 --- a/AutomobilePlantBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/AutomobilePlantBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,10 +1,10 @@ -using AutomobilePlantContracts.BindingModels; +using AutomobilePlantBusinessLogic.MailWorker; +using AutomobilePlantContracts.BindingModels; using AutomobilePlantContracts.BusinessLogicContracts; using AutomobilePlantContracts.SearchModels; using AutomobilePlantContracts.StorageContracts; using AutomobilePlantContracts.ViewModels; using AutomobilePlantDataModels.Enums; -using DocumentFormat.OpenXml.EMMA; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -18,14 +18,16 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; - static readonly object locker = new(); - - 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) { @@ -36,14 +38,16 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics return false; } model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) - { + var result = _orderStorage.Insert(model); + if (result == null) + { model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } - return true; - } + SendOrderStatusMail(result.ClientId, $"Новый заказ создан. Номер заказа #{result.Id}", $"Заказ #{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); + return true; + } public bool StatusUpdate(OrderBindingModel rawModel, OrderStatus newStatus) { @@ -83,24 +87,23 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics } model.Status = newStatus; if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; - if (_orderStorage.Update(model) == null) - { + var result = _orderStorage.Update(model); + if (result == null) + { model.Status--; _logger.LogWarning("Update operation failed"); return false; } - return true; - } + SendOrderStatusMail(result.ClientId, $"Изменен статус заказа #{result.Id}", $"Заказ #{result.Id} изменен статус на {result.Status}"); + return true; + } public bool TakeOrderInWork(OrderBindingModel model) { - lock (locker) - { - return StatusUpdate(model, OrderStatus.Выполняется); - } + return StatusUpdate(model, OrderStatus.Выполняется); } - - public bool DeliveryOrder(OrderBindingModel model) + + public bool DeliveryOrder(OrderBindingModel model) { return StatusUpdate(model, OrderStatus.Готов); } @@ -140,8 +143,24 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics return element; } - private void CheckModel(OrderBindingModel model, bool withParams = true) - { + private bool SendOrderStatusMail(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; + } + + private void CheckModel(OrderBindingModel model, bool withParams = true) + { if (model == null) { throw new ArgumentNullException(nameof(model)); diff --git a/AutomobilePlantBusinessLogic/MailWorker/AbstractMailWorker.cs b/AutomobilePlantBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..3f2ba39 --- /dev/null +++ b/AutomobilePlantBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,82 @@ +using AutomobilePlantContracts.BindingModels; +using AutomobilePlantContracts.BusinessLogicContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutomobilePlantBusinessLogic.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/AutomobilePlantBusinessLogic/MailWorker/MailKitWorker.cs b/AutomobilePlantBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..89b8388 --- /dev/null +++ b/AutomobilePlantBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,79 @@ +using AutomobilePlantContracts.BindingModels; +using AutomobilePlantContracts.BusinessLogicContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Mail; +using System.Net; +using System.Text; +using System.Threading.Tasks; +using MailKit.Net.Pop3; +using MailKit.Security; + +namespace AutomobilePlantBusinessLogic.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/AutomobilePlantClientApp/AutomobilePlantClientApp.csproj b/AutomobilePlantClientApp/AutomobilePlantClientApp.csproj index 249ff01..77e955c 100644 --- a/AutomobilePlantClientApp/AutomobilePlantClientApp.csproj +++ b/AutomobilePlantClientApp/AutomobilePlantClientApp.csproj @@ -14,4 +14,11 @@ + + + true + PreserveNewest + + + diff --git a/AutomobilePlantClientApp/Controllers/HomeController.cs b/AutomobilePlantClientApp/Controllers/HomeController.cs index 6e9142a..b74a194 100644 --- a/AutomobilePlantClientApp/Controllers/HomeController.cs +++ b/AutomobilePlantClientApp/Controllers/HomeController.cs @@ -135,5 +135,14 @@ namespace AutomobilePlantClientApp.Controllers return count * (c?.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/AutomobilePlantClientApp/Views/Home/Mails.cshtml b/AutomobilePlantClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..efc88cf --- /dev/null +++ b/AutomobilePlantClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using AutomobilePlantContracts.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/AutomobilePlantClientApp/Views/Shared/_Layout.cshtml b/AutomobilePlantClientApp/Views/Shared/_Layout.cshtml index 52aec19..3333c49 100644 --- a/AutomobilePlantClientApp/Views/Shared/_Layout.cshtml +++ b/AutomobilePlantClientApp/Views/Shared/_Layout.cshtml @@ -27,6 +27,9 @@ + @@ -45,7 +48,7 @@ diff --git a/AutomobilePlantContracts/BindingModels/MailConfigBindingModel.cs b/AutomobilePlantContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..99fa433 --- /dev/null +++ b/AutomobilePlantContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutomobilePlantContracts.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/AutomobilePlantContracts/BindingModels/MailSendInfoBindingModel.cs b/AutomobilePlantContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..b87ffaf --- /dev/null +++ b/AutomobilePlantContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutomobilePlantContracts.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/AutomobilePlantContracts/BindingModels/MessageInfoBindingModel.cs b/AutomobilePlantContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..a91bbb1 --- /dev/null +++ b/AutomobilePlantContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,24 @@ +using AutomobilePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutomobilePlantContracts.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/AutomobilePlantContracts/BusinessLogicContracts/IMessageInfoLogic.cs b/AutomobilePlantContracts/BusinessLogicContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..e2aef60 --- /dev/null +++ b/AutomobilePlantContracts/BusinessLogicContracts/IMessageInfoLogic.cs @@ -0,0 +1,17 @@ +using AutomobilePlantContracts.BindingModels; +using AutomobilePlantContracts.SearchModels; +using AutomobilePlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutomobilePlantContracts.BusinessLogicContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + bool Create(MessageInfoBindingModel model); + } +} diff --git a/AutomobilePlantContracts/SearchModels/MessageInfoSearchModel.cs b/AutomobilePlantContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..1c127a9 --- /dev/null +++ b/AutomobilePlantContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutomobilePlantContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + public string? MessageId { get; set; } + } +} diff --git a/AutomobilePlantContracts/StorageContracts/IMessageInfoStorage.cs b/AutomobilePlantContracts/StorageContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..dae6334 --- /dev/null +++ b/AutomobilePlantContracts/StorageContracts/IMessageInfoStorage.cs @@ -0,0 +1,19 @@ +using AutomobilePlantContracts.BindingModels; +using AutomobilePlantContracts.SearchModels; +using AutomobilePlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutomobilePlantContracts.StorageContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + List GetFilteredList(MessageInfoSearchModel model); + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/AutomobilePlantContracts/ViewModels/MessageInfoViewModel.cs b/AutomobilePlantContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..c48ca49 --- /dev/null +++ b/AutomobilePlantContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,25 @@ +using AutomobilePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutomobilePlantContracts.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/AutomobilePlantDataModels/Models/IMessageInfoModel.cs b/AutomobilePlantDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..25644a3 --- /dev/null +++ b/AutomobilePlantDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutomobilePlantDataModels.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/AutomobilePlantDatabaseImplement/AutomobilePlantDatabase.cs b/AutomobilePlantDatabaseImplement/AutomobilePlantDatabase.cs index d849bab..3df895b 100644 --- a/AutomobilePlantDatabaseImplement/AutomobilePlantDatabase.cs +++ b/AutomobilePlantDatabaseImplement/AutomobilePlantDatabase.cs @@ -16,7 +16,7 @@ namespace AutomobilePlantDatabaseImplement { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-50UQ1O1\MSSQLSERVER01;Initial Catalog=RenovationWorkDatabase3;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); + optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-50UQ1O1\MSSQLSERVER01;Initial Catalog=AutomobileWorkDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); } base.OnConfiguring(optionsBuilder); } @@ -26,5 +26,6 @@ namespace AutomobilePlantDatabaseImplement 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/AutomobilePlantDatabaseImplement/AutomobilePlantDatabaseImplement.csproj b/AutomobilePlantDatabaseImplement/AutomobilePlantDatabaseImplement.csproj index 35acf42..869eafc 100644 --- a/AutomobilePlantDatabaseImplement/AutomobilePlantDatabaseImplement.csproj +++ b/AutomobilePlantDatabaseImplement/AutomobilePlantDatabaseImplement.csproj @@ -20,4 +20,8 @@ + + + + diff --git a/AutomobilePlantDatabaseImplement/Implements/MessageInfoStorage.cs b/AutomobilePlantDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..a21ffdc --- /dev/null +++ b/AutomobilePlantDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,57 @@ +using AutomobilePlantContracts.BindingModels; +using AutomobilePlantContracts.SearchModels; +using AutomobilePlantContracts.StorageContracts; +using AutomobilePlantContracts.ViewModels; +using AutomobilePlantDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutomobilePlantDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + using var context = new AutomobilePlantDatabase(); + 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 AutomobilePlantDatabase(); + return context.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + using var context = new AutomobilePlantDatabase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + using var context = new AutomobilePlantDatabase(); + 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/AutomobilePlantDatabaseImplement/Migrations/20240621185857_init.Designer.cs b/AutomobilePlantDatabaseImplement/Migrations/20240621185857_init.Designer.cs new file mode 100644 index 0000000..e756daf --- /dev/null +++ b/AutomobilePlantDatabaseImplement/Migrations/20240621185857_init.Designer.cs @@ -0,0 +1,298 @@ +// +using System; +using AutomobilePlantDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace AutomobilePlantDatabaseImplement.Migrations +{ + [DbContext(typeof(AutomobilePlantDatabase))] + [Migration("20240621185857_init")] + partial class init + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("AutomobilePlantDatabaseImplement.Models.Car", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CarName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Cars"); + }); + + modelBuilder.Entity("AutomobilePlantDatabaseImplement.Models.CarComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CarId") + .HasColumnType("int"); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("CarId"); + + b.HasIndex("ComponentId"); + + b.ToTable("CarComponents"); + }); + + modelBuilder.Entity("AutomobilePlantDatabaseImplement.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("AutomobilePlantDatabaseImplement.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("AutomobilePlantDatabaseImplement.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("AutomobilePlantDatabaseImplement.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("AutomobilePlantDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CarId") + .HasColumnType("int"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("CarId"); + + b.HasIndex("ClientId"); + + b.HasIndex("ImplementerId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("AutomobilePlantDatabaseImplement.Models.CarComponent", b => + { + b.HasOne("AutomobilePlantDatabaseImplement.Models.Car", "Car") + .WithMany("Components") + .HasForeignKey("CarId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AutomobilePlantDatabaseImplement.Models.Component", "Component") + .WithMany("CarComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Car"); + + b.Navigation("Component"); + }); + + modelBuilder.Entity("AutomobilePlantDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("AutomobilePlantDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("AutomobilePlantDatabaseImplement.Models.Order", b => + { + b.HasOne("AutomobilePlantDatabaseImplement.Models.Car", "Car") + .WithMany("Orders") + .HasForeignKey("CarId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AutomobilePlantDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AutomobilePlantDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.Navigation("Car"); + + b.Navigation("Client"); + + b.Navigation("Implementer"); + }); + + modelBuilder.Entity("AutomobilePlantDatabaseImplement.Models.Car", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("AutomobilePlantDatabaseImplement.Models.Client", b => + { + b.Navigation("Messages"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("AutomobilePlantDatabaseImplement.Models.Component", b => + { + b.Navigation("CarComponents"); + }); + + modelBuilder.Entity("AutomobilePlantDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/AutomobilePlantDatabaseImplement/Migrations/20240621185857_init.cs b/AutomobilePlantDatabaseImplement/Migrations/20240621185857_init.cs new file mode 100644 index 0000000..14e5f00 --- /dev/null +++ b/AutomobilePlantDatabaseImplement/Migrations/20240621185857_init.cs @@ -0,0 +1,214 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace AutomobilePlantDatabaseImplement.Migrations +{ + /// + public partial class init : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Cars", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + CarName = table.Column(type: "nvarchar(max)", nullable: false), + Price = table.Column(type: "float", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Cars", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Clients", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ClientFIO = table.Column(type: "nvarchar(max)", nullable: false), + Email = table.Column(type: "nvarchar(max)", nullable: false), + Password = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Clients", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Components", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ComponentName = table.Column(type: "nvarchar(max)", nullable: false), + Cost = table.Column(type: "float", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Components", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Implementers", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ImplementerFIO = table.Column(type: "nvarchar(max)", nullable: false), + Password = table.Column(type: "nvarchar(max)", nullable: false), + WorkExperience = table.Column(type: "int", nullable: false), + Qualification = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Implementers", x => x.Id); + }); + + 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.CreateTable( + name: "CarComponents", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + CarId = table.Column(type: "int", nullable: false), + ComponentId = table.Column(type: "int", nullable: false), + Count = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_CarComponents", x => x.Id); + table.ForeignKey( + name: "FK_CarComponents_Cars_CarId", + column: x => x.CarId, + principalTable: "Cars", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_CarComponents_Components_ComponentId", + column: x => x.ComponentId, + principalTable: "Components", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Orders", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + CarId = table.Column(type: "int", nullable: false), + ClientId = table.Column(type: "int", nullable: false), + ImplementerId = table.Column(type: "int", nullable: true), + Count = table.Column(type: "int", nullable: false), + Sum = table.Column(type: "float", nullable: false), + Status = table.Column(type: "int", nullable: false), + DateCreate = table.Column(type: "datetime2", nullable: false), + DateImplement = table.Column(type: "datetime2", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Orders", x => x.Id); + table.ForeignKey( + name: "FK_Orders_Cars_CarId", + column: x => x.CarId, + principalTable: "Cars", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Orders_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Orders_Implementers_ImplementerId", + column: x => x.ImplementerId, + principalTable: "Implementers", + principalColumn: "Id"); + }); + + migrationBuilder.CreateIndex( + name: "IX_CarComponents_CarId", + table: "CarComponents", + column: "CarId"); + + migrationBuilder.CreateIndex( + name: "IX_CarComponents_ComponentId", + table: "CarComponents", + column: "ComponentId"); + + migrationBuilder.CreateIndex( + name: "IX_Messages_ClientId", + table: "Messages", + column: "ClientId"); + + migrationBuilder.CreateIndex( + name: "IX_Orders_CarId", + table: "Orders", + column: "CarId"); + + migrationBuilder.CreateIndex( + name: "IX_Orders_ClientId", + table: "Orders", + column: "ClientId"); + + migrationBuilder.CreateIndex( + name: "IX_Orders_ImplementerId", + table: "Orders", + column: "ImplementerId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "CarComponents"); + + migrationBuilder.DropTable( + name: "Messages"); + + migrationBuilder.DropTable( + name: "Orders"); + + migrationBuilder.DropTable( + name: "Components"); + + migrationBuilder.DropTable( + name: "Cars"); + + migrationBuilder.DropTable( + name: "Clients"); + + migrationBuilder.DropTable( + name: "Implementers"); + } + } +} diff --git a/AutomobilePlantDatabaseImplement/Migrations/AutomobilePlantDatabaseModelSnapshot.cs b/AutomobilePlantDatabaseImplement/Migrations/AutomobilePlantDatabaseModelSnapshot.cs index 62892a7..c139b29 100644 --- a/AutomobilePlantDatabaseImplement/Migrations/AutomobilePlantDatabaseModelSnapshot.cs +++ b/AutomobilePlantDatabaseImplement/Migrations/AutomobilePlantDatabaseModelSnapshot.cs @@ -140,6 +140,36 @@ namespace AutomobilePlantDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("AutomobilePlantDatabaseImplement.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("AutomobilePlantDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -202,6 +232,15 @@ namespace AutomobilePlantDatabaseImplement.Migrations b.Navigation("Component"); }); + modelBuilder.Entity("AutomobilePlantDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("AutomobilePlantDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("AutomobilePlantDatabaseImplement.Models.Order", b => { b.HasOne("AutomobilePlantDatabaseImplement.Models.Car", "Car") @@ -236,6 +275,8 @@ namespace AutomobilePlantDatabaseImplement.Migrations modelBuilder.Entity("AutomobilePlantDatabaseImplement.Models.Client", b => { + b.Navigation("Messages"); + b.Navigation("Orders"); }); diff --git a/AutomobilePlantDatabaseImplement/Models/Client.cs b/AutomobilePlantDatabaseImplement/Models/Client.cs index b2f5b14..8078b9b 100644 --- a/AutomobilePlantDatabaseImplement/Models/Client.cs +++ b/AutomobilePlantDatabaseImplement/Models/Client.cs @@ -26,8 +26,10 @@ namespace AutomobilePlantDatabaseImplement.Models [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); + [ForeignKey("ClientId")] + public virtual List Messages { get; set; } = new(); - public static Client? Create(ClientBindingModel model) + public static Client? Create(ClientBindingModel model) { if (model == null) { diff --git a/AutomobilePlantDatabaseImplement/Models/MessageInfo.cs b/AutomobilePlantDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..4643729 --- /dev/null +++ b/AutomobilePlantDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,57 @@ +using AutomobilePlantContracts.BindingModels; +using AutomobilePlantContracts.ViewModels; +using AutomobilePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutomobilePlantDatabaseImplement.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/AutomobilePlantFileImplement/DataFileSingleton.cs b/AutomobilePlantFileImplement/DataFileSingleton.cs index d32c775..e6117c1 100644 --- a/AutomobilePlantFileImplement/DataFileSingleton.cs +++ b/AutomobilePlantFileImplement/DataFileSingleton.cs @@ -18,12 +18,14 @@ namespace AutomobilePlantFileImplement private readonly string CarFileName = "Car.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; - public List Components { get; private set; } + private readonly string MessageInfoFileName = "MessageInfo.xml"; + public List Components { get; private set; } public List Orders { get; private set; } public List Cars { get; private set; } public List Clients { get; private set; } public List Implementers { get; private set; } - public static DataFileSingleton GetInstance() + public List Messages { get; private set; } + public static DataFileSingleton GetInstance() { if (instance == null) { @@ -36,14 +38,16 @@ namespace AutomobilePlantFileImplement public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); public void SaveImplementers() => SaveData(Orders, ImplementerFileName, "Implementers", x => x.GetXElement); - private DataFileSingleton() + public void SaveMessages() => SaveData(Orders, ImplementerFileName, "Messages", x => x.GetXElement); + private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Cars = LoadData(CarFileName, "Car", x => Car.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Impleneter", x => Implementer.Create(x)!)!; - } + Messages = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!; + } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { if (File.Exists(filename)) diff --git a/AutomobilePlantFileImplement/Implements/MessageInfoStorage.cs b/AutomobilePlantFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..3420ae3 --- /dev/null +++ b/AutomobilePlantFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,58 @@ +using AutomobilePlantContracts.BindingModels; +using AutomobilePlantContracts.SearchModels; +using AutomobilePlantContracts.StorageContracts; +using AutomobilePlantContracts.ViewModels; +using AutomobilePlantFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutomobilePlantFileImplement.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/AutomobilePlantFileImplement/Models/MessageInfo.cs b/AutomobilePlantFileImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..ac76fd9 --- /dev/null +++ b/AutomobilePlantFileImplement/Models/MessageInfo.cs @@ -0,0 +1,80 @@ +using AutomobilePlantContracts.BindingModels; +using AutomobilePlantContracts.ViewModels; +using AutomobilePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace AutomobilePlantFileImplement.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/AutomobilePlantListImplements/DataListSingleton.cs b/AutomobilePlantListImplements/DataListSingleton.cs index 6bfd6a5..7d4b7b1 100644 --- a/AutomobilePlantListImplements/DataListSingleton.cs +++ b/AutomobilePlantListImplements/DataListSingleton.cs @@ -10,14 +10,16 @@ namespace AutomobilePlantListImplements public List Cars { get; set; } public List Clients { get; set; } public List Implementers { get; set; } - private DataListSingleton() + public List Messages { get; set; } + private DataListSingleton() { Components = new List(); Orders = new List(); Cars = new List(); Clients = new List(); Implementers = new List(); - } + Messages = new List(); + } public static DataListSingleton GetInstance() { if (_instance == null) diff --git a/AutomobilePlantListImplements/Implements/MessageInfoStorage.cs b/AutomobilePlantListImplements/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..21ede2c --- /dev/null +++ b/AutomobilePlantListImplements/Implements/MessageInfoStorage.cs @@ -0,0 +1,65 @@ +using AutomobilePlantContracts.BindingModels; +using AutomobilePlantContracts.SearchModels; +using AutomobilePlantContracts.StorageContracts; +using AutomobilePlantContracts.ViewModels; +using AutomobilePlantListImplements.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutomobilePlantListImplements.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/AutomobilePlantListImplements/Models/MessageInfo.cs b/AutomobilePlantListImplements/Models/MessageInfo.cs new file mode 100644 index 0000000..1361408 --- /dev/null +++ b/AutomobilePlantListImplements/Models/MessageInfo.cs @@ -0,0 +1,53 @@ +using AutomobilePlantContracts.BindingModels; +using AutomobilePlantContracts.ViewModels; +using AutomobilePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutomobilePlantListImplements.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/AutomobilePlantRestApi/Controllers/ClientController.cs b/AutomobilePlantRestApi/Controllers/ClientController.cs index ffb3b4a..ade06bc 100644 --- a/AutomobilePlantRestApi/Controllers/ClientController.cs +++ b/AutomobilePlantRestApi/Controllers/ClientController.cs @@ -12,11 +12,14 @@ namespace AutomobilePlantRestApi.Controllers { private readonly ILogger _logger; private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger logger) - { + private readonly IMessageInfoLogic _mailLogic; + + public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger logger) + { _logger = logger; _logic = logic; - } + _mailLogic = mailLogic; + } [HttpGet] public ClientViewModel? Login(string login, string password) { @@ -60,5 +63,22 @@ namespace AutomobilePlantRestApi.Controllers 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/AutomobilePlantRestApi/Program.cs b/AutomobilePlantRestApi/Program.cs index 819d016..0fa9496 100644 --- a/AutomobilePlantRestApi/Program.cs +++ b/AutomobilePlantRestApi/Program.cs @@ -1,4 +1,6 @@ using AutomobilePlantBusinessLogic.BusinessLogics; +using AutomobilePlantBusinessLogic.MailWorker; +using AutomobilePlantContracts.BindingModels; using AutomobilePlantContracts.BusinessLogicContracts; using AutomobilePlantContracts.StorageContracts; using AutomobilePlantDatabaseImplement.Implements; @@ -12,9 +14,13 @@ 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.AddSingleton(); +builder.Services.AddTransient(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle @@ -30,6 +36,17 @@ 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/AutomobilePlantRestApi/appsettings.json b/AutomobilePlantRestApi/appsettings.json index 10f68b8..d4b4d1e 100644 --- a/AutomobilePlantRestApi/appsettings.json +++ b/AutomobilePlantRestApi/appsettings.json @@ -5,5 +5,12 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "mailforlab8@gmail.com", + "MailPassword": "pvmu cnof aakc ckvd" }