This commit is contained in:
Sasylika4598 2024-06-21 22:56:11 +04:00
parent 0475efd785
commit b37d1e9da1
45 changed files with 1656 additions and 76 deletions

View File

@ -1,8 +1,10 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SecurirySystemClientApp.Models;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using System.Diagnostics;
using System.Text;
namespace SecurirySystemClientApp.Controllers
{
@ -133,6 +135,15 @@ namespace SecurirySystemClientApp.Controllers
var prod = APIClient.GetRequest<SecureViewModel>($"api/main/getsecure?secureId={secure}");
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}"));
}
}
}

View File

@ -0,0 +1,48 @@
@using SecuritySystemContracts.ViewModels
@model List<MessageInfoViewModel>
@{
ViewData["Title"] = "Почта";
}
<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>

View File

@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace SecurirySystemClientApp.Views.Home
{
public class MailsModel : PageModel
{
public void OnGet()
{
}
}
}

View File

@ -6,7 +6,7 @@
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-4">Email:</div>
<div class="col-8"><input type="text" name="login" /></div>
</div>
<div class="row">

View File

@ -1,52 +1,55 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - SecuritySystemClientApp</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp action="Index">Системы безопасности</a>
<button class="navbar-toggler" type="button" data toggle="collapse" data-target=".navbar-collapse" aria controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp area="" asp-controller="Home" asp-action="Index">Заказы</a>
</li>
<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="Enter">Вход</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp area="" asp-controller="Home" asp-action="Register">Регистрация</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - SecuritySystemClientApp</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg white border-bottom box-shadow mb-3">
<div class="container">
&copy; 2024 - SecuritySystem - <a asp-area="" asp controller="Home" asp-action="Privacy">Личные данные</a>
<a class="navbar-brand" asp-area="" asp-controller="Home" asp action="Index">Системы безопасности</a>
<button class="navbar-toggler" type="button" data toggle="collapse" data-target=".navbar-collapse" aria controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp area="" asp-controller="Home" asp-action="Index">Заказы</a>
</li>
<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>
<li class="nav-item">
<a class="nav-link text-dark" asp area="" asp-controller="Home" asp-action="Register">Регистрация</a>
</li>
</ul>
</div>
</div>
</footer>
<script src="~/js/site.js" asp-append-version="true"></script>
@RenderSection("Scripts", required: false)
</body>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2024 - SecuritySystem - <a asp-area="" asp controller="Home" asp-action="Privacy">Личные данные</a>
</div>
</footer>
<script src="~/js/site.js" asp-append-version="true"></script>
@RenderSection("Scripts", required: false)
</body>
</html>

View File

