75 Commits

Author SHA1 Message Date
ffcd5fcef8 Добавил проверки на null в файловые реализации 2024-05-19 22:36:14 +04:00
56b1ae730c Реализовал Unity DI 2024-05-19 22:25:15 +04:00
7393382dd8 Убрал using из Program.cs 2024-05-19 22:11:10 +04:00
1147f65ab6 Убрал зависимости Storage из Program.cs 2024-05-19 22:06:37 +04:00
02d703f55d Убрал лишние условия в формах при резолве зависимостей 2024-05-19 22:04:59 +04:00
56b7de7d18 Удалил ServiceProvider из Program.cs 2024-05-19 21:52:57 +04:00
2bacaad2c3 Поменял на всех формах код внедрения зависимостей 2024-05-19 21:50:25 +04:00
0484b22e03 Добавил логику DI, нужно прописать Extension классы для проектов 2024-05-19 21:08:52 +04:00
622fddbe67 Реализовал логику бекапов для проекта хранения в файлах 2024-05-19 20:36:27 +04:00
beb88bcd82 Добавил атрибуты к сущностям БД для бекапирования, бекапы работают 2024-05-19 20:27:25 +04:00
df06851779 Добавлен атрибут Column для полей моделей 2024-05-19 19:55:10 +04:00
f587a9cad6 Переделана логика вывода информации в таблицы DataGridView 2024-05-19 19:33:18 +04:00
7bee609669 Добавил классы атрибутов 2024-05-19 18:35:07 +04:00
4e98e8ac47 Все работает 2024-05-06 11:04:52 +04:00
73609b1999 Добавил проверку пароля 2024-05-06 10:45:43 +04:00
daaed01ccd добавил веб, не работает отображение писем для клиента в вебе 2024-05-06 01:13:01 +04:00
68e7e61991 Поправил доделку заказов воркерами 2024-05-05 23:41:35 +04:00
f73d555c0e Работает отправка и принятие писем, отрабатывает отправка при приянтии заказа и переходе его состояний 2024-05-05 23:26:14 +04:00
2e0f9b9bc4 Фикс хранилища заказов 2024-05-05 23:25:46 +04:00
75604db1a8 Работает отправка и получение почты 2024-05-05 22:02:27 +04:00
0b2f2fa6aa Добавил форму для писем 2024-05-05 20:50:26 +04:00
d6b3ec7b03 Фикс логики почты 2024-05-05 20:50:11 +04:00
55aff66f7b Прописал добавленные классы для работы с почтой в главный метод программы, добавил конфигурационный файл 2024-05-05 19:42:09 +04:00
f990cfe4a6 Реализовал отправку писем в логике заказов 2024-05-05 18:05:56 +04:00
61641fcfdf Добавил классов для отправки почты 2024-05-05 17:40:26 +04:00
11cb3e0b57 Поправил модель БД для письма, добавив PK, создал миграции 2024-05-05 14:54:55 +04:00
ee3f0bf026 Добавил список писем в модель клиента в БД 2024-05-05 14:49:17 +04:00
f3d1de0db8 Реализовал хранение писем в БД 2024-05-05 14:48:06 +04:00
4d9d154821 Реализовал хранение писем в файлах 2024-05-05 14:36:48 +04:00
8da9d8b59c Фикс функции создания письма в реализации хранилищп для списка 2024-05-05 14:34:26 +04:00
bc20162bb9 Реализовал бизнеслогику для писем 2024-05-05 13:34:40 +04:00
3ee55e1fd7 Добавил класс реализацию бизнес логики писем 2024-05-05 13:28:33 +04:00
ae4d111f32 Реализовал хранение писем в списке 2024-05-05 13:28:14 +04:00
dbc3979d0c Добавил интерфейс хранилища для писем 2024-05-05 12:58:32 +04:00
08c1677432 Добавил интерфейс бизнес логики письма 2024-05-05 12:57:34 +04:00
7a7ff677a3 Добавил search модель письма 2024-05-05 12:57:21 +04:00
07883d6769 Добавил view модель письма 2024-05-05 12:50:52 +04:00
b92ffdc441 Добавил биндинг модель письма 2024-05-05 12:43:15 +04:00
8dbfbd88e9 Добавден интерфейс можели письма 2024-05-05 12:37:49 +04:00
bde0db3668 Добавил миграцию для удаления заказов 2024-04-22 12:46:01 +04:00
ce6b839975 Фикс хранилища, метод получения одного элемента заказа 2024-04-22 12:29:42 +04:00
5b500f9835 Отображение пароля клиента 2024-04-22 12:26:10 +04:00
ac5c359c5f Фикс хранилища заказов для отображения исполнителя 2024-04-22 12:25:56 +04:00
5786cfdc95 Фикс формы 2024-04-22 12:14:57 +04:00
23b67a747f Реализовал логику выполнения работ 2024-04-22 12:10:06 +04:00
23b9b538c9 Добавлен контроллер исполнителя в API 2024-04-22 12:01:55 +04:00
f6e470911d Добавлен метод ReadElement для логики заказа 2024-04-22 12:01:43 +04:00
4b1cc73321 Работа с формами 2024-04-22 11:52:50 +04:00
5e5eeffe7b Реализовал форму списка исполнителей 2024-04-22 11:39:58 +04:00
b33e1094da Реализовал форму добавления работника 2024-04-22 11:35:23 +04:00
86e83dac7b Это условие все таки нужно оказалось 2024-04-22 11:29:01 +04:00
9e79e50027 Фикс кода отдачи заказа на выполнение 2024-04-22 11:02:50 +04:00
86fa2bf375 Добавил вохможность поиска заказа по статусу и исполнителю 2024-04-22 10:58:35 +04:00
0ef5453070 Визуальные фиксы таблицы на главной форме 2024-04-22 10:52:30 +04:00
eaa6f1c3ca Создал миграции для добавления исполнителя 2024-04-22 10:52:09 +04:00
78fbcb7e13 Фикс пустого значения исполнителя в модели бд у заказа 2024-04-22 10:34:51 +04:00
bfbc7e59ee Реализовал связь моделей исполнителя и заказа в бд 2024-04-22 10:32:38 +04:00
fdb3444f21 Фиксы кода, реализация изменений по заказам для файлов и листа 2024-04-22 10:25:46 +04:00
6a118d4622 Добавил поле фио работника во view модель заказа, порписал поле id в модели бд 2024-04-22 10:18:23 +04:00
452f66187c Обновил поле ImplementerId в моделях заказа, теперь оно может быть null 2024-04-22 10:12:59 +04:00
653f011380 Добавил поле ImplementerId во все модели заказа 2024-04-22 10:04:47 +04:00
e0ccb4f889 Перевод метода взятия заказа в работу в однопоточный режим 2024-04-20 17:08:39 +04:00
92cab84005 Реализовано хранение исполнителя в бд 2024-04-20 16:34:56 +04:00
ff28061afa Реализовал модель хранения данных для исполнителя в бд 2024-04-20 16:15:24 +04:00
91e37358dc Реализовал хранилище исполнителей в файле 2024-04-20 14:51:30 +04:00
b752932b60 Реализовал хранилище для исполнителей на списке 2024-04-20 14:31:38 +04:00
ac043889c2 Реализовал модель хранения исполнителя для списка 2024-04-20 14:25:29 +04:00
2bb5209f9f Реализован класс логики исполнителя 2024-04-20 14:15:19 +04:00
01c7928e2a Добавлен интерфейс хранилища для исполнителя 2024-04-20 14:00:10 +04:00
3fef0274b2 Добавлен интерфейс логики для исполнителя 2024-04-20 13:58:24 +04:00
f7a7ed6ed6 Добавлена view модель исполнителя 2024-04-20 13:55:58 +04:00
fb7a2a4065 Добавил search модель исполнителя 2024-04-20 13:50:34 +04:00
cd0176b2d8 Добавил биндинг модель 2024-04-20 13:48:22 +04:00
198259830e Фикс модели исполнителя 2024-04-20 13:45:48 +04:00
72f55c5027 Добавлена модель-интерфейс исполнителя 2024-04-20 13:35:47 +04:00
117 changed files with 5008 additions and 324 deletions

