Morozov V.S. LabWork7 #8

Closed
VoldemarProger wants to merge 3 commits from LabWork7 into LabWork6
44 changed files with 2005 additions and 14 deletions

@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" />
<PackageReference Include="MailKit" Version="4.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
<PackageReference Include="System.Text.Encoding" Version="4.3.0" />

@ -8,6 +8,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace AutomobilePlantBusinessLogic.BusinessLogics
@ -96,13 +97,23 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
{
throw new ArgumentNullException("Нет имени клиента", nameof(model.ClientFIO));
}
if (string.IsNullOrEmpty(model.Email))
string email = model.Email;
Regex regex = new Regex(@"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");
Match match = regex.Match(email);
if (match.Success)
{
throw new ArgumentNullException("Нет почты клиента", nameof(model.Email));
throw new ArgumentNullException("Не верная почта клиента", nameof(model.Email));
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Нет пароля клиента", nameof(model.Password));
throw new ArgumentNullException("Не верный пароль клиента", nameof(model.Password));
}
string password = model.Password;
Regex regexPass = new Regex(@"^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$");
Match matchPass = regexPass.Match(password);
if (!matchPass.Success)
{
throw new ArgumentNullException("Не верный пароль клиента", nameof(model.Password));
}
_logger.LogInformation("Client. ClientName:{ClientName}. Id: { Id}", model.ClientFIO, model.Id);
var element = _clientStorage.GetElement(new ClientSearchModel

@ -0,0 +1,75 @@
using AbstractShopContracts.StoragesContracts;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.SearchModel;
using AutomobilePlantContracts.StoragesContracts;
using AutomobilePlantContracts.ViewModel;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantBusinessLogic.BusinessLogics
{
public class MessageLogic : IMessageInfoLogic
{
private readonly ILogger _logger;
private readonly IMessageInfoStorage _messageStorage;
public MessageLogic(ILogger<CarLogic> logger, IMessageInfoStorage messageStorage)
{
_logger = logger;
_messageStorage = messageStorage;
}
public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model)
{
_logger.LogInformation("ReadList");
var list = model == null ? _messageStorage.GetFullList() : _messageStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool Create(MessageInfoBindingModel model)
{
CheckModel(model);
if (_messageStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
private void CheckModel(MessageInfoBindingModel model, bool withParams =
true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.MessageId))
{
throw new ArgumentNullException("Нет айди письма", nameof(model.MessageId));
}
if (string.IsNullOrEmpty(model.Body))
{
throw new ArgumentNullException("Нет тела письма", nameof(model.Body));
}
if (string.IsNullOrEmpty(model.SenderName))
{
throw new ArgumentNullException("Нет отправителя письма", nameof(model.SenderName));
}
}
}
}

@ -1,4 +1,5 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantBusinessLogic.MailWorker;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.SearchModel;
using AutomobilePlantContracts.StoragesContracts;
@ -18,10 +19,14 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<ComponentLogic> logger, IOrderStorage orderStorage)
private readonly IClientStorage _clientStorage;
private readonly AbstractMailWorker _mailKitWorker;
public OrderLogic(ILogger<ComponentLogic> logger, IOrderStorage orderStorage, IClientStorage clientStorage, AbstractMailWorker abstractMailWorker)
{
_logger = logger;
_orderStorage = orderStorage;
_clientStorage = clientStorage;
_mailKitWorker = abstractMailWorker;
}
public bool CreateOrder(OrderBindingModel model)
@ -35,14 +40,20 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
}
model.Status = OrderStatus.Принят;
var newOrder = _orderStorage.Insert(model);
if (_orderStorage.Insert(model) == null)
if (newOrder == null)
{
model.Status = OrderStatus.Неизвестен;
_logger.LogWarning("Insert operation failed");
return false;
}
_mailKitWorker.MailSendAsync(new MailSendInfoBindingModel
{
MailAddress = (_clientStorage.GetElement(new ClientSearchModel { Id = newOrder.ClientId})).Email,
Subject = $"Заказ номер",
Text = $"Ваш заказ успешно принят. Машина: {model.CarName} в количестве: {model.Count} выйдет на сумму: {model.Sum}"
});
return true;
}
@ -89,6 +100,12 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
_logger.LogWarning("Update operation failed");
return false;
}
_mailKitWorker.MailSendAsync(new MailSendInfoBindingModel
{
MailAddress = (_clientStorage.GetElement(new ClientSearchModel { Id = model.ClientId })).Email,
Subject = $"Заказ номер {model.Id}",
Text = $"Ваш заказ переведен в статус {newStatus}"
});
return true;
}