@ -19,7 +19,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SecuritySystemDatabaseImple
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SecuritySystemRestApi", "SecuritySystemRestApi\SecuritySystemRestApi.csproj", "{A45C62CE-D0FF-4347-A6FF-773A6563BDA9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SecurirySystemClientApp", "SecurirySystemClientApp\SecurirySystemClientApp.csproj", "{4DEDBF73-8644-48A2-B9FC-604F96EE0324}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SecurirySystemClientApp", "SecurirySystemClientApp\SecurirySystemClientApp.csproj", "{4DEDBF73-8644-48A2-B9FC-604F96EE0324}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution

View File

@ -4,6 +4,7 @@ using SecuritySystemContracts.BusinessLogicsContracts;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;
using System.Text.RegularExpressions;
namespace SecuritySystemBusinessLogic.BusinessLogics
{
@ -93,10 +94,22 @@ namespace SecuritySystemBusinessLogic.BusinessLogics
{
throw new ArgumentNullException("Нет email клиента", nameof(model.Email));
}
string regexepEmailPattern = "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$";
Regex regexpEmail = new Regex(regexepEmailPattern);
if (!regexpEmail.IsMatch(model.Email))
{
throw new ArgumentException("Email не валидный");
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Нет пароля клиента", nameof(model.Password));
}
string regexpPasswordPattern = "^((\\w+\\d+\\W+)|(\\w+\\W+\\d+)|(\\d+\\w+\\W+)|(\\d+\\W+\\w+)|(\\W+\\w+\\d+)|(\\W+\\d+\\\r\nw+))[\\w\\d\\W]*$";
Regex regexPassword = new Regex(regexpPasswordPattern);
if (!regexPassword.IsMatch(model.Password))
{
throw new ArgumentException("Пароль не соответствует требованиям безопасности");
}
if (string.IsNullOrEmpty(model.ClientFIO))
{
throw new ArgumentNullException("Нет фио клиента", nameof(model.ClientFIO));

View File

@ -0,0 +1,78 @@
using DocumentFormat.OpenXml.Drawing;
using Microsoft.Extensions.Logging;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.BusinessLogicsContracts;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;
namespace SecuritySystemBusinessLogic.BusinessLogics
{
public class MessageInfoLogic : IMessageInfoLogic
{
private readonly ILogger _logger;
private readonly IMessageInfoStorage _messageInfoStorage;
private readonly IClientLogic _clientLogic;
public MessageInfoLogic(ILogger<MessageInfoLogic> logger, IMessageInfoStorage messageInfoStorage, IClientLogic clientLogic)
{
_logger = logger;
_messageInfoStorage = messageInfoStorage;
_clientLogic = clientLogic;
}
public bool Create(MessageInfoBindingModel model)
{
if (!CheckModelIsValid(model))
{
return false;
}
var client = _clientLogic.ReadElement(new ClientSearchModel { Email = model.SenderName });
if (client != null)
{
model.ClientId = client.Id;
}
if (_messageInfoStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model)
{
_logger.LogInformation("ReadList. MessageId:{Id}", model?.MessageId);
var list = model == null ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
private bool CheckModelIsValid(MessageInfoBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return true;
}
_logger.LogInformation("MessageInfo. MessageId: {MessageId}", model.MessageId);
var element = _messageInfoStorage.GetElement(new MessageInfoSearchModel
{
MessageId = model.MessageId
});
if (element != null)
{
_logger.LogDebug("Пиьсмо с таким идентификатором уже есть");
return false;
}
return true;
}
}
}

View File

@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging;
using SecuritySystemBusinessLogic.MailWorker;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.BusinessLogicsContracts;
using SecuritySystemContracts.SearchModels;
@ -12,12 +13,16 @@ namespace SecuritySystemBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
private readonly IClientStorage _clientStorage;
static readonly object locker = new object();
private readonly AbstractMailWorker _abstractMailWorker;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, AbstractMailWorker abstractMailWorker, IClientStorage clientStorage)
{
_logger = logger;
_orderStorage = orderStorage;
_abstractMailWorker = abstractMailWorker;
_clientStorage = clientStorage;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
@ -37,43 +42,55 @@ namespace SecuritySystemBusinessLogic.BusinessLogics
{
CheckModel(model);
if (model.Status != OrderStatus.Неизвестен) return false;
model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null)
var inserted = _orderStorage.Insert(model);
if (inserted == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
model.Id = inserted.Id;
return ChangeStatus(model, OrderStatus.Принят);
}
public bool ChangeStatus(OrderBindingModel model, OrderStatus status)
{
CheckModel(model, false);
var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (element == null)
var order = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (order == null)
{
_logger.LogWarning("Read operation failed");
return false;
}
if (element.Status != status - 1)
if (order.Status != status - 1)
{
_logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный");
}
if (element.ImplementerId.HasValue)
if (order.ImplementerId.HasValue)
{
model.ImplementerId = element.ImplementerId;
model.ImplementerId = order.ImplementerId;
}
OrderStatus oldStatus = model.Status;
model.Status = status;
if (model.Status == OrderStatus.Выдан)
model.DateImplement = DateTime.Now;
if (_orderStorage.Update(model) == null)
var updatedOrder = _orderStorage.Update(model);
if (updatedOrder == null)
{
model.Status = oldStatus;
_logger.LogWarning("Update operation failed");
return false;
}
var orderClient = _clientStorage.GetElement(new ClientSearchModel { Id = updatedOrder.ClientId });
if (orderClient != null)
{
SendMail(orderClient, updatedOrder);
}
return true;
}
@ -140,5 +157,37 @@ namespace SecuritySystemBusinessLogic.BusinessLogics
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
private void SendMail(ClientViewModel clientView, OrderViewModel orderView)
{
if (clientView == null || orderView == null)
{
return;
}
MailSendInfoBindingModel mailSendInfoBindingModel;
string subject = $"Заказ #{orderView.Id}";
string orderInfo = $"Ваш заказ #{orderView.Id} от {orderView.DateCreate} стоимостью {orderView.Sum}";
if (orderView.Status == OrderStatus.Принят)
{
mailSendInfoBindingModel = new MailSendInfoBindingModel
{
MailAddress = clientView.Email,
Subject = subject,
Text = orderInfo + " был принят"
};
}
else
{
mailSendInfoBindingModel = new MailSendInfoBindingModel
{
MailAddress = clientView.Email,
Subject = subject,
Text = orderInfo + $" поменял статус на {orderView.Status}"
};
}
_abstractMailWorker.MailSendAsync(mailSendInfoBindingModel);
}
}
}

View File

@ -26,10 +26,16 @@ namespace SecuritySystemBusinessLogic.BusinessLogics
_logger.LogWarning("DoWork. Implementers is null");
return;
}
var orders = _orderLogic.ReadList(new OrderSearchModel
var orders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Принят });
var inWorkOrders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Выполняется });
if (orders != null && inWorkOrders != null)
{
Status = OrderStatus.Принят
});
orders.AddRange(inWorkOrders);
}
else
{
orders = inWorkOrders;
}
if (orders == null || orders.Count == 0)
{
_logger.LogWarning("DoWork. Orders is null or empty");

View File

@ -0,0 +1,74 @@
using Microsoft.Extensions.Logging;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.BusinessLogicsContracts;
namespace SecuritySystemBusinessLogic.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();
}
}