1
.gitignore vendored
View File

@@ -398,3 +398,4 @@ FodyWeavers.xsd
# JetBrains Rider
*.sln.iml
ImplementationExtensions/

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

@@ -0,0 +1,95 @@
using Microsoft.Extensions.Logging;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.BusinessLogicsContracts;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemDataModels;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.Serialization.Json;
namespace SecuritySystemBusinessLogic.BusinessLogics
{
public class BackUpLogic : IBackUpLogic
{
private readonly ILogger _logger;
private readonly IBackUpInfoStorage _backUpInfo;
public BackUpLogic(ILogger<BackUpLogic> logger, IBackUpInfoStorage backUpInfo)
{
_logger = logger;
_backUpInfo = backUpInfo;
}
public void CreateBackUp(BackUpSaveBindingModel model)
{
if (_backUpInfo == null)
{
return;
}
try
{
_logger.LogDebug("Clear folder");
// зачистка папки и удаление старого архива
var dirInfo = new DirectoryInfo(model.FolderName);
if (dirInfo.Exists)
{
foreach (var file in dirInfo.GetFiles())
{
file.Delete();
}
}
_logger.LogDebug("Delete archive");
string fileName = $"{model.FolderName}.zip";
if (File.Exists(fileName))
{
File.Delete(fileName);
}
// берем метод для сохранения
_logger.LogDebug("Get assembly");
var typeIId = typeof(IId);
var assembly = typeIId.Assembly;
if (assembly == null)
{
throw new ArgumentNullException("Сборка не найдена",
nameof(assembly));
}
var types = assembly.GetTypes();
var method = GetType().GetMethod("SaveToFile", BindingFlags.NonPublic | BindingFlags.Instance);
_logger.LogDebug("Find {count} types", types.Length);
foreach (var type in types)
{
if (type.IsInterface && type.GetInterface(typeIId.Name) != null)
{
var modelType = _backUpInfo.GetTypeByModelInterface(type.Name);
if (modelType == null)
{
throw new InvalidOperationException($"Не найден класс - модель для {type.Name}");
}
_logger.LogDebug("Call SaveToFile method for {name} type", type.Name);
// вызываем метод на выполнение
method?.MakeGenericMethod(modelType).Invoke(this, new object[] { model.FolderName });
}
}
_logger.LogDebug("Create zip and remove folder");
// архивируем
ZipFile.CreateFromDirectory(model.FolderName, fileName);
// удаляем папку
dirInfo.Delete(true);
}
catch (Exception)
{
throw;
}
}
private void SaveToFile<T>(string folderName) where T : class, new()
{
var records = _backUpInfo.GetList<T>();
if (records == null)
{
_logger.LogWarning("{type} type get null list", typeof(T).Name);
return;
}
var jsonFormatter = new DataContractJsonSerializer(typeof(List<T>));
using var fs = new FileStream(string.Format("{0}/{1}.json", folderName, typeof(T).Name), FileMode.OpenOrCreate);
jsonFormatter.WriteObject(fs, records);
}
}
}

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,126 @@
using Microsoft.Extensions.Logging;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.BusinessLogicsContracts;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;
namespace SecuritySystemBusinessLogic.BusinessLogics
{
public class ImplementerLogic : IImplementerLogic
{
private ILogger _logger;
private IImplementerStorage _implementerStorage;
public ImplementerLogic(ILogger<ImplementerLogic> logger, IImplementerStorage implementerStorage)
{
_logger = logger;
_implementerStorage = implementerStorage;
}
public bool Create(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Delete(ImplementerBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_implementerStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public ImplementerViewModel? ReadElement(ImplementerSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. FIO:{FIO}. Id:{Id}", model.ImplementerFIO, model.Id);
var element = _implementerStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model)
{
_logger.LogInformation("ReadList. FIO:{FIO}. Id:{Id}", model?.ImplementerFIO, model?.Id);
var list = model == null ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool Update(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
private void CheckModel(ImplementerBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (model.WorkExperience < 0)
{
throw new ArgumentNullException("Опыт работы исполнителя должен быть больше или равен нулю", nameof(model.Password));
}
if (model.Qualification < 0)
{
throw new ArgumentNullException("Квалификация исполнителя должна быть больше или равна нулю", nameof(model.Password));
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Нет пароля исполнителя", nameof(model.Password));
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Нет пароля исполнителя", nameof(model.Password));
}
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
throw new ArgumentNullException("Нет фио клиента", nameof(model.ImplementerFIO));
}
_logger.LogInformation("ReadElement. FIO:{FIO}. Id:{Id}", model.ImplementerFIO, model.Id);
var element = _implementerStorage.GetElement(new ImplementerSearchModel
{
ImplementerFIO = model.ImplementerFIO
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Сотрудник с таким фио уже есть");
}
}
}
}

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,11 +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)
@@ -36,45 +42,64 @@ 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 (order.ImplementerId.HasValue)
{
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;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выполняется);
lock (locker)
{
return ChangeStatus(model, OrderStatus.Выполняется);
}
}
public bool FinishOrder(OrderBindingModel model)
@@ -115,5 +140,54 @@ namespace SecuritySystemBusinessLogic.BusinessLogics
}
_logger.LogInformation("Order. Sum:{Cost}. Id: {Id}", model.Sum, model.Id);
}
public OrderViewModel? ReadElement(OrderSearchModel? model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Order Id:{Id}", model.Id);
var element = _orderStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_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

@@ -0,0 +1,145 @@
using Microsoft.Extensions.Logging;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.BusinessLogicsContracts;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Enums;
namespace SecuritySystemBusinessLogic.BusinessLogics
{
public class WorkModeling : IWorkProcess
{
private readonly ILogger _logger;
private readonly Random _rnd;
private IOrderLogic? _orderLogic;
public WorkModeling(ILogger<WorkModeling> logger)
{
_logger = logger;
_rnd = new Random(1000);
}
public void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic)
{
_orderLogic = orderLogic;
var implementers = implementerLogic.ReadList(null);
if (implementers == null)
{
_logger.LogWarning("DoWork. Implementers is null");
return;
}
var orders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Принят });
var inWorkOrders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Выполняется });
if (orders != null && inWorkOrders != null)
{
orders.AddRange(inWorkOrders);
}
else
{
orders = inWorkOrders;
}
if (orders == null || orders.Count == 0)
{
_logger.LogWarning("DoWork. Orders is null or empty");
return;
}
_logger.LogDebug("DoWork for {Count} orders", orders.Count);
foreach (var implementer in implementers)
{
Task.Run(() => WorkerWorkAsync(implementer, orders));
}
}
/// <summary>
/// Иммитация работы исполнителя
/// </summary>
/// <param name="implementer"></param>
/// <param name="orders"></param>
private async Task WorkerWorkAsync(ImplementerViewModel implementer, List<OrderViewModel> orders)
{
if (_orderLogic == null || implementer == null)
{
return;
}
await RunOrderInWork(implementer);
await Task.Run(() =>
{
foreach (var order in orders)
{
try
{
_logger.LogDebug("DoWork. Worker {Id} try get order {Order}", implementer.Id, order.Id);
// пытаемся назначить заказ на исполнителя
_orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = order.Id,
ImplementerId = implementer.Id
});
// делаем работу
Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 1000) * order.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = order.Id
});
}
// кто-то мог уже перехватить заказ, игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// заканчиваем выполнение имитации в случае иной ошибки
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
// отдыхаем
Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100));
}
});
}
/// <summary>
/// Ищем заказ, которые уже в работе (вдруг исполнителя прервали)
/// </summary>
/// <param name="implementer"></param>
/// <returns></returns>
private async Task RunOrderInWork(ImplementerViewModel implementer)
{
if (_orderLogic == null || implementer == null)
{
return;
}
try
{
var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel
{
ImplementerId = implementer.Id,
Status = OrderStatus.Выполняется
}));
if (runOrder == null)
{
return;
}
_logger.LogDebug("DoWork. Worker {Id} back to order {Order}", implementer.Id, runOrder.Id);
// доделываем работу
Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 300) * runOrder.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = runOrder.Id
});
// отдыхаем
Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100));
}
// заказа может не быть, просто игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// а может возникнуть иная ошибка, тогда просто заканчиваем выполнение имитации
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
}
}
}

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,21 @@
namespace SecuritySystemContracts.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class ColumnAttribute : Attribute
{
public ColumnAttribute(string title = "", bool visible = true, int width = 0,
GridViewAutoSize gridViewAutoSize = GridViewAutoSize.None, bool isUseAutoSize = false)
{
Title = title;
Visible = visible;
Width = width;
GridViewAutoSize = gridViewAutoSize;
IsUseAutoSize = isUseAutoSize;
}
public string Title { get; private set; }
public bool Visible { get; private set; }
public int Width { get; private set; }
public GridViewAutoSize GridViewAutoSize { get; private set; }
public bool IsUseAutoSize { get; private set; }
}
}