@ -0,0 +1,97 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantBusinessLogic.MailWorker
{
public abstract class AbstractMailWorker
{
protected string _mailLogin = string.Empty;
protected string _mailPassword = string.Empty;
protected string _smtpClientHost = string.Empty;
protected int _smtpClientPort;
protected string _popHost = string.Empty;
protected int _popPort;
private readonly IMessageInfoLogic _messageInfoLogic;
private readonly ILogger _logger;
public AbstractMailWorker(ILogger<AbstractMailWorker> 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<List<MessageInfoBindingModel>> ReceiveMailAsync();
}
}

@ -0,0 +1,83 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using MailKit.Net.Pop3;
using MailKit.Security;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Net.Mail;
using System.Text;
using AutomobilePlantContracts.StoragesContracts;
using AutomobilePlantContracts.SearchModel;
namespace AutomobilePlantBusinessLogic.MailWorker
{
public class MailKitWorker : AbstractMailWorker
{
private readonly IClientStorage _clientStorage;
public MailKitWorker(ILogger<MailKitWorker> logger, IMessageInfoLogic messageInfoLogic, IClientStorage clientStorage) : base(logger, messageInfoLogic) { _clientStorage = clientStorage; }
protected override async Task SendMailAsync(MailSendInfoBindingModel info)
{
using var objMailMessage = new MailMessage();
using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort);
try
{
objMailMessage.From = new MailAddress(_mailLogin);
objMailMessage.To.Add(new MailAddress(info.MailAddress));
objMailMessage.Subject = info.Subject;
objMailMessage.Body = info.Text;
objMailMessage.SubjectEncoding = Encoding.UTF8;
objMailMessage.BodyEncoding = Encoding.UTF8;
objSmtpClient.UseDefaultCredentials = false;
objSmtpClient.EnableSsl = true;
objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword);
await Task.Run(() => objSmtpClient.Send(objMailMessage));
}
catch (Exception)
{
throw;
}
}
protected override async Task<List<MessageInfoBindingModel>> ReceiveMailAsync()
{
var list = new List<MessageInfoBindingModel>();
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 = DateTime.SpecifyKind(message.Date.DateTime, DateTimeKind.Utc),
ClientId = _clientStorage.GetElement(new ClientSearchModel { Email = mail.Address }).Id,
MessageId = message.MessageId,
SenderName = mail.Address,
Subject = message.Subject,
Body = message.TextBody
}); ;
}
}
}
catch (AuthenticationException)
{ }
finally
{
client.Disconnect(true);
}
});
return list;
}
}
}

@ -0,0 +1,17 @@
namespace AutomobilePlantContracts.BindingModels
{
public class MailConfigBindingModel
{
public string MailLogin { get; set; } = string.Empty;
public string MailPassword { get; set; } = string.Empty;
public string SmtpClientHost { get; set; } = string.Empty;
public int SmtpClientPort { get; set; }
public string PopHost { get; set; } = string.Empty;
public int PopPort { get; set; }
}
}

@ -0,0 +1,11 @@
namespace AutomobilePlantContracts.BindingModels
{
public class MailSendInfoBindingModel
{
public string MailAddress { get; set; } = string.Empty;
public string Subject { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty;
}
}

@ -0,0 +1,19 @@
using AutomobilePlantDataModels.Models;
namespace AutomobilePlantContracts.BindingModels
{
public class MessageInfoBindingModel : IMessageInfoModel
{
public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; }
public string SenderName { get; set; } = string.Empty;
public string Subject { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public DateTime DateDelivery { get; set; }
}
}

@ -0,0 +1,13 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.SearchModel;
using AutomobilePlantContracts.ViewModel;
namespace AutomobilePlantContracts.BusinessLogicsContracts
{
public interface IMessageInfoLogic
{
List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model);
bool Create(MessageInfoBindingModel model);
}
}

@ -0,0 +1,9 @@
namespace AutomobilePlantContracts.SearchModel
{
public class MessageInfoSearchModel
{
public int? ClientId { get; set; }
public string? MessageId { get; set; }
}
}