View File

@ -0,0 +1,77 @@
using Microsoft.Extensions.Logging;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.BusinessLogicsContracts;
using System.Net.Mail;
using System.Net;
using System.Text;
using MailKit.Net.Pop3;
using MailKit.Security;
using System.Text.RegularExpressions;
namespace SecuritySystemBusinessLogic.MailWorker
{
public class MailKitWorker : AbstractMailWorker
{
public MailKitWorker(ILogger<MailKitWorker> logger, IMessageInfoLogic messageInfoLogic) : base(logger, messageInfoLogic) { }
protected override async Task SendMailAsync(MailSendInfoBindingModel info)
{
if (info.MailAddress == null) return;
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 = message.Date.DateTime,
MessageId = message.MessageId,
SenderName = mail.Address,
Subject = message.Subject,
Body = message.TextBody != null ? message.TextBody : message.HtmlBody
});
}
}
}
catch (AuthenticationException)
{ }
finally
{
client.Disconnect(true);
}
});
return list;
}
}
}

View File

@ -9,6 +9,7 @@
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.0.2" />
<PackageReference Include="MailKit" Version="4.5.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
</ItemGroup>

View File

@ -0,0 +1,12 @@
namespace SecuritySystemContracts.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; }
}
}

View File

@ -0,0 +1,9 @@
namespace SecuritySystemContracts.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;
}
}

View File

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

View File

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

View File

@ -0,0 +1,8 @@
namespace SecuritySystemContracts.SearchModels
{
public class MessageInfoSearchModel
{
public string? MessageId { get; set; }
public int? ClientId { get; set; }
}
}

View File

@ -0,0 +1,14 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.ViewModels;
namespace SecuritySystemContracts.StoragesContracts
{
public interface IMessageInfoStorage
{
List<MessageInfoViewModel> GetFullList();
List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model);
MessageInfoViewModel? GetElement(MessageInfoSearchModel model);
MessageInfoViewModel? Insert(MessageInfoBindingModel model);
}
}

View File