View File

@@ -0,0 +1,14 @@
namespace SecuritySystemContracts.Attributes
{
public enum GridViewAutoSize
{
NotSet = 0,
None = 1,
ColumnHeader = 2,
AllCellsExceptHeader = 4,
AllCells = 6,
DisplayedCellsExceptHeader = 8,
DisplayedCells = 10,
Fill = 16
}
}

View File

@@ -0,0 +1,7 @@
namespace SecuritySystemContracts.BindingModels
{
public class BackUpSaveBindingModel
{
public string FolderName { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,13 @@
using SecuritySystemDataModels.Models;
namespace SecuritySystemContracts.BindingModels
{
public class ImplementerBindingModel : IImplementerModel
{
public string ImplementerFIO { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public int WorkExperience { get; set; }
public int Qualification { get; set; }
public int Id { get; set; }
}
}

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,15 @@
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;
public int Id => throw new NotImplementedException();
}
}

View File

@@ -8,6 +8,7 @@ namespace SecuritySystemContracts.BindingModels
public int Id { get; set; }
public int SecureId { get; set; }
public int ClientId { get; set; }
public int? ImplementerId { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;

View File

@@ -0,0 +1,9 @@
using SecuritySystemContracts.BindingModels;
namespace SecuritySystemContracts.BusinessLogicsContracts
{
public interface IBackUpLogic
{
void CreateBackUp(BackUpSaveBindingModel model);
}
}

View File

@@ -0,0 +1,15 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.ViewModels;
namespace SecuritySystemContracts.BusinessLogicsContracts
{
public interface IImplementerLogic
{
List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model);
ImplementerViewModel? ReadElement(ImplementerSearchModel model);
bool Create(ImplementerBindingModel model);
bool Update(ImplementerBindingModel model);
bool Delete(ImplementerBindingModel model);
}
}

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

@@ -7,6 +7,7 @@ namespace SecuritySystemContracts.BusinessLogicsContracts
public interface IOrderLogic
{
List<OrderViewModel>? ReadList(OrderSearchModel? model);
OrderViewModel? ReadElement(OrderSearchModel? model);
bool CreateOrder(OrderBindingModel model);
bool TakeOrderInWork(OrderBindingModel model);
bool FinishOrder(OrderBindingModel model);

View File

@@ -0,0 +1,7 @@
namespace SecuritySystemContracts.BusinessLogicsContracts
{
public interface IWorkProcess
{
void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic);
}
}

View File

@@ -0,0 +1,72 @@
using Microsoft.Extensions.Logging;
namespace SecuritySystemContracts.DI
{
/// <summary>
/// Менеджер для работы с зависимостями
/// </summary>
public class DependencyManager
{
private readonly IDependencyContainer _dependencyManager;
private static DependencyManager? _manager;
private static readonly object _locjObject = new();
private DependencyManager()
{
_dependencyManager = new ServiceDependencyContainer();
}
public static DependencyManager Instance
{
get
{
if (_manager == null)
{
lock (_locjObject)
{
_manager = new DependencyManager();
}
}
return _manager;
}
}
/// <summary>
/// Иницализация библиотек, в которых идут установки зависомстей
/// </summary>
public static void InitDependency()
{
var ext = ServiceProviderLoader.GetImplementationExtensions();
if (ext == null)
{
throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям");
}
// регистрируем зависимости
ext.RegisterServices();
}
/// <summary>
/// Регистрация логгера
/// </summary>
/// <param name="configure"></param>
public void AddLogging(Action<ILoggingBuilder> configure) => _dependencyManager.AddLogging(configure);
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
public void RegisterType<T, U>(bool isSingle = false)
where U : class, T
where T : class => _dependencyManager.RegisterType<T, U>(isSingle);
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
public void RegisterType<T>(bool isSingle = false)
where T : class => _dependencyManager.RegisterType<T>(isSingle);
/// <summary>
/// Получение класса со всеми зависмостями
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T Resolve<T>() => _dependencyManager.Resolve<T>();
}
}

View File

@@ -0,0 +1,36 @@
using Microsoft.Extensions.Logging;
namespace SecuritySystemContracts.DI
{
/// <summary>
/// Интерфейс установки зависмости между элементами
/// </summary>
public interface IDependencyContainer
{
/// <summary>
/// Регистрация логгера
/// </summary>
/// <param name="configure"></param>
void AddLogging(Action<ILoggingBuilder> configure);
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
/// <param name="isSingle"></param>
void RegisterType<T, U>(bool isSingle) where U : class, T where T :
class;
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="isSingle"></param>
void RegisterType<T>(bool isSingle) where T : class;
/// <summary>
/// Получение класса со всеми зависмостями
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
T Resolve<T>();
}
}

View File

@@ -0,0 +1,14 @@
namespace SecuritySystemContracts.DI
{
/// <summary>
/// Интерфейс для регистрации зависимостей в модулях
/// </summary>
public interface IImplementationExtension
{
public int Priority { get; }
/// <summary>
/// Регистрация сервисов
/// </summary>
public void RegisterServices();
}
}

View File

@@ -0,0 +1,56 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace SecuritySystemContracts.DI
{
public class ServiceDependencyContainer : IDependencyContainer
{
private ServiceProvider? _serviceProvider;
private readonly ServiceCollection _serviceCollection;
public ServiceDependencyContainer()
{
_serviceCollection = new ServiceCollection();
}
public void AddLogging(Action<ILoggingBuilder> configure)
{
_serviceCollection.AddLogging(configure);
}
public void RegisterType<T, U>(bool isSingle) where T : class where U : class, T
{
if (isSingle)
{
_serviceCollection.AddSingleton<T, U>();
}
else
{
_serviceCollection.AddTransient<T, U>();
}
_serviceProvider = null;
}
public T Resolve<T>()
{
if (_serviceProvider == null)
{
_serviceProvider = _serviceCollection.BuildServiceProvider();
}
return _serviceProvider.GetService<T>()!;
}
void IDependencyContainer.RegisterType<T>(bool isSingle) where T : class
{
if (isSingle)
{
_serviceCollection.AddSingleton<T>();
}
else
{
_serviceCollection.AddTransient<T>();
}
_serviceProvider = null;
}
}
}

View File

@@ -0,0 +1,53 @@
using System.Reflection;
namespace SecuritySystemContracts.DI
{
/// <summary>
/// Загрузчик данных
/// </summary>
public static partial class ServiceProviderLoader
{
/// <summary>
/// Загрузка всех классов-реализаций IImplementationExtension
/// </summary>
/// <returns></returns>
public static IImplementationExtension? GetImplementationExtensions()
{
IImplementationExtension? source = null;
var files = Directory.GetFiles(TryGetImplementationExtensionsFolder(), "*.dll", SearchOption.AllDirectories);
foreach (var file in files.Distinct())
{
Assembly asm = Assembly.LoadFrom(file);
foreach (var t in asm.GetExportedTypes())
{
if (t.IsClass && typeof(IImplementationExtension).IsAssignableFrom(t))
{
if (source == null)
{
source = (IImplementationExtension)Activator.CreateInstance(t)!;
}
else
{
var newSource = (IImplementationExtension)Activator.CreateInstance(t)!;
if (newSource.Priority > source.Priority)
{
source = newSource;
}
}
}
}
}
return source;
}
private static string TryGetImplementationExtensionsFolder()
{
var directory = new DirectoryInfo(Directory.GetCurrentDirectory());
while (directory != null && !directory.GetDirectories("ImplementationExtensions", SearchOption.AllDirectories).Any(x => x.Name == "ImplementationExtensions"))
{
directory = directory.Parent;
}
return $"{directory?.FullName}\\ImplementationExtensions";
}
}
}

View File

@@ -0,0 +1,38 @@

using Microsoft.Extensions.Logging;
using Unity;
using Unity.Microsoft.Logging;
namespace SecuritySystemContracts.DI
{
public class UnityDependencyContainer : IDependencyContainer
{
private readonly IUnityContainer _container;
public UnityDependencyContainer()
{
_container = new UnityContainer();
}
public void AddLogging(Action<ILoggingBuilder> configure)
{
var factory = LoggerFactory.Create(configure);
_container.AddExtension(new LoggingExtension(factory));
}
public void RegisterType<T, U>(bool isSingle) where U : class, T where T : class
{
_container.RegisterType<T, U>(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient);
}
public void RegisterType<T>(bool isSingle) where T : class
{
_container.RegisterType<T>(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient);
}
public T Resolve<T>()
{
return _container.Resolve<T>();
}
}
}

View File

@@ -0,0 +1,9 @@
namespace SecuritySystemContracts.SearchModels
{
public class ImplementerSearchModel
{
public string? ImplementerFIO { get; set; }
public string? Password { get; set; }
public int? Id { get; set; }
}
}

View File

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

View File

@@ -1,4 +1,6 @@
namespace SecuritySystemContracts.SearchModels
using SecuritySystemDataModels.Enums;
namespace SecuritySystemContracts.SearchModels
{
public class OrderSearchModel
{
@@ -6,5 +8,7 @@
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public int? ClientId { get; set; }
public int? ImplementerId { get; set; }
public OrderStatus? Status { get; set; }
}
}

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
@@ -7,6 +7,12 @@
<Platforms>AnyCPU;x64;x86</Platforms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SecuritySystemDataModels\SecuritySystemDataModels.csproj" />
</ItemGroup>

View File

@@ -0,0 +1,8 @@
namespace SecuritySystemContracts.StoragesContracts
{
public interface IBackUpInfoStorage
{
List<T>? GetList<T>() where T : class, new();
Type? GetTypeByModelInterface(string modelInterfaceName);
}
}

View File

@@ -0,0 +1,16 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.ViewModels;
namespace SecuritySystemContracts.StoragesContracts
{
public interface IImplementerStorage
{
List<ImplementerViewModel> GetFullList();
List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model);
ImplementerViewModel? GetElement(ImplementerSearchModel model);
ImplementerViewModel? Insert(ImplementerBindingModel model);
ImplementerViewModel? Update(ImplementerBindingModel model);
ImplementerViewModel? Delete(ImplementerBindingModel model);
}
}

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

@@ -1,16 +1,18 @@
using SecuritySystemDataModels.Models;
using SecuritySystemContracts.Attributes;
using SecuritySystemDataModels.Models;
using System.ComponentModel;
namespace SecuritySystemContracts.ViewModels
{
public class ClientViewModel : IClientModel
{
[Column(visible: false)]
public int Id { get; set; }
[DisplayName("ФИО клиента")]
[Column(title: "ФИО клиента", width: 150)]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Логин (эл. почта)")]
[Column(title: "Логин (эл. почта)", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Email { get; set; } = string.Empty;
[DisplayName("Пароль")]
[Column(title: "Пароль", width: 150)]
public string Password { get; set; } = string.Empty;
}
}

View File

@@ -1,14 +1,16 @@
using SecuritySystemDataModels.Models;
using SecuritySystemContracts.Attributes;
using SecuritySystemDataModels.Models;
using System.ComponentModel;
namespace SecuritySystemContracts.ViewModels
{
public class ComponentViewModel : IComponentModel
{
[Column(visible: false)]
public int Id { get; set; }
[DisplayName("Название компонента")]
[Column(title: "Название компонента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ComponentName { get; set; } = string.Empty;
[DisplayName("Цена")]
[Column(title: "Цена", width: 150)]
public double Cost { get; set; }
}
}

View File

@@ -0,0 +1,20 @@
using SecuritySystemContracts.Attributes;
using SecuritySystemDataModels.Models;
using System.ComponentModel;
namespace SecuritySystemContracts.ViewModels
{
public class ImplementerViewModel : IImplementerModel
{
[Column(visible: false)]
public int Id { get; set; }
[Column(title: "ФИО сотрудника", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ImplementerFIO { get; set; } = string.Empty;
[Column(title: "Пароль", width: 100)]
public string Password { get; set; } = string.Empty;
[Column(title: "Опыт работы", width: 50)]
public int WorkExperience { get; set; }
[Column(title: "Квалификация", width: 50)]
public int Qualification { get; set; }
}
}

View File

@@ -0,0 +1,24 @@
using SecuritySystemContracts.Attributes;
using SecuritySystemDataModels.Models;
using System.ComponentModel;
namespace SecuritySystemContracts.ViewModels
{
public class MessageInfoViewModel : IMessageInfoModel
{
[Column(visible: false)]
public string MessageId { get; set; } = string.Empty;
[Column(visible: false)]
public int? ClientId { get; set; } = null;
[Column(title: "Отправитель", width: 200)]
public string SenderName { get; set; } = string.Empty;
[Column(title: "Дата получения", width: 50)]
public DateTime DateDelivery { get; set; } = DateTime.Now;
[Column(title: "Тема", width: 200)]
public string Subject { get; set; } = string.Empty;
[Column(title: "Текст", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Body { get; set; } = string.Empty;
[Column(visible: false)]
public int Id => throw new NotImplementedException();
}
}

View File

@@ -1,4 +1,5 @@
using SecuritySystemDataModels.Enums;
using SecuritySystemContracts.Attributes;
using SecuritySystemDataModels.Enums;
using SecuritySystemDataModels.Models;
using System.ComponentModel;
@@ -6,23 +7,29 @@ namespace SecuritySystemContracts.ViewModels
{
public class OrderViewModel : IOrderModel
{
[DisplayName("Номер")]
[Column(title: "Номер", gridViewAutoSize: GridViewAutoSize.ColumnHeader, isUseAutoSize: true)]
public int Id { get; set; }
[Column(visible: false)]
public int ClientId { get; set; }
[Column(visible: false)]
public int SecureId { get; set; }
[DisplayName("ФИО клиента")]
[Column(visible: false)]
public int? ImplementerId { get; set; }
[Column(title: "ФИО работника", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ImplementerFIO { get; set; } = string.Empty;
[Column(title: "ФИО клиента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Изделие")]
[Column(title: "Изделие", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string SecureName { get; set; } = string.Empty;
[DisplayName("Количество")]
[Column(title: "Количество", gridViewAutoSize: GridViewAutoSize.ColumnHeader, isUseAutoSize: true)]
public int Count { get; set; }
[DisplayName("Сумма")]
[Column(title: "Сумма", width: 40)]
public double Sum { get; set; }
[DisplayName("Статус")]
[Column(title: "Статус", gridViewAutoSize: GridViewAutoSize.ColumnHeader, isUseAutoSize: true)]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")]
[Column(title: "Дата создания", gridViewAutoSize: GridViewAutoSize.ColumnHeader, isUseAutoSize: true)]
public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")]
[Column(title: "Дата выполнения", gridViewAutoSize: GridViewAutoSize.ColumnHeader, isUseAutoSize: true)]
public DateTime? DateImplement { get; set; }
}
}

View File

@@ -1,15 +1,18 @@
using SecuritySystemDataModels.Models;
using SecuritySystemContracts.Attributes;
using SecuritySystemDataModels.Models;
using System.ComponentModel;
namespace SecuritySystemContracts.ViewModels
{
public class SecureViewModel : ISecureModel
{
[Column(visible: false)]
public int Id { get; set; }
[DisplayName("Название изделия")]
[Column(title: "Название изделия", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string SecureName { get; set; } = string.Empty;
[DisplayName("Цена")]
[Column(title: "Цена", width: 50)]
public double Price { get; set; }
[Column(visible: false)]
public Dictionary<int, (IComponentModel, int)> SecureComponents { get; set; } = new();
}
}

View File

@@ -0,0 +1,10 @@
namespace SecuritySystemDataModels.Models
{
public interface IImplementerModel : IId
{
string ImplementerFIO { get; }
string Password { get; }
int WorkExperience { get; }
int Qualification { get; }
}
}

View File

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

View File

@@ -6,6 +6,7 @@ namespace SecuritySystemDataModels.Models
{
int SecureId { get; }
int ClientId { get; }
int? ImplementerId { get; }
int Count { get; }
double Sum { get; }
OrderStatus Status { get; }

View File

@@ -0,0 +1,21 @@
using SecuritySystemContracts.DI;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemDatabaseImplement.Implements;
namespace SecuritySystemDatabaseImplement
{
public class DatabaseImplementationExtension : IImplementationExtension
{
public int Priority => 2;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IComponentStorage, ComponentStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<ISecureStorage, SecureStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfoStorage, BackUpInfoStorage>();
}
}
}

View File

@@ -0,0 +1,27 @@
using SecuritySystemContracts.StoragesContracts;
namespace SecuritySystemDatabaseImplement.Implements
{
public class BackUpInfoStorage : IBackUpInfoStorage
{
public List<T>? GetList<T>() where T : class, new()
{
using var context = new SecuritySystemDatabase();
return context.Set<T>().ToList();
}
public Type? GetTypeByModelInterface(string modelInterfaceName)
{
var assembly = typeof(BackUpInfoStorage).Assembly;
var types = assembly.GetTypes();
foreach (var type in types)
{
if (type.IsClass &&
type.GetInterface(modelInterfaceName) != null)
{
return type;
}
}
return null;
}
}
}

View File

@@ -0,0 +1,80 @@
using Microsoft.IdentityModel.Tokens;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDatabaseImplement.Models;
namespace SecuritySystemDatabaseImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
using var context = new SecuritySystemDatabase();
var element = context.Implementers.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Implementers.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
return GetFilteredList(model).FirstOrDefault();
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
var implementers = GetFullList();
if (model.Id.HasValue)
{
implementers = implementers.Where(x => x.Id == model.Id.Value).ToList();
}
if (!model.Password.IsNullOrEmpty())
{
implementers = implementers.Where(x => x.Password == model.Password).ToList();
}
if (!model.ImplementerFIO.IsNullOrEmpty())
{
implementers = implementers.Where(x => x.ImplementerFIO == model.ImplementerFIO).ToList();
}
return implementers;
}
public List<ImplementerViewModel> GetFullList()
{
using var context = new SecuritySystemDatabase();
return context.Implementers.Select(x => x.GetViewModel).ToList();
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
var newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
using var context = new SecuritySystemDatabase();
context.Implementers.Add(newImplementer);
context.SaveChanges();
return newImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
using var context = new SecuritySystemDatabase();
var client = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
return null;
}
client.Update(model);
context.SaveChanges();
return client.GetViewModel;
}
}
}

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,35 +11,33 @@ namespace SecuritySystemDatabaseImplement.Implements
{
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new SecuritySystemDatabase();
return context.Orders.Include(x => x.Secure).Include(x => x.Client).FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
return GetFilteredList(model).FirstOrDefault();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
using var context = new SecuritySystemDatabase();
var orders = context.Orders
.Include(x => x.Secure)
.Include(x => x.Client)
.Select(x => x.GetViewModel)
.ToList();
if (model.Id.HasValue)
var orders = GetFullList();
if (model.Id != null)
{
orders = orders.Where(x => x.Id == model.Id.Value).ToList();
}
if (model.DateFrom.HasValue)
if (model.Status != null)
{
orders = orders.Where(x => x.Status == model.Status.Value).ToList();
}
if (model.ImplementerId != null)
{
orders = orders.Where(x => x.ImplementerId == model.ImplementerId.Value).ToList();
}
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();
}
@@ -49,7 +47,12 @@ namespace SecuritySystemDatabaseImplement.Implements
public List<OrderViewModel> GetFullList()
{
using var context = new SecuritySystemDatabase();
return context.Orders.Include(x => x.Secure).Include(x => x.Client).Select(x => x.GetViewModel).ToList();
return context.Orders
.Include(x => x.Secure)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Select(x => x.GetViewModel)
.ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
@@ -62,7 +65,7 @@ namespace SecuritySystemDatabaseImplement.Implements
using var context = new SecuritySystemDatabase();
context.Orders.Add(newOrder);
context.SaveChanges();
return context.Orders.Include(x => x.Secure).Include(x => x.Client).FirstOrDefault(x => x.Id == newOrder.Id)?.GetViewModel;
return GetFullList().FirstOrDefault(x => x.Id == newOrder.Id);
}
public OrderViewModel? Update(OrderBindingModel model)
@@ -75,7 +78,7 @@ namespace SecuritySystemDatabaseImplement.Implements
}
order.Update(model);
context.SaveChanges();
return context.Orders.Include(x => x.Secure).Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
return GetFullList().FirstOrDefault(x => x.Id == model.Id);
}
public OrderViewModel? Delete(OrderBindingModel model)
{

View File

@@ -0,0 +1,257 @@
// <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("20240422063546_AddImplementer")]
partial class AddImplementer
{
/// <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.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.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("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,67 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SecuritySystemDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class AddImplementer : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "ImplementerId",
table: "Orders",
type: "int",
nullable: true);
migrationBuilder.CreateTable(
name: "Implementers",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ImplementerFIO = table.Column<string>(type: "nvarchar(max)", nullable: false),
Password = table.Column<string>(type: "nvarchar(max)", nullable: false),
Qualification = table.Column<int>(type: "int", nullable: false),
WorkExperience = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Implementers", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
migrationBuilder.AddForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
table: "Orders",
column: "ImplementerId",
principalTable: "Implementers",
principalColumn: "Id");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
table: "Orders");
migrationBuilder.DropTable(
name: "Implementers");
migrationBuilder.DropIndex(
name: "IX_Orders_ImplementerId",
table: "Orders");
migrationBuilder.DropColumn(
name: "ImplementerId",
table: "Orders");
}
}
}

View File

@@ -0,0 +1,257 @@
// <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("20240422083731_ClearOrders")]
partial class ClearOrders
{
/// <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.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.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("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,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SecuritySystemDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class ClearOrders : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("DELETE FROM Orders;");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

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

@@ -67,6 +67,63 @@ namespace SecuritySystemDatabaseImplement.Migrations
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")
@@ -87,6 +144,9 @@ namespace SecuritySystemDatabaseImplement.Migrations
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("SecureId")
.HasColumnType("int");
@@ -100,6 +160,8 @@ namespace SecuritySystemDatabaseImplement.Migrations
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("SecureId");
b.ToTable("Orders");
@@ -151,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")
@@ -159,6 +230,10 @@ namespace SecuritySystemDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SecuritySystemDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("SecuritySystemDatabaseImplement.Models.Secure", "Secure")
.WithMany("Orders")
.HasForeignKey("SecureId")
@@ -167,6 +242,8 @@ namespace SecuritySystemDatabaseImplement.Migrations
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Secure");
});
@@ -191,6 +268,8 @@ namespace SecuritySystemDatabaseImplement.Migrations
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Client", b =>
{
b.Navigation("MessageInfos");
b.Navigation("Orders");
});
@@ -199,6 +278,11 @@ namespace SecuritySystemDatabaseImplement.Migrations
b.Navigation("SecureComponents");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Secure", b =>
{
b.Navigation("Components");

View File

@@ -3,20 +3,28 @@ using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
namespace SecuritySystemDatabaseImplement.Models
{
[DataContract]
public class Client : IClientModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
[Required]
public string ClientFIO { get; private set; } = string.Empty;
[DataMember]
[Required]
public string Email { get; private set; } = string.Empty;
[DataMember]
[Required]
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

@@ -3,19 +3,23 @@ using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace SecuritySystemDatabaseImplement.Models
{
[DataContract]
public class Component : IComponentModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
[Required]
public string ComponentName { get; private set; } = string.Empty;
[DataMember]
[Required]
public double Cost { get; set; }
[ForeignKey("ComponentId")]
public virtual List<SecureComponent> SecureComponents { get; set; } =
new();
public virtual List<SecureComponent> SecureComponents { get; set; } = new();
public static Component? Create(ComponentBindingModel model)
{
if (model == null)

View File

@@ -0,0 +1,75 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
namespace SecuritySystemDatabaseImplement.Models
{
[DataContract]
public class Implementer : IImplementerModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
[Required]
public string ImplementerFIO { get; private set; } = string.Empty;
[DataMember]
[Required]
public string Password { get; private set; } = string.Empty;
[DataMember]
[Required]
public int Qualification { get; private set; }
[DataMember]
[Required]
public int WorkExperience { get; private set; }
[ForeignKey("ImplementerId")]
public virtual List<Order> Orders { get; private set; } = new();
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
Qualification = model.Qualification,
Password = model.Password,
ImplementerFIO = model.ImplementerFIO,
WorkExperience = model.WorkExperience
};
}
public static Implementer Create(ImplementerViewModel model)
{
return new Implementer
{
Id = model.Id,
Qualification = model.Qualification,
Password = model.Password,
ImplementerFIO = model.ImplementerFIO,
WorkExperience = model.WorkExperience
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
Qualification = model.Qualification;
Password = model.Password;
ImplementerFIO = model.ImplementerFIO;
WorkExperience = model.WorkExperience;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Qualification = Qualification,
Password = Password,
ImplementerFIO = ImplementerFIO,
WorkExperience = WorkExperience
};
}
}

View File

@@ -0,0 +1,85 @@
using Microsoft.EntityFrameworkCore;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace SecuritySystemDatabaseImplement.Models
{
[DataContract]
[PrimaryKey("MessageId")]
public class MessageInfo : IMessageInfoModel
{
[DataMember]
public string MessageId { get; set; } = string.Empty;
[DataMember]
public int? ClientId { get; set; }
public virtual Client? Client { get; set; }
[DataMember]
[Required]
public string SenderName { get; set; } = string.Empty;
[DataMember]
[Required]
public DateTime DateDelivery { get; set; } = DateTime.Now;
[DataMember]
[Required]
public string Subject { get; set; } = string.Empty;
[DataMember]
[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,
};
public int Id => throw new NotImplementedException();
}
}

View File

@@ -3,27 +3,40 @@ using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Enums;
using SecuritySystemDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace SecuritySystemDatabaseImplement.Models
{
[DataContract]
public class Order : IOrderModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
[Required]
public int SecureId { get; private set; }
[DataMember]
[Required]
public int ClientId { get; private set; }
[DataMember]
public int? ImplementerId { get; private set; }
[DataMember]
[Required]
public int Count { get; private set; }
[DataMember]
[Required]
public double Sum { get; private set; }
[DataMember]
[Required]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[DataMember]
[Required]
public DateTime DateCreate { get; private set; } = DateTime.Now;
[DataMember]
public DateTime? DateImplement { get; private set; }
public virtual Secure Secure { get; private set; }
public virtual Client Client { get; private set; }
public virtual Implementer? Implementer { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
@@ -40,6 +53,7 @@ namespace SecuritySystemDatabaseImplement.Models
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
Id = model.Id,
ImplementerId = model.ImplementerId
};
}
@@ -51,6 +65,7 @@ namespace SecuritySystemDatabaseImplement.Models
}
Status = model.Status;
DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
}
public OrderViewModel GetViewModel => new()
@@ -64,7 +79,9 @@ namespace SecuritySystemDatabaseImplement.Models
Id = Id,
Status = Status,
SecureName = Secure.SecureName,
ClientFIO = Client.ClientFIO
ClientFIO = Client.ClientFIO,
ImplementerId = ImplementerId,
ImplementerFIO = Implementer?.ImplementerFIO ?? string.Empty
};
}
}

View File

@@ -3,18 +3,22 @@ using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using System.Runtime.Serialization;
namespace SecuritySystemDatabaseImplement.Models
{
[DataContract]
public class Secure : ISecureModel
{
[DataMember]
public int Id { get; set; }
[DataMember]
[Required]
public string SecureName { get; set; } = string.Empty;
[DataMember]
[Required]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _productComponents =
null;
private Dictionary<int, (IComponentModel, int)>? _productComponents = null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> SecureComponents
{

View File

@@ -1,14 +1,20 @@
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace SecuritySystemDatabaseImplement.Models
{
[DataContract]
public class SecureComponent
{
[DataMember]
public int Id { get; set; }
[DataMember]
[Required]
public int SecureId { get; set; }
[DataMember]
[Required]
public int ComponentId { get; set; }
[DataMember]
[Required]
public int Count { get; set; }
public virtual Component Component { get; set; } = new();

View File

@@ -1,6 +1,5 @@
using Microsoft.EntityFrameworkCore;
using SecuritySystemDatabaseImplement.Models;
using System.ComponentModel;
using Component = SecuritySystemDatabaseImplement.Models.Component;
namespace SecuritySystemDatabaseImplement
@@ -21,6 +20,8 @@ namespace SecuritySystemDatabaseImplement
public virtual DbSet<SecureComponent> SecureComponents { set; get; }
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

@@ -1,24 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Platforms>AnyCPU;x64</Platforms>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Platforms>AnyCPU;x64</Platforms>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SecuritySystemContracts\SecuritySystemContracts.csproj" />
<ProjectReference Include="..\SecuritySystemDataModels\SecuritySystemDataModels.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SecuritySystemContracts\SecuritySystemContracts.csproj" />
<ProjectReference Include="..\SecuritySystemDataModels\SecuritySystemDataModels.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.16">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.16">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project>

View File

@@ -10,10 +10,14 @@ namespace SecuritySystemFileImplement
private readonly string OrderFileName = "Order.xml";
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)
@@ -26,15 +30,18 @@ namespace SecuritySystemFileImplement
public void SaveSecures() => SaveData(Secures, SecureFileName, "Secures", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement);
public void 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)!)!;
Secures = LoadData(SecureFileName, "Secure", x => Secure.Create(x)!)!;
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)
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{
if (File.Exists(filename))
{

View File

@@ -0,0 +1,21 @@
using SecuritySystemContracts.DI;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemFileImplement.Implements;
namespace SecuritySystemFileImplement
{
public class FileImplementationExtension : IImplementationExtension
{
public int Priority => 1;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IComponentStorage, ComponentStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<ISecureStorage, SecureStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfoStorage, BackUpInfoStorage>();
}
}
}

View File

@@ -0,0 +1,39 @@
using SecuritySystemContracts.StoragesContracts;
namespace SecuritySystemFileImplement.Implements
{
public class BackUpInfoStorage : IBackUpInfoStorage
{
private readonly DataFileSingleton source;
public BackUpInfoStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<T>? GetList<T>() where T : class, new()
{
return (List<T>?)source
.GetType()
.GetProperties()
.FirstOrDefault(
x =>
x.PropertyType.IsGenericType &&
x.PropertyType.GetGenericArguments()[0] == typeof(T))?
.GetValue(source);
}
public Type? GetTypeByModelInterface(string modelInterfaceName)
{
var assembly = typeof(BackUpInfoStorage).Assembly;
var types = assembly.GetTypes();
foreach (var type in types)
{
if (type.IsClass &&
type.GetInterface(modelInterfaceName) != null)
{
return type;
}
}
return null;
}
}
}

View File

@@ -0,0 +1,85 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;
using SecuritySystemFileImplement.Models;
namespace SecuritySystemFileImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataFileSingleton source;
public ImplementerStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ImplementerViewModel> GetFullList()
{
return source.Implementers.Select(x => x.GetViewModel).ToList();
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
var clients = source.Implementers
.Select(x => x.GetViewModel)
.ToList();
if (model.Id.HasValue)
{
clients = clients.Where(x => x.Id == model.Id.Value).ToList();
}
if (model.Password != null)
{
clients = clients.Where(x => x.Password == model.Password).ToList();
}
if (model.ImplementerFIO != null)
{
clients = clients.Where(x => x.ImplementerFIO == model.ImplementerFIO).ToList();
}
return clients;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
return GetFilteredList(model).FirstOrDefault();
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = source.Implementers.Count > 0 ? source.Implementers.Max(x => x.Id) + 1 : 1;
var newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
source.Implementers.Add(newImplementer);
source.SaveImplementers();
return newImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
var client = source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
return null;
}
client.Update(model);
source.SaveImplementers();
return client.GetViewModel;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
var element = source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Implementers.Remove(element);
source.SaveImplementers();
return element.GetViewModel;
}
return null;
}
}
}

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