@ -0,0 +1,17 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.SearchModel;
using AutomobilePlantContracts.ViewModel;
namespace AbstractShopContracts.StoragesContracts
{
public interface IMessageInfoStorage
{
List<MessageInfoViewModel> GetFullList();
List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model);
MessageInfoViewModel? GetElement(MessageInfoSearchModel model);
MessageInfoViewModel? Insert(MessageInfoBindingModel model);
}
}

@ -0,0 +1,24 @@
using AutomobilePlantDataModels.Models;
using System.ComponentModel;
namespace AutomobilePlantContracts.ViewModel
{
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;
}
}

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantDataModels.Models
{
public interface IMessageInfoModel
{
string MessageId { get; }
int? ClientId { get; }
string SenderName { get; }
DateTime DateDelivery { get; }
string Subject { get; }
string Body { get; }
}
}

@ -15,6 +15,7 @@ namespace AutomobilePlantListImplement
public List<Car> Cars { get; set; }
public List<Client> Clients { get; set; }
public List<Implementer> Implementers { get; set; }
public List<MessageInfoModel> Messages { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
@ -22,6 +23,7 @@ namespace AutomobilePlantListImplement
Cars = new List<Car>();
Clients = new List<Client>();
Implementers = new List<Implementer>();
Messages = new List<MessageInfoModel>();
}
public static DataListSingleton GetInstance()
{

@ -0,0 +1,98 @@
using AbstractShopContracts.StoragesContracts;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.SearchModel;
using AutomobilePlantContracts.ViewModel;
using AutomobilePlantListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantListImplement.Implements
{
public class MessageInfoStorage : IMessageInfoStorage
{
private readonly DataListSingleton _source;
public MessageInfoStorage()
{
_source = DataListSingleton.GetInstance();
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
if (string.IsNullOrEmpty(model.MessageId) )
{
return null;
}
foreach (var message in _source.Messages)
{
if (!string.IsNullOrEmpty(model.MessageId) && message.MessageId.Equals(model.MessageId) )
{
return message.GetViewModel;
}
}
return null;
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
var result = new List<MessageInfoViewModel>();
if (!model.ClientId.HasValue)
{
return result;
}
foreach (var message in _source.Messages)
{
if (message.ClientId == model.ClientId)
{
result.Add(message.GetViewModel);
}
}
return result;
}
public List<MessageInfoViewModel> GetFullList()
{
var result = new List<MessageInfoViewModel>();
foreach (var message in _source.Messages)
{
result.Add(message.GetViewModel);
}
return result;
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
model.MessageId = "1";
foreach (var message in _source.Messages)
{
if (model.MessageId.Equals(message.MessageId))
{
model.MessageId = (Convert.ToInt32(message.MessageId) +1).ToString();
}
}
var newMes = MessageInfoModel.Create(model);
if (newMes == null)
{
return null;
}
_source.Messages.Add(newMes);
return newMes.GetViewModel;
}
}
}

@ -0,0 +1,54 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModel;
using AutomobilePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantListImplement.Models
{
public class MessageInfoModel : IMessageInfoModel
{
public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; }
public string SenderName { get; set; } = string.Empty;
public DateTime DateDelivery { get; set; }
public string Subject { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public static MessageInfoModel? Create(MessageInfoBindingModel? model)
{
if (model == null)
{
return null;
}
return new MessageInfoModel()
{
MessageId = model.MessageId,
ClientId = model.ClientId,
SenderName = model.SenderName,
DateDelivery = model.DateDelivery,
Subject = model.Subject,
Body = model.Body,
};
}
public MessageInfoViewModel GetViewModel => new()
{
MessageId = MessageId,
ClientId = ClientId,
SenderName = SenderName,
DateDelivery = DateDelivery,
Subject = Subject,
Body = Body,
};
}
}

@ -147,5 +147,14 @@ namespace AutoPlantClientApp.Controllers
var prod = APIClient.GetRequest<CarViewModel>($"api/main/getcar?carId={car}");
return count * (prod?.Price ?? 1);
}
[HttpGet]
public IActionResult Mails()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<MessageInfoViewModel>>($"api/client/getmessages?ClientId={APIClient.Client.Id}"));
}
}
}

