From ef719ee68956b666d75ca72284ad4fa4501693e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=B0=D0=BC=D0=B8=D1=80=20=D0=9D=D1=83=D0=B3=D0=B0?= =?UTF-8?q?=D0=B5=D0=B2?= Date: Sat, 3 Jun 2023 22:02:28 +0400 Subject: [PATCH] LabWork08 --- .../BlacksmithWorkshopBusinessLogic.csproj | 19 +- .../BusinessLogic/BackUpLogic.cs | 129 ++++++ .../BusinessLogic/ClientLogic.cs | 231 +++++------ .../Attributes/ColumnAttribute.cs | 12 + .../Attributes/GridViewAutoSize.cs | 27 ++ .../BindingModels/BackUpSaveBinidngModel.cs | 13 + .../BindingModels/MessageInfoBindingModel.cs | 2 + .../BlacksmithWorkshopContracts.csproj | 24 +- .../BusinessLogicsContracts/IBackUpLogic.cs | 12 + .../DI/DependencyManager.cs | 63 +++ .../DI/IDependencyContainer.cs | 26 ++ .../DI/IImplementationExtension.cs | 12 + .../DI/ServiceDependencyContainer.cs | 12 + .../DI/ServiceProviderLoader.cs | 61 +++ .../DI/UnityDependencyContainer.cs | 43 ++ .../StoragesContracts/IBackUpInfo.cs | 12 + .../ViewModels/ClientViewModel.cs | 24 +- .../ViewModels/ImplementerViewModel.cs | 12 +- .../ViewModels/ManufactureViewModel.cs | 25 +- .../ViewModels/MessageInfoViewModel.cs | 16 +- .../ViewModels/OrderViewModel.cs | 24 +- .../ViewModels/WorkPieceViewModel.cs | 20 +- .../Models/IMessageInfoModel.cs | 2 +- ...BlacksmithWorkshopDatabaseImplement.csproj | 40 +- .../DataBaseImplementationExtension.cs | 33 ++ .../Implements/BackUpInfo.cs | 36 ++ .../Models/Client.cs | 6 + .../Models/Implementer.cs | 7 + .../Models/Manufacture.cs | 174 +++++---- .../Models/ManufactureWorkPiece.cs | 28 +- .../Models/MessageInfo.cs | 9 +- .../Models/Order.cs | 11 + .../Models/WorkPiece.cs | 103 ++--- .../BlacksmithWorkshopFileImplement.csproj | 25 +- .../FileImplementationExtension.cs | 34 ++ .../Implements/BackUpInfo.cs | 12 + .../Models/Client.cs | 120 +++--- .../Models/Implementer.cs | 7 + .../Models/Manufacture.cs | 165 ++++---- .../Models/MessageInfo.cs | 10 + .../Models/Order.cs | 11 + .../Models/WorkPiece.cs | 109 +++--- .../BlacksmithWorkshopListImplement.csproj | 24 +- .../Implements/BackUpInfo.cs | 22 ++ .../ListImplementationExtension.cs | 34 ++ .../Models/MessageInfo.cs | 2 + .../DataGridViewExtension.cs | 63 +++ .../BlacksmithWorkshopView/FormClients.cs | 127 +++--- .../FormImplementers.cs | 36 +- .../BlacksmithWorkshopView/FormMails.cs | 10 +- .../FormMain.Designer.cs | 79 ++-- .../BlacksmithWorkshopView/FormMain.cs | 166 ++++---- .../BlacksmithWorkshopView/FormManufacture.cs | 367 +++++++++--------- .../FormManufactures.cs | 176 ++++----- .../BlacksmithWorkshopView/FormWorkPieces.cs | 180 ++++----- .../BlacksmithWorkshopView/Program.cs | 86 ++-- BlacksmithWorkshop/Для бэкапа.zip | Bin 0 -> 1726 bytes 57 files changed, 1921 insertions(+), 1212 deletions(-) create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/BackUpLogic.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/Attributes/ColumnAttribute.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/Attributes/GridViewAutoSize.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/BackUpSaveBinidngModel.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IBackUpLogic.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/DependencyManager.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/IDependencyContainer.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/IImplementationExtension.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/ServiceDependencyContainer.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/ServiceProviderLoader.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/UnityDependencyContainer.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IBackUpInfo.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/DataBaseImplementationExtension.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/BackUpInfo.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopFileImplement/FileImplementationExtension.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/BackUpInfo.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/BackUpInfo.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopListImplement/ListImplementationExtension.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopView/DataGridViewExtension.cs create mode 100644 BlacksmithWorkshop/Для бэкапа.zip diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BlacksmithWorkshopBusinessLogic.csproj b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BlacksmithWorkshopBusinessLogic.csproj index a72b0d1..02eef14 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BlacksmithWorkshopBusinessLogic.csproj +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BlacksmithWorkshopBusinessLogic.csproj @@ -1,10 +1,10 @@ - - net6.0 - enable - enable - + + net6.0 + enable + enable + @@ -13,9 +13,8 @@ - - + + + - - - + \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/BackUpLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/BackUpLogic.cs new file mode 100644 index 0000000..3bddeca --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/BackUpLogic.cs @@ -0,0 +1,129 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.StoragesContracts; +using BlacksmithWorkshopDataModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.IO.Compression; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization.Json; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopBusinessLogic.BusinessLogic +{ + public class BackUpLogic : IBackUpLogic + { + private readonly ILogger _logger; + + private readonly IBackUpInfo _backUpInfo; + + public BackUpLogic(ILogger logger, IBackUpInfo backUpInfo) + { + _logger = logger; + _backUpInfo = backUpInfo; + } + + public void CreateBackUp(BackUpSaveBinidngModel 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) + { + //проверка на то, является ли тип интерфейсом и унаследован ли он от IId + 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(string folderName) where T : class, new() + { + var records = _backUpInfo.GetList(); + + if (records == null) + { + _logger.LogWarning("{type} type get null list", typeof(T).Name); + + return; + } + + //три строчки ниже - сериализация файлов в json + var jsonFormatter = new DataContractJsonSerializer(typeof(List)); + + using var fs = new FileStream(string.Format("{0}/{1}.json", folderName, typeof(T).Name), FileMode.OpenOrCreate); + + jsonFormatter.WriteObject(fs, records); + } + } + +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/ClientLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/ClientLogic.cs index ebadb4d..a767b4d 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/ClientLogic.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/ClientLogic.cs @@ -8,153 +8,164 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace BlacksmithWorkshopBusinessLogic.BusinessLogic { - public class ClientLogic : IClientLogic - { - private readonly ILogger _logger; + public class ClientLogic : IClientLogic + { + private readonly ILogger _logger; - private readonly IClientStorage _clientStorage; + private readonly IClientStorage _clientStorage; - public ClientLogic(ILogger logger, IClientStorage clientStorage) - { - _logger = logger; - _clientStorage = clientStorage; - } + public ClientLogic(ILogger logger, IClientStorage clientStorage) + { + _logger = logger; + _clientStorage = clientStorage; + } - public List? ReadList(ClientSearchModel? model) - { - _logger.LogInformation("ReadList. ClientFIO:{ClientFIO}. Id:{Id}", model?.ClientFIO, model?.Id); + public List? ReadList(ClientSearchModel? model) + { + _logger.LogInformation("ReadList. ClientFIO:{ClientFIO}. Id:{Id}", model?.ClientFIO, model?.Id); - //list хранит весь список в случае, если model пришло со значением null на вход метода - var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model); + //list хранит весь список в случае, если model пришло со значением null на вход метода + var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model); - if (list == null) - { - _logger.LogWarning("ReadList return null list"); - return null; - } + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } - _logger.LogInformation("ReadList. Count:{Count}", list.Count); + _logger.LogInformation("ReadList. Count:{Count}", list.Count); - return list; - } + return list; + } - public ClientViewModel? ReadElement(ClientSearchModel model) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } + public ClientViewModel? ReadElement(ClientSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } - _logger.LogInformation("ReadList. ClientFIO:{ClientFIO}. Id:{Id}", model.ClientFIO, model?.Id); + _logger.LogInformation("ReadList. ClientFIO:{ClientFIO}. Id:{Id}", model.ClientFIO, model?.Id); - var element = _clientStorage.GetElement(model); + var element = _clientStorage.GetElement(model); - if (element == null) - { - _logger.LogWarning("ReadElement element not found"); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); - return null; - } + return null; + } - _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); - return element; - } + return element; + } - public bool Create(ClientBindingModel model) - { - CheckModel(model); + public bool Create(ClientBindingModel model) + { + CheckModel(model); - if (_clientStorage.Insert(model) == null) - { - _logger.LogWarning("Insert operation failed"); + if (_clientStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); - return false; - } + return false; + } - return true; - } + return true; + } - public bool Update(ClientBindingModel model) - { - CheckModel(model); + public bool Update(ClientBindingModel model) + { + CheckModel(model); - if (_clientStorage.Update(model) == null) - { - _logger.LogWarning("Update operation failed"); + if (_clientStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); - return false; - } + return false; + } - return true; - } + return true; + } - public bool Delete(ClientBindingModel model) - { - CheckModel(model, false); + public bool Delete(ClientBindingModel model) + { + CheckModel(model, false); - _logger.LogInformation("Delete. Id:{Id}", model.Id); + _logger.LogInformation("Delete. Id:{Id}", model.Id); - if (_clientStorage.Delete(model) == null) - { - _logger.LogWarning("Delete operation failed"); + if (_clientStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); - return false; - } + return false; + } - return true; - } + return true; + } - //проверка входного аргумента для методов Insert, Update и Delete - private void CheckModel(ClientBindingModel model, bool withParams = true) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } + //проверка входного аргумента для методов Insert, Update и Delete + private void CheckModel(ClientBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } - //так как при удалении передаём как параметр false - if (!withParams) - { - return; - } + //так как при удалении передаём как параметр false + if (!withParams) + { + return; + } - //проверка на наличие ФИО - if (string.IsNullOrEmpty(model.ClientFIO)) - { - throw new ArgumentNullException("Отсутствие ФИО в учётной записи", nameof(model.ClientFIO)); - } + //проверка на наличие ФИО + if (string.IsNullOrEmpty(model.ClientFIO)) + { + throw new ArgumentNullException("Отсутствие ФИО в учётной записи", nameof(model.ClientFIO)); + } - //проверка на наличие почты - if (string.IsNullOrEmpty(model.Email)) - { - throw new ArgumentNullException("Отсутствие почты в учётной записи (логина)", nameof(model.Email)); - } + //проверка на наличие почты + if (string.IsNullOrEmpty(model.Email)) + { + throw new ArgumentNullException("Отсутствие почты в учётной записи (логина)", nameof(model.Email)); + } - //проверка на наличие пароля - if (string.IsNullOrEmpty(model.Password)) - { - throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password)); - } + //проверка на наличие пароля + if (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password)); + } - _logger.LogInformation("WorkPiece. ClientFIO:{ClientFIO}. Email:{Email}. Password:{Password}. Id:{Id}", - model.ClientFIO, model.Email, model.Password, model.Id); + if (!Regex.IsMatch(model.Email, @"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$", RegexOptions.IgnoreCase)) + { + throw new ArgumentException("Некорректная почта", nameof(model.Email)); + } - //для проверка на наличие такого же аккаунта - var element = _clientStorage.GetElement(new ClientSearchModel - { - Email = model.Email, - }); + if (!Regex.IsMatch(model.Password, @"^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$", RegexOptions.IgnoreCase) && model.Password.Length < 10 && model.Password.Length > 50) + { + throw new ArgumentException("Необходимо придумать другой пароль", nameof(model.Password)); + } - //если элемент найден и его Id не совпадает с Id переданного объекта - if (element != null && element.Id != model.Id) - { - throw new InvalidOperationException("Аккаунт с таким логином уже есть"); - } - } - } + _logger.LogInformation("Client. ClientFIO:{ClientFIO}. Email:{Email}. Password:{Password}. Id:{Id}", + model.ClientFIO, model.Email, model.Password, model.Id); + + //для проверка на наличие такого же аккаунта + var element = _clientStorage.GetElement(new ClientSearchModel + { + Email = model.Email, + }); + + //если элемент найден и его Id не совпадает с Id переданного объекта + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Аккаунт с таким логином уже есть"); + } + } + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/Attributes/ColumnAttribute.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/Attributes/ColumnAttribute.cs new file mode 100644 index 0000000..d41dc62 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/Attributes/ColumnAttribute.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.Attributes +{ + internal class ColumnAttribute + { + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/Attributes/GridViewAutoSize.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/Attributes/GridViewAutoSize.cs new file mode 100644 index 0000000..74db4a8 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/Attributes/GridViewAutoSize.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.Attributes +{ + public enum GridViewAutoSize + { + NotSet = 0, + + None = 1, + + ColumnHeader = 2, + + AllCellsExceptHeader = 4, + + AllCells = 6, + + DisplayedCellsExceptHeader = 8, + + DisplayedCells = 10, + + Fill = 16 + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/BackUpSaveBinidngModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/BackUpSaveBinidngModel.cs new file mode 100644 index 0000000..5f1b9c2 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/BackUpSaveBinidngModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.BindingModels +{ + public class BackUpSaveBinidngModel + { + public string FolderName { get; set; } = string.Empty; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MessageInfoBindingModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MessageInfoBindingModel.cs index 0436419..720e4ed 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MessageInfoBindingModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MessageInfoBindingModel.cs @@ -9,6 +9,8 @@ namespace BlacksmithWorkshopContracts.BindingModels { public class MessageInfoBindingModel : IMessageInfoModel { + public int Id { get; set; } + public string MessageId { get; set; } = string.Empty; public int? ClientId { get; set; } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BlacksmithWorkshopContracts.csproj b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BlacksmithWorkshopContracts.csproj index f685e06..2a5c408 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BlacksmithWorkshopContracts.csproj +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BlacksmithWorkshopContracts.csproj @@ -1,13 +1,19 @@ - - net6.0 - enable - enable - + + net6.0 + enable + enable + - - - + + + + + - + + + + + \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IBackUpLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IBackUpLogic.cs new file mode 100644 index 0000000..dc6b464 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IBackUpLogic.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.BusinessLogicsContracts +{ + internal interface IBackUpLogic + { + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/DependencyManager.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/DependencyManager.cs new file mode 100644 index 0000000..486cb7b --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/DependencyManager.cs @@ -0,0 +1,63 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.DI +{ + /// + /// Менеджер для работы с зависимостями + /// + public class DependencyManager + { + private readonly IDependencyContainer _dependencyManager; + + private static DependencyManager? _manager; + + private static readonly object _locjObject = new(); + + private DependencyManager() + { + _dependencyManager = new UnityDependencyContainer(); + } + + public static DependencyManager Instance + { + get + { + if (_manager == null) { lock (_locjObject) { _manager = new DependencyManager(); } } + + return _manager; + } + } + + //Иницализация библиотек, в которых идут установки зависомстей + public static void InitDependency() + { + var ext = ServiceProviderLoader.GetImplementationExtensions(); + + if (ext == null) + { + throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям"); + } + + // регистрируем зависимости + ext.RegisterServices(); + } + + //Регистрация логгера + public void AddLogging(Action configure) => _dependencyManager.AddLogging(configure); + + //Добавление зависимости + public void RegisterType(bool isSingle = false) where U : class, T where T : class => _dependencyManager.RegisterType(isSingle); + + //Добавление зависимости + public void RegisterType(bool isSingle = false) where T : class => _dependencyManager.RegisterType(isSingle); + + //Получение класса со всеми зависмостями + public T Resolve() => _dependencyManager.Resolve(); + } + +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/IDependencyContainer.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/IDependencyContainer.cs new file mode 100644 index 0000000..c1a2105 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/IDependencyContainer.cs @@ -0,0 +1,26 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.DI +{ + //Интерфейс установки зависмости между элементами + public interface IDependencyContainer + { + //Регистрация логгера + void AddLogging(Action configure); + + //Добавление зависимости + void RegisterType(bool isSingle) where U : class, T where T : + class; + + //Добавление зависимости + void RegisterType(bool isSingle) where T : class; + + //Получение класса со всеми зависмостями + T Resolve(); + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/IImplementationExtension.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/IImplementationExtension.cs new file mode 100644 index 0000000..5e2a78e --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/IImplementationExtension.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.DI +{ + internal interface IImplementationExtension + { + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/ServiceDependencyContainer.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/ServiceDependencyContainer.cs new file mode 100644 index 0000000..631ee4d --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/ServiceDependencyContainer.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.DI +{ + internal class ServiceDependencyContainer + { + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/ServiceProviderLoader.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/ServiceProviderLoader.cs new file mode 100644 index 0000000..a7e2cca --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/ServiceProviderLoader.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.DI +{ + //Загрузчик данных + public static partial class ServiceProviderLoader + { + //Загрузка всех классов-реализаций IImplementationExtension + 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"; + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/UnityDependencyContainer.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/UnityDependencyContainer.cs new file mode 100644 index 0000000..32ce8ae --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/UnityDependencyContainer.cs @@ -0,0 +1,43 @@ +using Microsoft.Extensions.Logging; +using Unity.Microsoft.Logging; +using Unity; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.DI +{ + public class UnityDependencyContainer : IDependencyContainer + { + private readonly IUnityContainer _container; + + public UnityDependencyContainer() + { + _container = new UnityContainer(); + } + + public void AddLogging(Action configure) + { + var factory = LoggerFactory.Create(configure); + _container.AddExtension(new LoggingExtension(factory)); + } + + public void RegisterType(bool isSingle) where T : class + { + _container.RegisterType(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient); + + } + + public T Resolve() + { + return _container.Resolve(); + } + + void IDependencyContainer.RegisterType(bool isSingle) + { + _container.RegisterType(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient); + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IBackUpInfo.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IBackUpInfo.cs new file mode 100644 index 0000000..32f8d32 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IBackUpInfo.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.StoragesContracts +{ + internal interface IBackUpInfo + { + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ClientViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ClientViewModel.cs index 7ef898a..8712828 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ClientViewModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ClientViewModel.cs @@ -1,4 +1,5 @@ -using BlacksmithWorkshopDataModels.Models; +using BlacksmithWorkshopContracts.Attributes; +using BlacksmithWorkshopDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -8,18 +9,19 @@ using System.Threading.Tasks; namespace BlacksmithWorkshopContracts.ViewModels { - public class ClientViewModel : IClientModel - { - public int Id { get; set; } + public class ClientViewModel : IClientModel + { + [Column(visible: false)] + public int Id { get; set; } - [DisplayName("ФИО клиента")] - public string ClientFIO { get; set; } = string.Empty; + [Column(title: "ФИО клиента", width: 150)] + public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Логин (эл. почта)")] - public string Email { get; set; } = string.Empty; + [Column(title: "Логие (эл. почта)", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string Email { get; set; } = string.Empty; - [DisplayName("Пароль")] - public string Password { get; set; } = string.Empty; + [Column(title: "Пароль", width: 150)] + public string Password { get; set; } = string.Empty; - } + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ImplementerViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ImplementerViewModel.cs index 3260cb7..5a768c7 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ImplementerViewModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ImplementerViewModel.cs @@ -1,4 +1,5 @@ -using BlacksmithWorkshopDataModels.Models; +using BlacksmithWorkshopContracts.Attributes; +using BlacksmithWorkshopDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,18 +11,19 @@ namespace BlacksmithWorkshopContracts.ViewModels { public class ImplementerViewModel : IImplementerModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("ФИО исполнителя")] + [Column(title: "ФИО исполнителя", width: 150)] public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Пароль")] + [Column(title: "Пароль", width: 150)] public string Password { get; set; } = string.Empty; - [DisplayName("Стаж")] + [Column(title: "Стаж", width: 150)] public int WorkExperience { get; set; } - [DisplayName("Квалификация")] + [Column(title: "Квалификация", width: 150)] public int Qualification { get; set; } } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ManufactureViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ManufactureViewModel.cs index 9a4946f..1863dc7 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ManufactureViewModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ManufactureViewModel.cs @@ -1,4 +1,5 @@ -using BlacksmithWorkshopDataModels.Models; +using BlacksmithWorkshopContracts.Attributes; +using BlacksmithWorkshopDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -8,17 +9,19 @@ using System.Threading.Tasks; namespace BlacksmithWorkshopContracts.ViewModels { - //класс для отображения пользователю информаци о продуктах (изделиях) - public class ManufactureViewModel : IManufactureModel - { - public int Id { get; set; } + //класс для отображения пользователю информаци о продуктах (изделиях) + public class ManufactureViewModel : IManufactureModel + { + [Column(visible: false)] + public int Id { get; set; } - [DisplayName("Навание изделия")] - public string ManufactureName { get; set; } = string.Empty; + [Column(title: "Навание изделия", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string ManufactureName { get; set; } = string.Empty; - [DisplayName("Цена")] - public double Price { get; set; } + [Column(title: "Цена", width: 150)] + public double Price { get; set; } - public Dictionary ManufactureWorkPieces { get; set; } = new(); - } + [Column(visible: false)] + public Dictionary ManufactureWorkPieces { get; set; } = new(); + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/MessageInfoViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/MessageInfoViewModel.cs index 3973c63..aad6d07 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/MessageInfoViewModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/MessageInfoViewModel.cs @@ -1,4 +1,5 @@ -using BlacksmithWorkshopDataModels.Models; +using BlacksmithWorkshopContracts.Attributes; +using BlacksmithWorkshopDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,20 +11,25 @@ namespace BlacksmithWorkshopContracts.ViewModels { public class MessageInfoViewModel : IMessageInfoModel { + [Column(visible: false)] + public int Id { get; set; } + + [Column(visible: false)] public string MessageId { get; set; } = string.Empty; + [Column(visible: false)] public int? ClientId { get; set; } - [DisplayName("Отправитель")] + [Column(title: "Отправитель", width: 150)] public string SenderName { get; set; } = string.Empty; - [DisplayName("Дата отправки")] + [Column(title: "Дата отправки", width: 150)] public DateTime DateDelivery { get; set; } = DateTime.Now; - [DisplayName("Заголовок")] + [Column(title: "Заголовок", width: 150)] public string Subject { get; set; } = string.Empty; - [DisplayName("Текст")] + [Column(title: "Текст", width: 150)] public string Body { get; set; } = string.Empty; } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/OrderViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/OrderViewModel.cs index e400b3f..1d85523 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/OrderViewModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/OrderViewModel.cs @@ -1,4 +1,5 @@ -using BlacksmithWorkshopDataModels.Enums; +using BlacksmithWorkshopContracts.Attributes; +using BlacksmithWorkshopDataModels.Enums; using BlacksmithWorkshopDataModels.Models; using System; using System.Collections.Generic; @@ -12,37 +13,40 @@ namespace BlacksmithWorkshopContracts.ViewModels //класс для отображения пользователю информации о заказах public class OrderViewModel : IOrderModel { - [DisplayName("Номер")] + [Column(visible: false)] public int Id { get; set; } + [Column(visible: false)] public int ClientId { get; set; } + [Column(visible: false)] public int? ImplementerId { get; set; } + [Column(visible: false)] public int ManufactureId { get; set; } - [DisplayName("ФИО клиента")] + [Column(title: "ФИО клиента", width: 150)] public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Изделие")] + [Column(title: "Изделие", width: 150)] public string ManufactureName { get; set; } = string.Empty; - [DisplayName("ФИО исполнителя")] + [Column(title: "ФИО исполнителя", width: 150)] public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Количество")] + [Column(title: "Количество", width: 150)] public int Count { get; set; } - [DisplayName("Сумма")] + [Column(title: "Сумма", width: 150)] public double Sum { get; set; } - [DisplayName("Статус")] + [Column(title: "Статус", width: 150)] public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; - [DisplayName("Дата создания")] + [Column(title: "Дата создания", width: 150)] public DateTime DateCreate { get; set; } = DateTime.Now; - [DisplayName("Дата выполнения")] + [Column(title: "Дата выполнения", width: 150)] public DateTime? DateImplement { get; set; } } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/WorkPieceViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/WorkPieceViewModel.cs index 17e1910..f5e90dc 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/WorkPieceViewModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/WorkPieceViewModel.cs @@ -5,18 +5,20 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using BlacksmithWorkshopContracts.Attributes; namespace BlacksmithWorkshopContracts.ViewModels { - //класс для отображения пользователю данных о заготовких (заготовках) - public class WorkPieceViewModel : IWorkPieceModel - { - public int Id { get; set; } + //класс для отображения пользователю данных о заготовких (заготовках) + public class WorkPieceViewModel : IWorkPieceModel + { + [Column(visible: false)] + public int Id { get; set; } - [DisplayName("Название заготовки")] - public string WorkPieceName { get; set; } = string.Empty; + [Column(title: "Название заготовки", width: 150)] + public string WorkPieceName { get; set; } = string.Empty; - [DisplayName("Цена")] - public double Cost { get; set; } - } + [Column(title: "Цена", width: 150)] + public double Cost { get; set; } + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IMessageInfoModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IMessageInfoModel.cs index 2882524..7e186b2 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IMessageInfoModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IMessageInfoModel.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace BlacksmithWorkshopDataModels.Models { - public interface IMessageInfoModel + public interface IMessageInfoModel : IId { string MessageId { get; } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/BlacksmithWorkshopDatabaseImplement.csproj b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/BlacksmithWorkshopDatabaseImplement.csproj index bdecbbd..76a4020 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/BlacksmithWorkshopDatabaseImplement.csproj +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/BlacksmithWorkshopDatabaseImplement.csproj @@ -1,23 +1,27 @@ - - net6.0 - enable - enable - + + net6.0 + enable + enable + - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + - - - - + + + + - + + + + + \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/DataBaseImplementationExtension.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/DataBaseImplementationExtension.cs new file mode 100644 index 0000000..9a181f5 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/DataBaseImplementationExtension.cs @@ -0,0 +1,33 @@ +using BlacksmithWorkshopContracts.DI; +using BlacksmithWorkshopContracts.StoragesContracts; +using BlacksmithWorkshopDatabaseImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopDatabaseImplement +{ + public class DataBaseImplementationExtension : IImplementationExtension + { + public int Priority => 2; + + public void RegisterServices() + { + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/BackUpInfo.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..c15e5bc --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/BackUpInfo.cs @@ -0,0 +1,36 @@ +using BlacksmithWorkshopContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopDatabaseImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + using var context = new BlacksmithWorkshopDatabase(); + + return context.Set().ToList(); + } + + public Type? GetTypeByModelInterface(string modelInterfaceName) + { + var assembly = typeof(BackUpInfo).Assembly; + var types = assembly.GetTypes(); + + foreach (var type in types) + { + if (type.IsClass && type.GetInterface(modelInterfaceName) != null) + { + return type; + } + } + + return null; + } + } + +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Client.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Client.cs index 5369a34..953384b 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Client.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Client.cs @@ -6,22 +6,28 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace BlacksmithWorkshopDatabaseImplement.Models { + [DataContract] public class Client : IClientModel { + [DataMember] public int Id { get; set; } [Required] + [DataMember] public string ClientFIO { get; set; } = string.Empty; [Required] + [DataMember] public string Email { get; set; } = string.Empty; [Required] + [DataMember] public string Password { get; set; } = string.Empty; //для реализации связи многие ко многим с заказами (так как клиенты могу сделать одинаковый заказ) diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Implementer.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Implementer.cs index 963c158..c53947d 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Implementer.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Implementer.cs @@ -6,25 +6,32 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace BlacksmithWorkshopDatabaseImplement.Models { + [DataContract] public class Implementer : IImplementerModel { + [DataMember] public int Id { get; set; } [Required] + [DataMember] public string ImplementerFIO { get; set; } = string.Empty; [Required] + [DataMember] public string Password { get; set; } = string.Empty; [Required] + [DataMember] public int WorkExperience { get; set; } [Required] + [DataMember] public int Qualification { get; set; } //для реализации связи один ко многим с заказами diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Manufacture.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Manufacture.cs index 742aa11..3ed56d4 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Manufacture.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Manufacture.cs @@ -7,112 +7,118 @@ using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace BlacksmithWorkshopDatabaseImplement.Models { - public class Manufacture : IManufactureModel - { - public int Id { get; set; } + [DataContract] + public class Manufacture : IManufactureModel + { + [DataMember] + public int Id { get; set; } - [Required] - public string ManufactureName { get; set; } = string.Empty; + [Required] + [DataMember] + public string ManufactureName { get; set; } = string.Empty; - [Required] - public double Price { get; set; } + [Required] + [DataMember] + public double Price { get; set; } - public Dictionary? _manufactureWorkPieces = null; + public Dictionary? _manufactureWorkPieces = null; - //это поле не будет "мапиться" в бд - [NotMapped] - public Dictionary ManufactureWorkPieces - { - get - { - if(_manufactureWorkPieces == null) - { - _manufactureWorkPieces = WorkPieces - .ToDictionary(recPC => recPC.WorkPieceId, recPC => (recPC.WorkPiece as IWorkPieceModel, recPC.Count)); - } + //это поле не будет "мапиться" в бд + [NotMapped] + [DataMember] + public Dictionary ManufactureWorkPieces + { + get + { + if (_manufactureWorkPieces == null) + { + _manufactureWorkPieces = WorkPieces + .ToDictionary(recPC => recPC.WorkPieceId, recPC => (recPC.WorkPiece as IWorkPieceModel, recPC.Count)); + } - return _manufactureWorkPieces; - } - } + return _manufactureWorkPieces; + } + } - //для реализации связи многие ко многим с заготовками - [ForeignKey("ManufactureId")] - public virtual List WorkPieces { get; set; } = new(); + //для реализации связи многие ко многим с заготовками + [ForeignKey("ManufactureId")] + public virtual List WorkPieces { get; set; } = new(); - [ForeignKey("ManufactureId")] - public virtual List Orders { get; set; } = new(); + [ForeignKey("ManufactureId")] + public virtual List Orders { get; set; } = new(); - public static Manufacture Create(BlacksmithWorkshopDatabase context, ManufactureBindingModel model) - { - return new Manufacture() - { - Id = model.Id, - ManufactureName = model.ManufactureName, - Price = model.Price, - WorkPieces = model.ManufactureWorkPieces.Select(x => new ManufactureWorkPiece - { - WorkPiece = context.WorkPieces.First(y => y.Id == x.Key), - Count = x.Value.Item2 - }).ToList() - }; - } + public static Manufacture Create(BlacksmithWorkshopDatabase context, ManufactureBindingModel model) + { + return new Manufacture() + { + Id = model.Id, + ManufactureName = model.ManufactureName, + Price = model.Price, + WorkPieces = model.ManufactureWorkPieces.Select(x => new ManufactureWorkPiece + { + WorkPiece = context.WorkPieces.First(y => y.Id == x.Key), + Count = x.Value.Item2 + }).ToList() + }; + } - public void Update(ManufactureBindingModel model) - { - ManufactureName = model.ManufactureName; - Price = model.Price; - } + public void Update(ManufactureBindingModel model) + { + ManufactureName = model.ManufactureName; + Price = model.Price; + } - public ManufactureViewModel GetViewModel => new() - { - Id = Id, - ManufactureName = ManufactureName, - Price = Price, - ManufactureWorkPieces = ManufactureWorkPieces - }; + public ManufactureViewModel GetViewModel => new() + { + Id = Id, + ManufactureName = ManufactureName, + Price = Price, + ManufactureWorkPieces = ManufactureWorkPieces + }; - Dictionary IManufactureModel.ManufactureWorkPieces => throw new NotImplementedException(); + Dictionary IManufactureModel.ManufactureWorkPieces => throw new NotImplementedException(); - public void UpdateWorkPieces(BlacksmithWorkshopDatabase context, ManufactureBindingModel model) - { - var manufactureWorkPieces = context.ManufactureWorkPieces.Where(rec => rec.ManufactureId == model.Id).ToList(); + public void UpdateWorkPieces(BlacksmithWorkshopDatabase context, ManufactureBindingModel model) + { + var manufactureWorkPieces = context.ManufactureWorkPieces.Where(rec => rec.ManufactureId == model.Id).ToList(); - if (manufactureWorkPieces != null && manufactureWorkPieces.Count > 0) - { - // удалили те, которых нет в модели - context.ManufactureWorkPieces.RemoveRange(manufactureWorkPieces.Where(rec => !model.ManufactureWorkPieces.ContainsKey(rec.ManufactureId))); - context.SaveChanges(); + if (manufactureWorkPieces != null && manufactureWorkPieces.Count > 0) + { + // удалили те, которых нет в модели + context.ManufactureWorkPieces.RemoveRange(manufactureWorkPieces.Where(rec => !model.ManufactureWorkPieces.ContainsKey(rec.ManufactureId))); + context.SaveChanges(); - // обновили количество у существующих записей - foreach (var updateManufacture in manufactureWorkPieces) - { - updateManufacture.Count = model.ManufactureWorkPieces[updateManufacture.ManufactureId].Item2; - model.ManufactureWorkPieces.Remove(updateManufacture.ManufactureId); - } + // обновили количество у существующих записей + foreach (var updateManufacture in manufactureWorkPieces) + { + updateManufacture.Count = model.ManufactureWorkPieces[updateManufacture.ManufactureId].Item2; + model.ManufactureWorkPieces.Remove(updateManufacture.ManufactureId); + } - context.SaveChanges(); - } + context.SaveChanges(); + } - var manufacture = context.Manufactures.First(x => x.Id == Id); + var manufacture = context.Manufactures.First(x => x.Id == Id); - foreach (var pc in model.ManufactureWorkPieces) - { - context.ManufactureWorkPieces.Add(new ManufactureWorkPiece - { - Manufacture = manufacture, - WorkPiece = context.WorkPieces.First(x => x.Id == pc.Key), - Count = pc.Value.Item2 - }); + foreach (var pc in model.ManufactureWorkPieces) + { + context.ManufactureWorkPieces.Add(new ManufactureWorkPiece + { + Manufacture = manufacture, + WorkPiece = context.WorkPieces.First(x => x.Id == pc.Key), + Count = pc.Value.Item2 + }); - context.SaveChanges(); - } + context.SaveChanges(); + } - _manufactureWorkPieces = null; - } - } + _manufactureWorkPieces = null; + } + } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/ManufactureWorkPiece.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/ManufactureWorkPiece.cs index dbe90f6..17e4e0a 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/ManufactureWorkPiece.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/ManufactureWorkPiece.cs @@ -2,26 +2,28 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace BlacksmithWorkshopDatabaseImplement.Models { - public class ManufactureWorkPiece - { - public int Id { get; set; } + [DataContract] + public class ManufactureWorkPiece + { + public int Id { get; set; } - [Required] - public int ManufactureId { get; set; } + [Required] + public int ManufactureId { get; set; } - [Required] - public int WorkPieceId { get; set; } + [Required] + public int WorkPieceId { get; set; } - [Required] - public int Count { get; set; } + [Required] + public int Count { get; set; } - public virtual WorkPiece WorkPiece { get; set; } = new(); + public virtual WorkPiece WorkPiece { get; set; } = new(); - public virtual Manufacture Manufacture { get; set; } = new(); - } -} + public virtual Manufacture Manufacture { get; set; } = new(); + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/MessageInfo.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/MessageInfo.cs index 98544af..5596270 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/MessageInfo.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/MessageInfo.cs @@ -5,28 +5,29 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace BlacksmithWorkshopDatabaseImplement.Models { + [DataContract] public class MessageInfo : IMessageInfoModel { + public int Id => throw new NotImplementedException(); + [Key] + [DataMember] public string MessageId { get; set; } = string.Empty; public int? ClientId { get; set; } - [Required] public string SenderName { get; set; } = string.Empty; - [Required] public DateTime DateDelivery { get; set; } = DateTime.Now; - [Required] public string Subject { get; set; } = string.Empty; - [Required] public string Body { get; set; } = string.Empty; public virtual Client? Client { get; set; } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Order.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Order.cs index d899de2..318c207 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Order.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Order.cs @@ -6,36 +6,47 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace BlacksmithWorkshopDatabaseImplement.Models { + [DataContract] public class Order : IOrderModel { + [DataMember] public int Id { get; private set; } [Required] + [DataMember] public int ManufactureId { get; private set; } [Required] + [DataMember] public int ClientId { get; private set; } + [DataMember] public int? ImplementerId { get; private set; } [Required] + [DataMember] public int Count { get; private set; } [Required] + [DataMember] public double Sum { get; private set; } [Required] + [DataMember] public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; [Required] + [DataMember] public DateTime DateCreate { get; private set; } = DateTime.Now; + [DataMember] public DateTime? DateImplement { get; private set; } //для передачи названия изделия diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/WorkPiece.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/WorkPiece.cs index 8ef7ca3..d0de924 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/WorkPiece.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/WorkPiece.cs @@ -7,66 +7,71 @@ using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace BlacksmithWorkshopDatabaseImplement.Models { - public class WorkPiece : IWorkPieceModel - { - public int Id { get; private set; } + [DataContract] + public class WorkPiece : IWorkPieceModel + { + [DataMember] + public int Id { get; private set; } - [Required] - public string WorkPieceName { get; private set; } = string.Empty; + [Required] + [DataMember] + public string WorkPieceName { get; private set; } = string.Empty; - [Required] - public double Cost { get; set; } + [Required] + [DataMember] + public double Cost { get; set; } - //для реализации связи многие ко многим с изделиями - [ForeignKey("WorkPieceId")] - public virtual List ManufactureWorkPieces { get; set; } = new(); + //для реализации связи многие ко многим с изделиями + [ForeignKey("WorkPieceId")] + public virtual List ManufactureWorkPieces { get; set; } = new(); - public static WorkPiece? Create(WorkPieceBindingModel model) - { - if(model == null) - { - return null; - } + public static WorkPiece? Create(WorkPieceBindingModel model) + { + if (model == null) + { + return null; + } - return new WorkPiece() - { - Id = model.Id, - WorkPieceName = model.WorkPieceName, - Cost = model.Cost - }; - } + return new WorkPiece() + { + Id = model.Id, + WorkPieceName = model.WorkPieceName, + Cost = model.Cost + }; + } - public static WorkPiece Create(WorkPieceViewModel model) - { - return new WorkPiece - { - Id = model.Id, - WorkPieceName = model.WorkPieceName, - Cost = model.Cost - }; - } + public static WorkPiece Create(WorkPieceViewModel model) + { + return new WorkPiece + { + Id = model.Id, + WorkPieceName = model.WorkPieceName, + Cost = model.Cost + }; + } - public void Update(WorkPieceBindingModel model) - { - if(model == null) - { - return; - } + public void Update(WorkPieceBindingModel model) + { + if (model == null) + { + return; + } - WorkPieceName = model.WorkPieceName; - Cost = model.Cost; - } + WorkPieceName = model.WorkPieceName; + Cost = model.Cost; + } - public WorkPieceViewModel GetViewModel => new() - { - Id = Id, - WorkPieceName = WorkPieceName, - Cost = Cost - }; - } -} + public WorkPieceViewModel GetViewModel => new() + { + Id = Id, + WorkPieceName = WorkPieceName, + Cost = Cost + }; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/BlacksmithWorkshopFileImplement.csproj b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/BlacksmithWorkshopFileImplement.csproj index c1033f7..0b53093 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/BlacksmithWorkshopFileImplement.csproj +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/BlacksmithWorkshopFileImplement.csproj @@ -1,15 +1,18 @@ - - net6.0 - enable - enable - + + net6.0 + enable + enable + - - - - - + + + + - + + + + + \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/FileImplementationExtension.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/FileImplementationExtension.cs new file mode 100644 index 0000000..ecc72ab --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/FileImplementationExtension.cs @@ -0,0 +1,34 @@ +using BlacksmithWorkshopContracts.DI; +using BlacksmithWorkshopContracts.StoragesContracts; +using BlacksmithWorkshopFileImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopFileImplement +{ + //для реализации нужных нам зависимостей в данном варианте хранения информации + public class FileImplementationExtension : IImplementationExtension + { + public int Priority => 1; + + public void RegisterServices() + { + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/BackUpInfo.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..b6ae6af --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/BackUpInfo.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopFileImplement.Implements +{ + internal class BackUpInfo + { + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Client.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Client.cs index f00dc0a..dbda54b 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Client.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Client.cs @@ -7,78 +7,84 @@ using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace BlacksmithWorkshopFileImplement.Models { - public class Client : IClientModel - { - public int Id { get; private set; } + [DataContract] + public class Client : IClientModel + { + [DataMember] + public int Id { get; private set; } - public string ClientFIO { get; private set; } = string.Empty; + [DataMember] + public string ClientFIO { get; private set; } = string.Empty; - public string Email { get; private set; } = string.Empty; + [DataMember] + public string Email { get; private set; } = string.Empty; - public string Password { get; private set; } = string.Empty; + [DataMember] + public string Password { get; private set; } = string.Empty; - public static Client? Create(ClientBindingModel model) - { - if (model == null) - { - return null; - } + public static Client? Create(ClientBindingModel model) + { + if (model == null) + { + return null; + } - return new Client() - { - Id = model.Id, - ClientFIO = model.ClientFIO, - Email = model.Email, - Password = model.Password - }; - } + return new Client() + { + Id = model.Id, + ClientFIO = model.ClientFIO, + Email = model.Email, + Password = model.Password + }; + } - public static Client? Create(XElement element) - { - if (element == null) - { - return null; - } + public static Client? Create(XElement element) + { + if (element == null) + { + return null; + } - return new Client() - { - Id = Convert.ToInt32(element.Attribute("Id")!.Value), - ClientFIO = element.Element("ClientFIO")!.Value, - Email = element.Element("Email")!.Value, - Password = element.Element("Password")!.Value - }; - } + return new Client() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ClientFIO = element.Element("ClientFIO")!.Value, + Email = element.Element("Email")!.Value, + Password = element.Element("Password")!.Value + }; + } - public void Update(ClientBindingModel model) - { - if (model == null) - { - return; - } + public void Update(ClientBindingModel model) + { + if (model == null) + { + return; + } - ClientFIO = model.ClientFIO; - Email = model.Email; - Password = model.Password; - } + ClientFIO = model.ClientFIO; + Email = model.Email; + Password = model.Password; + } - public ClientViewModel GetViewModel => new() - { - Id = Id, - ClientFIO = ClientFIO, - Email = Email, - Password = Password - }; + public ClientViewModel GetViewModel => new() + { + Id = Id, + ClientFIO = ClientFIO, + Email = Email, + Password = Password + }; - public XElement GetXElement => new("Order", - new XAttribute("Id", Id), - new XElement("ClientFIO", ClientFIO), - new XElement("Email", Email), - new XElement("Password", Password)); - } + public XElement GetXElement => new("Order", + new XAttribute("Id", Id), + new XElement("ClientFIO", ClientFIO), + new XElement("Email", Email), + new XElement("Password", Password)); + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Implementer.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Implementer.cs index 9c09e35..63413d1 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Implementer.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Implementer.cs @@ -5,22 +5,29 @@ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace BlacksmithWorkshopFileImplement.Models { + [DataContract] public class Implementer : IImplementerModel { + [DataMember] public int Id { get; private set; } + [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; } public static Implementer? Create(ImplementerBindingModel model) diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Manufacture.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Manufacture.cs index 59951e5..0a077e8 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Manufacture.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Manufacture.cs @@ -4,105 +4,110 @@ using BlacksmithWorkshopDataModels.Models; using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace BlacksmithWorkshopFileImplement.Models { - //класс реализующий интерфейс модели изделия - public class Manufacture : IManufactureModel - { - public int Id { get; private set; } + //класс реализующий интерфейс модели изделия + [DataContract] + public class Manufacture : IManufactureModel + { + [DataMember] + public int Id { get; private set; } - public string ManufactureName { get; private set; } = string.Empty; + [DataMember] + public string ManufactureName { get; private set; } = string.Empty; - public double Price { get; private set; } + [DataMember] + public double Price { get; private set; } - public Dictionary WorkPieces { get; private set; } = new(); + public Dictionary WorkPieces { get; private set; } = new(); + private Dictionary? _manufactureWorkPieces = null; - private Dictionary? _manufactureWorkPieces = null; + [DataMember] + public Dictionary ManufactureWorkPieces + { + get + { + if (_manufactureWorkPieces == null) + { + var source = DataFileSingleton.GetInstance(); - public Dictionary ManufactureWorkPieces - { - get - { - if (_manufactureWorkPieces == null) - { - var source = DataFileSingleton.GetInstance(); + _manufactureWorkPieces = WorkPieces.ToDictionary(x => x.Key, + y => ((source.WorkPieces.FirstOrDefault(z => z.Id == y.Key) as IWorkPieceModel)!, y.Value)); + } - _manufactureWorkPieces = WorkPieces.ToDictionary(x => x.Key, - y => ((source.WorkPieces.FirstOrDefault(z => z.Id == y.Key) as IWorkPieceModel)!, y.Value)); - } + return _manufactureWorkPieces; + } + } - return _manufactureWorkPieces; - } - } + public static Manufacture? Create(ManufactureBindingModel model) + { + if (model == null) + { + return null; + } - public static Manufacture? Create(ManufactureBindingModel model) - { - if (model == null) - { - return null; - } + return new Manufacture() + { + Id = model.Id, + ManufactureName = model.ManufactureName, + Price = model.Price, + WorkPieces = model.ManufactureWorkPieces.ToDictionary(x => x.Key, x => x.Value.Item2) + }; + } - return new Manufacture() - { - Id = model.Id, - ManufactureName = model.ManufactureName, - Price = model.Price, - WorkPieces = model.ManufactureWorkPieces.ToDictionary(x => x.Key, x => x.Value.Item2) - }; - } + public static Manufacture? Create(XElement element) + { + if (element == null) + { + return null; + } - public static Manufacture? Create(XElement element) - { - if (element == null) - { - return null; - } + return new Manufacture() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ManufactureName = element.Element("ManufactureName")!.Value, + Price = Convert.ToDouble(element.Element("Price")!.Value), + WorkPieces = element.Element("ManufactureWorkPieces")!.Elements("ManufactureWorkPieces").ToDictionary( + x => Convert.ToInt32(x.Element("Key")?.Value), + x => Convert.ToInt32(x.Element("Value")?.Value)) + }; + } - return new Manufacture() - { - Id = Convert.ToInt32(element.Attribute("Id")!.Value), - ManufactureName = element.Element("ManufactureName")!.Value, - Price = Convert.ToDouble(element.Element("Price")!.Value), - WorkPieces = element.Element("ManufactureWorkPieces")!.Elements("ManufactureWorkPieces").ToDictionary( - x => Convert.ToInt32(x.Element("Key")?.Value), - x => Convert.ToInt32(x.Element("Value")?.Value)) - }; - } + public void Update(ManufactureBindingModel model) + { + if (model == null) + { + return; + } - public void Update(ManufactureBindingModel model) - { - if (model == null) - { - return; - } + ManufactureName = model.ManufactureName; + Price = model.Price; + WorkPieces = model.ManufactureWorkPieces.ToDictionary(x => x.Key, x => x.Value.Item2); + _manufactureWorkPieces = null; + } - ManufactureName = model.ManufactureName; - Price = model.Price; - WorkPieces = model.ManufactureWorkPieces.ToDictionary(x => x.Key, x => x.Value.Item2); - _manufactureWorkPieces = null; - } + public ManufactureViewModel GetViewModel => new() + { + Id = Id, + ManufactureName = ManufactureName, + Price = Price, + ManufactureWorkPieces = ManufactureWorkPieces + }; - public ManufactureViewModel GetViewModel => new() - { - Id = Id, - ManufactureName = ManufactureName, - Price = Price, - ManufactureWorkPieces = ManufactureWorkPieces - }; - - public XElement GetXElement => new("Manufacture", - new XAttribute("Id", Id), - new XElement("ManufactureName", ManufactureName), - new XElement("Price", Price.ToString()), - new XElement("ManufactureWorkPieces", WorkPieces.Select( - x => new XElement("ManufactureWorkPieces", - new XElement("Key", x.Key), - new XElement("Value", x.Value)) - ).ToArray())); - } + public XElement GetXElement => new("Manufacture", + new XAttribute("Id", Id), + new XElement("ManufactureName", ManufactureName), + new XElement("Price", Price.ToString()), + new XElement("ManufactureWorkPieces", WorkPieces.Select( + x => new XElement("ManufactureWorkPieces", + new XElement("Key", x.Key), + new XElement("Value", x.Value)) + ).ToArray())); + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/MessageInfo.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/MessageInfo.cs index 61398e1..847cc35 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/MessageInfo.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/MessageInfo.cs @@ -6,24 +6,34 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace BlacksmithWorkshopFileImplement.Models { + [DataContract] public class MessageInfo : IMessageInfoModel { + public int Id { get; private set; } + + [DataMember] public string MessageId { get; private set; } = string.Empty; + [DataMember] public int? ClientId { get; private set; } + [DataMember] public string SenderName { get; private set; } = string.Empty; + [DataMember] public DateTime DateDelivery { get; private set; } = DateTime.Now; + [DataMember] public string Subject { get; private set; } = string.Empty; + [DataMember] public string Body { get; private set; } = string.Empty; public static MessageInfo? Create(MessageInfoBindingModel model) diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Order.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Order.cs index 0c9df8c..b7148e7 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Order.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Order.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; @@ -13,24 +14,34 @@ using System.Xml.Linq; namespace BlacksmithWorkshopFileImplement.Models { //класс, реализующий интерфейс модели заказа + [DataContract] public class Order : IOrderModel { + [DataMember] public int Id { get; private set; } + [DataMember] public int ClientId { get; private set; } + [DataMember] public int? ImplementerId { get; private set; } + [DataMember] public int ManufactureId { 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) diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/WorkPiece.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/WorkPiece.cs index c9e4eb0..8613a48 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/WorkPiece.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/WorkPiece.cs @@ -5,72 +5,77 @@ using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace BlacksmithWorkshopFileImplement.Models { - //реализация интерфейса модели заготовки - public class WorkPiece : IWorkPieceModel - { - public int Id { get; private set; } + //реализация интерфейса модели заготовки + [DataContract] + public class WorkPiece : IWorkPieceModel + { + [DataMember] + public int Id { get; private set; } - public string WorkPieceName { get; private set; } = string.Empty; + [DataMember] + public string WorkPieceName { get; private set; } = string.Empty; - public double Cost { get; set; } + [DataMember] + public double Cost { get; set; } - public static WorkPiece? Create(WorkPieceBindingModel model) - { - if (model == null) - { - return null; - } + public static WorkPiece? Create(WorkPieceBindingModel model) + { + if (model == null) + { + return null; + } - return new WorkPiece() - { - Id = model.Id, - WorkPieceName = model.WorkPieceName, - Cost = model.Cost - }; - } + return new WorkPiece() + { + Id = model.Id, + WorkPieceName = model.WorkPieceName, + Cost = model.Cost + }; + } - public static WorkPiece? Create(XElement element) - { - if (element == null) - { - return null; - } + public static WorkPiece? Create(XElement element) + { + if (element == null) + { + return null; + } - return new WorkPiece() - { - Id = Convert.ToInt32(element.Attribute("Id")!.Value), - WorkPieceName = element.Element("WorkPieceName")!.Value, - Cost = Convert.ToDouble(element.Element("Cost")!.Value) - }; - } + return new WorkPiece() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + WorkPieceName = element.Element("WorkPieceName")!.Value, + Cost = Convert.ToDouble(element.Element("Cost")!.Value) + }; + } - public void Update(WorkPieceBindingModel model) - { - if (model == null) - { - return; - } + public void Update(WorkPieceBindingModel model) + { + if (model == null) + { + return; + } - WorkPieceName = model.WorkPieceName; - Cost = model.Cost; - } + WorkPieceName = model.WorkPieceName; + Cost = model.Cost; + } - public WorkPieceViewModel GetViewModel => new() - { - Id = Id, - WorkPieceName = WorkPieceName, - Cost = Cost - }; + public WorkPieceViewModel GetViewModel => new() + { + Id = Id, + WorkPieceName = WorkPieceName, + Cost = Cost + }; - public XElement GetXElement => new("WorkPiece", - new XAttribute("Id", Id), - new XElement("WorkPieceName", WorkPieceName), - new XElement("Cost", Cost.ToString())); - } + public XElement GetXElement => new("WorkPiece", + new XAttribute("Id", Id), + new XElement("WorkPieceName", WorkPieceName), + new XElement("Cost", Cost.ToString())); + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/BlacksmithWorkshopListImplement.csproj b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/BlacksmithWorkshopListImplement.csproj index b65badc..0b53093 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/BlacksmithWorkshopListImplement.csproj +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/BlacksmithWorkshopListImplement.csproj @@ -1,14 +1,18 @@ - - net6.0 - enable - enable - + + net6.0 + enable + enable + - - - - + + + + - + + + + + \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/BackUpInfo.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..163082c --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/BackUpInfo.cs @@ -0,0 +1,22 @@ +using BlacksmithWorkshopContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopListImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + throw new NotImplementedException(); + } + + public Type? GetTypeByModelInterface(string modelInterfaceName) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/ListImplementationExtension.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/ListImplementationExtension.cs new file mode 100644 index 0000000..ca37fad --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/ListImplementationExtension.cs @@ -0,0 +1,34 @@ +using BlacksmithWorkshopContracts.DI; +using BlacksmithWorkshopContracts.StoragesContracts; +using BlacksmithWorkshopListImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopListImplement +{ + public class ListImplementationExtension : IImplementationExtension + { + public int Priority => 0; + + public void RegisterServices() + { + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + } + } + +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/MessageInfo.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/MessageInfo.cs index 54117c8..ee7a586 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/MessageInfo.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/MessageInfo.cs @@ -12,6 +12,8 @@ namespace BlacksmithWorkshopListImplement.Models { public class MessageInfo : IMessageInfoModel { + public int Id { get; private set; } + public string MessageId { get; private set; } = string.Empty; public int? ClientId { get; private set; } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/DataGridViewExtension.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/DataGridViewExtension.cs new file mode 100644 index 0000000..7e76b6f --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/DataGridViewExtension.cs @@ -0,0 +1,63 @@ +using BlacksmithWorkshopContracts.Attributes; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshop +{ + public static class DataGridViewExtension + { + public static void FillandConfigGrid(this DataGridView grid, List? data) + { + if (data == null) + { + return; + } + + grid.DataSource = data; + + //получаем тип + var type = typeof(T); + + //получаем свойства + var properties = type.GetProperties(); + + foreach (DataGridViewColumn column in grid.Columns) + { + var property = properties.FirstOrDefault(x => x.Name == column.Name); + + if (property == null) + { + throw new InvalidOperationException($"В типе {type.Name} не найдено свойство с именем {column.Name}"); + } + + var attribute = property.GetCustomAttributes(typeof(ColumnAttribute), true)?.SingleOrDefault(); + + if (attribute == null) + { + throw new InvalidOperationException($"Не найден атрибут типа ColumnAttribute для свойства {property.Name}"); + } + + // ищем нужный нам атрибут + if (attribute is ColumnAttribute columnAttr) + { + column.HeaderText = columnAttr.Title; + column.Visible = columnAttr.Visible; + + if (columnAttr.IsUseAutoSize) + { + column.AutoSizeMode = (DataGridViewAutoSizeColumnMode)Enum.Parse(typeof(DataGridViewAutoSizeColumnMode), + columnAttr.GridViewAutoSize.ToString()); + } + else + { + column.Width = columnAttr.Width; + } + } + } + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormClients.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormClients.cs index c1a17b5..658b61d 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormClients.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormClients.cs @@ -15,82 +15,73 @@ using System.Windows.Forms; namespace BlacksmithWorkshop { - public partial class FormClients : Form - { - private readonly ILogger _logger; + public partial class FormClients : Form + { + private readonly ILogger _logger; - private readonly IClientLogic _clientLogic; + private readonly IClientLogic _clientLogic; - public FormClients(ILogger logger, IClientLogic clientLogic) - { - InitializeComponent(); + public FormClients(ILogger logger, IClientLogic clientLogic) + { + InitializeComponent(); - _logger = logger; - _clientLogic = clientLogic; - } + _logger = logger; + _clientLogic = clientLogic; + } - private void FormClients_Load(object sender, EventArgs e) - { - LoadData(); - } + private void FormClients_Load(object sender, EventArgs e) + { + LoadData(); + } - private void LoadData() - { - _logger.LogInformation("Загрузка клиентов"); + private void LoadData() + { + try + { + dataGridView.FillandConfigGrid(_clientLogic.ReadList(null)); + _logger.LogInformation("Загрузка клиентов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки клиентов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - try - { - var list = _clientLogic.ReadList(null); + private void ButtonDelete_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + _logger.LogInformation("Удаление клиента"); - _logger.LogInformation("Успешная загрузка клиентов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки клиентов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + try + { + if (!_clientLogic.Delete(new ClientBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } - private void ButtonDelete_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } - _logger.LogInformation("Удаление клиента"); - - try - { - if (!_clientLogic.Delete(new ClientBindingModel - { - Id = id - })) - { - throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); - } - - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка удаления компонента"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - } - - private void ButtonRef_Click(object sender, EventArgs e) - { - LoadData(); - } - } + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementers.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementers.cs index 46d0dbf..267e6e4 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementers.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementers.cs @@ -1,5 +1,7 @@ -using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopBusinessLogic.BusinessLogic; +using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.DI; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -36,15 +38,7 @@ namespace BlacksmithWorkshop { try { - var list = _logic.ReadList(null); - - //растягиваем колонку Название на всю ширину, колонку Id скрываем - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillandConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка исполнителей"); } @@ -58,14 +52,11 @@ namespace BlacksmithWorkshop private void ButtonCreate_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormImplementer form) + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } @@ -73,16 +64,13 @@ namespace BlacksmithWorkshop { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormImplementer form) + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + + if (form.ShowDialog() == DialogResult.OK) { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormMails.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMails.cs index 78327b4..36bebfc 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormMails.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMails.cs @@ -38,15 +38,7 @@ namespace BlacksmithWorkshop try { - var list = _messageLogic.ReadList(null); - - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["MessageId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillandConfigGrid(_messageLogic.ReadList(null)); _logger.LogInformation("Успешная загрузка писем"); } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.Designer.cs index 6783697..05fb824 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.Designer.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.Designer.cs @@ -30,20 +30,23 @@ { dataGridView = new DataGridView(); buttonCreateOrder = new Button(); - buttonTakeOrderInWork = new Button(); - buttonOrderReady = new Button(); buttonIssuedOrder = new Button(); buttonRef = new Button(); menuStrip = new MenuStrip(); toolStripMenuItem = new ToolStripMenuItem(); workPieceToolStripMenuItem = new ToolStripMenuItem(); manufactureToolStripMenuItem = new ToolStripMenuItem(); + mailsToolStripMenuItem = new ToolStripMenuItem(); reportsToolStripMenuItem = new ToolStripMenuItem(); workPiecesToolStripMenuItem = new ToolStripMenuItem(); workPieceManufacturesToolStripMenuItem = new ToolStripMenuItem(); ordersToolStripMenuItem = new ToolStripMenuItem(); workWithClientsToolStripMenuItem = new ToolStripMenuItem(); clientsToolStripMenuItem = new ToolStripMenuItem(); + работаСИсполнителямиToolStripMenuItem = new ToolStripMenuItem(); + implementerToolStripMenuItem = new ToolStripMenuItem(); + startingWorkToolStripMenuItem = new ToolStripMenuItem(); + createBackUpToolStripMenuItem = new ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); menuStrip.SuspendLayout(); SuspendLayout(); @@ -68,29 +71,9 @@ buttonCreateOrder.UseVisualStyleBackColor = true; buttonCreateOrder.Click += ButtonCreateOrder_Click; // - // buttonTakeOrderInWork - // - buttonTakeOrderInWork.Location = new Point(1247, 147); - buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; - buttonTakeOrderInWork.Size = new Size(235, 29); - buttonTakeOrderInWork.TabIndex = 2; - buttonTakeOrderInWork.Text = "Отдать на выполнение"; - buttonTakeOrderInWork.UseVisualStyleBackColor = true; - buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; - // - // buttonOrderReady - // - buttonOrderReady.Location = new Point(1247, 224); - buttonOrderReady.Name = "buttonOrderReady"; - buttonOrderReady.Size = new Size(235, 29); - buttonOrderReady.TabIndex = 3; - buttonOrderReady.Text = "Заказ готов"; - buttonOrderReady.UseVisualStyleBackColor = true; - buttonOrderReady.Click += ButtonOrderReady_Click; - // // buttonIssuedOrder // - buttonIssuedOrder.Location = new Point(1247, 300); + buttonIssuedOrder.Location = new Point(1247, 144); buttonIssuedOrder.Name = "buttonIssuedOrder"; buttonIssuedOrder.Size = new Size(235, 29); buttonIssuedOrder.TabIndex = 4; @@ -100,7 +83,7 @@ // // buttonRef // - buttonRef.Location = new Point(1247, 373); + buttonRef.Location = new Point(1247, 221); buttonRef.Name = "buttonRef"; buttonRef.Size = new Size(235, 29); buttonRef.TabIndex = 5; @@ -111,7 +94,7 @@ // menuStrip // menuStrip.ImageScalingSize = new Size(20, 20); - menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, reportsToolStripMenuItem, workWithClientsToolStripMenuItem }); + menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, reportsToolStripMenuItem, workWithClientsToolStripMenuItem, работаСИсполнителямиToolStripMenuItem, startingWorkToolStripMenuItem, createBackUpToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; menuStrip.Size = new Size(1506, 28); @@ -120,7 +103,7 @@ // // toolStripMenuItem // - toolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { workPieceToolStripMenuItem, manufactureToolStripMenuItem }); + toolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { workPieceToolStripMenuItem, manufactureToolStripMenuItem, mailsToolStripMenuItem }); toolStripMenuItem.Name = "toolStripMenuItem"; toolStripMenuItem.Size = new Size(117, 24); toolStripMenuItem.Text = "Справочники"; @@ -139,6 +122,13 @@ manufactureToolStripMenuItem.Text = "Изделия"; manufactureToolStripMenuItem.Click += ManufactureToolStripMenuItem_Click; // + // mailsToolStripMenuItem + // + mailsToolStripMenuItem.Name = "mailsToolStripMenuItem"; + mailsToolStripMenuItem.Size = new Size(162, 26); + mailsToolStripMenuItem.Text = "Письма"; + mailsToolStripMenuItem.Click += MailsToolStripMenuItem_Click; + // // reportsToolStripMenuItem // reportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { workPiecesToolStripMenuItem, workPieceManufacturesToolStripMenuItem, ordersToolStripMenuItem }); @@ -181,6 +171,34 @@ clientsToolStripMenuItem.Text = "Клиенты"; clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; // + // работаСИсполнителямиToolStripMenuItem + // + работаСИсполнителямиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { implementerToolStripMenuItem }); + работаСИсполнителямиToolStripMenuItem.Name = "работаСИсполнителямиToolStripMenuItem"; + работаСИсполнителямиToolStripMenuItem.Size = new Size(196, 24); + работаСИсполнителямиToolStripMenuItem.Text = "Работа с исполнителями"; + // + // implementerToolStripMenuItem + // + implementerToolStripMenuItem.Name = "implementerToolStripMenuItem"; + implementerToolStripMenuItem.Size = new Size(185, 26); + implementerToolStripMenuItem.Text = "Исполнители"; + implementerToolStripMenuItem.Click += ImplementerToolStripMenuItem_Click; + // + // startingWorkToolStripMenuItem + // + startingWorkToolStripMenuItem.Name = "startingWorkToolStripMenuItem"; + startingWorkToolStripMenuItem.Size = new Size(114, 24); + startingWorkToolStripMenuItem.Text = "Запуск работ"; + startingWorkToolStripMenuItem.Click += StartingWorkToolStripMenuItem_Click; + // + // createBackUpToolStripMenuItem + // + createBackUpToolStripMenuItem.Name = "createBackUpToolStripMenuItem"; + createBackUpToolStripMenuItem.Size = new Size(123, 24); + createBackUpToolStripMenuItem.Text = "Создать бекап"; + createBackUpToolStripMenuItem.Click += CreateBackUpToolStripMenuItem_Click; + // // FormMain // AutoScaleDimensions = new SizeF(8F, 20F); @@ -188,8 +206,6 @@ ClientSize = new Size(1506, 450); Controls.Add(buttonRef); Controls.Add(buttonIssuedOrder); - Controls.Add(buttonOrderReady); - Controls.Add(buttonTakeOrderInWork); Controls.Add(buttonCreateOrder); Controls.Add(dataGridView); Controls.Add(menuStrip); @@ -208,8 +224,6 @@ private DataGridView dataGridView; private Button buttonCreateOrder; - private Button buttonTakeOrderInWork; - private Button buttonOrderReady; private Button buttonIssuedOrder; private Button buttonRef; private MenuStrip menuStrip; @@ -222,5 +236,10 @@ private ToolStripMenuItem ordersToolStripMenuItem; private ToolStripMenuItem workWithClientsToolStripMenuItem; private ToolStripMenuItem clientsToolStripMenuItem; + private ToolStripMenuItem startingWorkToolStripMenuItem; + private ToolStripMenuItem работаСИсполнителямиToolStripMenuItem; + private ToolStripMenuItem implementerToolStripMenuItem; + private ToolStripMenuItem mailsToolStripMenuItem; + private ToolStripMenuItem createBackUpToolStripMenuItem; } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.cs index e8058df..b513cbc 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.cs @@ -1,6 +1,7 @@ using BlacksmithWorkshopBusinessLogic.BusinessLogic; using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.DI; using BlacksmithWorkshopDataModels.Enums; using Microsoft.Extensions.Logging; using System; @@ -23,13 +24,19 @@ namespace BlacksmithWorkshop private readonly IReportLogic _reportLogic; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic) + private readonly IWorkProcess _workProcess; + + private readonly IBackUpLogic _backUpLogic; + + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic) { InitializeComponent(); _logger = logger; _orderLogic = orderLogic; _reportLogic = reportLogic; + _workProcess = workProcess; + _backUpLogic = backUpLogic; } private void FormMain_Load(object sender, EventArgs e) @@ -43,16 +50,7 @@ namespace BlacksmithWorkshop try { - var list = _orderLogic.ReadList(null); - - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ManufactureId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ManufactureName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillandConfigGrid(_orderLogic.ReadList(null)); _logger.LogInformation("Загрузка заказов"); } @@ -65,92 +63,24 @@ namespace BlacksmithWorkshop private void WorkPieceToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormWorkPieces)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormWorkPieces form) - { - form.ShowDialog(); - } + form.ShowDialog(); } private void ManufactureToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormManufactures)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormManufactures form) - { - form.ShowDialog(); - } + form.ShowDialog(); } private void ButtonCreateOrder_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } - - } - - private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); - - try - { - var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel - { - Id = id - }); - - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка передачи заказа в работу"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - - private void ButtonOrderReady_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); - - try - { - var operationResult = _orderLogic.FinishOrder(new OrderBindingModel - { - Id = id - }); - - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о готовности заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + form.ShowDialog(); + LoadData(); } private void ButtonIssuedOrder_Click(object sender, EventArgs e) @@ -206,31 +136,69 @@ namespace BlacksmithWorkshop private void WorkPieceManufacturesToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormReportManufactureWorkPieces)); + var form = DependencyManager.Instance.Resolve(); + + form.ShowDialog(); - if (service is FormReportManufactureWorkPieces form) - { - form.ShowDialog(); - } } private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormReportOrders form) - { - form.ShowDialog(); - } + form.ShowDialog(); } private void ClientsToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormClients form) + form.ShowDialog(); + } + + private void StartingWorkToolStripMenuItem_Click(object sender, EventArgs e) + { + _workProcess.DoWork(DependencyManager.Instance.Resolve()!, _orderLogic); + + MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + + private void ImplementerToolStripMenuItem_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + + form.ShowDialog(); + } + + private void MailsToolStripMenuItem_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + + form.ShowDialog(); + } + + private void CreateBackUpToolStripMenuItem_Click(object sender, EventArgs e) + { + try { - form.ShowDialog(); + if (_backUpLogic != null) + { + var fbd = new FolderBrowserDialog(); + + if (fbd.ShowDialog() == DialogResult.OK) + { + _backUpLogic.CreateBackUp(new BackUpSaveBinidngModel + { + FolderName = fbd.SelectedPath + }); + + MessageBox.Show("Бекап создан", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.cs index eef23ce..ea391cd 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.cs @@ -1,5 +1,6 @@ using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.DI; using BlacksmithWorkshopContracts.SearchModels; using BlacksmithWorkshopDataModels.Models; using Microsoft.Extensions.Logging; @@ -15,232 +16,226 @@ using System.Windows.Forms; namespace BlacksmithWorkshop { - public partial class FormManufacture : Form - { - private readonly ILogger _logger; + public partial class FormManufacture : Form + { + private readonly ILogger _logger; - private readonly IManufactureLogic _logic; + private readonly IManufactureLogic _logic; - private int? _id; + private int? _id; - private Dictionary _manufactureWorkPieces; + private Dictionary _manufactureWorkPieces; - public int Id { set { _id = value; } } + public int Id { set { _id = value; } } - public FormManufacture(ILogger logger, IManufactureLogic logic) - { - InitializeComponent(); + public FormManufacture(ILogger logger, IManufactureLogic logic) + { + InitializeComponent(); - _logger = logger; - _logic = logic; - _manufactureWorkPieces = new Dictionary(); - } + _logger = logger; + _logic = logic; + _manufactureWorkPieces = new Dictionary(); + } - private void FormManufacture_Load(object sender, EventArgs e) - { - if (_id.HasValue) - { - _logger.LogInformation("Загрузка изделия"); + private void FormManufacture_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Загрузка изделия"); - try - { - var view = _logic.ReadElement(new ManufactureSearchModel { Id = _id.Value }); + try + { + var view = _logic.ReadElement(new ManufactureSearchModel { Id = _id.Value }); - if (view != null) - { - textBoxName.Text = view.ManufactureName; - textBoxPrice.Text = view.Price.ToString(); - _manufactureWorkPieces = view.ManufactureWorkPieces ?? new Dictionary(); - LoadData(); - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки изделия"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + if (view != null) + { + textBoxName.Text = view.ManufactureName; + textBoxPrice.Text = view.Price.ToString(); + _manufactureWorkPieces = view.ManufactureWorkPieces ?? new Dictionary(); + LoadData(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } - private void LoadData() - { - _logger.LogInformation("Загрузка заготовок для изделия"); + private void LoadData() + { + _logger.LogInformation("Загрузка заготовок для изделия"); - try - { - if (_manufactureWorkPieces != null) - { - dataGridView.Rows.Clear(); + try + { + if (_manufactureWorkPieces != null) + { + dataGridView.Rows.Clear(); - foreach (var awp in _manufactureWorkPieces) - { - dataGridView.Rows.Add(new object[] { awp.Key, awp.Value.Item1.WorkPieceName, awp.Value.Item2 }); - } + foreach (var awp in _manufactureWorkPieces) + { + dataGridView.Rows.Add(new object[] { awp.Key, awp.Value.Item1.WorkPieceName, awp.Value.Item2 }); + } - textBoxPrice.Text = CalcPrice().ToString(); - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заготовки для изделия"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + textBoxPrice.Text = CalcPrice().ToString(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заготовки для изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - private void ButtonAdd_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormManufactureWorkPiece)); + private void ButtonAdd_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); - if (service is FormManufactureWorkPiece form) - { - if (form.ShowDialog() == DialogResult.OK) - { - if (form.WorkPieceModel == null) - { - return; - } + if (form.ShowDialog() == DialogResult.OK) + { + if (form.WorkPieceModel == null) + { + return; + } - _logger.LogInformation("Добавление новой заготовки:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count); + _logger.LogInformation("Добавление новой заготовки:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count); - if (_manufactureWorkPieces.ContainsKey(form.Id)) - { - _manufactureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count); - } - else - { - _manufactureWorkPieces.Add(form.Id, (form.WorkPieceModel, form.Count)); - } + if (_manufactureWorkPieces.ContainsKey(form.Id)) + { + _manufactureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count); + } + else + { + _manufactureWorkPieces.Add(form.Id, (form.WorkPieceModel, form.Count)); + } - LoadData(); - } - } - } + LoadData(); + } + } - private void ButtonUpd_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - var service = Program.ServiceProvider?.GetService(typeof(FormManufactureWorkPiece)); + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var form = DependencyManager.Instance.Resolve(); - if (service is FormManufactureWorkPiece form) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); - form.Id = id; - form.Count = _manufactureWorkPieces[id].Item2; + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); + form.Id = id; + form.Count = _manufactureWorkPieces[id].Item2; - if (form.ShowDialog() == DialogResult.OK) - { - if (form.WorkPieceModel == null) - { - return; - } + if (form.ShowDialog() == DialogResult.OK) + { + if (form.WorkPieceModel == null) + { + return; + } - _logger.LogInformation("Изменение компонента:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count); - _manufactureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count); + _logger.LogInformation("Изменение компонента:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count); + _manufactureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count); - LoadData(); - } - } - } - } + LoadData(); + } + } + } - private void ButtonDel_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) - { - try - { - _logger.LogInformation("Удаление заготовки:{WorkPieceName} - {Count}", dataGridView.SelectedRows[0].Cells[1].Value); - _manufactureWorkPieces?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } + private void ButtonDel_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + try + { + _logger.LogInformation("Удаление заготовки:{WorkPieceName} - {Count}", dataGridView.SelectedRows[0].Cells[1].Value); + _manufactureWorkPieces?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } - LoadData(); - } - } - } + LoadData(); + } + } + } - private void ButtonRef_Click(object sender, EventArgs e) - { - LoadData(); - } + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } - private void ButtonSave_Click(object sender, EventArgs e) - { - if (string.IsNullOrEmpty(textBoxName.Text)) - { - MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } + return; + } - if (string.IsNullOrEmpty(textBoxPrice.Text)) - { - MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + if (string.IsNullOrEmpty(textBoxPrice.Text)) + { + MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } + return; + } - if (_manufactureWorkPieces == null || _manufactureWorkPieces.Count == 0) - { - MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + if (_manufactureWorkPieces == null || _manufactureWorkPieces.Count == 0) + { + MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } + return; + } - _logger.LogInformation("Сохранение изделия"); + _logger.LogInformation("Сохранение изделия"); - try - { - var model = new ManufactureBindingModel - { - Id = _id ?? 0, - ManufactureName = textBoxName.Text, - Price = Convert.ToDouble(textBoxPrice.Text), - ManufactureWorkPieces = _manufactureWorkPieces - }; + try + { + var model = new ManufactureBindingModel + { + Id = _id ?? 0, + ManufactureName = textBoxName.Text, + Price = Convert.ToDouble(textBoxPrice.Text), + ManufactureWorkPieces = _manufactureWorkPieces + }; - var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } - MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - DialogResult = DialogResult.OK; + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; - Close(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка сохранения изделия"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - private void ButtonCancel_Click(object sender, EventArgs e) - { - DialogResult = DialogResult.Cancel; - Close(); - } + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } - //в конце умножить на 1.1, так как прибавляем к итоговой стоимости некоторый процент (в данном случае 10%) - private double CalcPrice() - { - double price = 0; + //в конце умножить на 1.1, так как прибавляем к итоговой стоимости некоторый процент (в данном случае 10%) + private double CalcPrice() + { + double price = 0; - foreach (var elem in _manufactureWorkPieces) - { - price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2); - } + foreach (var elem in _manufactureWorkPieces) + { + price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2); + } - return Math.Round(price * 1.1, 2); - } - } + return Math.Round(price * 1.1, 2); + } + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactures.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactures.cs index 54191d9..30a9960 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactures.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactures.cs @@ -1,5 +1,7 @@ -using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopBusinessLogic.BusinessLogic; +using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.DI; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -13,114 +15,100 @@ using System.Windows.Forms; namespace BlacksmithWorkshop { - public partial class FormManufactures : Form - { - private readonly ILogger _logger; + public partial class FormManufactures : Form + { + private readonly ILogger _logger; - private readonly IManufactureLogic _logic; + private readonly IManufactureLogic _logic; - public FormManufactures(ILogger logger, IManufactureLogic logic) - { + public FormManufactures(ILogger logger, IManufactureLogic logic) + { - InitializeComponent(); + InitializeComponent(); - _logger = logger; - _logic = logic; - } + _logger = logger; + _logic = logic; + } - private void FormManufactures_Load(object sender, EventArgs e) - { - LoadData(); - } + private void FormManufactures_Load(object sender, EventArgs e) + { + LoadData(); + } - private void LoadData() - { - try - { - var list = _logic.ReadList(null); + private void LoadData() + { + try + { + dataGridView.FillandConfigGrid(_logic.ReadList(null)); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ManufactureWorkPieces"].Visible = false; - dataGridView.Columns["ManufactureName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + _logger.LogInformation("Загрузка изделий"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки изделий"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - _logger.LogInformation("Загрузка изделий"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки изделий"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + private void ButtonAdd_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); - private void ButtonAdd_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormManufacture)); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } - if (service is FormManufacture form) - { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } - } + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var form = DependencyManager.Instance.Resolve(); - private void ButtonUpd_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - var service = Program.ServiceProvider?.GetService(typeof(FormManufacture)); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (service is FormManufacture form) - { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } - } - } + private void ButtonDelete_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - private void ButtonDelete_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление изделия"); - _logger.LogInformation("Удаление изделия"); + try + { + if (!_logic.Delete(new ManufactureBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } - try - { - if (!_logic.Delete(new ManufactureBindingModel - { - Id = id - })) - { - throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); - } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка удаления компонента"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - } - - private void ButtonRef_Click(object sender, EventArgs e) - { - LoadData(); - } - } + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPieces.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPieces.cs index 6bc847c..a08e69e 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPieces.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPieces.cs @@ -1,5 +1,7 @@ -using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopBusinessLogic.BusinessLogic; +using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.DI; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -13,114 +15,100 @@ using System.Windows.Forms; namespace BlacksmithWorkshop { - public partial class FormWorkPieces : Form - { - private readonly ILogger _logger; + public partial class FormWorkPieces : Form + { + private readonly ILogger _logger; - private readonly IWorkPieceLogic _logic; + private readonly IWorkPieceLogic _logic; - public FormWorkPieces(ILogger logger, IWorkPieceLogic logic) - { - InitializeComponent(); - _logger = logger; - _logic = logic; - } + public FormWorkPieces(ILogger logger, IWorkPieceLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } - private void FormWorkPiece_Load(object sender, EventArgs e) - { - LoadData(); - } + private void FormWorkPiece_Load(object sender, EventArgs e) + { + LoadData(); + } - private void LoadData() - { - try - { - var list = _logic.ReadList(null); + private void LoadData() + { + try + { + dataGridView.FillandConfigGrid(_logic.ReadList(null)); - //растягиваем колонку Название на всю ширину, колонку Id скрываем - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["WorkPieceName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + _logger.LogInformation("Загрузка заготовок"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заготовок"); - _logger.LogInformation("Загрузка заготовок"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заготовок"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + private void ButtonAdd_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); - private void ButtonAdd_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormWorkPiece)); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } - if (service is FormWorkPiece form) - { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } - } + //проверяем наличие выделенной строки + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var form = DependencyManager.Instance.Resolve(); - //проверяем наличие выделенной строки - private void ButtonUpd_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - var service = Program.ServiceProvider?.GetService(typeof(FormWorkPiece)); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } - if (service is FormWorkPiece form) - { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } - } - } + private void ButtonDelete_Click(object sender, EventArgs e) + { + //проверяем наличие выделенной строки + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - private void ButtonDelete_Click(object sender, EventArgs e) - { - //проверяем наличие выделенной строки - if (dataGridView.SelectedRows.Count == 1) - { - if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление компонента"); - _logger.LogInformation("Удаление компонента"); + try + { + if (!_logic.Delete(new WorkPieceBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } - try - { - if (!_logic.Delete(new WorkPieceBindingModel - { - Id = id - })) - { - throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); - } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка удаления компонента"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - } - - private void ButtonRef_Click(object sender, EventArgs e) - { - LoadData(); - } - } + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/Program.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/Program.cs index aa288e5..670c60b 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/Program.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/Program.cs @@ -1,9 +1,10 @@ -using BlacksmithWorkshopBusinessLogic.BusinessLogic; +using BlacksmithWorkshopBusinessLogic.BusinessLogic; using BlacksmithWorkshopBusinessLogic.MailWorker; using BlacksmithWorkshopBusinessLogic.OfficePackage; using BlacksmithWorkshopBusinessLogic.OfficePackage.Implements; using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.DI; using BlacksmithWorkshopContracts.StoragesContracts; using BlacksmithWorkshopDatabaseImplement.Implements; using Microsoft.Extensions.DependencyInjection; @@ -14,10 +15,6 @@ namespace BlacksmithWorkshop { internal static class Program { - private static ServiceProvider? _serviceProvider; - - public static ServiceProvider? ServiceProvider => _serviceProvider; - /// /// The main entry point for the application. /// @@ -28,12 +25,11 @@ namespace BlacksmithWorkshop // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); var services = new ServiceCollection(); - ConfigureServices(services); - _serviceProvider = services.BuildServiceProvider(); + InitDependency(); try { - var mailSender = _serviceProvider.GetService(); + var mailSender = DependencyManager.Instance.Resolve(); mailSender?.MailConfig(new MailConfigBindingModel { MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, @@ -44,65 +40,61 @@ namespace BlacksmithWorkshop PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) }); - // <20><> <20><> + // ñîçäàåì òàéìåð var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); } catch (Exception ex) { - var logger = _serviceProvider.GetService(); + var logger = DependencyManager.Instance.Resolve(); - logger?.LogError(ex, "<22><> <20><> <20> <20><>"); + logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé"); } - Application.Run(_serviceProvider.GetRequiredService()); + Application.Run(DependencyManager.Instance.Resolve()); } - private static void ConfigureServices(ServiceCollection services) + private static void InitDependency() { - services.AddLogging(option => + DependencyManager.InitDependency(); + + DependencyManager.Instance.AddLogging(option => { option.SetMinimumLevel(LogLevel.Information); option.AddNLog("nlog.config"); }); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(true); - services.AddTransient(); - services.AddSingleton(); - - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient( ); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); } - private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + private static void MailCheck(object obj) => DependencyManager.Instance.Resolve()?.MailCheck(); } } \ No newline at end of file diff --git a/BlacksmithWorkshop/Для бэкапа.zip b/BlacksmithWorkshop/Для бэкапа.zip new file mode 100644 index 0000000000000000000000000000000000000000..092d7bcdd87766c03f984a1f29c57d5b57ff66d2 GIT binary patch literal 1726 zcmWIWW@Zs#U|`^2c;d4-?2h@1wh|z(9*DVt*f}RNHLpZ3t2jTedtF%3xsyI;wF^Ig z3Evd7%i!ywcih%`W^p&TT4swh+&L@$EjEY2(2Q|rwEmmDH<%|euF4F*6j*fD_ski_ zEN|cQ`j@=Vp49R4)xB)IWs5;EgXas;sZ3WZmT5%Je5JvvA|^ilxj3VxSDPE#F*i20 zV_sV~G6bMFu1W8XOB>Kpoj@!A#GbhYIjOlo_oWuWT=>Z+aFfxcz)xp%Pk5g7J*(}h zTLf|Kh7X7Kb@Kw9c%wA&c*=nkuyMx@oBbRaOC~LxxN_!3&H$YaCWh+9y2h3pRgCTZPo4^J*ROK zruvqlCr>Rg6GL-zio4t2^+31gF+$wzo0wOcmY7^pT9k_7<|~1pe9vh6di&^U>Uw?k zKI0n-3}T?8uXX#1m&M*#P_Xggp*C)5{Wm*qlqEI`b=~^#XVII6GgqEmNm5 z?p%0f+Y6xQc$uM|OD!%=Oi%U9OUnm)u6NRIFBeAvm;Xrty=)8&T)@!rFG_(X(4|*)`yDnAVS7;ikwq!!{N1wa zn@SR1c}Oa82n9t4c&c3~Kb{#Ha?(O2wNvQ1#lMn2*8TB$8!NNR-hMiIc56}h_q^-7 zEJNSz%bR_4pJ%vv`RmC470qHE7gnb)D`00T*gbD&@Y|x_8#A}P^p4y)v0p&{)bFhv zm$K}OXZ`exAX3QQI6Od8omAQ^N&wg-Cm}6G)KF7KWgq;XQPaE4sy zg=3cmITRK@E>*wM(iHWx;}ApaO_7Y8E5ViW`sXF*E@NG`|LsdD#ivUpBo>84Y~$Wg zBys!O7U!g6)Aui)Z2Ps)E9u-f6T_q>hcBC>hW*KU-o8*!b^~HQAP&zj$_~g(O@?Q- zqI3Fsz#_uP;6fm{thf@$bzc7z-w7XIKUl6ac$jp!)mGdrCTG_To|N2xRaYA`jZIs# zj1Mi!ec1X}ybM%wOg^-DTIMoH8O6vX!hpL71-b$WAQh+q-l!VUi#LR>xj-g*VTZ08 zy`Vwp4g{t}^kN5HH+oJ+=+PE}g=(^EUJVLh%uw+1_e{_B5v4zlgfCWA70=!v) R`H6vn4G7bLK5}FQ@c=Yqo<;xw literal 0 HcmV?d00001 -- 2.25.1