@@ -33,6 +33,14 @@ namespace SecuritySystemFileImplement.Implements
{
orders = orders.Where(x => x.Id == model.Id.Value).ToList();
}
if (model.Status.HasValue)
{
orders = orders.Where(x => x.Status == model.Status.Value).ToList();
}
if (model.ImplementerId.HasValue)
{
orders = orders.Where(x => x.ImplementerId == model.ImplementerId.Value).ToList();
}
if (model.DateFrom.HasValue)
{
orders = orders.Where(x => x.DateCreate >= model.DateFrom.Value).ToList();

View File

@@ -3,15 +3,21 @@ using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using SecuritySystemFileImplement.Models;
using System.Reflection;
using System.Runtime.Serialization;
using System.Xml.Linq;
namespace SecuritySystemFileImplement.Models
{
[DataContract]
public class Client : IClientModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public string ClientFIO { get; private set; } = string.Empty;
[DataMember]
public string Email { get; private set; } = string.Empty;
[DataMember]
public string Password { get; private set; } = string.Empty;
public static Client? Create(ClientBindingModel model)
{
@@ -36,9 +42,9 @@ namespace SecuritySystemFileImplement.Models
return new Client()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
Email = Convert.ToString(element.Attribute("Email")!.Value),
Password = Convert.ToString(element.Attribute("Password")!.Value),
ClientFIO = Convert.ToString(element.Attribute("ClientFIO")!.Value)
Email = Convert.ToString(element.Element("Email")!.Value),
Password = Convert.ToString(element.Element("Password")!.Value),
ClientFIO = Convert.ToString(element.Element("ClientFIO")!.Value)
};
}
public void Update(ClientBindingModel model)

View File

@@ -1,14 +1,19 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using System.Runtime.Serialization;
using System.Xml.Linq;
namespace SecuritySystemFileImplement.Models
{
[DataContract]
public class Component : IComponentModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public string ComponentName { get; private set; } = string.Empty;
[DataMember]
public double Cost { get; set; }
public static Component? Create(ComponentBindingModel model)
{

View File

@@ -0,0 +1,79 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using System.Runtime.Serialization;
using System.Xml.Linq;
namespace SecuritySystemFileImplement.Models
{
[DataContract]
public class Implementer : IImplementerModel
{
[DataMember]
public string ImplementerFIO { get; private set; } = string.Empty;
[DataMember]
public string Password { get; private set; } = string.Empty;
[DataMember]
public int WorkExperience { get; private set; }
[DataMember]
public int Qualification { get; private set; }
[DataMember]
public int Id { get; private set; }
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
Qualification = model.Qualification,
Password = model.Password,
ImplementerFIO = model.ImplementerFIO,
WorkExperience = model.WorkExperience
};
}
public static Implementer? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Implementer()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
Qualification = Convert.ToInt32(element.Element("Qualification")!.Value),
Password = Convert.ToString(element.Element("Password")!.Value),
ImplementerFIO = Convert.ToString(element.Element("ImplementerFIO")!.Value),
WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value)
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
Qualification = model.Qualification;
Password = model.Password;
ImplementerFIO = model.ImplementerFIO;
WorkExperience = model.WorkExperience;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Qualification = Qualification,
Password = Password,
ImplementerFIO = ImplementerFIO,
WorkExperience = WorkExperience
};
public XElement GetXElement => new("Сlient",
new XAttribute("Id", Id),
new XElement("Qualification", Qualification),
new XElement("Password", Password),
new XElement("ImplementerFIO", ImplementerFIO),
new XElement("WorkExperience", WorkExperience)
);
}
}