@ -0,0 +1,54 @@
@using AutomobilePlantContracts.ViewModel
@model List<MessageInfoViewModel>
@{
ViewData["Title"] = "Mails";
}
<div class="text-center">
<h1 class="display-4">Заказы</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<table class="table">
<thead>
<tr>
<th>
Дата письма
</th>
<th>
Заголовок
</th>
<th>
Текст
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.DateDelivery)
</td>
<td>
@Html.DisplayFor(modelItem => item.Subject)
</td>
<td>
@Html.DisplayFor(modelItem => item.Body)
</td>
</tr>
}
</tbody>
</table>
}
</div>

@ -29,6 +29,9 @@
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Mails">Письма</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Enter">Вход</a>
</li>

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SmtpClientHost" value="smtp.gmail.com" />
<add key="SmtpClientPort" value="587" />
<add key="PopHost" value="pop.gmail.com" />
<add key="PopPort" value="995" />
<add key="MailLogin" value="labrpp89@gmail.com" />
<add key="MailPassword" value="swly dzcy ccaz vdvr" />
</appSettings>
</configuration>

@ -37,4 +37,10 @@
<ProjectReference Include="..\AutomobilePlantDataBaseImplements\AutomobilePlantDataBaseImplements.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="App.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

@ -43,6 +43,7 @@
this.CreateOrderButton = new System.Windows.Forms.Button();
this.IssuedOrderButton = new System.Windows.Forms.Button();
this.UpdateListButton = new System.Windows.Forms.Button();
this.письмаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.MenuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.DataGridView)).BeginInit();
this.SuspendLayout();
@ -55,7 +56,8 @@
this.отчетыToolStripMenuItem,
this.клиентыToolStripMenuItem,
this.исполнителиToolStripMenuItem,
this.начатьРаботуToolStripMenuItem});
this.начатьРаботуToolStripMenuItem,
this.письмаToolStripMenuItem});
this.MenuStrip.Location = new System.Drawing.Point(0, 0);
this.MenuStrip.Name = "MenuStrip";
this.MenuStrip.Padding = new System.Windows.Forms.Padding(7, 3, 0, 3);
@ -182,6 +184,13 @@
this.UpdateListButton.UseVisualStyleBackColor = true;
this.UpdateListButton.Click += new System.EventHandler(this.UpdateListButton_Click);
//
// письмаToolStripMenuItem
//
this.письмаToolStripMenuItem.Name = "письмаToolStripMenuItem";
this.письмаToolStripMenuItem.Size = new System.Drawing.Size(77, 24);
this.письмаToolStripMenuItem.Text = "Письма";
this.письмаToolStripMenuItem.Click += new System.EventHandler(this.письмаToolStripMenuItem_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
@ -222,5 +231,6 @@
private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem;
private ToolStripMenuItem начатьРаботуToolStripMenuItem;
private ToolStripMenuItem письмаToolStripMenuItem;
}
}

@ -256,5 +256,14 @@ namespace AutomobilePlant
MessageBox.Show("Процесс обработки запущен", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void письмаToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormMessages));
if (service is FormMessages form)
{
form.ShowDialog();
}
}
}
}

@ -0,0 +1,72 @@
namespace AutomobilePlant
{
partial class FormMessages
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dataGridView = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.AllowUserToAddRows = false;
this.dataGridView.AllowUserToDeleteRows = false;
this.dataGridView.BackgroundColor = System.Drawing.SystemColors.ControlLightLight;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Dock = System.Windows.Forms.DockStyle.Left;
this.dataGridView.Location = new System.Drawing.Point(0, 0);
this.dataGridView.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.dataGridView.Name = "dataGridView";
this.dataGridView.ReadOnly = true;
this.dataGridView.RowHeadersVisible = false;
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView.Size = new System.Drawing.Size(617, 480);
this.dataGridView.TabIndex = 0;
//
// FormMessages
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(619, 480);
this.Controls.Add(this.dataGridView);
this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.Name = "FormMessages";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Клиенты";
this.Load += new System.EventHandler(this.FormMessages_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.DataGridView dataGridView;
}
}