@ -0,0 +1,20 @@
using SecuritySystemDataModels.Models;
using System.ComponentModel;
namespace SecuritySystemContracts.ViewModels
{
public class MessageInfoViewModel : IMessageInfoModel
{
[DisplayName("Идентификатор")]
public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; } = null;
[DisplayName("Отправитель")]
public string SenderName { get; set; } = string.Empty;
[DisplayName("Дата получения")]
public DateTime DateDelivery { get; set; } = DateTime.Now;
[DisplayName("Тема")]
public string Subject { get; set; } = string.Empty;
[DisplayName("Текст")]
public string Body { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,12 @@
namespace SecuritySystemDataModels.Models
{
public interface IMessageInfoModel
{
string MessageId { get; }
int? ClientId { get; }
string SenderName { get; }
DateTime DateDelivery { get; }
string Subject { get; }
string Body { get; }
}
}

View File

@ -0,0 +1,50 @@
using Microsoft.EntityFrameworkCore;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDatabaseImplement.Models;
namespace SecuritySystemDatabaseImplement.Implements
{
public class MessageInfoStorage : IMessageInfoStorage
{
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
return GetFilteredList(model).FirstOrDefault();
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
var messageInfos = GetFullList();
if (!string.IsNullOrEmpty(model.MessageId))
{
messageInfos = messageInfos.Where(x => x.MessageId == model.MessageId).ToList();
}
if (model.ClientId != null)
{
messageInfos = messageInfos.Where(x => x.ClientId == model.ClientId).ToList();
}
return messageInfos;
}
public List<MessageInfoViewModel> GetFullList()
{
using var context = new SecuritySystemDatabase();
return context.MessageInfos.Include(x => x.Client).Select(x => x.GetViewModel).ToList();
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
var messageInfo = MessageInfo.Create(model);
if (messageInfo == null)
{
return null;
}
using var context = new SecuritySystemDatabase();
context.MessageInfos.Add(messageInfo);
context.SaveChanges();
return messageInfo.GetViewModel;
}
}
}

View File

@ -11,37 +11,33 @@ namespace SecuritySystemDatabaseImplement.Implements
{
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return GetFilteredList(model).FirstOrDefault();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
var orders = GetFullList();
if (model.Id.HasValue)
if (model.Id != null)
{
orders = orders.Where(x => x.Id == model.Id.Value).ToList();
}
if (model.Status.HasValue)
if (model.Status != null)
{
orders = orders.Where(x => x.Status == model.Status.Value).ToList();
}
if (model.ImplementerId.HasValue)
if (model.ImplementerId != null)
{
orders = orders.Where(x => x.ImplementerId == model.ImplementerId.Value).ToList();
}
if (model.DateFrom.HasValue)
if (model.DateFrom != null)
{
orders = orders.Where(x => x.DateCreate >= model.DateFrom.Value).ToList();
}
if (model.DateTo.HasValue)
if (model.DateTo != null)
{
orders = orders.Where(x => x.DateCreate <= model.DateTo.Value).ToList();
}
if (model.ClientId.HasValue)
if (model.ClientId != null)
{
orders = orders.Where(x => x.ClientId == model.ClientId.Value).ToList();
}

View File

@ -0,0 +1,298 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SecuritySystemDatabaseImplement;
#nullable disable
namespace SecuritySystemDatabaseImplement.Migrations
{
[DbContext(typeof(SecuritySystemDatabase))]
[Migration("20240505105357_AddMessageInfoModel")]
partial class AddMessageInfoModel
{
/// <inheritdoc />
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("SecuritySystemDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("ClientId")
.HasColumnType("int");
b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("MessageInfos");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("SecureId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("SecureId");
b.ToTable("Orders");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Secure", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Price")
.HasColumnType("float");
b.Property<string>("SecureName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Secures");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.SecureComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("SecureId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("SecureId");
b.ToTable("SecureComponents");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("SecuritySystemDatabaseImplement.Models.Client", "Client")
.WithMany("MessageInfos")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Order", b =>
{
b.HasOne("SecuritySystemDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SecuritySystemDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("SecuritySystemDatabaseImplement.Models.Secure", "Secure")
.WithMany("Orders")
.HasForeignKey("SecureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Secure");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.SecureComponent", b =>
{
b.HasOne("SecuritySystemDatabaseImplement.Models.Component", "Component")
.WithMany("SecureComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SecuritySystemDatabaseImplement.Models.Secure", "Secure")
.WithMany("Components")
.HasForeignKey("SecureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Secure");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Client", b =>
{
b.Navigation("MessageInfos");
b.Navigation("Orders");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Component", b =>
{
b.Navigation("SecureComponents");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Secure", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,48 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SecuritySystemDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class AddMessageInfoModel : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "MessageInfos",
columns: table => new
{
MessageId = table.Column<string>(type: "nvarchar(450)", nullable: false),
ClientId = table.Column<int>(type: "int", nullable: true),
SenderName = table.Column<string>(type: "nvarchar(max)", nullable: false),
DateDelivery = table.Column<DateTime>(type: "datetime2", nullable: false),
Subject = table.Column<string>(type: "nvarchar(max)", nullable: false),
Body = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_MessageInfos", x => x.MessageId);
table.ForeignKey(
name: "FK_MessageInfos_Clients_ClientId",
column: x => x.ClientId,
principalTable: "Clients",
principalColumn: "Id");
});
migrationBuilder.CreateIndex(
name: "IX_MessageInfos_ClientId",
table: "MessageInfos",
column: "ClientId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "MessageInfos");
}
}
}

View File

@ -94,6 +94,36 @@ namespace SecuritySystemDatabaseImplement.Migrations
b.ToTable("Implementers");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("ClientId")
.HasColumnType("int");
b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("MessageInfos");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -183,6 +213,15 @@ namespace SecuritySystemDatabaseImplement.Migrations
b.ToTable("SecureComponents");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("SecuritySystemDatabaseImplement.Models.Client", "Client")
.WithMany("MessageInfos")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Order", b =>
{
b.HasOne("SecuritySystemDatabaseImplement.Models.Client", "Client")
@ -229,6 +268,8 @@ namespace SecuritySystemDatabaseImplement.Migrations
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Client", b =>
{
b.Navigation("MessageInfos");
b.Navigation("Orders");
});

View File

@ -17,6 +17,8 @@ namespace SecuritySystemDatabaseImplement.Models
public string Password { get; private set; } = string.Empty;
[ForeignKey("ClientId")]
public virtual List<Order> Orders { get; set; } = new();
[ForeignKey("ClientId")]
public virtual List<MessageInfo> MessageInfos { get; set; } = new();
public static Client? Create(ClientBindingModel model)
{
if (model == null)

View File

@ -0,0 +1,75 @@
using Microsoft.EntityFrameworkCore;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using System.ComponentModel.DataAnnotations;
namespace SecuritySystemDatabaseImplement.Models
{
[PrimaryKey("MessageId")]
public class MessageInfo : IMessageInfoModel
{
public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; }
public virtual Client? Client { get; set; }
[Required]
public string SenderName { get; set; } = string.Empty;
[Required]
public DateTime DateDelivery { get; set; } = DateTime.Now;
[Required]
public string Subject { get; set; } = string.Empty;
[Required]
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(MessageInfoViewModel model)
{
return new MessageInfo
{
MessageId = model.MessageId,
ClientId = model.ClientId,
SenderName = model.SenderName,
DateDelivery = model.DateDelivery,
Subject = model.Subject,
Body = model.Body,
};
}
public void Update(MessageInfoBindingModel model)
{
if (model == null)
{
return;
}
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,
};
}
}

View File

@ -21,6 +21,7 @@ namespace SecuritySystemDatabaseImplement
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> MessageInfos { set; get; }
}
}

View File

@ -11,11 +11,13 @@ namespace SecuritySystemFileImplement
private readonly string SecureFileName = "Secure.xml";
private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
private readonly string MessageInfoFileName = "MessageInfo.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Secure> Secures { get; private set; }
public List<Client> Clients { get; private set; }
public List<Implementer> Implementers { get; private set; }
public List<MessageInfo> MessageInfos { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
@ -29,6 +31,7 @@ namespace SecuritySystemFileImplement
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement);
public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement);
public void SaveMessageInfos() => SaveData(MessageInfos, MessageInfoFileName, "MessageInfos", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
@ -36,6 +39,7 @@ namespace SecuritySystemFileImplement
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!;
MessageInfos = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{

View File

@ -0,0 +1,53 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;
using SecuritySystemFileImplement.Models;
namespace SecuritySystemFileImplement.Implements
{
public class MessageInfoStorage : IMessageInfoStorage
{
private DataFileSingleton _source;
public MessageInfoStorage()
{
_source = DataFileSingleton.GetInstance();
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
return GetFilteredList(model).FirstOrDefault();
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
var messageInfos = GetFullList();
if (!string.IsNullOrEmpty(model.MessageId))
{
messageInfos = messageInfos.Where(x => x.MessageId == model.MessageId).ToList();
}
if (model.ClientId != null)
{
messageInfos = messageInfos.Where(x => x.ClientId == model.ClientId).ToList();
}
return messageInfos;
}
public List<MessageInfoViewModel> GetFullList()
{
return _source.MessageInfos.Select(x => x.GetViewModel).ToList();
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
var messageInfo = MessageInfo.Create(model);
if (messageInfo == null)
{
return null;
}
_source.MessageInfos.Add(messageInfo);
_source.SaveMessageInfos();
return messageInfo.GetViewModel;
}
}
}

View File

@ -0,0 +1,81 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using System.Reflection;
using System.Xml.Linq;
namespace SecuritySystemFileImplement.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; } = DateTime.Now;
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.Element("ClientId")!.Value),
SenderName = element.Element("SenderName")!.Value,
DateDelivery = Convert.ToDateTime(element.Element("DateDelivery")!.Value),
Subject = element.Element("Subject")!.Value,
Body = element.Element("Body")!.Value,
};
}
public void Update(MessageInfoBindingModel model)
{
if (model == null)
{
return;
}
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,
};
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)
);
}
}