View File

@@ -0,0 +1,92 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using System.Reflection;
using System.Runtime.Serialization;
using System.Xml.Linq;
namespace SecuritySystemFileImplement.Models
{
[DataContract]
public class MessageInfo : IMessageInfoModel
{
[DataMember]
public string MessageId { get; set; } = string.Empty;
[DataMember]
public int? ClientId { get; set; }
[DataMember]
public string SenderName { get; set; } = string.Empty;
[DataMember]
public DateTime DateDelivery { get; set; } = DateTime.Now;
[DataMember]
public string Subject { get; set; } = string.Empty;
[DataMember]
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 = string.IsNullOrEmpty(element.Element("ClientId")!.Value) ?
null : 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)
);
public int Id => throw new NotImplementedException();
}
}

View File

@@ -2,19 +2,31 @@
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Enums;
using SecuritySystemDataModels.Models;
using System.Runtime.Serialization;
using System.Xml.Linq;
namespace SecuritySystemFileImplement.Models
{
[DataContract]
public class Order : IOrderModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public int SecureId { get; private set; }
[DataMember]
public int ClientId { get; private set; }
[DataMember]
public int? ImplementerId { get; private set; }
[DataMember]
public int Count { get; private set; }
[DataMember]
public double Sum { get; private set; }
[DataMember]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[DataMember]
public DateTime DateCreate { get; private set; } = DateTime.Now;
[DataMember]
public DateTime? DateImplement { get; private set; }
public static Order? Create(OrderBindingModel? model)
@@ -32,6 +44,7 @@ namespace SecuritySystemFileImplement.Models
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
ImplementerId = model.ImplementerId
};
}
@@ -49,7 +62,10 @@ namespace SecuritySystemFileImplement.Models
Count = Convert.ToInt32(element.Element("Count")!.Value),
Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value),
DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value),
DateImplement = string.IsNullOrEmpty(element.Element("DateImplement")!.Value) ? null : Convert.ToDateTime(element.Element("DateImplement")!.Value)
DateImplement = string.IsNullOrEmpty(element.Element("DateImplement")!.Value) ?
null : Convert.ToDateTime(element.Element("DateImplement")!.Value),
ImplementerId = string.IsNullOrEmpty(element.Element("ImplementerId")!.Value) ?
null : Convert.ToInt32(element.Element("ImplementerId")!.Value),
};
}
@@ -61,6 +77,7 @@ namespace SecuritySystemFileImplement.Models
}
Status = model.Status;
DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
}
public OrderViewModel GetViewModel => new()
@@ -72,6 +89,7 @@ namespace SecuritySystemFileImplement.Models
DateCreate = DateCreate,
DateImplement = DateImplement,
Status = Status,
ImplementerId = ImplementerId,
};
public XElement GetXElement => new(
@@ -82,7 +100,8 @@ namespace SecuritySystemFileImplement.Models
new XElement("Sum", Sum.ToString()),
new XElement("Status", Status.ToString()),
new XElement("DateCreate", DateCreate.ToString()),
new XElement("DateImplement", DateImplement.ToString())
new XElement("DateImplement", DateImplement.ToString()),
new XElement("ImplementerId", ImplementerId.ToString())
);
}
}