@ -0,0 +1,58 @@
using AbstractShopView;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.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 AutomobilePlant
{
public partial class FormMessages : Form
{
private readonly ILogger _logger;
private readonly IMessageInfoLogic _logic;
public FormMessages(ILogger<FormClients> logger, IMessageInfoLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormMessages_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["MessageId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["SenderName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка клиентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки клиентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

@ -9,6 +9,9 @@ using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System.Drawing;
using AbstractShopView;
using AbstractShopContracts.StoragesContracts;
using AutomobilePlantBusinessLogic.MailWorker;
using AutomobilePlantContracts.BindingModels;
namespace AutomobilePlant
{
@ -28,7 +31,30 @@ namespace AutomobilePlant
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
try
{
var mailSender = _serviceProvider.GetService<AbstractMailWorker>();
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<ILogger>();
logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé");
}
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
}
private static void ConfigureServices(ServiceCollection services)
{
@ -42,13 +68,17 @@ namespace AutomobilePlant
services.AddTransient<ICarStorage, CarStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IMessageInfoStorage, MessageStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<ICarLogic, CarLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IMessageInfoLogic, MessageLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
@ -67,7 +97,9 @@ namespace AutomobilePlant
services.AddTransient<FormClients>();
services.AddTransient<FormImplementer>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormMessages>();
}
private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck();
}
}

@ -29,5 +29,7 @@ namespace AutomobilePlantDataBaseImplements
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; }
public virtual DbSet<MessageInfo> Messages { set; get; }
}
}