View File

@ -10,6 +10,7 @@ namespace SecuritySystemListImplement
public List<Secure> Secures { get; set; }
public List<Client> Clients { get; set; }
public List<Implementer> Implementers { get; set; }
public List<MessageInfo> MessageInfos { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
@ -17,6 +18,7 @@ namespace SecuritySystemListImplement
Secures = new List<Secure>();
Clients = new List<Client>();
Implementers = new List<Implementer>();
MessageInfos = new List<MessageInfo>();
}
public static DataListSingleton GetInstance()
{

View File

@ -0,0 +1,52 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;
using SecuritySystemListImplement.Models;
namespace SecuritySystemListImplement.Implements
{
public class MessageInfoStorage : IMessageInfoStorage
{
private readonly DataListSingleton _source;
public MessageInfoStorage(DataListSingleton source)
{
_source = source;
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
return GetFilteredList(model).FirstOrDefault();
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
var messageInfos = GetFullList();
if (!string.IsNullOrEmpty(model.MessageId))
{
messageInfos = messageInfos.Where(x => x.MessageId == model.MessageId).ToList();
}
if (model.ClientId != null)
{
messageInfos = messageInfos.Where(x => x.ClientId == model.ClientId).ToList();
}
return messageInfos;
}
public List<MessageInfoViewModel> GetFullList()
{
return _source.MessageInfos.Select(x => x.GetViewModel).ToList();
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
var messageInfo = MessageInfo.Create(model);
if (messageInfo == null)
{
return null;
}
_source.MessageInfos.Add(messageInfo);
return messageInfo.GetViewModel;
}
}
}

View File

@ -0,0 +1,55 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using System.Reflection;
namespace SecuritySystemListImplement.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; } = DateTime.Now;
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 void Update(MessageInfoBindingModel? model)
{
if (model == null)
{
return;
}
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,
};
}
}