View File

@@ -1,17 +1,23 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using System.Runtime.Serialization;
using System.Xml.Linq;
namespace SecuritySystemFileImplement.Models
{
[DataContract]
public class Secure : ISecureModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public string SecureName { get; private set; } = string.Empty;
[DataMember]
public double Price { get; private set; }
public Dictionary<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _secureComponents = null;
[DataMember]
public Dictionary<int, (IComponentModel, int)> SecureComponents
{
get

View File

@@ -1,15 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Platforms>AnyCPU;x64;x86</Platforms>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Platforms>AnyCPU;x64;x86</Platforms>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SecuritySystemContracts\SecuritySystemContracts.csproj" />
<ProjectReference Include="..\SecuritySystemDataModels\SecuritySystemDataModels.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SecuritySystemContracts\SecuritySystemContracts.csproj" />
<ProjectReference Include="..\SecuritySystemDataModels\SecuritySystemDataModels.csproj" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project>

View File

@@ -9,12 +9,16 @@ namespace SecuritySystemListImplement
public List<Order> Orders { get; set; }
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>();
Orders = new List<Order>();
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,17 @@
using SecuritySystemContracts.StoragesContracts;
namespace SecuritySystemListImplement.Implements
{
public class BackUpInfoStorage : IBackUpInfoStorage
{
public List<T>? GetList<T>() where T : class, new()
{
throw new NotImplementedException();
}
public Type? GetTypeByModelInterface(string modelInterfaceName)
{
throw new NotImplementedException();
}
}
}

View File

@@ -0,0 +1,99 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;
using SecuritySystemListImplement.Models;
namespace SecuritySystemListImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataListSingleton _source;
public ImplementerStorage(DataListSingleton source)
{
_source = DataListSingleton.GetInstance();
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
for (int i = 0; i < _source.Implementers.Count; ++i)
{
if (_source.Implementers[i].Id == model.Id)
{
var element = _source.Implementers[i];
_source.Implementers.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
return GetFilteredList(model).FirstOrDefault();
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
var implementers = _source.Implementers
.Select(x => x.GetViewModel)
.ToList();
if (model.Id.HasValue)
{
implementers = implementers.Where(x => x.Id == model.Id.Value).ToList();
}
if (model.Password != null)
{
implementers = implementers.Where(x => x.Password == model.Password).ToList();
}
if (model.ImplementerFIO != null)
{
implementers = implementers.Where(x => x.ImplementerFIO == model.ImplementerFIO).ToList();
}
return implementers;
}
public List<ImplementerViewModel> GetFullList()
{
var result = new List<ImplementerViewModel>();
foreach (var implementer in _source.Implementers)
{
result.Add(implementer.GetViewModel);
}
return result;
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = 1;
foreach (var implementer in _source.Implementers)
{
if (model.Id <= implementer.Id)
{
model.Id = implementer.Id + 1;
}
}
var newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
_source.Implementers.Add(newImplementer);
return newImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
foreach (var implementer in _source.Implementers)
{
if (implementer.Id == model.Id)
{
implementer.Update(model);
return implementer.GetViewModel;
}
}
return null;
}
}
}

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

@@ -31,6 +31,14 @@ namespace SecuritySystemListImplement.Implements
{
orders = orders.Where(x => x.Id == model.Id.Value).ToList();
}
if (model.Status.HasValue)
{
orders = orders.Where(x => x.Status == model.Status.Value).ToList();
}
if (model.ImplementerId.HasValue)
{
orders = orders.Where(x => x.ImplementerId == model.ImplementerId.Value).ToList();
}
if (model.DateFrom.HasValue)
{
orders = orders.Where(x => x.DateCreate >= model.DateFrom.Value).ToList();

View File

@@ -0,0 +1,21 @@
using SecuritySystemContracts.DI;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemListImplement.Implements;
namespace SecuritySystemListImplement
{
public class ListImplementationExtension : IImplementationExtension
{
public int Priority => 0;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IComponentStorage, ComponentStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<ISecureStorage, SecureStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfoStorage, BackUpInfoStorage>();
}
}
}

View File

@@ -0,0 +1,49 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
namespace SecuritySystemListImplement.Models
{
public class Implementer : IImplementerModel
{
public string ImplementerFIO { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty;
public int WorkExperience { get; private set; }
public int Qualification { get; private set; }
public int Id { get; private set; }
public static Implementer? Create(ImplementerBindingModel? model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
Qualification = model.Qualification,
Password = model.Password,
ImplementerFIO = model.ImplementerFIO,
WorkExperience = model.WorkExperience
};
}
public void Update(ImplementerBindingModel? model)
{
if (model == null)
{
return;
}
Qualification = model.Qualification;
Password = model.Password;
ImplementerFIO = model.ImplementerFIO;
WorkExperience = model.WorkExperience;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Qualification = Qualification,
Password = Password,
ImplementerFIO = ImplementerFIO,
WorkExperience = WorkExperience
};
}
}

View File

@@ -0,0 +1,57 @@
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,
};
public int Id => throw new NotImplementedException();
}
}

