From 41e37e2ba3883d266a3f2a0742c552065936b5fb Mon Sep 17 00:00:00 2001 From: Zakharov_Rostislav Date: Tue, 7 May 2024 17:51:22 +0400 Subject: [PATCH 01/13] lab-7 --- .../DataFileSingleton.cs | 6 + .../Implements/MessageInfoStorage.cs | 55 ++++++++ .../Models/MessageInfo.cs | 71 +++++++++++ .../BlacksmithWorkshop/App.config | 11 ++ .../BlacksmithWorkshop/FormMain.Designer.cs | 11 +- .../BlacksmithWorkshop/FormMain.cs | 8 ++ .../BlacksmithWorkshop/Program.cs | 40 +++++- .../ViewMailForm.Designer.cs | 62 +++++++++ .../BlacksmithWorkshop/ViewMailForm.cs | 47 +++++++ .../BlacksmithWorkshop/ViewMailForm.resx | 120 ++++++++++++++++++ .../BlacksmithWorkshopBusinessLogic.csproj | 1 + .../BusinessLogics/ClientLogic.cs | 9 ++ .../BusinessLogics/MessageInfoLogic.cs | 46 +++++++ .../BusinessLogics/OrderLogic.cs | 34 ++++- .../MailWorker/AbstractMailWorker.cs | 83 ++++++++++++ .../MailWorker/MailKitWorker.cs | 81 ++++++++++++ .../Controllers/HomeController.cs | 10 ++ .../Views/Home/Mails.cshtml | 49 +++++++ .../Views/Shared/_Layout.cshtml | 3 + .../BindingModels/MailConfigBindingModel.cs | 18 +++ .../BindingModels/MailSendInfoBindingModel.cs | 15 +++ .../BindingModels/MessageInfoBindingModel .cs | 19 +++ .../IMessageInfoLogic.cs | 17 +++ .../SearchModels/MessageInfoSearchModel.cs | 14 ++ .../StoragesContracts/IMessageInfoStorage.cs | 19 +++ .../ViewModels/MessageInfoViewModel.cs | 24 ++++ .../Models/IMessageInfoModel.cs | 18 +++ .../BlacksmithWorkshopDataBase.cs | 1 + .../Implements/MessageInfoStorage.cs | 53 ++++++++ .../Models/MessageInfo.cs | 50 ++++++++ .../DataListSingleton.cs | 2 + .../Implements/MessageInfoStorage.cs | 62 +++++++++ .../Models/MessageInfo.cs | 46 +++++++ .../Controllers/ClientController.cs | 23 +++- .../BlacksmithWorkshopRestApi/Program.cs | 27 +++- .../appsettings.json | 8 +- 36 files changed, 1151 insertions(+), 12 deletions(-) create mode 100644 BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Implements/MessageInfoStorage.cs create mode 100644 BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Models/MessageInfo.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshop/App.config create mode 100644 BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.Designer.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.resx create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Home/Mails.cshtml create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MessageInfoBindingModel .cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IMessageInfoModel.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/MessageInfoStorage.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/MessageInfo.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/MessageInfoStorage.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/MessageInfo.cs diff --git a/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/DataFileSingleton.cs b/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/DataFileSingleton.cs index 2df3458..b712b05 100644 --- a/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/DataFileSingleton.cs +++ b/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/DataFileSingleton.cs @@ -11,11 +11,13 @@ namespace BlackcmithWorkshopFileImplement private readonly string ManufactureFileName = "Manufacture.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageInfoFileName = "MessageInfo.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Manufactures { get; private set; } public List Clients { get; private set; } public List Implementers { get; private set; } + public List Messages { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -34,6 +36,8 @@ namespace BlackcmithWorkshopFileImplement "Clients", x => x.GetXElement); public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); + public void SaveMessages() => SaveData(Orders, ImplementerFileName, + "Messages", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => @@ -46,6 +50,8 @@ namespace BlackcmithWorkshopFileImplement Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; + Messages = LoadData(MessageInfoFileName, "MessageInfo", x => + MessageInfo.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) diff --git a/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Implements/MessageInfoStorage.cs b/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..9137086 --- /dev/null +++ b/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,55 @@ +using BlackcmithWorkshopFileImplement; +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.StoragesContracts; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopFileImplement.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/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Models/MessageInfo.cs b/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..f487570 --- /dev/null +++ b/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Models/MessageInfo.cs @@ -0,0 +1,71 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace BlacksmithWorkshopFileImplement.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 ?? 0), + new XAttribute("MessageId", MessageId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery) + ); + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/App.config b/BlacksmithWorkshop/BlacksmithWorkshop/App.config new file mode 100644 index 0000000..4525262 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.Designer.cs index a7639bd..08ad4c8 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.Designer.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.Designer.cs @@ -45,6 +45,7 @@ buttonIssued = new Button(); buttonReady = new Button(); buttonTakeInWork = new Button(); + MailToolStripMenuItem = new ToolStripMenuItem(); menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -60,7 +61,7 @@ // // GuidesToolStripMenuItem // - GuidesToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ComponentsToolStripMenuItem, ManufacturesToolStripMenuItem, ClientsToolStripMenuItem, ImplementersToolStripMenuItem, StartWorkingToolStripMenuItem }); + GuidesToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ComponentsToolStripMenuItem, ManufacturesToolStripMenuItem, ClientsToolStripMenuItem, ImplementersToolStripMenuItem, StartWorkingToolStripMenuItem, MailToolStripMenuItem }); GuidesToolStripMenuItem.Name = "GuidesToolStripMenuItem"; GuidesToolStripMenuItem.Size = new Size(94, 20); GuidesToolStripMenuItem.Text = "Справочники"; @@ -187,6 +188,13 @@ buttonTakeInWork.UseVisualStyleBackColor = true; buttonTakeInWork.Click += TakeInWorkButton_Click; // + // MailToolStripMenuItem + // + MailToolStripMenuItem.Name = "MailToolStripMenuItem"; + MailToolStripMenuItem.Size = new Size(181, 22); + MailToolStripMenuItem.Text = "Почта"; + MailToolStripMenuItem.Click += MailToolStripMenuItem_Click; + // // FormMain // AutoScaleDimensions = new SizeF(7F, 15F); @@ -230,5 +238,6 @@ private ToolStripMenuItem ClientsToolStripMenuItem; private ToolStripMenuItem ImplementersToolStripMenuItem; private ToolStripMenuItem StartWorkingToolStripMenuItem; + private ToolStripMenuItem MailToolStripMenuItem; } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.cs b/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.cs index 70600d7..18de462 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.cs @@ -222,5 +222,13 @@ namespace BlacksmithWorkshop form.ShowDialog(); } } + private void MailToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(ViewMailForm)); + if (service is ViewMailForm form) + { + form.ShowDialog(); + } + } } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs b/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs index b8d0edc..03bc363 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs @@ -1,4 +1,4 @@ -using BlacksmithWorkshopBusinessLogic.BusinessLogics; +using BlacksmithWorkshopBusinessLogic.BusinessLogics; using BlacksmithWorkshopBusinessLogic.OfficePackage.Implements; using BlacksmithWorkshopBusinessLogic.OfficePackage; using BlacksmithWorkshopContracts.BusinessLogicsContracts; @@ -8,6 +8,8 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using System; +using BlacksmithWorkshopBusinessLogic.MailWorker; +using BlacksmithWorkshopContracts.BindingModels; namespace BlacksmithWorkshop { @@ -27,6 +29,36 @@ namespace BlacksmithWorkshop var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); + try + { + var mailSender = + _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = + System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? + string.Empty, + MailPassword = + System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? + string.Empty, + SmtpClientHost = + System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? + string.Empty, + SmtpClientPort = + Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = + System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = + Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + var timer = new System.Threading.Timer(new + TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, "Ошибка работы с почтой"); + } Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) @@ -50,6 +82,9 @@ namespace BlacksmithWorkshop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -63,6 +98,9 @@ namespace BlacksmithWorkshop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } + private static void MailCheck(object obj) => ServiceProvider? + .GetService()?.MailCheck(); } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.Designer.cs new file mode 100644 index 0000000..e4757b2 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.Designer.cs @@ -0,0 +1,62 @@ +namespace BlacksmithWorkshop +{ + partial class ViewMailForm + { + /// + /// 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; + // + // ViewMailForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(dataGridView); + Name = "ViewMailForm"; + Text = "ViewMailForm"; + Load += ViewMailForm_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.cs b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.cs new file mode 100644 index 0000000..04ab472 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.cs @@ -0,0 +1,47 @@ +using BlacksmithWorkshopContracts.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 BlacksmithWorkshop +{ + public partial class ViewMailForm : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + public ViewMailForm(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + private void ViewMailForm_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/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.resx b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.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/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BlacksmithWorkshopBusinessLogic.csproj b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BlacksmithWorkshopBusinessLogic.csproj index fa4281a..3578658 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BlacksmithWorkshopBusinessLogic.csproj +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BlacksmithWorkshopBusinessLogic.csproj @@ -10,6 +10,7 @@ + diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/ClientLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/ClientLogic.cs index 729b4f2..7c5f1b1 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/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 BlacksmithWorkshopBusinessLogic.BusinessLogics @@ -106,6 +107,14 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics throw new ArgumentNullException("Нет пароля клиента", nameof(model.ClientFIO)); } + 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. ClientFIO:{ClientFIO}." + "Email:{ Email}. Password:{ Password}. Id: { Id} ", model.ClientFIO, model.Email, model.Password, model.Id); var element = _clientStorage.GetElement(new ClientSearchModel diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..8a5a6f4 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,46 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.StoragesContracts; +using BlacksmithWorkshopContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopBusinessLogic.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/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs index 282e732..58bfcb0 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,4 +1,5 @@ -using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopBusinessLogic.MailWorker; +using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.BusinessLogicsContracts; using BlacksmithWorkshopContracts.SearchModels; using BlacksmithWorkshopContracts.StoragesContracts; @@ -17,12 +18,16 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; static readonly object locker = new object(); - - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, + AbstractMailWorker mailWorker, IClientLogic clientLogic) { - _logger = logger; _orderStorage = orderStorage; + _logger = logger; + _mailWorker = mailWorker; + _clientLogic = clientLogic; } public OrderViewModel? ReadElement(OrderSearchModel model) { @@ -57,12 +62,29 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics { CheckModel(model); if (model.Status != OrderStatus.Неизвестен) return false; - model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) + model.Status = OrderStatus.Принят; + var res = _orderStorage.Insert(model); + if (res == null) { _logger.LogWarning("Insert operation failed"); return false; } + SendOrderStatusMail(model.ClientId, $"Изменен статус заказа #{res.Id}", $"Заказ #{res.Id} изменен статус на {model.Status}"); + return 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; } public bool ChangeStatus(OrderBindingModel model, OrderStatus status) diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..03e517e --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,83 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopBusinessLogic.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 ILogger _logger; + public AbstractMailWorker(ILogger logger, + IMessageInfoLogic messageInfoLogic) + { + _logger = logger; + _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; + _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) + { + _messageInfoLogic.Create(mail); + } + } + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + protected abstract Task> + ReceiveMailAsync(); + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/MailKitWorker.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..bfa6985 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,81 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using MailKit.Net.Pop3; +using MailKit.Security; +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; + +namespace BlacksmithWorkshopBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic + messageInfoLogic) : base(logger, messageInfoLogic) { } + 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 (AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Controllers/HomeController.cs b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Controllers/HomeController.cs index f4345f3..21a93fb 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Controllers/HomeController.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Controllers/HomeController.cs @@ -143,5 +143,15 @@ namespace BlacksmithWorkshopClientApp.Controllers APIClient.GetRequest($"api/main/getmanufacture?manufactureid={manufacture}"); return Math.Round(count * (_manufacture?.Price ?? 1), 2); } + [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + return + View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + } } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Home/Mails.cshtml b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..9741b90 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,49 @@ +@using BlacksmithWorkshopContracts.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/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Shared/_Layout.cshtml b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Shared/_Layout.cshtml index dde77fd..f490f14 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Shared/_Layout.cshtml +++ b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Shared/_Layout.cshtml @@ -26,6 +26,9 @@ + diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MailConfigBindingModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..a956755 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.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/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MailSendInfoBindingModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..00c42c9 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.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/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MessageInfoBindingModel .cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MessageInfoBindingModel .cs new file mode 100644 index 0000000..6073666 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MessageInfoBindingModel .cs @@ -0,0 +1,19 @@ +using BlacksmithWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.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/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..6b7e3bf --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,17 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + bool Create(MessageInfoBindingModel model); + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/MessageInfoSearchModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..3b8e202 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + public string? MessageId { get; set; } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IMessageInfoStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..e522311 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,19 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + List GetFilteredList(MessageInfoSearchModel model); + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/MessageInfoViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..9093103 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,24 @@ +using BlacksmithWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.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/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IMessageInfoModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..e25db0d --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopDataModels.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/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/BlacksmithWorkshopDataBase.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/BlacksmithWorkshopDataBase.cs index 8d7ee0a..220d20f 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/BlacksmithWorkshopDataBase.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/BlacksmithWorkshopDataBase.cs @@ -25,6 +25,7 @@ namespace BlacksmithWorkshopDatabaseImplement 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/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/MessageInfoStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..8d64638 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,53 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.StoragesContracts; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + using var context = new BlacksmithWorkshopDataBase(); + 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 BlacksmithWorkshopDataBase(); + return context.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + public List GetFullList() + { + using var context = new BlacksmithWorkshopDataBase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + using var context = new BlacksmithWorkshopDataBase(); + var newMessage = MessageInfo.Create(context, 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/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/MessageInfo.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..261a1e9 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,50 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopDatabaseImplement.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 Client? Client { get; private set; } + public static MessageInfo? Create(BlacksmithWorkshopDataBase context, MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = context.Clients.FirstOrDefault(x => x.Email == model.SenderName).Id, + Client = context.Clients.FirstOrDefault(x => x.Email == model.SenderName), + 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/BlacksmithWorkshop/BlacksmithWorkshopListImplement/DataListSingleton.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/DataListSingleton.cs index bd1cc04..174fa66 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/DataListSingleton.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/DataListSingleton.cs @@ -15,6 +15,7 @@ namespace BlacksmithWorkshopListImplement public List Manufactures { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List Messages { get; set; } private DataListSingleton() { Components = new List(); @@ -22,6 +23,7 @@ namespace BlacksmithWorkshopListImplement Manufactures = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } public static DataListSingleton GetInstance() { diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/MessageInfoStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..530daf0 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,62 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.StoragesContracts; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopListImplement.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/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/MessageInfo.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..e20590b --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/MessageInfo.cs @@ -0,0 +1,46 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopListImplement.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/BlacksmithWorkshop/BlacksmithWorkshopRestApi/Controllers/ClientController.cs b/BlacksmithWorkshop/BlacksmithWorkshopRestApi/Controllers/ClientController.cs index 1bd7fcd..086784c 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopRestApi/Controllers/ClientController.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopRestApi/Controllers/ClientController.cs @@ -17,11 +17,14 @@ namespace BlacksmithWorkshopRestApi.Controllers public class ClientController : Controller { private readonly ILogger _logger; - private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger logger) + private readonly IClientLogic _logic; + 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) @@ -53,6 +56,22 @@ namespace BlacksmithWorkshopRestApi.Controllers throw; } } + [HttpGet] + public List? GetMessages(int clientId) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } + } [HttpPost] public void UpdateData(ClientBindingModel model) { diff --git a/BlacksmithWorkshop/BlacksmithWorkshopRestApi/Program.cs b/BlacksmithWorkshop/BlacksmithWorkshopRestApi/Program.cs index 23167b1..1aab5ef 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopRestApi/Program.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopRestApi/Program.cs @@ -1,4 +1,6 @@ using BlacksmithWorkshopBusinessLogic.BusinessLogics; +using BlacksmithWorkshopBusinessLogic.MailWorker; +using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.BusinessLogicsContracts; using BlacksmithWorkshopContracts.StoragesContracts; using BlacksmithWorkshopDatabaseImplement.Implements; @@ -10,9 +12,14 @@ builder.Logging.AddLog4Net("log4net.config"); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddSingleton(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at //https://aka.ms/aspnetcore/swashbuckle @@ -26,7 +33,25 @@ builder.Services.AddSwaggerGen(c => = "v1" }); }); -var app = builder.Build(); +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/BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json b/BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json index 10f68b8..01ad592 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json +++ b/BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json @@ -5,5 +5,11 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "sasda3183@gmail.com", + "MailPassword": "ozxp vjof uinv fcmj" } -- 2.25.1 From d0faedb14c25dd580e991f89e39a5c4a8ea9a15e Mon Sep 17 00:00:00 2001 From: Zakharov_Rostislav Date: Tue, 7 May 2024 22:56:33 +0400 Subject: [PATCH 02/13] lab-7 add migration --- .../20240507185552_AddMessages.Designer.cs | 296 ++++++++++++++++++ .../Migrations/20240507185552_AddMessages.cs | 48 +++ ...BlacksmithWorkshopDataBaseModelSnapshot.cs | 39 +++ 3 files changed, 383 insertions(+) create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240507185552_AddMessages.Designer.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240507185552_AddMessages.cs diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240507185552_AddMessages.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240507185552_AddMessages.Designer.cs new file mode 100644 index 0000000..69f7770 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240507185552_AddMessages.Designer.cs @@ -0,0 +1,296 @@ +// +using System; +using BlacksmithWorkshopDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BlacksmithWorkshopDatabaseImplement.Migrations +{ + [DbContext(typeof(BlacksmithWorkshopDataBase))] + [Migration("20240507185552_AddMessages")] + partial class AddMessages + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.16") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BlacksmithWorkshopDataModels.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("BlacksmithWorkshopDatabaseImplement.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("BlacksmithWorkshopDatabaseImplement.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("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ManufactureName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Manufactures"); + }); + + modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("ManufactureId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("ManufactureId"); + + b.ToTable("ManufactureComponents"); + }); + + modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.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("BlacksmithWorkshopDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("ManufactureId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ImplementerId"); + + b.HasIndex("ManufactureId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b => + { + b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Component", "Component") + .WithMany("ManufactureComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture") + .WithMany("Components") + .HasForeignKey("ManufactureId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Manufacture"); + }); + + modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client") + .WithMany() + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b => + { + b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BlacksmithWorkshopDataModels.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture") + .WithMany("Orders") + .HasForeignKey("ManufactureId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Implementer"); + + b.Navigation("Manufacture"); + }); + + modelBuilder.Entity("BlacksmithWorkshopDataModels.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Component", b => + { + b.Navigation("ManufactureComponents"); + }); + + modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240507185552_AddMessages.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240507185552_AddMessages.cs new file mode 100644 index 0000000..b89caf3 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240507185552_AddMessages.cs @@ -0,0 +1,48 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BlacksmithWorkshopDatabaseImplement.Migrations +{ + /// + public partial class AddMessages : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Messages", + columns: table => new + { + MessageId = table.Column(type: "nvarchar(450)", nullable: false), + ClientId = table.Column(type: "int", nullable: true), + SenderName = table.Column(type: "nvarchar(max)", nullable: false), + DateDelivery = table.Column(type: "datetime2", nullable: false), + Subject = table.Column(type: "nvarchar(max)", nullable: false), + Body = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Messages", x => x.MessageId); + table.ForeignKey( + name: "FK_Messages_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id"); + }); + + migrationBuilder.CreateIndex( + name: "IX_Messages_ClientId", + table: "Messages", + column: "ClientId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Messages"); + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/BlacksmithWorkshopDataBaseModelSnapshot.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/BlacksmithWorkshopDataBaseModelSnapshot.cs index 8aafc9b..31fe326 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/BlacksmithWorkshopDataBaseModelSnapshot.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/BlacksmithWorkshopDataBaseModelSnapshot.cs @@ -140,6 +140,36 @@ namespace BlacksmithWorkshopDatabaseImplement.Migrations b.ToTable("ManufactureComponents"); }); + modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.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("BlacksmithWorkshopDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -202,6 +232,15 @@ namespace BlacksmithWorkshopDatabaseImplement.Migrations b.Navigation("Manufacture"); }); + modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client") + .WithMany() + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b => { b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client") -- 2.25.1 From e77be06f6018c6859dff64704cd9b950c9bf3999 Mon Sep 17 00:00:00 2001 From: Zakharov_Rostislav Date: Wed, 8 May 2024 15:29:42 +0400 Subject: [PATCH 03/13] lab-7 some fixes (do not work) --- .../BlacksmithWorkshop/App.config | 4 ++-- .../BlacksmithWorkshop/Program.cs | 24 +++++++------------ .../BlacksmithWorkshopRestApi/Program.cs | 20 +++++++--------- .../appsettings.json | 4 ++-- 4 files changed, 21 insertions(+), 31 deletions(-) diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/App.config b/BlacksmithWorkshop/BlacksmithWorkshop/App.config index 4525262..4f2239b 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/App.config +++ b/BlacksmithWorkshop/BlacksmithWorkshop/App.config @@ -5,7 +5,7 @@ - - + + \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs b/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs index 03bc363..cfe0ab0 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs @@ -35,21 +35,15 @@ namespace BlacksmithWorkshop _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"]) + 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); diff --git a/BlacksmithWorkshop/BlacksmithWorkshopRestApi/Program.cs b/BlacksmithWorkshop/BlacksmithWorkshopRestApi/Program.cs index 1aab5ef..407d030 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopRestApi/Program.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopRestApi/Program.cs @@ -39,18 +39,14 @@ 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()) + 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/BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json b/BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json index 01ad592..c459107 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json +++ b/BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json @@ -10,6 +10,6 @@ "SmtpClientPort": "587", "PopHost": "pop.gmail.com", "PopPort": "995", - "MailLogin": "sasda3183@gmail.com", - "MailPassword": "ozxp vjof uinv fcmj" + "MailLogin": "r.for.labs@gmail.com", + "MailPassword": "keyy rroi mgyu yotq" } -- 2.25.1 From 2dd7c33347704cbd2468aae3b95a7908e613481f Mon Sep 17 00:00:00 2001 From: Zakharov_Rostislav Date: Wed, 8 May 2024 16:01:42 +0400 Subject: [PATCH 04/13] lab-7 it does not work --- BlacksmithWorkshop/BlacksmithWorkshop/Program.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs b/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs index cfe0ab0..8f98da0 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs @@ -31,8 +31,7 @@ namespace BlacksmithWorkshop _serviceProvider = services.BuildServiceProvider(); try { - var mailSender = - _serviceProvider.GetService(); + var mailSender = _serviceProvider.GetService(); mailSender?.MailConfig(new MailConfigBindingModel { MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] -- 2.25.1 From 0cda93cbb41bdc5a95014262ddc60858df032b5f Mon Sep 17 00:00:00 2001 From: Zakharov_Rostislav Date: Wed, 8 May 2024 16:23:36 +0400 Subject: [PATCH 05/13] lab-7 new password --- BlacksmithWorkshop/BlacksmithWorkshop/App.config | 2 +- BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/App.config b/BlacksmithWorkshop/BlacksmithWorkshop/App.config index 4f2239b..4734522 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/App.config +++ b/BlacksmithWorkshop/BlacksmithWorkshop/App.config @@ -6,6 +6,6 @@ - + \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json b/BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json index c459107..4bde0df 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json +++ b/BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json @@ -11,5 +11,5 @@ "PopHost": "pop.gmail.com", "PopPort": "995", "MailLogin": "r.for.labs@gmail.com", - "MailPassword": "keyy rroi mgyu yotq" + "MailPassword": "jouu dcra gclx keup" } -- 2.25.1 From fd478094986efdd6327ef6a06c49aad50967876c Mon Sep 17 00:00:00 2001 From: Zakharov_Rostislav Date: Wed, 8 May 2024 17:37:59 +0400 Subject: [PATCH 06/13] lab-7 it is work --- BlacksmithWorkshop/BlacksmithWorkshop/App.config | 4 ++-- .../BusinessLogics/OrderLogic.cs | 10 ++++++++-- .../BlacksmithWorkshopRestApi/appsettings.json | 4 ++-- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/App.config b/BlacksmithWorkshop/BlacksmithWorkshop/App.config index 4734522..ad9202d 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/App.config +++ b/BlacksmithWorkshop/BlacksmithWorkshop/App.config @@ -5,7 +5,7 @@ - - + + \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs index 58bfcb0..723de2c 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -69,7 +69,7 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics _logger.LogWarning("Insert operation failed"); return false; } - SendOrderStatusMail(model.ClientId, $"Изменен статус заказа #{res.Id}", $"Заказ #{res.Id} изменен статус на {model.Status}"); + SendOrderStatusMail(res.ClientId, $"Изменен статус заказа #{res.Id}", $"Заказ #{res.Id} изменен статус на {model.Status}"); return true; } private bool SendOrderStatusMail(int clientId, string subject, string text) @@ -106,7 +106,13 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics model.DateImplement = DateTime.Now; if (element.ImplementerId.HasValue) model.ImplementerId = element.ImplementerId; - _orderStorage.Update(model); + var result = _orderStorage.Update(model); + if (result == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + SendOrderStatusMail(result.ClientId, $"Изменен статус заказа #{result.Id}", $"Заказ #{result.Id} изменен статус на {result.Status}"); return true; } public bool TakeOrderInWork(OrderBindingModel model) diff --git a/BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json b/BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json index 4bde0df..805e230 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json +++ b/BlacksmithWorkshop/BlacksmithWorkshopRestApi/appsettings.json @@ -10,6 +10,6 @@ "SmtpClientPort": "587", "PopHost": "pop.gmail.com", "PopPort": "995", - "MailLogin": "r.for.labs@gmail.com", - "MailPassword": "jouu dcra gclx keup" + "MailLogin": "forlabspibd23@gmail.com", + "MailPassword": "euby honk jvrl rrjj" } -- 2.25.1 From fa7bca6a5fc6d88beb60f78bba733cde02622415 Mon Sep 17 00:00:00 2001 From: Zakharov_Rostislav Date: Sun, 12 May 2024 20:52:37 +0400 Subject: [PATCH 07/13] fix mail form title --- .../ViewMailForm.Designer.cs | 72 ++++++++++--------- .../BlacksmithWorkshop/ViewMailForm.resx | 50 ++++++------- 2 files changed, 62 insertions(+), 60 deletions(-) diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.Designer.cs index e4757b2..d7351ac 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.Designer.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.Designer.cs @@ -20,43 +20,45 @@ base.Dispose(disposing); } - #region Windows Form Designer generated code + #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; - // - // ViewMailForm - // - AutoScaleDimensions = new SizeF(8F, 20F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 450); - Controls.Add(dataGridView); - Name = "ViewMailForm"; - Text = "ViewMailForm"; - Load += ViewMailForm_Load; - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - ResumeLayout(false); - } + /// + /// 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(10, 9); + dataGridView.Margin = new Padding(3, 2, 3, 2); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(679, 320); + dataGridView.TabIndex = 0; + // + // ViewMailForm + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(700, 338); + Controls.Add(dataGridView); + Margin = new Padding(3, 2, 3, 2); + Name = "ViewMailForm"; + Text = "Почта"; + Load += ViewMailForm_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } - #endregion + #endregion - private DataGridView dataGridView; + private DataGridView dataGridView; } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.resx b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.resx index 1af7de1..af32865 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.resx +++ b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.resx @@ -1,17 +1,17 @@  - -- 2.25.1 From c074afa0a98b7d4d02961276e46835abbf07fee6 Mon Sep 17 00:00:00 2001 From: Zakharov_Rostislav Date: Sun, 19 May 2024 13:18:31 +0400 Subject: [PATCH 08/13] lab-7 fix migration --- .../Migrations/20240507185552_AddMessages.cs | 48 ---- ...20240519091548_addingMessages.Designer.cs} | 8 +- .../20240519091548_addingMessages.cs | 214 ++++++++++++++++++ ...BlacksmithWorkshopDataBaseModelSnapshot.cs | 4 +- .../Models/Client.cs | 4 +- 5 files changed, 225 insertions(+), 53 deletions(-) delete mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240507185552_AddMessages.cs rename BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/{20240507185552_AddMessages.Designer.cs => 20240519091548_addingMessages.Designer.cs} (98%) create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519091548_addingMessages.cs diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240507185552_AddMessages.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240507185552_AddMessages.cs deleted file mode 100644 index b89caf3..0000000 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240507185552_AddMessages.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -#nullable disable - -namespace BlacksmithWorkshopDatabaseImplement.Migrations -{ - /// - public partial class AddMessages : Migration - { - /// - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "Messages", - columns: table => new - { - MessageId = table.Column(type: "nvarchar(450)", nullable: false), - ClientId = table.Column(type: "int", nullable: true), - SenderName = table.Column(type: "nvarchar(max)", nullable: false), - DateDelivery = table.Column(type: "datetime2", nullable: false), - Subject = table.Column(type: "nvarchar(max)", nullable: false), - Body = table.Column(type: "nvarchar(max)", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Messages", x => x.MessageId); - table.ForeignKey( - name: "FK_Messages_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id"); - }); - - migrationBuilder.CreateIndex( - name: "IX_Messages_ClientId", - table: "Messages", - column: "ClientId"); - } - - /// - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "Messages"); - } - } -} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240507185552_AddMessages.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519091548_addingMessages.Designer.cs similarity index 98% rename from BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240507185552_AddMessages.Designer.cs rename to BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519091548_addingMessages.Designer.cs index 69f7770..cac691e 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240507185552_AddMessages.Designer.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519091548_addingMessages.Designer.cs @@ -12,8 +12,8 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace BlacksmithWorkshopDatabaseImplement.Migrations { [DbContext(typeof(BlacksmithWorkshopDataBase))] - [Migration("20240507185552_AddMessages")] - partial class AddMessages + [Migration("20240519091548_addingMessages")] + partial class addingMessages { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) @@ -238,7 +238,7 @@ namespace BlacksmithWorkshopDatabaseImplement.Migrations modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b => { b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client") - .WithMany() + .WithMany("MessageInfos") .HasForeignKey("ClientId"); b.Navigation("Client"); @@ -276,6 +276,8 @@ namespace BlacksmithWorkshopDatabaseImplement.Migrations modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b => { + b.Navigation("MessageInfos"); + b.Navigation("Orders"); }); diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519091548_addingMessages.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519091548_addingMessages.cs new file mode 100644 index 0000000..2dc123b --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519091548_addingMessages.cs @@ -0,0 +1,214 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BlacksmithWorkshopDatabaseImplement.Migrations +{ + /// + public partial class addingMessages : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + 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), + Qualification = table.Column(type: "int", nullable: false), + WorkExperience = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Implementers", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Manufactures", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ManufactureName = table.Column(type: "nvarchar(max)", nullable: false), + Price = table.Column(type: "float", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Manufactures", 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: "ManufactureComponents", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ManufactureId = 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_ManufactureComponents", x => x.Id); + table.ForeignKey( + name: "FK_ManufactureComponents_Components_ComponentId", + column: x => x.ComponentId, + principalTable: "Components", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ManufactureComponents_Manufactures_ManufactureId", + column: x => x.ManufactureId, + principalTable: "Manufactures", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Orders", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ClientId = table.Column(type: "int", nullable: false), + 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), + ManufactureId = table.Column(type: "int", nullable: false), + ImplementerId = table.Column(type: "int", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Orders", x => x.Id); + 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"); + table.ForeignKey( + name: "FK_Orders_Manufactures_ManufactureId", + column: x => x.ManufactureId, + principalTable: "Manufactures", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_ManufactureComponents_ComponentId", + table: "ManufactureComponents", + column: "ComponentId"); + + migrationBuilder.CreateIndex( + name: "IX_ManufactureComponents_ManufactureId", + table: "ManufactureComponents", + column: "ManufactureId"); + + migrationBuilder.CreateIndex( + name: "IX_Messages_ClientId", + table: "Messages", + column: "ClientId"); + + migrationBuilder.CreateIndex( + name: "IX_Orders_ClientId", + table: "Orders", + column: "ClientId"); + + migrationBuilder.CreateIndex( + name: "IX_Orders_ImplementerId", + table: "Orders", + column: "ImplementerId"); + + migrationBuilder.CreateIndex( + name: "IX_Orders_ManufactureId", + table: "Orders", + column: "ManufactureId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ManufactureComponents"); + + migrationBuilder.DropTable( + name: "Messages"); + + migrationBuilder.DropTable( + name: "Orders"); + + migrationBuilder.DropTable( + name: "Components"); + + migrationBuilder.DropTable( + name: "Clients"); + + migrationBuilder.DropTable( + name: "Implementers"); + + migrationBuilder.DropTable( + name: "Manufactures"); + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/BlacksmithWorkshopDataBaseModelSnapshot.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/BlacksmithWorkshopDataBaseModelSnapshot.cs index 31fe326..dd341f1 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/BlacksmithWorkshopDataBaseModelSnapshot.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/BlacksmithWorkshopDataBaseModelSnapshot.cs @@ -235,7 +235,7 @@ namespace BlacksmithWorkshopDatabaseImplement.Migrations modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b => { b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client") - .WithMany() + .WithMany("MessageInfos") .HasForeignKey("ClientId"); b.Navigation("Client"); @@ -273,6 +273,8 @@ namespace BlacksmithWorkshopDatabaseImplement.Migrations modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b => { + b.Navigation("MessageInfos"); + b.Navigation("Orders"); }); diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Client.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Client.cs index 7d781f4..9ab918f 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Client.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Client.cs @@ -22,7 +22,9 @@ namespace BlacksmithWorkshopDatabaseImplement.Models public string Password { get; set; } = string.Empty; [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); - public static Client? Create(ClientBindingModel model) + [ForeignKey("ClientId")] + public virtual List MessageInfos { get; set; } = new(); + public static Client? Create(ClientBindingModel model) { if (model == null) { -- 2.25.1 From 922f3bcec2a6f9128a1f3953e24c3212417604d8 Mon Sep 17 00:00:00 2001 From: Zakharov_Rostislav Date: Sun, 19 May 2024 13:24:04 +0400 Subject: [PATCH 09/13] lab-7 fix migration --- .../20240325174141_InitialCreate.Designer.cs | 171 ------------ .../20240325174141_InitialCreate.cs | 125 --------- ...20240406155953_CreatingClients.Designer.cs | 214 --------------- .../20240406155953_CreatingClients.cs | 68 ----- ...40422165434_addingImplementors.Designer.cs | 257 ------------------ .../20240422165434_addingImplementors.cs | 67 ----- ... 20240519092241_initialCreate.Designer.cs} | 4 +- ...ges.cs => 20240519092241_initialCreate.cs} | 2 +- 8 files changed, 3 insertions(+), 905 deletions(-) delete mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240325174141_InitialCreate.Designer.cs delete mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240325174141_InitialCreate.cs delete mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240406155953_CreatingClients.Designer.cs delete mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240406155953_CreatingClients.cs delete mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240422165434_addingImplementors.Designer.cs delete mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240422165434_addingImplementors.cs rename BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/{20240519091548_addingMessages.Designer.cs => 20240519092241_initialCreate.Designer.cs} (99%) rename BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/{20240519091548_addingMessages.cs => 20240519092241_initialCreate.cs} (99%) diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240325174141_InitialCreate.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240325174141_InitialCreate.Designer.cs deleted file mode 100644 index 4643766..0000000 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240325174141_InitialCreate.Designer.cs +++ /dev/null @@ -1,171 +0,0 @@ -// -using System; -using BlacksmithWorkshopDatabaseImplement; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; - -#nullable disable - -namespace BlacksmithWorkshopDatabaseImplement.Migrations -{ - [DbContext(typeof(BlacksmithWorkshopDataBase))] - [Migration("20240325174141_InitialCreate")] - partial class InitialCreate - { - /// - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "7.0.16") - .HasAnnotation("Relational:MaxIdentifierLength", 128); - - SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.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("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ManufactureName") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Price") - .HasColumnType("float"); - - b.HasKey("Id"); - - b.ToTable("Manufactures"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ComponentId") - .HasColumnType("int"); - - b.Property("Count") - .HasColumnType("int"); - - b.Property("ManufactureId") - .HasColumnType("int"); - - b.HasKey("Id"); - - b.HasIndex("ComponentId"); - - b.HasIndex("ManufactureId"); - - b.ToTable("ManufactureComponents"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("Count") - .HasColumnType("int"); - - b.Property("DateCreate") - .HasColumnType("datetime2"); - - b.Property("DateImplement") - .HasColumnType("datetime2"); - - b.Property("ManufactureId") - .HasColumnType("int"); - - b.Property("Status") - .HasColumnType("int"); - - b.Property("Sum") - .HasColumnType("float"); - - b.HasKey("Id"); - - b.HasIndex("ManufactureId"); - - b.ToTable("Orders"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b => - { - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Component", "Component") - .WithMany("ManufactureComponents") - .HasForeignKey("ComponentId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture") - .WithMany("Components") - .HasForeignKey("ManufactureId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Component"); - - b.Navigation("Manufacture"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b => - { - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture") - .WithMany("Orders") - .HasForeignKey("ManufactureId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Manufacture"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Component", b => - { - b.Navigation("ManufactureComponents"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b => - { - b.Navigation("Components"); - - b.Navigation("Orders"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240325174141_InitialCreate.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240325174141_InitialCreate.cs deleted file mode 100644 index 7a57164..0000000 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240325174141_InitialCreate.cs +++ /dev/null @@ -1,125 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -#nullable disable - -namespace BlacksmithWorkshopDatabaseImplement.Migrations -{ - /// - public partial class InitialCreate : Migration - { - /// - protected override void Up(MigrationBuilder migrationBuilder) - { - 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: "Manufactures", - columns: table => new - { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), - ManufactureName = table.Column(type: "nvarchar(max)", nullable: false), - Price = table.Column(type: "float", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Manufactures", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "ManufactureComponents", - columns: table => new - { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), - ManufactureId = 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_ManufactureComponents", x => x.Id); - table.ForeignKey( - name: "FK_ManufactureComponents_Components_ComponentId", - column: x => x.ComponentId, - principalTable: "Components", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_ManufactureComponents_Manufactures_ManufactureId", - column: x => x.ManufactureId, - principalTable: "Manufactures", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "Orders", - columns: table => new - { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), - 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), - ManufactureId = table.Column(type: "int", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Orders", x => x.Id); - table.ForeignKey( - name: "FK_Orders_Manufactures_ManufactureId", - column: x => x.ManufactureId, - principalTable: "Manufactures", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateIndex( - name: "IX_ManufactureComponents_ComponentId", - table: "ManufactureComponents", - column: "ComponentId"); - - migrationBuilder.CreateIndex( - name: "IX_ManufactureComponents_ManufactureId", - table: "ManufactureComponents", - column: "ManufactureId"); - - migrationBuilder.CreateIndex( - name: "IX_Orders_ManufactureId", - table: "Orders", - column: "ManufactureId"); - } - - /// - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "ManufactureComponents"); - - migrationBuilder.DropTable( - name: "Orders"); - - migrationBuilder.DropTable( - name: "Components"); - - migrationBuilder.DropTable( - name: "Manufactures"); - } - } -} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240406155953_CreatingClients.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240406155953_CreatingClients.Designer.cs deleted file mode 100644 index 1bdecfd..0000000 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240406155953_CreatingClients.Designer.cs +++ /dev/null @@ -1,214 +0,0 @@ -// -using System; -using BlacksmithWorkshopDatabaseImplement; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; - -#nullable disable - -namespace BlacksmithWorkshopDatabaseImplement.Migrations -{ - [DbContext(typeof(BlacksmithWorkshopDataBase))] - [Migration("20240406155953_CreatingClients")] - partial class CreatingClients - { - /// - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "7.0.16") - .HasAnnotation("Relational:MaxIdentifierLength", 128); - - SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.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("BlacksmithWorkshopDatabaseImplement.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("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ManufactureName") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Price") - .HasColumnType("float"); - - b.HasKey("Id"); - - b.ToTable("Manufactures"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ComponentId") - .HasColumnType("int"); - - b.Property("Count") - .HasColumnType("int"); - - b.Property("ManufactureId") - .HasColumnType("int"); - - b.HasKey("Id"); - - b.HasIndex("ComponentId"); - - b.HasIndex("ManufactureId"); - - b.ToTable("ManufactureComponents"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ClientId") - .HasColumnType("int"); - - b.Property("Count") - .HasColumnType("int"); - - b.Property("DateCreate") - .HasColumnType("datetime2"); - - b.Property("DateImplement") - .HasColumnType("datetime2"); - - b.Property("ManufactureId") - .HasColumnType("int"); - - b.Property("Status") - .HasColumnType("int"); - - b.Property("Sum") - .HasColumnType("float"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.HasIndex("ManufactureId"); - - b.ToTable("Orders"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b => - { - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Component", "Component") - .WithMany("ManufactureComponents") - .HasForeignKey("ComponentId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture") - .WithMany("Components") - .HasForeignKey("ManufactureId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Component"); - - b.Navigation("Manufacture"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b => - { - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client") - .WithMany("Orders") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture") - .WithMany("Orders") - .HasForeignKey("ManufactureId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - - b.Navigation("Manufacture"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b => - { - b.Navigation("Orders"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Component", b => - { - b.Navigation("ManufactureComponents"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b => - { - b.Navigation("Components"); - - b.Navigation("Orders"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240406155953_CreatingClients.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240406155953_CreatingClients.cs deleted file mode 100644 index 536a1bc..0000000 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240406155953_CreatingClients.cs +++ /dev/null @@ -1,68 +0,0 @@ -using Microsoft.EntityFrameworkCore.Migrations; - -#nullable disable - -namespace BlacksmithWorkshopDatabaseImplement.Migrations -{ - /// - public partial class CreatingClients : Migration - { - /// - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.AddColumn( - name: "ClientId", - table: "Orders", - type: "int", - nullable: false, - defaultValue: 0); - - 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.CreateIndex( - name: "IX_Orders_ClientId", - table: "Orders", - column: "ClientId"); - - migrationBuilder.AddForeignKey( - name: "FK_Orders_Clients_ClientId", - table: "Orders", - column: "ClientId", - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - } - - /// - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropForeignKey( - name: "FK_Orders_Clients_ClientId", - table: "Orders"); - - migrationBuilder.DropTable( - name: "Clients"); - - migrationBuilder.DropIndex( - name: "IX_Orders_ClientId", - table: "Orders"); - - migrationBuilder.DropColumn( - name: "ClientId", - table: "Orders"); - } - } -} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240422165434_addingImplementors.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240422165434_addingImplementors.Designer.cs deleted file mode 100644 index c6b2862..0000000 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240422165434_addingImplementors.Designer.cs +++ /dev/null @@ -1,257 +0,0 @@ -// -using System; -using BlacksmithWorkshopDatabaseImplement; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; - -#nullable disable - -namespace BlacksmithWorkshopDatabaseImplement.Migrations -{ - [DbContext(typeof(BlacksmithWorkshopDataBase))] - [Migration("20240422165434_addingImplementors")] - partial class addingImplementors - { - /// - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "7.0.16") - .HasAnnotation("Relational:MaxIdentifierLength", 128); - - SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); - - modelBuilder.Entity("BlacksmithWorkshopDataModels.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("BlacksmithWorkshopDatabaseImplement.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("BlacksmithWorkshopDatabaseImplement.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("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ManufactureName") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Price") - .HasColumnType("float"); - - b.HasKey("Id"); - - b.ToTable("Manufactures"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ComponentId") - .HasColumnType("int"); - - b.Property("Count") - .HasColumnType("int"); - - b.Property("ManufactureId") - .HasColumnType("int"); - - b.HasKey("Id"); - - b.HasIndex("ComponentId"); - - b.HasIndex("ManufactureId"); - - b.ToTable("ManufactureComponents"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ClientId") - .HasColumnType("int"); - - b.Property("Count") - .HasColumnType("int"); - - b.Property("DateCreate") - .HasColumnType("datetime2"); - - b.Property("DateImplement") - .HasColumnType("datetime2"); - - b.Property("ImplementerId") - .HasColumnType("int"); - - b.Property("ManufactureId") - .HasColumnType("int"); - - b.Property("Status") - .HasColumnType("int"); - - b.Property("Sum") - .HasColumnType("float"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.HasIndex("ImplementerId"); - - b.HasIndex("ManufactureId"); - - b.ToTable("Orders"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b => - { - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Component", "Component") - .WithMany("ManufactureComponents") - .HasForeignKey("ComponentId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture") - .WithMany("Components") - .HasForeignKey("ManufactureId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Component"); - - b.Navigation("Manufacture"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b => - { - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client") - .WithMany("Orders") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("BlacksmithWorkshopDataModels.Models.Implementer", "Implementer") - .WithMany("Orders") - .HasForeignKey("ImplementerId"); - - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture") - .WithMany("Orders") - .HasForeignKey("ManufactureId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - - b.Navigation("Implementer"); - - b.Navigation("Manufacture"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDataModels.Models.Implementer", b => - { - b.Navigation("Orders"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b => - { - b.Navigation("Orders"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Component", b => - { - b.Navigation("ManufactureComponents"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b => - { - b.Navigation("Components"); - - b.Navigation("Orders"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240422165434_addingImplementors.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240422165434_addingImplementors.cs deleted file mode 100644 index d6ee27e..0000000 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240422165434_addingImplementors.cs +++ /dev/null @@ -1,67 +0,0 @@ -using Microsoft.EntityFrameworkCore.Migrations; - -#nullable disable - -namespace BlacksmithWorkshopDatabaseImplement.Migrations -{ - /// - public partial class addingImplementors : Migration - { - /// - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.AddColumn( - name: "ImplementerId", - table: "Orders", - type: "int", - nullable: true); - - 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), - Qualification = table.Column(type: "int", nullable: false), - WorkExperience = table.Column(type: "int", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Implementers", x => x.Id); - }); - - migrationBuilder.CreateIndex( - name: "IX_Orders_ImplementerId", - table: "Orders", - column: "ImplementerId"); - - migrationBuilder.AddForeignKey( - name: "FK_Orders_Implementers_ImplementerId", - table: "Orders", - column: "ImplementerId", - principalTable: "Implementers", - principalColumn: "Id"); - } - - /// - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropForeignKey( - name: "FK_Orders_Implementers_ImplementerId", - table: "Orders"); - - migrationBuilder.DropTable( - name: "Implementers"); - - migrationBuilder.DropIndex( - name: "IX_Orders_ImplementerId", - table: "Orders"); - - migrationBuilder.DropColumn( - name: "ImplementerId", - table: "Orders"); - } - } -} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519091548_addingMessages.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519092241_initialCreate.Designer.cs similarity index 99% rename from BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519091548_addingMessages.Designer.cs rename to BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519092241_initialCreate.Designer.cs index cac691e..1951cb5 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519091548_addingMessages.Designer.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519092241_initialCreate.Designer.cs @@ -12,8 +12,8 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace BlacksmithWorkshopDatabaseImplement.Migrations { [DbContext(typeof(BlacksmithWorkshopDataBase))] - [Migration("20240519091548_addingMessages")] - partial class addingMessages + [Migration("20240519092241_initialCreate")] + partial class initialCreate { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519091548_addingMessages.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519092241_initialCreate.cs similarity index 99% rename from BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519091548_addingMessages.cs rename to BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519092241_initialCreate.cs index 2dc123b..ce7cb93 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519091548_addingMessages.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240519092241_initialCreate.cs @@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Migrations; namespace BlacksmithWorkshopDatabaseImplement.Migrations { /// - public partial class addingMessages : Migration + public partial class initialCreate : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) -- 2.25.1 From 1e75647ce8211fd77d41c45865c49633fe18fe2f Mon Sep 17 00:00:00 2001 From: Zakharov_Rostislav Date: Tue, 21 May 2024 18:07:25 +0400 Subject: [PATCH 10/13] lab-7-hard --- .../Implements/MessageInfoStorage.cs | 31 +- .../Models/MessageInfo.cs | 38 +- .../BlacksmithWorkshop/FormLetter.Designer.cs | 189 +++++++++ .../BlacksmithWorkshop/FormLetter.cs | 141 +++++++ .../BlacksmithWorkshop/FormLetter.resx | 120 ++++++ .../ViewMailForm.Designer.cs | 85 +++- .../BlacksmithWorkshop/ViewMailForm.cs | 102 ++++- .../BusinessLogics/MessageInfoLogic.cs | 31 +- .../BusinessLogics/OrderLogic.cs | 5 +- .../MailWorker/AbstractMailWorker.cs | 155 +++---- .../MailWorker/MailKitWorker.cs | 147 ++++--- .../BlacksmithWorkshopClientApp/APIClient.cs | 3 +- .../Controllers/HomeController.cs | 6 +- .../Views/Home/Mails.cshtml | 18 + .../Views/Shared/_Layout.cshtml | 2 +- .../MailReplySendInfoBindingModel.cs | 13 + .../BindingModels/MessageInfoBindingModel .cs | 5 +- .../IMessageInfoLogic.cs | 6 +- .../SearchModels/MessageInfoSearchModel.cs | 4 +- .../StoragesContracts/IMessageInfoStorage.cs | 3 +- .../ViewModels/MessageInfoViewModel.cs | 7 +- .../Models/IMessageInfoModel.cs | 5 +- .../BlacksmithWorkshopDataBase.cs | 2 +- .../Implements/MessageInfoStorage.cs | 69 ++- .../20240521123604_InitialCreate.Designer.cs | 394 ++++++++++++++++++ ...ate.cs => 20240521123604_InitialCreate.cs} | 42 ++ ...BlacksmithWorkshopDataBaseModelSnapshot.cs | 17 + .../Models/MessageInfo.cs | 50 ++- .../Implements/MessageInfoStorage.cs | 55 ++- .../Models/MessageInfo.cs | 29 +- .../Controllers/ClientController.cs | 36 +- 31 files changed, 1545 insertions(+), 265 deletions(-) create mode 100644 BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.Designer.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.resx create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MailReplySendInfoBindingModel.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240521123604_InitialCreate.Designer.cs rename BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/{20240507165329_InitialCreate.cs => 20240521123604_InitialCreate.cs} (83%) diff --git a/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Implements/MessageInfoStorage.cs b/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Implements/MessageInfoStorage.cs index 9137086..9134528 100644 --- a/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Implements/MessageInfoStorage.cs +++ b/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Implements/MessageInfoStorage.cs @@ -28,12 +28,19 @@ namespace BlacksmithWorkshopFileImplement.Implements return null; } public List GetFilteredList(MessageInfoSearchModel model) - { - return _source.Messages - .Where(x => x.ClientId == model.ClientId) - .Select(x => x.GetViewModel) + { + var res = _source.Messages + .Where(x => !model.ClientId.HasValue || x.ClientId == model.ClientId) + .Select(x => x.GetViewModel); + if (!(model.PageIndex.HasValue && model.PageLength.HasValue)) + { + return res.ToList(); + } + return res + .Skip((model.PageIndex.Value - 1) * model.PageLength.Value) + .Take(model.PageLength.Value) .ToList(); - } + } public List GetFullList() { return _source.Messages @@ -50,6 +57,16 @@ namespace BlacksmithWorkshopFileImplement.Implements _source.Messages.Add(newMessage); _source.SaveMessages(); return newMessage.GetViewModel; - } - } + } + public MessageInfoViewModel? Update(MessageInfoBindingModel model) + { + var res = _source.Messages.FirstOrDefault(x => x.MessageId.Equals(model.MessageId)); + if (res != null) + { + res.Update(model); + _source.SaveMessages(); + } + return res?.GetViewModel; + } + } } diff --git a/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Models/MessageInfo.cs b/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Models/MessageInfo.cs index f487570..0eadf4d 100644 --- a/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Models/MessageInfo.cs +++ b/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Models/MessageInfo.cs @@ -18,7 +18,10 @@ namespace BlacksmithWorkshopFileImplement.Models 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) + public bool IsReaded { get; private set; } + public bool IsReply { get; private set; } + public string? ReplyMessageId { get; private set; } = string.Empty; + public static MessageInfo? Create(MessageInfoBindingModel model) { if (model == null) { @@ -32,7 +35,10 @@ namespace BlacksmithWorkshopFileImplement.Models MessageId = model.MessageId, SenderName = model.SenderName, DateDelivery = model.DateDelivery, - }; + IsReply = model.IsReply, + IsReaded = model.IsReaded, + ReplyMessageId = model.ReplyMessageId, + }; } public static MessageInfo? Create(XElement element) { @@ -48,9 +54,21 @@ namespace BlacksmithWorkshopFileImplement.Models MessageId = element.Attribute("MessageId")!.Value, SenderName = element.Attribute("SenderName")!.Value, DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), - }; + IsReply = Convert.ToBoolean(element.Attribute("IsReply")!.Value), + IsReaded = Convert.ToBoolean(element.Attribute("HasRead")!.Value), + ReplyMessageId = element.Attribute("ReplyMessageId")!.Value, + }; } - public MessageInfoViewModel GetViewModel => new() + public void Update(MessageInfoBindingModel model) + { + if (model == null) + { + return; + } + IsReply = model.IsReply; + IsReaded = model.IsReaded; + } + public MessageInfoViewModel GetViewModel => new() { Body = Body, Subject = Subject, @@ -58,14 +76,20 @@ namespace BlacksmithWorkshopFileImplement.Models MessageId = MessageId, SenderName = SenderName, DateDelivery = DateDelivery, - }; + IsReply = IsReply, + IsReaded = IsReaded, + ReplyMessageId = ReplyMessageId, + }; public XElement GetXElement => new("MessageInfo", new XAttribute("Body", Body), new XAttribute("Subject", Subject), new XAttribute("ClientId", ClientId ?? 0), new XAttribute("MessageId", MessageId), new XAttribute("SenderName", SenderName), - new XAttribute("DateDelivery", DateDelivery) - ); + new XAttribute("DateDelivery", DateDelivery), + new XAttribute("IsReply", IsReply), + new XAttribute("IsReaded", IsReaded), + new XAttribute("ReplyMessageId", ReplyMessageId ?? "") + ); } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.Designer.cs new file mode 100644 index 0000000..4385684 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.Designer.cs @@ -0,0 +1,189 @@ +namespace BlacksmithWorkshop +{ + partial class FormLetter + { + /// + /// 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() + { + textBoxEmail = new TextBox(); + labelAdress = new Label(); + labelSubject = new Label(); + textBoxSubject = new TextBox(); + labelBody = new Label(); + textBoxBody = new TextBox(); + buttonClose = new Button(); + buttonReply = new Button(); + labelDate = new Label(); + textBoxDate = new TextBox(); + buttonSend = new Button(); + SuspendLayout(); + // + // textBoxEmail + // + textBoxEmail.Location = new Point(63, 4); + textBoxEmail.Margin = new Padding(3, 2, 3, 2); + textBoxEmail.Name = "textBoxEmail"; + textBoxEmail.ReadOnly = true; + textBoxEmail.Size = new Size(163, 23); + textBoxEmail.TabIndex = 0; + // + // labelAdress + // + labelAdress.AutoSize = true; + labelAdress.Location = new Point(10, 7); + labelAdress.Name = "labelAdress"; + labelAdress.Size = new Size(43, 15); + labelAdress.TabIndex = 1; + labelAdress.Text = "Адрес:"; + // + // labelSubject + // + labelSubject.AutoSize = true; + labelSubject.Location = new Point(10, 41); + labelSubject.Name = "labelSubject"; + labelSubject.Size = new Size(37, 15); + labelSubject.TabIndex = 2; + labelSubject.Text = "Тема:"; + // + // textBoxSubject + // + textBoxSubject.Location = new Point(63, 39); + textBoxSubject.Margin = new Padding(3, 2, 3, 2); + textBoxSubject.Name = "textBoxSubject"; + textBoxSubject.ReadOnly = true; + textBoxSubject.Size = new Size(484, 23); + textBoxSubject.TabIndex = 3; + // + // labelBody + // + labelBody.AutoSize = true; + labelBody.Location = new Point(10, 72); + labelBody.Name = "labelBody"; + labelBody.Size = new Size(83, 15); + labelBody.TabIndex = 4; + labelBody.Text = "Текст письма:"; + // + // textBoxBody + // + textBoxBody.Location = new Point(10, 89); + textBoxBody.Margin = new Padding(3, 2, 3, 2); + textBoxBody.Multiline = true; + textBoxBody.Name = "textBoxBody"; + textBoxBody.ReadOnly = true; + textBoxBody.Size = new Size(536, 140); + textBoxBody.TabIndex = 5; + // + // buttonClose + // + buttonClose.Location = new Point(430, 244); + buttonClose.Margin = new Padding(3, 2, 3, 2); + buttonClose.Name = "buttonClose"; + buttonClose.Size = new Size(97, 29); + buttonClose.TabIndex = 6; + buttonClose.Text = "Закрыть"; + buttonClose.UseVisualStyleBackColor = true; + buttonClose.Click += buttonClose_Click; + // + // buttonReply + // + buttonReply.Location = new Point(327, 244); + buttonReply.Margin = new Padding(3, 2, 3, 2); + buttonReply.Name = "buttonReply"; + buttonReply.Size = new Size(97, 29); + buttonReply.TabIndex = 7; + buttonReply.Text = "Ответить"; + buttonReply.UseVisualStyleBackColor = true; + buttonReply.Click += buttonReply_Click; + // + // labelDate + // + labelDate.AutoSize = true; + labelDate.Location = new Point(243, 7); + labelDate.Name = "labelDate"; + labelDate.Size = new Size(101, 15); + labelDate.TabIndex = 8; + labelDate.Text = "Дата получения: "; + // + // textBoxDate + // + textBoxDate.Location = new Point(360, 4); + textBoxDate.Margin = new Padding(3, 2, 3, 2); + textBoxDate.Name = "textBoxDate"; + textBoxDate.ReadOnly = true; + textBoxDate.Size = new Size(187, 23); + textBoxDate.TabIndex = 9; + // + // buttonSend + // + buttonSend.Location = new Point(224, 244); + buttonSend.Margin = new Padding(3, 2, 3, 2); + buttonSend.Name = "buttonSend"; + buttonSend.Size = new Size(97, 29); + buttonSend.TabIndex = 10; + buttonSend.Text = "Отправить"; + buttonSend.UseVisualStyleBackColor = true; + buttonSend.Visible = false; + buttonSend.Click += buttonSend_Click; + // + // FormLetter + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(556, 283); + Controls.Add(buttonSend); + Controls.Add(textBoxDate); + Controls.Add(labelDate); + Controls.Add(buttonReply); + Controls.Add(buttonClose); + Controls.Add(textBoxBody); + Controls.Add(labelBody); + Controls.Add(textBoxSubject); + Controls.Add(labelSubject); + Controls.Add(labelAdress); + Controls.Add(textBoxEmail); + Margin = new Padding(3, 2, 3, 2); + Name = "FormLetter"; + Text = "Письмо"; + Load += FormLetter_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private TextBox textBoxEmail; + private Label labelAdress; + private Label labelSubject; + private TextBox textBoxSubject; + private Label labelBody; + private TextBox textBoxBody; + private Button buttonClose; + private Button buttonReply; + private Label labelDate; + private TextBox textBoxDate; + private Button buttonSend; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.cs b/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.cs new file mode 100644 index 0000000..f5e8129 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.cs @@ -0,0 +1,141 @@ +using BlacksmithWorkshopBusinessLogic.MailWorker; +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.ViewModels; +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; +using System.Windows.Forms.VisualStyles; + +namespace BlacksmithWorkshop +{ + public partial class FormLetter : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + private readonly AbstractMailWorker _worker; + public MessageInfoViewModel? model; + public string? messageId; + public FormLetter(ILogger logger, IMessageInfoLogic logic, AbstractMailWorker worker) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + _worker = worker; + } + private void FormLetter_Load(object sender, EventArgs e) + { + if (!string.IsNullOrEmpty(messageId)) + { + ReloadLetter(); + return; + } + else if (model != null) + { + ConfigurateToCreateAnsver(); + return; + } + _logger.LogError("Для формы не переданно сведений о письме, на которое отвечаем!"); + DialogResult = DialogResult.Abort; + Close(); + return; + } + private void ReloadLetter() + { + _logger.LogInformation("Загрузка существующего письма с id:{}", messageId); + model = _logic.ReadElement(new MessageInfoSearchModel + { + MessageId = messageId + }); + if (model != null) + { + _logger.LogInformation("Письмо найдено"); + textBoxEmail.Text = model.SenderName; + textBoxDate.Text = model.DateDelivery.ToString(); + textBoxSubject.Text = model.Subject; + textBoxBody.Text = model.Body; + if (model.IsReply) + { + _logger.LogInformation("Письмо само и есть ответ"); + buttonReply.Visible = false; + } + else + { + if (!string.IsNullOrEmpty(model.ReplyMessageId)) + { + _logger.LogInformation("У письма есть ответ."); + buttonReply.Text = "Прочитать ответ"; + } + } + return; + } + _logger.LogWarning("Письмо с таким id не удалось найти"); + DialogResult = DialogResult.Abort; + Close(); + return; + } + private void ConfigurateToCreateAnsver() + { + textBoxEmail.Text = model.SenderName; + labelDate.Visible = false; + textBoxDate.Visible = false; + textBoxSubject.Text = $"re: {model.Subject}"; + textBoxBody.ReadOnly = false; + buttonReply.Visible = false; + buttonSend.Visible = true; + _logger.LogInformation("Запущена форма создания нового письма - ответа"); + } + private void buttonClose_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + private void buttonReply_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormLetter)); + if (service is FormLetter form) + { + if (!string.IsNullOrEmpty(model.ReplyMessageId)) + { + form.messageId = model.ReplyMessageId; + } + else + { + form.model = model; + } + + if (form.ShowDialog() != DialogResult.Cancel) + { + buttonReply.Visible = false; + } + } + } + private void buttonSend_Click(object sender, EventArgs e) + { + if (model == null) + { + return; + } + string subject = textBoxSubject.Text; + string text = textBoxBody.Text; + + Task.Run(() => _worker.MailSendReplyAsync(new MailReplySendInfoBindingModel + { + MailAddress = model.SenderName, + Subject = subject, + Text = text, + ParentMessageId = model.MessageId, + })); + DialogResult = DialogResult.OK; + Close(); + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.resx b/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.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/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.Designer.cs index d7351ac..1134e76 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.Designer.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.Designer.cs @@ -28,37 +28,108 @@ /// private void InitializeComponent() { + panel1 = new Panel(); dataGridView = new DataGridView(); + buttonOpen = new Button(); + numericUpDownPage = new NumericUpDown(); + buttonPreveous = new Button(); + buttonNext = new Button(); + panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDownPage).BeginInit(); SuspendLayout(); // + // panel1 + // + panel1.Controls.Add(dataGridView); + panel1.Location = new Point(3, 1); + panel1.Name = "panel1"; + panel1.Size = new Size(696, 323); + panel1.TabIndex = 0; + // // dataGridView // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(10, 9); + dataGridView.Dock = DockStyle.Fill; + dataGridView.Location = new Point(0, 0); dataGridView.Margin = new Padding(3, 2, 3, 2); dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; dataGridView.RowHeadersWidth = 51; dataGridView.RowTemplate.Height = 29; - dataGridView.Size = new Size(679, 320); - dataGridView.TabIndex = 0; + dataGridView.Size = new Size(696, 323); + dataGridView.TabIndex = 2; + // + // buttonOpen + // + buttonOpen.Location = new Point(722, 187); + buttonOpen.Name = "buttonOpen"; + buttonOpen.Size = new Size(74, 23); + buttonOpen.TabIndex = 1; + buttonOpen.Text = "Прочитать"; + buttonOpen.UseVisualStyleBackColor = true; + buttonOpen.Click += buttonOpen_Click; + // + // numericUpDownPage + // + numericUpDownPage.Location = new Point(722, 215); + numericUpDownPage.Margin = new Padding(3, 2, 3, 2); + numericUpDownPage.Name = "numericUpDownPage"; + numericUpDownPage.Size = new Size(74, 23); + numericUpDownPage.TabIndex = 4; + numericUpDownPage.ValueChanged += numericUpDownPage_ValueChanged; + // + // buttonPreveous + // + buttonPreveous.Location = new Point(722, 242); + buttonPreveous.Margin = new Padding(3, 2, 3, 2); + buttonPreveous.Name = "buttonPreveous"; + buttonPreveous.Size = new Size(34, 22); + buttonPreveous.TabIndex = 5; + buttonPreveous.Text = "<-"; + buttonPreveous.UseVisualStyleBackColor = true; + buttonPreveous.Click += buttonPreveous_Click; + // + // buttonNext + // + buttonNext.Location = new Point(763, 242); + buttonNext.Margin = new Padding(3, 2, 3, 2); + buttonNext.Name = "buttonNext"; + buttonNext.Size = new Size(34, 22); + buttonNext.TabIndex = 6; + buttonNext.Text = "->"; + buttonNext.UseVisualStyleBackColor = true; + buttonNext.Click += buttonNext_Click; // // ViewMailForm // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(700, 338); - Controls.Add(dataGridView); + ClientSize = new Size(809, 321); + Controls.Add(buttonNext); + Controls.Add(buttonPreveous); + Controls.Add(numericUpDownPage); + Controls.Add(buttonOpen); + Controls.Add(panel1); Margin = new Padding(3, 2, 3, 2); Name = "ViewMailForm"; - Text = "Почта"; + Text = "Письма"; Load += ViewMailForm_Load; + panel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDownPage).EndInit(); ResumeLayout(false); } #endregion + private Panel panel1; private DataGridView dataGridView; - } + private Button buttonOpen; + private NumericUpDown numericUpDownPage; + private Button buttonPreveous; + private Button buttonNext; + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.cs b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.cs index 04ab472..17727d7 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.cs @@ -1,4 +1,6 @@ -using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.SearchModels; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -16,7 +18,9 @@ namespace BlacksmithWorkshop { private readonly ILogger _logger; private readonly IMessageInfoLogic _logic; - public ViewMailForm(ILogger logger, IMessageInfoLogic logic) + private int currentPage = 1; + private int pageLength = 2; + public ViewMailForm(ILogger logger, IMessageInfoLogic logic) { InitializeComponent(); _logger = logger; @@ -24,24 +28,80 @@ namespace BlacksmithWorkshop } private void ViewMailForm_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); - } + LoadData(); + numericUpDownPage.Value = pageLength; } - } + private void LoadData() + { + try + { + var list = _logic.ReadList(new MessageInfoSearchModel() + { + PageLength = pageLength, + PageIndex = currentPage + }); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["ReplyMessageId"].Visible = false; + dataGridView.Columns["Reply"].Visible = false; + dataGridView.Columns["IsReply"].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 buttonOpen_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count <= 0) + return; + + var service = Program.ServiceProvider?.GetService(typeof(FormLetter)); + if (service is FormLetter form) + { + string? messageId = dataGridView.SelectedRows[0].Cells["MessageId"].Value.ToString(); + if (messageId == null) return; + form.messageId = messageId; + + if (!Convert.ToBoolean(dataGridView.SelectedRows[0].Cells["IsReaded"].Value)) + { + _logic.Update(new MessageInfoBindingModel + { + MessageId = messageId, + IsReaded = true, + ReplyMessageId = dataGridView.SelectedRows[0].Cells["ReplyMessageId"].Value?.ToString() + }); + } + + form.ShowDialog(); + LoadData(); + } + } + + private void buttonPreveous_Click(object sender, EventArgs e) + { + currentPage = Math.Max(1, currentPage - 1); + LoadData(); + } + + private void buttonNext_Click(object sender, EventArgs e) + { + currentPage++; + LoadData(); + } + + private void numericUpDownPage_ValueChanged(object sender, EventArgs e) + { + pageLength = Math.Max(1, (int)numericUpDownPage.Value); + LoadData(); + } + } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs index 8a5a6f4..c575e04 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -16,11 +16,11 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IMessageInfoStorage _messageInfoStorage; - public MessageInfoLogic(ILogger logger, IMessageInfoStorage MessageInfoStorage) + public MessageInfoLogic(ILogger logger, IMessageInfoStorage MessageInfoStorage) { _logger = logger; _messageInfoStorage = MessageInfoStorage; - } + } public bool Create(MessageInfoBindingModel model) { if (_messageInfoStorage.Insert(model) == null) @@ -41,6 +41,29 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics } _logger.LogInformation("ReadList. Count:{Count}", list.Count); return list; - } - } + } + public MessageInfoViewModel? ReadElement(MessageInfoSearchModel model) + { + _logger.LogInformation("ReadElement. MessageId:{MessageId}", model?.MessageId); + if (model == null) + throw new ArgumentNullException(nameof(model)); + var element = _messageInfoStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.MessageId); + return element; + } + public bool Update(MessageInfoBindingModel model) + { + if (_messageInfoStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs index b77d6c2..e6ab3c9 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -26,9 +26,8 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics private readonly IClientLogic _clientLogic; static readonly object locker = new object(); public OrderLogic(ILogger logger, IOrderStorage orderStorage, - IManufactureStorage manufactureStorage, IShopLogic shopLogic, IShopStorage shopStorage) - public OrderLogic(ILogger logger, IOrderStorage orderStorage, - AbstractMailWorker mailWorker, IClientLogic clientLogic) + AbstractMailWorker mailWorker, IClientLogic clientLogic, IShopLogic shopLogic, + IManufactureStorage manufactureStorage, IShopStorage shopStorage) { _orderStorage = orderStorage; _logger = logger; diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs index 03e517e..981528e 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -9,75 +9,88 @@ using System.Threading.Tasks; namespace BlacksmithWorkshopBusinessLogic.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 ILogger _logger; - public AbstractMailWorker(ILogger logger, - IMessageInfoLogic messageInfoLogic) - { - _logger = logger; - _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; - _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) - { - _messageInfoLogic.Create(mail); - } - } - protected abstract Task SendMailAsync(MailSendInfoBindingModel info); - protected abstract Task> - ReceiveMailAsync(); - } + 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 ILogger _logger; + + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic) + { + _logger = logger; + _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; + _logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", + _mailLogin, _mailPassword.Length, _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) + _messageInfoLogic.Create(mail); + } + public async void MailSendReplyAsync(MailReplySendInfoBindingModel 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) || string.IsNullOrEmpty(info.ParentMessageId)) + return; + _logger.LogDebug("Send Mail as reply: {To}, {Subject}, {parentId}", info.MailAddress, info.Subject, info.ParentMessageId); + string? messageId = await SendMailAsync(info); + if (string.IsNullOrEmpty(messageId)) + throw new InvalidOperationException("Непредвиденная ошибка при отправке сообщения в ответ"); + if (_messageInfoLogic.Create(new MessageInfoBindingModel + { + MessageId = messageId, + DateDelivery = DateTime.Now, + SenderName = _mailLogin, + IsReply = true, + Subject = info.Subject, + Body = info.Text, + })) + { + _messageInfoLogic.Update(new MessageInfoBindingModel() + { + MessageId = info.ParentMessageId, + ReplyMessageId = messageId, + IsReaded = true + }); + } + } + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + protected abstract Task> ReceiveMailAsync(); + } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/MailKitWorker.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/MailKitWorker.cs index bfa6985..7921e70 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/MailKitWorker.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/MailKitWorker.cs @@ -13,69 +13,86 @@ using System.Threading.Tasks; namespace BlacksmithWorkshopBusinessLogic.MailWorker { - public class MailKitWorker : AbstractMailWorker - { - public MailKitWorker(ILogger logger, IMessageInfoLogic - messageInfoLogic) : base(logger, messageInfoLogic) { } - 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 (AuthenticationException) - { } - finally - { - client.Disconnect(true); - } - }); - return list; - } - } + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic) : base(logger, messageInfoLogic) { } + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + string? resount = null; + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + try + { + ConfigurateSmtpClient(objSmtpClient); + CreateMessage(objMailMessage, info); + + if (info is MailReplySendInfoBindingModel replyInfo) + { + objMailMessage.Headers.Add("In-Reply-To", replyInfo.ParentMessageId); + objMailMessage.Headers.Add("References", replyInfo.ParentMessageId); + + string messageGuid = Guid.NewGuid().ToString(); + objMailMessage.Headers.Add("Message-Id", messageGuid); + resount = messageGuid; + } + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + return resount; + } + 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 (AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + private void CreateMessage(MailMessage objMailMessage, MailSendInfoBindingModel info) + { + 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; + } + private void ConfigurateSmtpClient(SmtpClient objSmtpClient) + { + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + } + } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/APIClient.cs b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/APIClient.cs index 1824cf9..51304df 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/APIClient.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/APIClient.cs @@ -9,7 +9,8 @@ namespace BlacksmithWorkshopClientApp { private static readonly HttpClient _client = new(); public static ClientViewModel? Client { get; set; } = null; - public static void Connect(IConfiguration configuration) + public static int MailPage { get; set; } = 1; + public static void Connect(IConfiguration configuration) { _client.BaseAddress = new Uri(configuration["IPAddress"]); _client.DefaultRequestHeaders.Accept.Clear(); diff --git a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Controllers/HomeController.cs b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Controllers/HomeController.cs index 21a93fb..6df7466 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Controllers/HomeController.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Controllers/HomeController.cs @@ -144,14 +144,14 @@ namespace BlacksmithWorkshopClientApp.Controllers return Math.Round(count * (_manufacture?.Price ?? 1), 2); } [HttpGet] - public IActionResult Mails() + public IActionResult Mails(int page = 1) { if (APIClient.Client == null) { return Redirect("~/Home/Enter"); } - return - View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + page = Math.Max(page, 1); + return View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}&page={page}")); } } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Home/Mails.cshtml b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Home/Mails.cshtml index 9741b90..707747a 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Home/Mails.cshtml +++ b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Home/Mails.cshtml @@ -1,5 +1,6 @@ @using BlacksmithWorkshopContracts.ViewModels @model List +@Url.ActionContext.RouteData.Values["page"] @{ ViewData["Title"] = "Mails"; } @@ -45,5 +46,22 @@ } +
+ @{ + int page = int.Parse(Context.Request.Query["page"]); +
+ +
+ if (page > 1) + { + <- + } + else + { +

<-

+ } + -> + } +
} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Shared/_Layout.cshtml b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Shared/_Layout.cshtml index f490f14..a1c6313 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Shared/_Layout.cshtml +++ b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Shared/_Layout.cshtml @@ -27,7 +27,7 @@ Личные данные