@ -34,7 +34,7 @@ namespace AutomobilePlantDataBaseImplements.Implements
.Where(x => x.ClientFIO.Contains(model.ClientFIO))
.Select(x => x.GetViewModel)
.ToList();
}else if (!string.IsNullOrEmpty(model.Email))
}else if (!string.IsNullOrEmpty(model.Email)) // Поиск клиента по логину
{
return context.Clients
.Where(x => x.Email.Contains(model.Email))

@ -0,0 +1,68 @@
using AbstractShopContracts.StoragesContracts;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.SearchModel;
using AutomobilePlantContracts.ViewModel;
using AutomobilePlantDataBaseImplements.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantDataBaseImplements.Implements
{
public class MessageStorage : IMessageInfoStorage
{
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
if (string.IsNullOrEmpty(model.MessageId) )
{
return null;
}
using var context = new AutoPlantDataBase();
return context.Messages
.Include(x => x.client)
.FirstOrDefault(x => x.MessageId.Equals(model.MessageId))
?.GetViewModel;
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
if (!model.ClientId.HasValue)
{
return new();
}
using var context = new AutoPlantDataBase();
return context.Messages
.Include(x => x.client)
.Where(x => x.ClientId == model.ClientId)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<MessageInfoViewModel> GetFullList()
{
using var context = new AutoPlantDataBase();
return context.Messages
.Include(x => x.client)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
using var context = new AutoPlantDataBase();
var newMes = MessageInfo.Create(model);
if (newMes == null)
{
return null;
}
context.Messages.Add(newMes);
context.SaveChanges();
return newMes.GetViewModel;
}
}
}

@ -0,0 +1,312 @@
// <auto-generated />
using System;
using AutomobilePlantDataBaseImplements;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace AutomobilePlantDataBaseImplements.Migrations
{
[DbContext(typeof(AutoPlantDataBase))]
[Migration("20230427155513_EmailAdd")]
partial class EmailAdd
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Car", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("CarName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("Id");
b.ToTable("Cars");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.CarComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("CarId")
.HasColumnType("integer");
b.Property<int>("ComponentId")
.HasColumnType("integer");
b.Property<int>("Count")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("CarId");
b.HasIndex("ComponentId");
b.ToTable("CarComponents");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Cost")
.HasColumnType("double precision");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Qualification")
.HasColumnType("integer");
b.Property<int>("WorkExperience")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("text");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("ClientId")
.IsRequired()
.HasColumnType("integer");
b.Property<DateTime>("DateDelivery")
.HasColumnType("timestamp with time zone");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("text");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("Messages");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("CarId")
.HasColumnType("integer");
b.Property<string>("CarName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ClientId")
.HasColumnType("integer");
b.Property<string>("ClientName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<DateTime>("DateCreate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime?>("DateImplement")
.HasColumnType("timestamp with time zone");
b.Property<int?>("ImplementerId")
.HasColumnType("integer");
b.Property<string>("ImplementerName")
.HasColumnType("text");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("CarId");
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.CarComponent", b =>
{
b.HasOne("AutomobilePlantDataBaseImplements.Models.Car", "Car")
.WithMany("Components")
.HasForeignKey("CarId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AutomobilePlantDataBaseImplements.Models.Component", "Component")
.WithMany("CarComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Car");
b.Navigation("Component");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.MessageInfo", b =>
{
b.HasOne("AutomobilePlantDataBaseImplements.Models.Client", "client")
.WithMany("Messages")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("client");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Order", b =>
{
b.HasOne("AutomobilePlantDataBaseImplements.Models.Car", "car")
.WithMany("Orders")
.HasForeignKey("CarId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AutomobilePlantDataBaseImplements.Models.Client", "client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AutomobilePlantDataBaseImplements.Models.Implementer", "implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("car");
b.Navigation("client");
b.Navigation("implementer");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Car", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Client", b =>
{
b.Navigation("Messages");
b.Navigation("Orders");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Component", b =>
{
b.Navigation("CarComponents");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Implementer", b =>
{
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

@ -0,0 +1,49 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AutomobilePlantDataBaseImplements.Migrations
{
/// <inheritdoc />
public partial class EmailAdd : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Messages",
columns: table => new
{
MessageId = table.Column<string>(type: "text", nullable: false),
ClientId = table.Column<int>(type: "integer", nullable: false),
SenderName = table.Column<string>(type: "text", nullable: false),
DateDelivery = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
Subject = table.Column<string>(type: "text", nullable: false),
Body = table.Column<string>(type: "text", 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",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Messages_ClientId",
table: "Messages",
column: "ClientId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Messages");
}
}
}

@ -0,0 +1,309 @@
// <auto-generated />
using System;
using AutomobilePlantDataBaseImplements;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace AutomobilePlantDataBaseImplements.Migrations
{
[DbContext(typeof(AutoPlantDataBase))]
[Migration("20230427192728_EmailAdd2")]
partial class EmailAdd2
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Car", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("CarName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("Id");
b.ToTable("Cars");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.CarComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("CarId")
.HasColumnType("integer");
b.Property<int>("ComponentId")
.HasColumnType("integer");
b.Property<int>("Count")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("CarId");
b.HasIndex("ComponentId");
b.ToTable("CarComponents");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Cost")
.HasColumnType("double precision");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Qualification")
.HasColumnType("integer");
b.Property<int>("WorkExperience")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("text");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("ClientId")
.HasColumnType("integer");
b.Property<DateTime>("DateDelivery")
.HasColumnType("timestamp with time zone");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("text");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("Messages");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("CarId")
.HasColumnType("integer");
b.Property<string>("CarName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ClientId")
.HasColumnType("integer");
b.Property<string>("ClientName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<DateTime>("DateCreate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime?>("DateImplement")
.HasColumnType("timestamp with time zone");
b.Property<int?>("ImplementerId")
.HasColumnType("integer");
b.Property<string>("ImplementerName")
.HasColumnType("text");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("CarId");
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.CarComponent", b =>
{
b.HasOne("AutomobilePlantDataBaseImplements.Models.Car", "Car")
.WithMany("Components")
.HasForeignKey("CarId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AutomobilePlantDataBaseImplements.Models.Component", "Component")
.WithMany("CarComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Car");
b.Navigation("Component");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.MessageInfo", b =>
{
b.HasOne("AutomobilePlantDataBaseImplements.Models.Client", "client")
.WithMany("Messages")
.HasForeignKey("ClientId");
b.Navigation("client");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Order", b =>
{
b.HasOne("AutomobilePlantDataBaseImplements.Models.Car", "car")
.WithMany("Orders")
.HasForeignKey("CarId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AutomobilePlantDataBaseImplements.Models.Client", "client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AutomobilePlantDataBaseImplements.Models.Implementer", "implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("car");
b.Navigation("client");
b.Navigation("implementer");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Car", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Client", b =>
{
b.Navigation("Messages");
b.Navigation("Orders");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Component", b =>
{
b.Navigation("CarComponents");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Implementer", b =>
{
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

@ -0,0 +1,59 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AutomobilePlantDataBaseImplements.Migrations
{
/// <inheritdoc />
public partial class EmailAdd2 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Messages_Clients_ClientId",
table: "Messages");
migrationBuilder.AlterColumn<int>(
name: "ClientId",
table: "Messages",
type: "integer",
nullable: true,
oldClrType: typeof(int),
oldType: "integer");
migrationBuilder.AddForeignKey(
name: "FK_Messages_Clients_ClientId",
table: "Messages",
column: "ClientId",
principalTable: "Clients",
principalColumn: "Id");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Messages_Clients_ClientId",
table: "Messages");
migrationBuilder.AlterColumn<int>(
name: "ClientId",
table: "Messages",
type: "integer",
nullable: false,
defaultValue: 0,
oldClrType: typeof(int),
oldType: "integer",
oldNullable: true);
migrationBuilder.AddForeignKey(
name: "FK_Messages_Clients_ClientId",
table: "Messages",
column: "ClientId",
principalTable: "Clients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
}

@ -140,6 +140,36 @@ namespace AutomobilePlantDataBaseImplements.Migrations
b.ToTable("Implementers");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("text");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("ClientId")
.HasColumnType("integer");
b.Property<DateTime>("DateDelivery")
.HasColumnType("timestamp with time zone");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("text");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("Messages");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Order", b =>
{
b.Property<int>("Id")
@ -213,6 +243,15 @@ namespace AutomobilePlantDataBaseImplements.Migrations
b.Navigation("Component");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.MessageInfo", b =>
{
b.HasOne("AutomobilePlantDataBaseImplements.Models.Client", "client")
.WithMany("Messages")
.HasForeignKey("ClientId");
b.Navigation("client");
});
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Order", b =>
{
b.HasOne("AutomobilePlantDataBaseImplements.Models.Car", "car")
@ -247,6 +286,8 @@ namespace AutomobilePlantDataBaseImplements.Migrations
modelBuilder.Entity("AutomobilePlantDataBaseImplements.Models.Client", b =>
{
b.Navigation("Messages");
b.Navigation("Orders");
});

@ -30,6 +30,9 @@ namespace AutomobilePlantDataBaseImplements.Models
[ForeignKey("ClientId")]
public virtual List<Order> Orders { get; set; } = new();
[ForeignKey("ClientId")]
public virtual List<MessageInfo> Messages { get; set; } = new();
public static Client Create( ClientBindingModel model)
{
return new Client()

@ -0,0 +1,55 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModel;
using AutomobilePlantDataModels.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantDataBaseImplements.Models
{
public class MessageInfo : IMessageInfoModel
{
[Key]
public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; }
public Client? client { get; private set; }
public string SenderName { get; set; } = string.Empty;
public DateTime DateDelivery { get; set; }
public string Subject { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public static MessageInfo? Create(MessageInfoBindingModel? model)
{
if (model == null)
{
return null;
}
return new MessageInfo()
{
MessageId = model.MessageId,
ClientId = model.ClientId,
SenderName = model.SenderName,
DateDelivery = model.DateDelivery,
Subject = model.Subject,
Body = model.Body,
};
}
public MessageInfoViewModel GetViewModel => new()
{
MessageId = MessageId,
ClientId = ClientId,
SenderName = SenderName,
DateDelivery = DateDelivery,
Subject = Subject,
Body = Body,
};
}
}

@ -16,11 +16,13 @@ namespace AutomomilePlantFileImplement
private readonly string CarFileName = "Car.xml";
private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
private readonly string MessageFileName = "Message.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Car> Cars { get; private set; }
public List<Client> Clients { get; private set; }
public List<Implementer> Implementers { get; private set; }
public List<MessageInfo> Messages { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
@ -39,6 +41,8 @@ namespace AutomomilePlantFileImplement
"Cars", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x
=> x.GetXElement);
public void SaveMessages() => SaveData(Messages, MessageFileName, "Messages", x
=> x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x =>
@ -50,6 +54,7 @@ namespace AutomomilePlantFileImplement
Implementers = LoadData(ImplementerFileName, "Implementers", x =>
Implementer.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Messages = LoadData(MessageFileName, "Message", x => MessageInfo.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName,
Func<XElement, T> selectFunction)

@ -0,0 +1,74 @@
using AbstractShopContracts.StoragesContracts;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.SearchModel;
using AutomobilePlantContracts.ViewModel;
using AutomobilePlantDataModels.Models;
using AutomomilePlantFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomomilePlantFileImplement.Implements
{
public class MessageStorage : IMessageInfoStorage
{
private readonly DataFileSingleton source;
public MessageStorage()
{
source = DataFileSingleton.GetInstance();
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
if (string.IsNullOrEmpty(model.MessageId) )
{
return null;
}
return source.Messages
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.MessageId) && x.MessageId.Equals(model.MessageId)))
?.GetViewModel;
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
if (!model.ClientId.HasValue)
{
return new();
}
return source.Messages
.Where(x => x.ClientId== model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
}
public List<MessageInfoViewModel> GetFullList()
{
return source.Messages
.Select(x => x.GetViewModel)
.ToList();
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
if (source.Messages.Count > 0)
{
var id = source.Messages.Count + 1;
model.MessageId = id.ToString();
}
else
model.MessageId = "1";
var newMes = MessageInfo.Create(model);
if (newMes == null)
{
return null;
}
source.Messages.Add(newMes);
source.SaveMessages();
return newMes.GetViewModel;
}
}
}

@ -0,0 +1,77 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModel;
using AutomobilePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AutomomilePlantFileImplement.Models
{
public class MessageInfo : IMessageInfoModel
{
public string MessageId {get;set;} = string.Empty;
public int? ClientId { get; set; }
public string SenderName { get; set; } = string.Empty;
public DateTime DateDelivery { get; set; }
public string Subject { get; set; } = string.Empty;
public string Body { get; set;} = string.Empty;
public static MessageInfo? Create(MessageInfoBindingModel model)
{
if (model == null)
{
return null;
}
return new MessageInfo()
{
MessageId = model.MessageId,
ClientId = model.ClientId,
SenderName = model.SenderName,
DateDelivery = model.DateDelivery,
Subject = model.Subject,
Body = model.Body,
};
}
public static MessageInfo? Create(XElement element)
{
if (element == null)
{
return null;
}
return new MessageInfo()
{
MessageId =element.Attribute("MessageId")!.Value,
ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value),
SenderName = element.Attribute("SenderName")!.Value,
DateDelivery = DateTime.Parse(element.Element("DateDelivery")!.Value),
Subject = element.Attribute("Subject")!.Value,
Body = element.Attribute("Body")!.Value,
};
}
public MessageInfoViewModel GetViewModel => new()
{
MessageId = MessageId,
ClientId = ClientId,
SenderName = SenderName,
DateDelivery = DateDelivery,
Subject = Subject,
Body = Body,
};
public XElement GetXElement => new("MessageInfo",
new XAttribute("MessageId", MessageId),
new XElement("ClientId", ClientId.ToString()),
new XElement("SenderName", SenderName),
new XElement("DateDelivery", DateDelivery.ToString()),
new XElement("Subject", Subject),
new XElement("Body", Body)
);
}
}

@ -13,11 +13,12 @@ namespace AutoplantRestApi.Controllers
private readonly ILogger _logger;
private readonly IClientLogic _logic;
public ClientController(IClientLogic logic, ILogger<ClientController> logger)
private IMessageInfoLogic _messageLogic;
public ClientController(IClientLogic logic, ILogger<ClientController> logger, IMessageInfoLogic messageLogic)
{
_logger = logger;
_logic = logic;
_messageLogic = messageLogic;
}
[HttpGet]
@ -65,5 +66,21 @@ namespace AutoplantRestApi.Controllers
throw;
}
}
[HttpGet]
public List<MessageInfoViewModel>? GetMessages(int clientId)
{
try
{
return _messageLogic.ReadList(new MessageInfoSearchModel
{
ClientId = clientId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения писем клиента");
throw;
}
}
}
}

@ -1,4 +1,7 @@
using AbstractShopContracts.StoragesContracts;
using AutomobilePlantBusinessLogic.BusinessLogics;
using AutomobilePlantBusinessLogic.MailWorker;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.StoragesContracts;
using AutomobilePlantDataBaseImplements.Implements;
@ -12,11 +15,17 @@ builder.Logging.AddLog4Net("log4net.config");
// Add services to the container.
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IImplementerStorage, ImplementerStorage>();
builder.Services.AddTransient<ICarStorage, CarStorage>();
builder.Services.AddTransient<IMessageInfoStorage, MessageStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IImplementerLogic, ImplementerLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<ICarLogic, CarLogic>();
builder.Services.AddTransient<IMessageInfoLogic, MessageLogic>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
@ -27,7 +36,16 @@ builder.Services.AddSwaggerGen(c =>
});
var app = builder.Build();
var mailSender = app.Services.GetService<AbstractMailWorker>();
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())
{

@ -5,5 +5,12 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "labrpp89@gmail.com",
"MailPassword": "swly dzcy ccaz vdvr"
}