View File

@@ -1,15 +1,17 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Enums;
using SecuritySystemDataModels.Models;
namespace SecuritySystemListImplement.Models
{
public class Order
public class Order : IOrderModel
{
public int SecureId { get; private set; }
public int ClientId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public int? ImplementerId { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
@@ -29,6 +31,7 @@ namespace SecuritySystemListImplement.Models
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
ImplementerId = model.ImplementerId,
};
}
public void Update(OrderBindingModel? model)
@@ -39,6 +42,7 @@ namespace SecuritySystemListImplement.Models
}
Status = model.Status;
DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
}
public OrderViewModel GetViewModel => new()
{
@@ -49,6 +53,7 @@ namespace SecuritySystemListImplement.Models
DateImplement = DateImplement,
Id = Id,
Status = Status,
ImplementerId = ImplementerId,
};
}
}

View File

@@ -12,4 +12,8 @@
<ProjectReference Include="..\SecuritySystemDataModels\SecuritySystemDataModels.csproj" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project>

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

@@ -0,0 +1,100 @@
using DocumentFormat.OpenXml.Office2010.Excel;
using Microsoft.AspNetCore.Mvc;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.BusinessLogicsContracts;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Enums;
namespace SecuritySystemRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ImplementerController : Controller
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IImplementerLogic _implementerLogic;
public ImplementerController(IOrderLogic order, IImplementerLogic logic, ILogger<ImplementerController> logger)
{
_logger = logger;
_orderLogic = order;
_implementerLogic = logic;
}
[HttpGet]
public ImplementerViewModel? Login(string login, string password)
{
try
{
return _implementerLogic.ReadElement(new ImplementerSearchModel
{
ImplementerFIO = login,
Password = password
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка авторизации сотрудника");
throw;
}
}
[HttpGet]
public List<OrderViewModel>? GetNewOrders()
{
try
{
return _orderLogic.ReadList(new OrderSearchModel
{
Status = OrderStatus.Принят
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения новых заказов");
throw;
}
}
[HttpGet]
public OrderViewModel? GetImplementerOrder(int implementerId)
{
try
{
return _orderLogic.ReadElement(new OrderSearchModel
{
ImplementerId = implementerId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения текущего заказа исполнителя");
throw;
}
}
[HttpPost]
public void TakeOrderInWork(OrderBindingModel model)
{
try
{
_orderLogic.TakeOrderInWork(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка перевода заказа с #{Id} в работу", model.Id);
throw;
}
}
[HttpPost]
public void FinishOrder(OrderBindingModel model)
{
try
{
_orderLogic.FinishOrder(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа с #{Id}", model.Id);
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.beget.com",
"SmtpClientPort": "2525",
"PopHost": "pop3.beget.com",
"PopPort": "995",
"MailLogin": "securitysystemshop@nspotapov.ru",
"MailPassword": "2iD8*KBY"
}

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SmtpClientHost" value="smtp.beget.com" />
<add key="SmtpClientPort" value="2525" />
<add key="PopHost" value="pop3.beget.com" />
<add key="PopPort" value="995" />
<add key="MailLogin" value="securitysystemshop@nspotapov.ru" />
<add key="MailPassword" value="2iD8*KBY" />
</appSettings>
</configuration>

Some files were not shown because too many files have changed in this diff Show More