View File

@ -12,11 +12,12 @@ namespace SecuritySystemRestApi.Controllers
{
private readonly ILogger _logger;
private readonly IClientLogic _logic;
public ClientController(IClientLogic logic, ILogger<ClientController>
logger)
private readonly IMessageInfoLogic _mailLogic;
public ClientController(IClientLogic logic, ILogger<ClientController> logger, IMessageInfoLogic mailLogic)
{
_logger = logger;
_logic = logic;
_mailLogic = mailLogic;
}
[HttpGet]
public ClientViewModel? Login(string login, string password)
@ -61,6 +62,23 @@ namespace SecuritySystemRestApi.Controllers
throw;
}
}
[HttpGet]
public List<MessageInfoViewModel>? GetMessages(int clientId)
{
try
{
var mails = _mailLogic.ReadList(new MessageInfoSearchModel
{
ClientId = clientId
});
return mails;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения писем клиента");
throw;
}
}
}
}

View File

@ -3,6 +3,8 @@ using SecuritySystemContracts.BusinessLogicsContracts;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemDatabaseImplement.Implements;
using Microsoft.OpenApi.Models;
using SecuritySystemBusinessLogic.MailWorker;
using SecuritySystemContracts.BindingModels;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.SetMinimumLevel(LogLevel.Trace);
@ -12,9 +14,12 @@ builder.Logging.AddLog4Net("log4net.config");
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<ISecureStorage, SecureStorage>();
builder.Services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<ISecureLogic, SecureLogic>();
builder.Services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
@ -29,6 +34,19 @@ 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())
{

View File

@ -5,5 +5,11 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"SmtpClientHost": "smtp.gamil.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "lawfirmlab7@gmail.com",
"MailPassword": "logf arhv rtkk rqfe"
}

View File

@ -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="lawfirmlab7@gmail.com" />
<add key="MailPassword" value="logf arhv rtkk rqfe" />
</appSettings>
</configuration>

View File

@ -43,6 +43,7 @@
buttonCreateOrder = new Button();
button4 = new Button();
buttonRefresh = new Button();
почтаToolStripMenuItem = new ToolStripMenuItem();
menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
@ -50,7 +51,7 @@
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem });
menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, почтаToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1043, 28);
@ -174,6 +175,13 @@
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// почтаToolStripMenuItem
//
почтаToolStripMenuItem.Name = "почтаToolStripMenuItem";
почтаToolStripMenuItem.Size = new Size(65, 24);
почтаToolStripMenuItem.Text = "Почта";
почтаToolStripMenuItem.Click += MailsToolStripMenuItem_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -212,5 +220,6 @@
private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem;
private ToolStripMenuItem запускРаботToolStripMenuItem;
private ToolStripMenuItem почтаToolStripMenuItem;
}
}

View File

@ -3,6 +3,7 @@ using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.BusinessLogicsContracts;
using SecuritySystemView.Client;
using SecuritySystemView.Implementer;
using SecuritySystemView.Mail;
using SecuritySystemView.Report;
namespace SecuritySystemView
@ -213,5 +214,14 @@ namespace SecuritySystemView
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void MailsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormMails));
if (service is FormMails form)
{
form.ShowDialog();
}
}
}
}

View File

@ -0,0 +1,79 @@
namespace SecuritySystemView.Mail
{
partial class FormMails
{
/// <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()
{
dataGridView = new DataGridView();
buttonRefresh = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(0, 42);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(800, 408);
dataGridView.TabIndex = 0;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(12, 7);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(94, 29);
buttonRefresh.TabIndex = 1;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += buttonRefresh_Click;
//
// FormMails
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(buttonRefresh);
Controls.Add(dataGridView);
Name = "FormMails";
Text = "Почта";
Load += FormMails_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonRefresh;
}
}

View File

@ -0,0 +1,47 @@
using Microsoft.Extensions.Logging;
using SecuritySystemContracts.BusinessLogicsContracts;
namespace SecuritySystemView.Mail
{
public partial class FormMails : Form
{
private readonly ILogger _logger;
private readonly IMessageInfoLogic _logic;
public FormMails(ILogger<FormMails> logger, IMessageInfoLogic messageInfoLogic)
{
InitializeComponent();
_logger = logger;
_logic = messageInfoLogic;
}
private void FormMails_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["MessageId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
}
_logger.LogInformation("Загрузка почты");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки почты");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void buttonRefresh_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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>

View File

@ -2,13 +2,16 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using SecuritySystemBusinessLogic.BusinessLogics;
using SecuritySystemBusinessLogic.MailWorker;
using SecuritySystemBusinessLogic.OfficePackage;
using SecuritySystemBusinessLogic.OfficePackage.Implements;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.BusinessLogicsContracts;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemDatabaseImplement.Implements;
using SecuritySystemView.Client;
using SecuritySystemView.Implementer;
using SecuritySystemView.Mail;
using SecuritySystemView.Report;
namespace SecuritySystemView
@ -29,6 +32,28 @@ namespace SecuritySystemView
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
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, 5000);
}
catch (Exception ex)
{
var logger = _serviceProvider.GetService<ILogger>();
logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé");
}
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
}
private static void ConfigureServices(ServiceCollection services)
@ -43,16 +68,19 @@ namespace SecuritySystemView
services.AddTransient<ISecureStorage, SecureStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<ISecureLogic, SecureLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
@ -65,6 +93,8 @@ namespace SecuritySystemView
services.AddTransient<FormClients>();
services.AddTransient<FormImplementer>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormMails>();
}
private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck();
}
}